59
Logical Operators and Control Statements

Logical Operators and Control Statements

  • Upload
    khalil

  • View
    67

  • Download
    3

Embed Size (px)

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 Presentation

Citation preview

Page 1: Logical Operators and Control Statements

Logical Operators and Control Statements

Page 2: 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;

Page 3: Logical Operators and Control Statements

Example

Page 4: Logical Operators and Control Statements

Boolean Operators Used for constructing Boolean

expressions. and && or || not ! equal == Not equal != Comparison <, >, <=, >=

Page 5: Logical Operators and Control Statements

And (&&)

Both values are to be “true”.

true && true = true false && true = false true && false = false false && false = false

Page 6: Logical Operators and Control Statements

Or (||)

At least one value is to be “true”.

true || true = true false || true = true true || false = true false || false = false

Page 7: Logical Operators and Control Statements

Not (!)

Reverses the value.

!true = false

!false = true

Page 8: Logical Operators and Control Statements

Equal (==)

Returns true if two values are equal.

1 == 21 == 2 1 == 01 == 0 42 == 4242 == 42 variable1variable1 == == otherVariableotherVariable

Page 9: Logical Operators and Control Statements

Not Equal (!=)

Returns true if two values are not equal.

1 != 21 != 2 1 != 01 != 0 42 != 4242 != 42 aa != != variable variable

Page 10: Logical Operators and Control Statements

Comparison (>,<,>=,<=)

1 < 21 < 2 0 > 10 > 1 42 <= 4242 <= 42 ageage>= 18>= 18

Page 11: Logical Operators and Control Statements

Operator Priority

Parantheses Not (!) Comparison(<, >, <=, >=) Equals(==) Not Equals(!=) And(&&) Or(||)

HighestHighest

LowestLowest

Page 12: Logical Operators and Control Statements

Example

Page 13: Logical Operators and Control Statements

Common Mistakes

Writing logical expressions without taking operator priorities in to account.

Writing just one equals(=) instead of two (==).

Page 14: Logical Operators and Control Statements

Control statements

Page 15: Logical Operators and 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.

Page 16: Logical Operators and Control Statements

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.

Page 17: Logical Operators and Control Statements

If case If control statements has two forms:

if ( expression ) {codes;

}

or

if ( expression ) code;

Page 18: Logical Operators and Control Statements

Example

Page 19: Logical Operators and Control Statements

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!!!!

Page 20: Logical Operators and Control Statements

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 ;;

Page 21: Logical Operators and Control Statements

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;;

Page 22: Logical Operators and Control Statements

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;;} }

Page 23: Logical Operators and Control Statements

Example: Comparing two numbers

Page 24: Logical Operators and Control Statements

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.

Page 25: Logical Operators and Control Statements

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.");

????

Page 26: Logical Operators and Control Statements

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"); }}}}

Page 27: Logical Operators and Control Statements

switch – case conditions

Selection control using multiple values

Page 28: Logical Operators and Control Statements

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.

Page 29: Logical Operators and Control Statements

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;;}}

Page 30: Logical Operators and Control Statements

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.

Page 31: Logical Operators and Control Statements

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"

Page 32: Logical Operators and Control Statements

Example Cont.

Page 33: Logical Operators and Control Statements

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.

Page 34: Logical Operators and Control Statements

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.

Page 35: Logical Operators and Control Statements

Loops

while, do-while and for loops

Page 36: Logical Operators and Control Statements

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.

Page 37: Logical Operators and Control Statements

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.

Page 38: Logical Operators and Control Statements

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;;

}}

Page 39: Logical Operators and Control Statements

Example

Page 40: Logical Operators and Control Statements

do-while loop

do statement; while(logical expression is true);

dodo{{ statement;; statement;;} } while(while(logical expression is true) ;) ;

Page 41: Logical Operators and Control Statements

Example

Page 42: Logical Operators and Control Statements

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;}}

Page 43: Logical Operators and Control Statements

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.

Page 44: Logical Operators and Control Statements

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.

Page 45: Logical Operators and Control Statements

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.

Page 46: Logical Operators and Control Statements

Example

for (int counter = 1; counter <= 10; counter ++){

Console.WriteLine(counter.ToString());}

Page 47: Logical Operators and Control Statements

Exampleint counter = 1;for ( ; counter <= 10; ){

Console.WriteLine(counter.ToString()); counter ++;

}

int counter = 1;for ( ; ; ){

Console.WriteLine(counter.ToString());counter ++;if (counter >10) break;

}

Page 48: Logical Operators and Control Statements

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.

Page 49: Logical Operators and Control Statements

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.

Page 50: Logical Operators and Control Statements

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););}}

Page 51: Logical Operators and Control Statements

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.

Page 52: Logical Operators and Control Statements

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.

Page 53: Logical Operators and Control Statements

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””

}}

Page 54: Logical Operators and Control Statements

Solution

Page 55: Logical Operators and Control Statements

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.

Page 56: Logical Operators and Control Statements

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++;

}}

Page 57: Logical Operators and Control Statements

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);

}}

Page 58: Logical Operators and Control Statements

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.

Page 59: Logical Operators and Control Statements

Example: Nested For Loops