View
216
Download
0
Category
Preview:
Citation preview
C# Programming: From Problem Analysis to Program Design
1
Data Types
and
Expressions 2 C# Programming: From Problem Analysis to Program Design
4th Edition
C# Programming: From Problem Analysis to Program Design
2
Chapter Objectives
C# Programming: From Problem Analysis to Program Design
3
Chapter Objectives (continued)
C# Programming: From Problem Analysis to Program Design
4
Chapter Objectives (continued)
C# Programming: From Problem Analysis to Program Design
5
Data Representation
0/1
0 1 2 3 4 5 6 7
Bits and Bytes
6
7
Decimal Number System
Decimal Number System 6 5 4 3 2 1 0
106 105 104 103 102 101 100
1M 100K 10K 1000 100 10 1
0 2 0 3 4 6 5
200,000 + 3000 + 400 + 60 + 5 = 203,465
C# Programming: From Problem Analysis to Program Design
9
Data Representation (continued)
Table 2-1
Binary
equivalent
of selected
decimal
values
10
Binary Number System
(continued)
Figure 2-2 Decimal equivalent of 01101001
11
Binary Number System
Figure 2-1 Base-10 positional notation of 36
7 6 5 4 3 2 1 0
27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1
0 0 1 0 0 1 0 0
32 + 4 = 36
12
Binary Number System
Figure 2-1 Base-10 positional notation of 161
7 6 5 4 3 2 1 0
27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1
1 0 0 1 0 1 1 1
13
Data Representation (continued)
'€' '\u20AC'
Data Representation (continued)
ASCII Table
Data Representation (continued)
Data Representation (continued)
Console.WriteLine('\u00D1');
17
Data Representation (continued)
18
Memory Locations for Data
customerName, productCode, addressLine1, savingAccountBalance
19
Reserved Words in C#
Contextual Keywords
20
Table 2-4 C# contextual keywords
Never use these words as variable names – It is a very bad idea!!!
21
Naming Conventions
– Eg: FirstName, LastName
– Eg: firstName, lastName, savingAccountBalance
22
Examples of Valid Names (Identifiers)
Table 2-5 Valid identifiers
23
Examples of Invalid Names (Identifiers)
Table 2-6 Invalid identifier
type identifier = expression;
24
Variables
C# Programming: From Problem Analysis to Program Design
25
Types, Classes, and Objects
int, string
C# Programming: From Problem Analysis to Program Design
26
Type, Class, and Object Examples
Table 2-7 Sample data types
27
Predefined Data Types
• Common Type System (CTS)
• Divided into two major categories
Figure 2-3 .NET common types
28
Value and Reference Types
Figure 2-4 Memory representation for value and reference types
29
Value Types
Figure 2-5 Value type hierarchy
30
Value Types
• Integral: 123
• Floating point: 1.57e+3 (same as 1570)
• Decimal: 1.23
• Boolean true / false
• Struct class Person…{name, age, sex…}
• Enumerated enum Days { Sunday, Monday, Tuesday,
Wednesday, Thursday, Friday, Saturday };
enum Months : byte { Jan, Feb, Mar, Apr,
May, Jun, Jul, Aug, Sep, Oct, Nov, Dec };
Figure 2-5 Type Examples
31
Value Types (continued)
32
Integral Data Types
– byte & sbyte
– char
– int & uint
– long & ulong
– short & ushort
Data Types
33 Table 2-9 Values and sizes for integral types
34
Examples of Integral Variable
Declarations
int studentCount; // number of students in the class
int ageOfStudent = 20; // age-originally initialized to 20
int numberOfExams; // number of exams
int coursesEnrolled; // number of courses enrolled
35
Floating-Point Types
Table 2-10 Values and sizes for floating-point types
36
Examples of Floating-Point
Declarations
double extraPerson = 3.50; // extraPerson originally set
// to 3.50
double averageScore = 70.0; // averageScore originally set
// to 70.0
double priceOfTicket; // cost of a movie ticket
double gradePointAverage; // grade point average
float totalAmount = 23.57f; // note the f must be placed after
// the value for float types
37
Decimal Types
• Examples
decimal endowmentAmount = 33897698.26M;
decimal deficit;
Table 2-11 Value and size for decimal data type
38
Boolean Variables
→
false
bool undergraduateStudent;
bool moreData = true;
39
Strings
string studentName;
string courseName = "Programming I";
string twoLines = "Line1\nLine2";
40
Making Data Constant
const
const type identifier = expression;
const double TAX_RATE = 0.0675;
const int SPEED = 70;
const char HIGHEST_GRADE = 'A';
41
Assignment Statements
variable = expression;
42
Examples of Assignment
Statements
int numberOfMinutes,
count,
minIntValue;
numberOfMinutes = 45;
count = 0;
minIntValue = -2147483648;
count = count + 1;
numberOfMinutes = 10 + Delay(clerkId);
Examples of Assignment
Statements
char firstInitial,
yearInSchool,
punctuation,
enterKey,
lastChar;
firstInitial = 'B';
yearInSchool = '1';
punctuation = ';';
enterKey = '\n'; // newline escape character
lastChar = '\u005A'; // Unicode character 'Z'
euroSymbol= '\u20AC'; // Unicode character '€'
43
44
Examples of Assignment
Statements (continued)
double accountBalance,
weight;
bool isFinished;
accountBalance = 4783.68;
weight = 1.7E-3; //scientific notation may be used
isFinished = false; //declared previously as a bool
//Notice – no quotes used
45
Examples of Assignment
Statements (continued)
decimal amountOwed,
deficitValue;
amountOwed = 3000.50m; // m or M must be suffixed to
// decimal data types
deficitValue = -322888672.50M;
46
Examples of Assignment
Statements (continued)
string aSaying, fileLocation;
aSaying = "First day of the rest of your life!\n";
fileLocation = @ "C:\textFiles\newChapter2";
@
47
Examples of Assignment
Statements (continued)
Figure 2-7 Impact of assignment statement
48
Arithmetic Operations
resultVariable = operand1 operator operand2;
49
Basic Arithmetic Operations
Figure 2-8 Result of 67 % 3
50
Basic Arithmetic Operations
(continued)
string result;
string fullName;
string firstName = "Daenerys";
string lastName = "Targaryen";
fullName = firstName + " " + lastName;
//now fullName is "Daenerys Targaryen"
51
Concatenation
Figure 2-9 String concatenation
52
Basic Arithmetic Operations
(continued)
num++; // num = num + 1;
--value1; // value = value – 1;
int num = 100;
Console.WriteLine(num++); // Displays 100
Console.WriteLine(num); // Displays 101
Console.WriteLine(++num); // Displays 102
Basic Arithmetic Operations
(continued)
53
Figure 2-10 Declaration of value type variables
Basic Arithmetic Operations
(continued)
54 Figure 2-11 Change in memory after count++; statement executed
C# Programming: From Problem Analysis to Program Design
55
Basic Arithmetic Operations
(continued) int num = 100;
Console.WriteLine(num++); //prints 100
Console.WriteLine(num); //prints 101
Console.WriteLine(++num); //prints 102
56
Basic Arithmetic Operations
(continued)
Figure 2-12 Results after statement is executed
57
Compound Operations
58
Basic Arithmetic Operations
(continued)
answer = 100;
answer += 50 * 3 / 25 – 4;
50 * 3 = 150
150 / 25 = 6
6 – 4 = 2
100 + 2 = 102
59
Order of Operations
Table 2-14 Operator precedence
60
Order of Operations (continued)
Figure 2-13 Order of execution of the operators
61
Mixed Expressions
double answer; answer = 10 / 3; // Does not produce 3.3333333 double answer2; answer2 = 10.0 / 3; // produces 3.3333333 int value1 = 440, anotherNumber = 70; double value2 = 100.60; value2 = value1; // ok, 440.0 stored in value2
62
Mixed Expressions int value1 = 440; double value2 = 100.60;
value1 = value2; // syntax error as shown in Figure 2-14
double int
63
Mixed Expressions (continued)
(type) expression examAverage = (exam1 + exam2 + exam3) / (double) count;
int value1 = 0,
anotherNumber = 75;
double value2 = 100.99,
anotherDouble = 100;
value1 = (int) value2; // value1 = 100
value2 = (double) anotherNumber; // value2 = 75.0
64
Mixed Expressions (continued)
Convert
int v1 = Convert.ToInt32(1.999); // v1 is 1
long v2 = Convert.ToInt64("5.7777"); // v2 is 5.7777
string v3 = Convert.ToString(1.999); // v3 is "1.999"
char v4 = Convert.ToChar(65); // v4 is 'A'
65
Formatting Output
66
Formatting Output (continued)
Table 2-15 Examples using format specifiers
67
Numeric Format Specifiers
68
Numeric Format Specifiers
(continued)
69
Custom Numeric Format Specifiers
Table 2-17 Custom numeric format specifiers
Custom Numeric Format
Specifiers (continued)
70
Width Specifier
Console.WriteLine("{0,10:F0}{1,8:C}", 9, 14);
9 $14.00 //Right justified values
------------------
123456789012345678
71
Interpolated Strings (New in C# 6)
72
• $•
•
string name = "Diana Prince"; DateTime date = DateTime.Now; // Composite formatting: Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date); // String interpolation: Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's " + $"{date:HH:mm} now."); // in both cases the output is // Hello, Diana Prince! Today is Sunday, it's 15:20 now.
73
Programming Example –
CarpetCalculator
74
Data Needs for the
CarpetCalculator
Table 2-18 Variables
75
Nonchanging Definitions for the
CarpetCalculator
Table 2-19 Constants
Side Note: 1 yard = 3 feet
1 sqy = 9 sqf
76
CarpetCalculator Example
77
Algorithm for
CarpetCalculator
Example
Figure 2-17 CarpetCalculator flowchart
78
Algorithm for the
CarpetCalculator Example
(continued)
Figure 2-18 Structured English for the CarpetCalculator example
79
CarpetCalculator Example
(continued)
Figure 2-19 Class diagram for the CarpetCalculator example
CarpetCalculator Example
(continued)
80 Figure 2-20 Revised class diagram without methods
81
/* CarpetCalculator.cs Author: Doyle
*/
using System;
namespace CarpetExample
{
class CarpetCalculator
{
static void Main( )
{
const int SQ_FT_PER_SQ_YARD = 9;
const int INCHES_PER_FOOT = 12;
const string BEST_CARPET = "Berber";
const string ECONOMY_CARPET = "Pile";
int roomLengthFeet = 12, roomLengthInches = 2,
roomWidthFeet = 14, roomWidthInches = 7;
double roomLength, roomWidth, carpetPrice,
numOfSquareFeet,
numOfSquareYards,
totalCost;
82
roomLength = roomLengthFeet +
(double) roomLengthInches / INCHES_PER_FOOT;
roomWidth = roomWidthFeet +
(double) roomWidthInches / INCHES_PER_FOOT;
numOfSquareFeet = roomLength * roomWidth;
numOfSquareYards = numOfSquareFeet / SQ_FT_PER_SQ_YARD;
carpetPrice = 27.95; //per square yard
totalCost = numOfSquareYards * carpetPrice;
Console.WriteLine("The cost of " + BEST_CARPET
+ " is {0:C}", totalCost);
Console.WriteLine( );
carpetPrice = 15.95; //per square yard
totalCost = numOfSquareYards * carpetPrice;
Console.WriteLine("The cost of " + ECONOMY_CARPET
+ " is " + "{0:C}", totalCost);
Console.Read();
}
}
}
Coding Standards
C# Programming: From Problem Analysis to Program Design
83
Resources
Naming Guidelines for .NET – http://msdn.microsoft.com/en-us/library/xzf533w0(VS.71).aspx
Writing Readable Code – http://software.ac.uk/resources/guides/writing-readable-source-code#node-131
C# Video tutorials – http://www.programmingvideotutorials.com/csharp/csharp-introduction
Visual Studio 2012 – C# – http://msdn.microsoft.com/en-us/library/kx37x36(V=VS.110).aspx
84
Chapter Summary
C# Programming: From Problem Analysis to Program Design
85
C# Programming: From Problem Analysis to Program Design
86
Chapter Summary (continued)
C# Programming: From Problem Analysis to Program Design
87
Chapter Summary (continued)
• Constants
• Assignment statements
– Order of operations
• Formatting output
88
using System; using System.Globalization; using System.Resources; using System.Threading; class Sample { public static void Main() { Console.WriteLine(String.Format("{0:0.00}", 123.4567)); // 123.46 Console.WriteLine(String.Format("{0:0.00}", 1.2)); // 1.20 Console.WriteLine(String.Format("{0:0.00}", 0.1)); // 0.10 Console.WriteLine(String.Format("{0:0.00}", 123.0)); // 123.00 Console.WriteLine(String.Format("{0:0.00}", 123)); // 123.00 Console.WriteLine(String.Format("{0:00.0}", 123.4567) ); // 123.5 Console.WriteLine(String.Format("{0:00.0}", 1.99) ); // 02.0 Console.WriteLine(String.Format("{0:0,0.0}", 12345.67)); // 12,345.7 Console.WriteLine(String.Format("{0:#.00}", 0.1) ); // .10 Console.WriteLine(String.Format("{0,10:0.0}", 123.4567)); // _____123.5 Console.WriteLine(String.Format("{0,-10:0.0}", 123.4567)); // 123.5____ Console.WriteLine(String.Format("Balance is ${0,-10:0.0}USD", 123.4567)); // Balance is $123.5____USD Console.WriteLine(String.Format("{0:Balance is $0.0 USD}", 123.4567)); // Balance is $123.5____USD Console.WriteLine(String.Format("{0:00000}", 123) ); // 00123 Console.WriteLine(String.Format("{0,5}", 123) ); // __123 Console.WriteLine(String.Format("{0,-5}", 123)); // 123__ Console.WriteLine(String.Format("{0:(###) ###-####}", 2165551234)); // (216) 555-1234 Console.WriteLine(String.Format("{0:(000) 000-0000}", 2165551234)); // (216) 555-1234 double decNum = 1.23; string strUSA = decNum.ToString(CultureInfo.InvariantCulture.NumberFormat); // "1.23" string strEurope = decNum.ToString(CultureInfo.GetCultureInfo("es-ES").NumberFormat); // "1,23" Console.WriteLine(strUSA ); // "1.23" Console.WriteLine(strEurope ); // "1,23" Console.ReadKey(); } }
Appendix 1 Formatting Numbers
C# Programming: From Problem Analysis to Program Design
89
using System; using System.Globalization; using System.Resources; using System.Threading; class DemoFormatDates { public static void Main() { //using other Culture values. See Link: // https://msdn.microsoft.com/en-US/library/Ee825488(v=CS.20).aspx //Thread.CurrentThread.CurrentCulture = new CultureInfo("es-VE"); //Thread.CurrentThread.CurrentCulture = new CultureInfo("en-UK"); //Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); //Thread.CurrentThread.CurrentCulture = new CultureInfo("el-GR"); CultureInfo ci = Thread.CurrentThread.CurrentCulture; Console.WriteLine(ci); // en-US DateTime dt = DateTime.Now; Console.WriteLine(dt); // 8 / 8 / 2015 4:39:58 PM Console.WriteLine(String.Format("{0:y yy yyy yyyy}", dt)); // 15 15 2015 2015 Console.WriteLine(String.Format("{0:M MM MMM MMMM}", dt)); // 8 08 Aug August Console.WriteLine(String.Format("{0:d dd ddd dddd}", dt)); // 8 08 Sat Saturday Console.WriteLine(String.Format("{0:h hh H HH}", dt)); // 4 04 16 16 hour 12/24 Console.WriteLine(String.Format("{0:m mm}", dt)); // 39 39 minutes Console.WriteLine(String.Format("{0:s ss}", dt)); // 58 58 seconds Console.WriteLine(String.Format("{0:t tt}", dt)); // P PM A.M. or P.M. Console.WriteLine(String.Format("{0:z zz zzz}", dt)); // -4 -04 -04:00 time zone Console.ReadKey(); } }
Appendix 2 Formatting Dates
C# Programming: From Problem Analysis to Program Design
90
using System; using System.Globalization; using System.Resources; using System.Threading; class Sample { public static void Main() { DateTime dt = DateTime.Now; Console.WriteLine(dt); // 8 / 8 / 2015 10:22:15 PM Console.WriteLine(String.Format("{0:t}", dt)); // 10:22 PM ShortTime Console.WriteLine(String.Format("{0:T}", dt)); // 10:22:15 PM LongTime Console.WriteLine(String.Format("{0:d}", dt)); // 8 / 8 / 2015 ShortDate Console.WriteLine(String.Format("{0:D}", dt)); // Saturday, August 08, 2015 LongDate Console.WriteLine(String.Format("{0:F}", dt)); // Saturday, August 08, 2015 10:22:15 PM FullDateTime Console.WriteLine(String.Format("{0:r}", dt)); // Sat, 08 Aug 2015 22:22:15 GMT RFC1123 Console.WriteLine(String.Format("{0:u}", dt)); // 2015 - 08 - 08 22:22:15Z UniversalSortableDate Console.ReadKey(); } }
Appendix 3 Formatting Dates
91
using System; using System.Globalization; using System.Resources; using System.Threading; class Sample { public static void Main() { Console.WriteLine("First Name| Last Name | Age "); Console.WriteLine("----------+===============+-----"); Console.WriteLine(String.Format("{0,-10}|{1,-15}|{2,5}", "Daenerys", "Targaryen", 19)); Console.WriteLine(String.Format("{0,-10}|{1,-15}|{2,5}", "Drogon", "", 3)); Console.WriteLine(String.Format("{0,-10}|{1,-15}|{2,5}", "Maester", "Aemon", 102)); Console.WriteLine("----------+===============+-----"); Console.ReadKey(); } }
Appendix 4 Formatting Tables
Recommended