Download presentation
Presentation is loading. Please wait.
1
Visual Programming COMP-315
Chapter #2 Variables, C# Data Types, and IO, Operators & Program Control Statements
2
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 9200 9204 9208 9212 9216 9220 9224 9228 9232 numberOfStudents: average: max: total: int numberOfStudents; … int average, max; data type variable name int total; Which ones are valid variable names? myBigVar VAR _test @test 99bottles namespace It’s-all-over
3
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;
4
Example static void Main(string[] args) { int total; total = 15;
System.Console.Write(“total = “); System.Console.WriteLine(total); total = ; }
5
constant int numberOfStudents = 42;
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 numberOfStudents = 42; Why constants? give names to otherwise unclear literal values facilitate changes to the code prevent inadvertent errors
6
C# Data Types There are 15 data types in C#
Eight of them represent integers: byte, sbyte, short, ushort, int, uint, long,ulong Two of them represent floating point numbers float, double One of them represents decimals: decimal One of them represents boolean values: bool One of them represents characters: char One of them represents strings: string One of them represents objects: object
7
Numeric Data Types The difference between the various numeric types is their size, and therefore the values they can store: Type byte sbyte short ushort int uint long ulong decimal float double Storage 8 bits 16 bits 32 bits 64 bits 128 bits Range -32, -2,147,483,648 – 2,147,483,647 0 – 4,294,967,295 -9 to 91018 0 – 1.81019 1.010-28; 7.91028 with significant digits 1.510-45; 3.41038 with 7 significant digits 5.010-324; 1.710308 with significant digits Question: you need a variable to represent world population. Which type do you use?
8
Examples of Numeric Variables
int x = 1; short y = 10; float pi = 3.14f; // f denotes float float f3 = 7E-02f; // 0.07 double d1 = 7E-100; // use m to denote a decimal decimal microsoftStockPrice = 28.38m;
9
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 doAgain = true;
10
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: Character literals are represented in a program by delimiting with single quotes, e.g., 'a‘ 'X‘ '7' '$‘ ',‘ char response = ‘Y’;
11
Common Escape Sequences
12
string message = “Hello World”;
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.edu\zs9$\MyDocs Strings can be created with verbatim string literals by starting e.g., string a2
13
Data Input Console.ReadLine()
Used to get a value from the user input Example string myString = Console.ReadLine(); Convert from string to the correct data type Int32.Parse() Used to convert a string argument to an integer Allows math to be preformed once the string is converted Example: string myString = “1023”; int myInt = Int32.Parse( myString ); Double.Parse() Single.Parse()
14
System.Console.WriteLine(“Price = {0:C}.”, price);
Output Console.WriteLine(variableName) will print the variable You can use the values of some variables at some positions of a string: System.Console.WriteLine(“{0} {1}.”, iAmVar0, iAmVar1); You can control the output format by using the format specifiers: float price = 2.5f; System.Console.WriteLine(“Price = {0:C}.”, price); Price = $2.50.
15
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 %
16
Division and Remainder
If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 14 / equals? 4 8 / equals? The remainder operator (%) returns the remainder after dividing the second operand into the first 14 % equals? 2 8 % equals? 8
17
result = total + count / max - offset;
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
18
Precedence of Arithmetic Operations
19
Operator Precedence: Examples
What is the order of evaluation in the following expressions? a + b + c + d + e a + b * c - d / e 1 2 3 4 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1 Example: TemperatureConverter.cs
20
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)
21
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: aFloatVar = anIntVar Arithmetic promotion happens automatically when operators in expressions convert their operands Example: aFloatVar / anIntVar Casting
22
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;
23
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 = sum / 4 + MAX * lowest; 4 1 3 2 Then the result is stored in the variable on the left hand side
24
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 = count + 1; Then the result is stored back into count (overwriting the original value)
25
Assignment Operators
26
Increment and Decrement Operators
27
Precedence and Associativity
high low
28
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
29
Equality and Relational Operators
Note the difference between the equality operator (==) and the assignment operator (=) Question: if (grade = 100) Console.WriteLine( “Great!” );
30
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.WriteLine("+ is less than J"); The uppercase alphabet (A-Z) and the lowercase alphabet (a-z) both appear in alphabetical order in Unicode
31
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
32
Logical and Conditional Operators
33
Logical and Conditional Operators
34
Comparison: Logical and Conditional Operators
Logical AND (&) and Logical OR (|) Always evaluate both conditions Conditional AND (&&) and Conditional OR (||) Would not evaluate the second condition if the result of the first condition would already decide the final outcome. Ex 1: false && (x++ > 10) no need to evaluate the 2nd condition Ex 2: if (count != 0 && total /count) { … }
35
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 e1?e2:e3 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 for structure foreach structure (Chapter 12)
36
C# Control Structures: Selection
F if structure (single selection) if/else structure (double selection) switch structure (multiple selections) . . break .
37
C# Control Structures: Repetition
F while structure do/while structure for structure/foreach structure
38
The if Statement The if statement has the following syntax:
The condition must be a boolean expression. It must evaluate to either true or false. if is a C# reserved word if ( condition ) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped.
39
if Statement The 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
40
if/else Statement The if/else structure 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
41
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(“IceCream Parlor”); if (sunny) System.out.println(“Tennis”); System.out.println(“Volleyball”); // beginning of the next statement
42
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 (studentGrade >= 90) Console.WriteLine(“A”); else if (studentGrade >= 80) Console.WriteLine(“B”); else if (studentGrade >= 70) Console.WriteLine(“C”); else if (studentGrade >= 60) Console.WriteLine(“D”); else Console.WriteLine(“F”); // beginning of the next statement
43
Ternary Conditional Operator (?:)
Conditional Operator (e1?e2:e3) C#’s only ternary operator Can be used to construct expressions Similar to an if/else structure string result; int numQ; ………… result = (numQ==1) ? “Quarter” : “Quarters”; // beginning of the next statement
44
while Statement The while statement has the following syntax:
If the condition is true, the statement is executed. Then the condition is evaluated again. while is a reserved word while ( condition ) statement; The statement (or a block of statements) is executed repetitively until the condition becomes false.
45
while Statement Repetition Structure 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
46
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
47
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
48
The do Statement The do statement has the following syntax: do
{ statement; } while ( condition ); Uses both the do and while reserved words The statement is executed once initially, then the condition is evaluated The statement is repetitively executed until the condition becomes false
49
Comparing the while and do Loops
The while loops vs. the do/while loops Using a while loop Condition is tested The action is performed Loop could be skipped altogether Using a do/while loop Action is performed Then the loop condition is tested Loop will be run at least once T F while structure T F do/while structure
50
The for Statement The for statement has the following syntax:
The initialization portion is executed once before the loop begins The statement is executed until the condition becomes false Reserved word for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration
51
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
52
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 }
53
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.
54
The foreach Loop // Use the foreach loop. using System; class ForeachDemo { 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.WriteLine("Value is: " + x); sum += x; } Console.WriteLine("Summation: " + sum); 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.
55
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
56
The switch Statement: Syntax
The general syntax of a switch statement is: switch and case default are reserved words switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case ... default : statement-list } If expression matches value2, control jumps to here
57
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
58
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.