Visual Programming COMP315 Chapter 2 Variables C Data

Visual Programming COMP-315 Chapter #2 Variables, C# Data Types, and IO, Operators & Program Control Statements

Variables • • A variable is a typed name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name number. Of. Students: int number. Of. Students; … int total; … int average, max; 9200 total: 9204 9208 9212 9216 average: 9220 max: 9224 9228 9232 Which ones are valid variable names? my. Big. Var 99 bottles VAR 1 _test @test namespace It’s-all-over 2

Assignment • • • An assignment statement changes the value of a variable The assignment operator is the = sign int total; … total = 55; The value on the right is stored in the variable on the left • • • The value that was in total is overwritten You can only assign a value to a variable that is consistent with the variable's declared type (more later) You can declare and assign initial value to a variable at the same time, e. g. , int total = 55; 3
![Example static void Main(string[] args) { int total; total = 15; System. Console. Write(“total Example static void Main(string[] args) { int total; total = 15; System. Console. Write(“total](http://slidetodoc.com/presentation_image_h2/065d37225443db07d0defca254e2d53d/image-4.jpg)
Example static void Main(string[] args) { int total; total = 15; System. Console. Write(“total = “); System. Console. Write. Line(total); total = 55 + 5; System. Console. Write(“total = “); System. Console. Write. Line(total); } 4

Constants • A constant is similar to a variable except that it holds one value for its entire existence • The compiler will issue an error if you try to change a constant • In C#, we use the constant modifier to declare a constant • constant int number. Of. Students = 42; • Why constants? • give names to otherwise unclear literal values • facilitate changes to the code • prevent inadvertent errors 5

C# Data Types • • There are 15 data types in C# Eight of them represent integers: • • Two of them represent floating point numbers • • char One of them represents strings: • • bool One of them represents characters: • • decimal One of them represents boolean values: • • float, double One of them represents decimals: • • byte, short, ushort, int, uint, long, ulong string One of them represents objects: • object 6

Numeric Data Types • The difference between the various numeric types is their size, and therefore the values they can store: Type Storage Range byte short ushort int uint long ulong 8 bits 16 bits 32 bits 64 bits 0 - 255 -128 - 127 -32, 768 - 32767 0 - 65537 -2, 147, 483, 648 – 2, 147, 483, 647 0 – 4, 294, 967, 295 -9 1018 to 9 1018 0 – 1. 8 1019 decimal 128 bits 1. 0 10 -28; 7. 9 1028 with 28 -29 significant digits float double 32 bits 64 bits 1. 5 10 -45; 3. 4 1038 with 7 significant digits 5. 0 10 -324; 1. 7 10308 with 15 -16 significant digits Question: you need a variable to represent world population. Which type do you use? 7

Examples of Numeric Variables int x = 1; short y = 10; float pi = 3. 14 f; // f denotes float f 3 = 7 E-02 f; // 0. 07 double d 1 = 7 E-100; // use m to denote a decimal microsoft. Stock. Price = 28. 38 m; 8

Boolean • A bool value represents a true or false condition • A boolean can also be used to represent any two states, such as a light bulb being on or off • The reserved words true and false are the only valid values for a boolean type bool do. Again = true; 9

Characters • • • A char is a single character from the a character set A character set is an ordered list of characters; each character is given a unique number C# uses the Unicode character set, a superset of ASCII • • • Uses sixteen bits per character, allowing for 65, 536 unique characters It is an international character set, containing symbols and characters from many languages Code chart can be found at: http: //www. unicode. org/charts/ Character literals are represented in a program by delimiting with single quotes, e. g. , 'a‘ 'X‘ '7' '$‘ ', ‘ char response = ‘Y’; 10

Common Escape Sequences 11

string • A string represents a sequence of characters, e. g. , string message = “Hello World”; • Question: how to represent this string: The double quotation mark is “ • Question: how to represent this string: \plucky. cs. yale. eduzs 9$My. Docs • Strings can be created with verbatim string literals by starting with @, e. g. , string a 2 = @“\serverfileshareHello. cs”; 12

Data Input • Console. Read. Line() • • Used to get a value from the user input Example string my. String = Console. Read. Line(); • Convert from string to the correct data type • Int 32. Parse() • Used to convert a string argument to an integer • Allows math to be preformed once the string is converted • Example: string my. String = “ 1023”; int my. Int = Int 32. Parse( my. String ); • • Double. Parse() Single. Parse() 13

Output • Console. Write. Line(variable. Name) will print the variable • You can use the values of some variables at some positions of a string: System. Console. Write. Line(“{0} {1}. ”, i. Am. Var 0, i. Am. Var 1); • You can control the output format by using the format specifiers: float price = 2. 5 f; System. Console. Write. Line(“Price = {0: C}. ”, price); Price = $2. 50. 14

Arithmetic Expressions • An expression is a combination of operators and operands • Arithmetic expressions (we will see logical expressions later) compute numeric results and make use of the arithmetic operators: Addition Subtraction Multiplication Division Remainder + * / % 15

Division and Remainder • • If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 14 / 3 equals? 4 8 / 12 equals? 0 The remainder operator (%) returns the remainder after dividing the second operand into the first 14 % 3 equals? 2 8 % 12 equals? 8 16

Operator Precedence • Operators can be combined into complex expressions • result = total + count / max - offset; • Operators have a well-defined precedence which determines the order in which they are evaluated • Precedence rules • Parenthesis are done first • Division, multiplication and modulus are done second • Left to right if same precedence (this is called associativity) • Addition and subtraction are done last • Left to right if same precedence 17

Precedence of Arithmetic Operations 18

Operator Precedence: Examples • What is the order of evaluation in the following expressions? a + b + c + d + e 1 2 3 4 a + b * c - d / e 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1 Example: Temperature. Converter. cs 19

Data Conversions • Sometimes it is convenient to convert data from one type to another • For example, we may want to treat an integer as a floating point value during a computation • Conversions must be handled carefully to avoid losing information • Two types of conversions • Widening conversions are generally safe because they tend to go from a small data type to a larger one (such as a short to an int) • Q: how about int to long? • Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short) 20

Data Conversions • In C#, data conversions can occur in three ways: • Assignment conversion • occurs automatically when a value of one type is assigned to a variable of another • only widening conversions can happen via assignment • Example: a. Float. Var = an. Int. Var • Arithmetic promotion • happens automatically when operators in expressions convert their operands • Example: a. Float. Var / an. Int. Var • Casting 21

Data Conversions: Casting • Casting is the most powerful, and dangerous, technique for conversion • Both widening and narrowing conversions can be accomplished by explicitly casting a value • To cast, the type is put in parentheses in front of the value being converted • For example, if total and count are integers, but we want a floating point result when dividing them, we can cast total: result = (float) total / count; 22

Assignment • You can consider assignment as another operator, with a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated answer = 4 sum / 4 + MAX * lowest; 1 3 2 Then the result is stored in the variable on the left hand side 23

Assignment • The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count = count + 1; Then the result is stored back into count (overwriting the original value) 24

Assignment Operators 25

Increment and Decrement Operators 26

Precedence and Associativity high low 27

Boolean Expressions: Basics • A condition often uses one of C#’s equality operators (==, !=) or relational operators (<, >, <=, >=), which all return boolean results: == != < > <= >= equal to not equal to less than greater than less than or equal to greater than or equal to 28

Equality and Relational Operators Note the difference between the equality operator (==) and the assignment operator (=) Question: if (grade = 100) Console. Write. Line( “Great!” ); 29

Comparing Characters • We can also use the relational operators on character data • The results are based on the Unicode character set • The following condition is true because the character '+' comes before the character 'J' in Unicode: if ('+' < 'J') Console. Write. Line("+ is less than J"); • The uppercase alphabet (A-Z) and the lowercase alphabet (a -z) both appear in alphabetical order in Unicode 30

More Complex (Compound) Boolean Expressions: Logical Operators • Boolean expressions can also use the following logical and conditional operators: ! & | ^ && || Logical NOT Logical AND Logical OR Logical exclusive OR (XOR) Conditional AND Conditional OR • They all take boolean operands and produce boolean results 31

Logical and Conditional Operators 32

Logical and Conditional Operators 33

Comparison: Logical and Conditional Operators • Logical AND (&) and Logical OR (|) • Always evaluate both conditions • Conditional AND (&&) and Conditional OR (||) • Would not evaluate the secondition if the result of the first condition would already decide the final outcome. • Ex 1: false && (x++ > 10) --- no need to evaluate the 2 nd condition • Ex 2: if (count != 0 && total /count) { … } 34

More Interesting: Control Statements • Selection (a. k. a. , conditional statements): decide whether or not to execute a particular statement; these are also called the selection statements or decision statements • if selection (one choice) • if/else selection (two choices) – Also: the ternary conditional operator e 1? e 2: e 3 • switch statement (multiple choices) • Repetition (a. k. a. , loop statements): repeatedly executing the same statements (for a certain number of times or until a test condition is satisfied). • while structure • do/while structure • foreach structure (Chapter 12) 35

C# Control Structures: Selection switch structure (multiple selections) if/else structure (double selection) T F T break F if structure (single selection) T . . . T break F F break 36

C# Control Structures: Repetition for structure/foreach structure while structure T F T do/while structure F T F 37

The if Statement • The if statement has the following syntax: if is a C# reserved word The condition must be a boolean expression. It must evaluate to either true or false. if ( condition ) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped. 38

if Statement if ( <test> ) <code executed if <test> is true> ; • The if statement • • Causes the program to make a selection Chooses based on conditional • <test>: any expression that evaluates to a bool type • True: perform an action • False: skip the action • Single entry/exit point • No semicolon after the condition 39

if/else Statement if ( <test> ) <code executed if <test> is true> ; else <code executed if <test> is false> ; • The if/else structure • • • Alternate courses can be taken when the statement is false Rather than one action there are two choices Nested structures can test many cases 40

Nested if/else Statements • The statement executed as a result of an if statement or else clause could be another if statement • These are called nested if /else statements if (temperature > 90) //int temperature if (sunny) // boolean sunny System. out. println(“Beach”); else System. out. println(“Ice. Cream Parlor”); else if (sunny) System. out. println(“Tennis”); else System. out. println(“Volleyball”); // beginning of the next statement 41

The if-else-if Ladder • A common programming construct that is based upon the nested if is the if-else-if ladder. It looks like this: • The conditional expressions are evaluated from the top downward. As soon as a true condition is found, the statement associated with it is executed, and the rest of the ladder is bypassed. if (student. Grade >= 90) Console. Write. Line(“A”); else if (student. Grade >= 80) Console. Write. Line(“B”); else if (student. Grade >= 70) Console. Write. Line(“C”); else if (student. Grade >= 60) Console. Write. Line(“D”); else Console. Write. Line(“F”); // beginning of the next statement 42

Ternary Conditional Operator (? : ) • Conditional Operator (e 1? e 2: e 3) • C#’s only ternary operator • Can be used to construct expressions • Similar to an if/else structure string result; int num. Q; ………… result = (num. Q==1) ? “Quarter” : “Quarters”; // beginning of the next statement 43

while Statement • The while statement has the following syntax: while is a reserved word If the condition is true, the statement is executed. Then the condition is evaluated again. while ( condition ) statement; The statement (or a block of statements) is executed repetitively until the condition becomes false. 44

while Statement while ( <test> ) { <code to be repeated if <test> is true> ; } • Repetition Structure • An action is to be repeated • Continues while <test> is true • Ends when <test> is false • Contains either a line or a body of code 45

while Statement • Note that if the condition of a while statement is false initially, the statement is never executed • Therefore, the body of a while loop will execute zero or more times 46

Infinite Loops • The body of a while loop must eventually make the condition false • If not, it is an infinite loop, which will execute until the user interrupts the program • This is a common type of logical error • You should always double check to ensure that your loops will terminate normally 47

The do Statement • The do statement has the following syntax: Uses both the do and while reserved words do { statement; } while ( condition ); The statement is executed once initially, then the condition is evaluated The statement is repetitively executed until the condition becomes false 48

Comparing the while and do Loops • The while loops vs. the do/while loops while structure • Using a while loop • Condition is tested • The action is performed • Loop could be skipped altogether T F do/while structure • Using a do/while loop • Action is performed • Then the loop condition is tested • Loop will be run at least once T F 49

The for Statement • The for statement has the following syntax: Reserved word The initialization portion is executed once before the loop begins The statement is executed until the condition becomes false for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration 50

The for Statement • It is well suited for executing a specific number of times that can be determined in advance • Increment/Decrement • When incrementing In most cases < or <= is used • When decrementing In most cases > or >= is used 51

The flexibility of the for Statement • Each expression in the header of a for loop is optional • • • If the initialization is left out, no initialization is performed If the condition is left out, it is always considered to be true, and therefore creates an infinite loop If the increment is left out, no increment operation is performed • Both semi-colons are always required in the for loop header for ( ; ; ) { // do something } 52

Statements break and continue • Used to alter the flow of control • The break statement • Used to exit a loop early • The continue statement • Used to skip the rest of the statements in a loop and restart at the first statement in the loop • Programs can be completed without their usage; use with caution. 53

The foreach Loop • The foreach loop cycles through the elements of a collection. A collection is a group of objects. • C# defines several types of collections, of which one is an array. // Use the foreach loop. using System; class Foreach. Demo { static void Main() { int sum = 0; int[] nums = new int[10]; // Give nums some values. for(int i = 0; i < 10; i++) nums[i] = i; // Use foreach to display and sum the values. foreach(int x in nums) { Console. Write. Line("Value is: " + x); sum += x; } Console. Write. Line("Summation: " + sum); } } 54

The switch Statement • The switch statement provides another means to decide which statement to execute next • The switch statement evaluates an expression, then attempts to match the result to one of several possible cases • Each case contains a value and a list of statements • The flow of control transfers to statement list associated with the first value that matches 55

The switch Statement: Syntax The general syntax of a switch statement is: switch and case and default are reserved words switch ( expression ) { case value 1 : statement-list 1 case value 2 : statement-list 2 case. . . If expression matches value 2, default : control jumps statement-list to here } 56

The switch Statement • The expression of a switch statement must result in an integral data type, like an integer or character or a string • Note that the implicit boolean condition in a switch statement is equality - it tries to match the expression with a value 57

The switch Statement • A switch statement can have an optional default case as the last case in the statement • • • The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it if no other case value matches If there is no default case, and no other value matches the expression, control falls through to the statement after the switch • A break statement is used as the last statement in each case's statement list • A break statement causes control to transfer to the end of the switch statement 58
- Slides: 58