algorithms and computing lecture 3 control statements by dr. m. tahir khaleeq

42
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

Upload: florence-gordon

Post on 27-Dec-2015

218 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

Algorithms and Computing

Lecture 3

Control Statements

By

Dr. M. Tahir Khaleeq

Page 2: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

2

Topics

• Control Flow Statements• The for Statement• The while Statement• The do while Statement• The if Statement • The if else Statement• The else if Statement• The break Statement • The continue Statement• The goto Statement• The switch Statement

Page 3: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

3

Control flow statements

• The logic of solving a problem forces the execution of program statements in a specific order, function of the state of the solving process.

• The control flow statements and expressions serve this purpose.– Loop statements: for, while, do

– Conditional statements: if, if-else

– Selection statements: switch

– Unconditional jump statement: goto

– Conditional expressions

Page 4: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

4

• The general form of a for statement is: for(expr1;expr2;expr3)statement;

The for statement 1/2

Initialize Test Increment Body of

the Loop

Ex. N = 0 N <= 10 N++ printf(“ N = %d”,N)

for(N = 0; N<=10; N++) printf(“ %d”, N);

No semi-colon (;)

Output: 0 1 2 3 4 5 6 7 8 9 10

Page 5: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

5

• The for statement may be used as:

N=0;

for( ; N<=10 ; )

{

printf(“ %d”, N);

N++;

}

The for statement 2/2

Initialize Test

Increment

semi-colons (;) are necessary

Put braces if more than one

statementsin the for loop

Page 6: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

6

• Logic flow of a for statement: for(expr1;expr2;expr3)statement; next statement

statement

expr2

next statement

expr1

expr3

0

0

Operation of the for Loop

Page 7: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

7

• Find even and odd numbers between 1 to 20

#include <stdio.h>

void main(void){

int X,Y;

for(X=0;X<=2;X++){

printf(“\n”);

for(Y=X;Y<=20;Y+=2)

printf("%d",Y);

}

}

Using for

Output1 3 5 7 9 11 13 15 17 19

2 4 6 8 10 12 14 16 18 20

Page 8: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

8

Implements the repetition in an algorithm

• Repeatedly executes a block of statements

• Tests a condition (Boolean expression) at the start of each iteration

• Terminates when condition becomes false (zero)

The while statement 1/4

Page 9: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

9

• The general form of a while statement is: while(expression) statement;

Test Body of

the Loop

Ex. getche() == ‘a’ printf(“This character is a”)

while(getche() == ‘a’) printf(“This character is a”)

No semi-colon (;)

The while statement 2/4

Page 10: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

10

• The while statement may be used as:

N=0;

while(N<=10) {

printf(“ %d”, N);

N++;

}

The while statement 3/4

Initialize Test

Increment

No semi-colons (;)

Put braces if more than one

statementsin the while loop

Page 11: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

11

• Common Mistakes in while is extra semi-colon.

N=0;

while(N<=10); {

printf(“ %d”, N);

N++;

}

The while statement 4/4

Semi-colon marks the end of the while-block

-- usual cause of infinite loops

Page 12: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

12

• Logic flow of a while statement: while(expression) statement;

next statement

Operation of the while Loop

statement

expression

0

next statement

0

Page 13: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

13

• Count characters in a pharase typed in

#include <stdio.h>

void main(void){

int count=0;

printf(”Type a character:”);

while(getche() != ‘\r’);

count++;}

printf(”\n character count is: %d",count);

}

Using while

Outputarthdfi

character count is: 7

Press Enter

Page 14: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

14

• The general form of a for statement is: for(expr1;expr2;expr3)statement; next statement

• The while statement:

expr1;

while(expr2){

statement

expr3;

}

next statement

Structure of The for and The while statements

statement

expr2

next statement

expr1

expr3

0

0

Page 15: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

15

• The general form of a do statement is: do statement while(expression);

Test

Body of the Loop

Ex. printf(“N = %d”, N) N <= 10 N++

do { printf(“N = %d”, N); N++; } while(N<=10);

No semi-colon (;) semi-colon (;)

The do while statement 1/3

Page 16: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

16

• The do while statement may be used as:

N=0;

do {

printf(“ %d”, N);

N++;

} while(N<=10);

The do while statement 2/3

Initialize

Test

Increment

No semi-colons (;)

Put braces if more than one

statementsin the do while loop

semi-colon (;)

Page 17: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

17

The do while statement 3/3

Increment

• The do while statement may be used as:

N=0; do { printf(“ %d”, N); N++; } while(N<=10);

IMPORTANT!!The increment is performed AFTER the body of the loop

Page 18: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

18

• The general form of a do statement is: do statement while(expression);

next statement

Operation of the do while Loop

statement

expression0

next statement

0

Page 19: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

19

• Determines whether a block is executed.

• Implements the selection instructions within an algorithm.

• Decides what to do by evaluating a Boolean expression.

• If the expression is true (non-zero), the block is executed.

The if statement 1/5

Page 20: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

20

• The general form of an if statement is:

if (expression) statement;

next statement

• If the expression evaluates to a nonzero value the statement is executed and then the control passes to the next statement.

• If the expression evaluates to a zero value the statement is skipped and the control passes directly to the next statement.

The if statement 2/5

Page 21: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

21

• Common mistake

if (number % 2 != 0); { printf("%d is an odd ", number); } printf("number\n");

The if statement 3/5

Do not put semicolon here!

Page 22: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

22

• Common mistake

if (number % 2 = 0) { printf("%d is an odd ", number); } printf("number\n");

The if statement 4/5

Should be ==

Page 23: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

23

• Common mistake

if (number % 2 == 0) { printf("%d is an odd ", number); } printf("number\n");

The if statement 5/5

Do not put “then” here!

Page 24: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

24

/* Read in a number, and echo it

if it is odd. */

#include <stdio.h>

void main()

{

int number;

printf("Enter an integer: ");

scanf("%d", &number);

if (number % 2 != 0)

{

printf("%d\n", number);

}

}

Example

Page 25: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

25

• Which of the following code fragments are equivalent?

if (number % 2 != 0) { printf("%d", number); } printf(” is odd\n");

if (number % 2 != 0) printf("%d", number); printf(” is odd\n");

if (number % 2 != 0) { printf("%d", number); printf(” is odd\n"); }

A

B

C

Exercise 1/2

Page 26: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

26

• A and B are equivalent?

if (number % 2 != 0) { printf("%d", number); } printf(” is odd\n");

if (number % 2 != 0) printf("%d", number); printf(” is odd\n");

if (number % 2 != 0) { printf("%d", number); printf(” is odd\n"); }

A

B

C

Exercise 2/2

Page 27: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

If-else statement

• The general form of an if-else statement is:

if (expression) statement1;

else statement2;

next statement

• If the expression evaluates to a nonzero value the statement1 is executed and then the control passes to the next statement.

• If the expression evaluates to a zero value the statement1 is skipped, statement2 is executed and then the control passes to the next statement.

Page 28: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

• If there are several successive if statements followed by an else part then the else part is paired with the closest if statement.

if (expression1) statement1;

if (expression2) statement2;

. . .

if (expressionn) statementn;

else statementn+1;

Dangling else problem

No semicolons here!

Page 29: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

29

/* Determine whether an input number is odd or even. */#include <stdio.h>main(){ int number;

printf("Enter an integer: "); scanf("%d", &number);

if (number % 2 != 0) { printf("%d is an odd number\n", number); } else { printf("%d is an even number\n", number); }}

Example: if else

Page 30: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

• Find the minimum number out of three given integers X,Y and Z.

#include <stdio.h>

void main(void){

int X,Y,Z,min;

scanf("%d%d%d",&X,&Y,&Z);

if(X < Y && X < Z) min=X;

else if(Y < X && Y < Z) min=Y

else min=Z;

printf("min=%d\n",min);

}

Using else if

Nested if-else

Page 31: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

31

if (ch >= ’a’ && ch <= ’z’){ printf(“%c is in lower case.\n”, ch);}else if (ch >= ’A’ && ch <= ’Z’){ printf(“%c is in upper case.\n”. ch);}else if (ch >= ’0’ && ch <= ’9’){ printf(“%c is a digit with value %d.\n”, ch, ch - ’0’);}

Example: else if

Page 32: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

32

• Multiple alternative blocks each with a Boolean expression.

• First expression which evaluates to true causes execution of the associated block.

• Only at most one block will be executed.

Nested if statement

Page 33: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

• The execution of a cycle statement (while, do, for) can be terminated unconditionally using the statement

break

• Break terminates the innermost cycle that contains it and the control passes to the statement following the cycle.

while(expr1){

statements1

if(expr2)break;

statements2

}

next statement

The break statement

expr20

Page 34: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

• Read floating-point numbers from standard input:– For each number X > 0 compute log10(X)

– Terminate the program when X <= 0.

#include <stdio.h>

#include <math.h>

void main(void){

double X;

while(1){

printf(”Enter a number");

scanf("%f",&X);

if(X <= 0) break;

printf("log10(%f)=%f\n",X,log10(X));

}

}

Using break

Exit the cycle

“while (True)”infinite loop

Page 35: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

• The execution of a cycle statement (while, do, for) can be continued skipping part of the cycle body using the statement

continue

• The following sequences are equivalent.

The continue statement

while(expr1){ statements1 if(expr2)continue; statements2}next statement

while(expr1){ statements1 if(expr2==0){ statements2 }}next statement

Page 36: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

• Print all numbers from 1 to 10 except 5.

#include <stdio.h>

void main(void){

int X;

while(x =1; x <= 10; x++){

if(X == 5) continue;

printf("%d",x);

}

}

Using continue

Continue cyclewithout printing 5

Page 37: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

The goto statement

• The format of the goto statement is

goto label

where label is an identifier.

• The goto statement performs an unconditional jump to a labeled statement. The program continues from that statement.

• A labeled statement has the form:

label: statement

• The goto statement is useful for exiting at once several nested control statements (while, do, case, if) or when it is necessary to continue processing from a "remote" part of the currently executing function.

Page 38: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

• The goto statement is considered harmful according to the standards of modern programming methodology.

• If used carelessly it can undermine the clear program structure provided by other structured control-flow statements.

• The goto statement must be used only when other control statements would lead to a complex program structure.

Warning

Page 39: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

39

The switch Statement 1/2

• The switch statement is similar to the else-if construct.

• If break statement is not used following a case, control will fall through to the next case.

• Switch variable is integer or character variable or expression. Floating point number is not used.

Page 40: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

40

• Structure of the switch statement:

switch(op)

{

case ‘a’:

statement;

break;

default:

statement;

}

Integer or character variable or expression

Integer or character constant

Statements are executedif switch variable op = ‘a’

Statements are executedif no other case applies

The switch Statement 2/2

Page 41: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

41

switch(op)

{

case ‘+’:

printf(“%f”, N1+N2);

break;

case ‘-’:

printf(“%f”, N1-N2);

break;

default:

printf(“ neither + nor - operator”) ;

}

Example: switch statement

Page 42: Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq

#include <stdio.h>

void main(){

float mark; printf("What is your mark? "); scanf("%f", &mark); if (mark < 50) { printf("Sorry. You failed.\n"); } else { printf("Yey! You passed!\n"); }

}

Complete Example

Declares that mark is a variable which can contain a floating point number

Outputs a “prompt” so the user knows what the program wants.

Inputs the floating point content of the variable mark.(Note: ampersand!)

This block of instructions is performed if the comparison is true.

This block of instructions is performed if the comparison is false.