logical operators and control statements
DESCRIPTION
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. - PowerPoint PPT PresentationTRANSCRIPT
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 “boo
l” 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 && true = true false && true = false true && false = false false && false = false
Or (||)
At least one value is to be “true”.
true || true = true false || true = true true || false = true false || false = false
Not (!)
Reverses the value.
!true = false
!false = true
Equal (==)
Returns true if two values are equal.
1 == 21 == 2 1 == 01 == 0 42 == 4242 == 42 variable1variable1 == == otherVariableotherVariable
Not Equal (!=)
Returns true if two values are not equal.
1 != 21 != 2 1 != 01 != 0 42 != 4242 != 42 aa != != variable variable
Comparison (>,<,>=,<=)
1 < 21 < 2 0 > 10 > 1 42 <= 4242 <= 42 ageage>= 18>= 18
Operator Priority
Parantheses Not (!) Comparison(<, >, <=, >=) Equals(==) Not Equals(!=) And(&&) Or(||)
HighestHighest
LowestLowest
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 :
We can also write if – else as:
if ( expression ) if ( expression ) statement;statement;
No semicolons No semicolons here!!!!here!!!!
No semicolons No semicolons here!!!!here!!!!
if (expression ) if (expression ) statement1;statement1;
else else statement2;statement2;
No semicolons No semicolons here!!!!here!!!!
No semicolons No semicolons here!!!!here!!!!
No semicolons No semicolons here!!!!here!!!!
No semicolons No semicolons here!!!!here!!!!
if – else if – else
if ( if ( boolean expression is trueboolean expression is true ) ) statementstatement ; ;
else if (else if (boolean expression is trueboolean expression is true)) statementstatement ; ;
elseelse statement 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 (if (boolean expression is trueboolean expression is true ) ) statementstatement;;
else if (else if (boolean expression is true boolean expression is true )) statementstatement; ;
else if (else if (boolean expression is true boolean expression is true )) statementstatement;;
elseelse statementstatement;;
if – else if – else blocks
if (if (boolean expression is trueboolean expression is true ) ){{ statement blocksstatement blocks;;}}else if (else if (boolean expression is trueboolean expression is true ) ){{ statement blocksstatement blocks; ; }}elseelse{{ statement blocksstatement 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 and lower “too dry" %21 - %40: “dry" %41 - %60: “little dry" %61 - %80: “little moist" %81 and higher: “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 (humudity < 20) if (temperature <= 0)if (temperature <= 0) Console.WriteLine(Console.WriteLine(““A cold and dry day.")A cold and dry day.") if (ruzgar < 10) if (ruzgar < 10) Console.WriteLine(Console.WriteLine(““Wonderful, no wind!");Wonderful, no wind!"); else else Console.WriteLine(Console.WriteLine(““low moist and higher than 0 degrees");low moist and higher than 0 degrees"); else if (humudity < 60)else if (humudity < 60) if (temperature <= 0)if (temperature <= 0) Console.WriteLine(Console.WriteLine(““cold and moderate moisture.");cold and moderate moisture."); elseelse Console.WriteLine(Console.WriteLine(““Higher than 0, moderate moisture.");Higher than 0, moderate moisture.");
????
Nested if Conditionsif (humudity < 20) {if (humudity < 20) { if (temperature <= 0) {if (temperature <= 0) { Console.WriteLine("A cold and dry day.") Console.WriteLine("A cold and dry day.") if (ruzgar < 10) {if (ruzgar < 10) { Console.WriteLine(Console.WriteLine(““Wonderful, no wind!");Wonderful, no wind!"); } } }} else {else { Console.WriteLine(Console.WriteLine(““low moist and higher than 0");low moist and higher than 0"); }}}}else if (humudity < 60) {else if (humudity < 60) { if (temperature <= 0) {if (temperature <= 0) { Console.WriteLine(Console.WriteLine(““cold and moderate moist.");cold and moderate moist."); }} else{else{ Console.WriteLine(Console.WriteLine(““Hidher than 0, moderate moist");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
switchswitch ( (variable variable )){{ casecase constant_value1constant_value1 : : statementsstatements;;
breakbreak;; casecase constant_value2constant_value2 : : statementsstatements;;
breakbreak;; casecase constant_value3 : constant_value3 : statementsstatements;;
breakbreak;; defaultdefault : : statementsstatements;;
breakbreak;;}}
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 and lower “too dry" %21 - %40: “dry" %41 - %60: “little dry" %61 - %80: “little moist" %81 and higher: “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 (while (logical expression is truelogical expression is true) ) statementstatement;;
while (while (logical expression is truelogical expression is true)){{
statementstatement;;statementstatement;;
}}
Example
do-while loop
do statement; while(logical expression is true);
dodo{{ statement;; statement;;} } while(while(logical expression is true) ;) ;
Example
For loop
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( for( initializationinitialization; ; logical expr.(termination)logical expr.(termination); ; incrementincrement)){{
statement;statement;}}
for Loop
for (for (expression1expression1 ; ; expression2expression2 ; ; expresion3expresion3)){{
statementsstatements;; } }
expression1, executed once before for loop starts. It could be one or multiple mathematical or other operations.
for Loop
for (for (expresion1expresion1 ; ; expression2expression2 ; ; expresion3expresion3)){{
statementsstatements;; } }
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 (for (expression1expression1; ; expression2expression2;; expression3expression3)){{
statementsstatements ; ; } }
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());}
Exampleint 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;expression1;while (expression2)while (expression2){ {
statements;statements; expression3;expression3;}}
for (expression1; expression2; expression3)for (expression1; expression2; expression3){{
statements; statements; }}
Her iki örnek de birbirinin aynısı şekilde
çalışır.
Her iki örnek de birbirinin aynısı şekilde
çalışır.
Example
int int countercounter;;
countercounter = 1 ; = 1 ;while (while (countercounter <= 10 ) <= 10 ){ { Console.WriteLine(Console.WriteLine(““The value of counter :The value of counter :”” + counter + counter);); countercounter++ ;++ ;
}}
int int countercounter;;
for(counter = 0; counter <= 10; counter++) {for(counter = 0; counter <= 10; counter++) { Console.WriteLine(Console.WriteLine(““The value of counter :The value of counter :”” + counter + counter););}}
Example
static static void main ( )void main ( ){{ int k, n ;int k, n ; for(for( k = 1, n = 12k = 1, n = 12 ;; k<9 && n>6 ;k<9 && n>6 ; k++, n--)k++, n--) {{ Console.WriteLineConsole.WriteLine ( (""k=k= ““ + k + + k + ““ n=n= ““ + + n) ;n) ; }}}}
There can be multiple There can be multiple expressions separated expressions separated with commas.with commas.
There can be multiple There can be multiple expressions separated expressions separated with commas.with commas.
There can be multiple There can be multiple expressions separated expressions separated with commas.with commas.
There can be multiple There can be multiple expressions separated expressions separated with commas.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 100number = pick a random number bettween 0 and 100
while(true)while(true){{
print print ““Make a guess"Make a guess"read guessread guess
if (guess is equal to the number) if (guess is equal to the number) break loopbreak loop
else if(guess is smaller than number) else if(guess is smaller than number) print print ““smallersmaller””
else else print print ““biggerbigger””
}}
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;int x = 0;
for( ; ; ) { /* infinite loop */for( ; ; ) { /* infinite loop */
if(x == 5) if(x == 5) breakbreak;;Console.WriteLine(x.ToString());Console.WriteLine(x.ToString());x++;x++;
}}
continue: resuming next loop iteration
The code section seen below prints the numbers between 0 and 9 except for 5.
int x;int x;
for( x = 0; x < 10 ; x++) {for( x = 0; x < 10 ; x++) {
if(x == 5) if(x == 5) continuecontinue;;Console.WriteLine(Console.WriteLine(““X = X = ““+ x);+ x);
}}
continue
for( x = 0; x < 10 ; x++) {for( x = 0; x < 10 ; x++) {
if(x == 5) if(x == 5) continuecontinue;; Console.WriteLine(x.ToString());Console.WriteLine(x.ToString());
}}
for( x = 0; x < 10 ; x++) {for( x = 0; x < 10 ; x++) {
if(x != 5) {if(x != 5) { Console.WriteLine(x.ToString());Console.WriteLine(x.ToString());}}
}}
Both codes produces Both codes produces same results.same results.
Both codes produces Both codes produces same results.same results.
Example: Nested For Loops