Logical Operators and Control Statements Boolean Boolean takes true or false values. Used in deciding states. Commonly used in conditional statements and loops. A logical operation is a formula that has a true or false result. Boolean variables are defined with “bool” keyword. bool bVal = true; Example Boolean Operators Used for constructing Boolean expressions. and or not equal Not equal Comparison && || ! == != <, >, <=, >= And (&&) Both values are to be “true”. true false true false && true = true && true = false && false = false && false = false Or (||) At least one value is to be “true”. true false true false || true = true || true = true || false = true || false = false Not (!) Reverses the value. !true = false !false = true Equal (==) Returns true if two values are equal. 1 == 2 1 == 0 42 == 42 variable1 == otherVariable Not Equal (!=) Returns true if two values are not equal. 1 != 2 1 != 0 42 != 42 a != variable Comparison (>,<,>=,<=) 1<2 0>1 42 <= 42 age>= 18 Operator Priority Highest Lowest Parantheses Not (!) Comparison(<, >, <=, >=) Equals(==) Not Equals(!=) And(&&) Or(||) Example Common Mistakes Writing logical expressions without taking operator priorities in to account. Writing just one equals(=) instead of two (==). Control statements if – else Decides which code block will run depending on the result of logical expression. Logical expressions return boolean values. If return value is true then code blocks within the if statement will be executed. Otherwise else statement will be executed. if – else A simple if case decides whether corresponding code block will be executed or not. A structure that is composed of if and else will execute two different code blocks depending on the logical expression. if/else statement can be used in nested forms to express more complex situations. If case If control statements has two forms: if ( expression ) { codes; } or if ( expression ) code; Example if – else if – else Common if use case : if ( expression ) statement; No semicolons here!!!! We can also write if – else as: if (expression ) statement1; else statement2; No semicolons here!!!! No semicolons here!!!! if – else if – else if ( boolean expression is true ) statement ; else if (boolean expression is true) statement ; else statement ; Multiple if – else if – else When there are multiple conditions with one line of statements, we can use if-else structure seen below: if (boolean expression is true ) statement; else if (boolean expression is true ) statement; else if (boolean expression is true ) statement; else statement; if – else if – else blocks if (boolean expression is true ) { statement blocks; } else if (boolean expression is true ) { statement blocks; } else { statement blocks; } Example: Comparing two numbers Exercise Meteorogy department asks for a program that converts humudity values to a human readable format. Program will write to output the following results depending input ranges between 0 and 100. %20 %21 %41 %61 %81 and lower - %40: - %60: - %80: and higher: “too dry" “dry" “little dry" “little moist" “moist“ Write a program that takes a humudiy value from user and writes it’s corresponding human readable output. Nested if conditions C# compiler matches else condition to nearest if condition. Because of this, using {} paranthesis makes life easier and your code readable. if (humudity < 20) if (temperature <= 0) Console.WriteLine(“A cold and dry day.") if (ruzgar < 10) Console.WriteLine(“Wonderful, no wind!"); else ? Console.WriteLine(“low moist and higher than 0 degrees"); else if (humudity < 60) if (temperature <= 0) Console.WriteLine(“cold and moderate moisture."); else Console.WriteLine(“Higher than 0, moderate moisture."); Nested if Conditions if (humudity < 20) { if (temperature <= 0) { Console.WriteLine("A cold and dry day.") if (ruzgar < 10) { Console.WriteLine(“Wonderful, no wind!"); } } else { Console.WriteLine(“low moist and higher than 0"); } } else if (humudity < 60) { if (temperature <= 0) { Console.WriteLine(“cold and moderate moist."); } else{ Console.WriteLine(“Hidher than 0, moderate moist"); } } switch – case conditions Selection control using multiple values switch - case Used if the value of a variable is used for controlling the program flow. May execute different code blocks for each different value of the variable. C# language offers this functionality with switch-case structure. Notation switch (variable ) { case constant_value1 : statements; break; case constant_value2 : statements; break; case constant_value3 : statements; break; default : statements; break; } switch - case switch is the starting point of the structre. A variable should be provided after switch. This variable could be numeric or character. We should use only constant value in case sections, no expressions. All cases should end with break keywords. No need to use { } paranthesis aftes cases. Example Write a program that takes the course grade (just one letter) from user.Your program will write the following result to the output depending on the grade. A: “best" B: “good" C: “all right" D: “not bad" F: “bad" Example Cont. Example Meteorogy department asks for a program that converts humudity values to a human readable format. Program will write to output the following results depending input ranges between 0 and 100. %20 %21 %41 %61 %81 and lower - %40: - %60: - %80: and higher: “too dry" “dry" “little dry" “little moist" “moist“ Write a program that takes a humudiy value from user and writes it’s corresponding human readable output by using switch /case control structure. Switch – Case Notes double,decimal types are not used within switch paranthesis. Any number of statements can be used within the case element. Using default: element help us to detect defects. Forgetting to use breaks is the most common coding bad habbit. Check for breaks after constructing the switch structure. Loops while, do-while and for loops Loops Loops are used for executing code blocks repeatedly. Decision of continuing loop is given by boolean expression. If boolean expression is false, then the code block is not executed. For loops repeats the execution of code blocks in a certain number. Count controlled loop. while and do-while loops repeats code execution in an unknown number of iterations. Condition controlled loop. Loops In for and while loops, logical expressions are tested first. If expression is true then the code block inside the loop is executed, else program doesn’t enter the loop. In do-while loops code block is executed without checking boolean expression result for once. Then before second iteration boolean expression result is checked, and loop continuation is decided. while loop Two types of uses: while (logical expression is true) statement; while (logical expression is true) { statement; statement; } Example do-while loop do statement; while(logical expression is true); do { statement; statement; } while(logical expression is true) ; Example For loop for( initialization; logical expr.(termination); increment) { statement; } initialization expressions are executed once before loop starts. If there are multiple initialization expressions, they are separated with a comma ",". increment ,expression are executed after each iteration If there are multiple increment expressions, they are separated with a comma ",". Execution order is from left to right. After increment operations, logical expression is evaluated and loop terminates if logical expression is false. Else loop enters next iteration. for Loop for (expression1 ; expression2 ; expresion3) { statements; } expression1, executed once before for loop starts. It could be one or multiple mathematical or other operations. for Loop for (expresion1 ; expression2 ; expresion3) { statements; } expression2, is a logical operation that returns true or false result. It is not a requirement that expression2 includes variables used in expression1. for Loop for (expression1; expression2; expression3) { statements ; } expression3, usually changes result of expression2, but it is not a necessity. It is executed after each iteration. Example for (int counter = 1; counter <= 10; counter ++) { Console.WriteLine(counter.ToString()); } Example int counter = 1; for ( ; counter <= 10; ) { Console.WriteLine(counter.ToString()); counter ++; } int counter = 1; for ( ; ; ) { Console.WriteLine(counter.ToString()); counter ++; if (counter >10) break; } Notes expression1, expression2, and expression3 within the for loop could be empty but, we must use semi colons. If epression1 and epression3 are not used, for loop behaves like while loop. We can not know when will the loop terminated if expression2 is not used. In this case loop can be terminated by break expression. expression1 and expression3 might include more than one expressions. The intention of this type of usage is simplifying program code. for while expression1; while (expression2) { statements; expression3; } Her iki örnek de birbirinin aynısı şekilde çalışır. for (expression1; expression2; expression3) { statements; } Example int counter; for(counter = 0; counter <= 10; counter++) { Console.WriteLine(“The value of counter :” + counter); } int counter; counter = 1 ; while (counter <= 10 ) { Console.WriteLine(“The value of counter :” + counter); counter++ ; } Example static void main ( ) { int k, n ; for( k = 1, n = 12 ; k<9 && n>6 ; k++, n--) { Console.WriteLine ("k= “ + k + “ n= “ + n) ; } } There can be multiple expressions separated with commas. There can be multiple expressions separated with commas. Exercise Write a game that generates a random number between 0 and 100 which user will try to guess the number. After user enters a number, program will reply to the user that, his/her guess is bigger or smaller that the generated number. If user writes the correct answer, program will congratulate user and exit. Algorithm number = pick a random number bettween 0 and 100 while(true) { print “Make a guess" read guess if (guess is equal to the number) break loop else if(guess is smaller than number) print “smaller” else print “bigger” } Solution Breaking the Loop break keyword is used to terminate the loop. If there are nested loops break terminates only the inner loop. continue keyword skips current iteration and jumps to next one. Both keyword are heavily used in the implementation of the algorithms. break: terminating the loop The loop seen below terminates when variable x x takes the value of 5. int x = 0; for( ; ; ) { /* infinite loop */ if(x == 5) break; Console.WriteLine(x.ToString()); x++; } continue: resuming next loop iteration The code section seen below prints the numbers between 0 and 9 except for 5. int x; for( x = 0; x < 10 ; x++) { if(x == 5) continue; Console.WriteLine(“X = “+ x); } continue for( x = 0; x < 10 ; x++) { if(x == 5) continue; Console.WriteLine(x.ToString()); } Both codes produces same results. for( x = 0; x < 10 ; x++) { if(x != 5) { Console.WriteLine(x.ToString()); } } Example: Nested For Loops