algorithms and computing lecture 3 control statements by dr. m. tahir khaleeq
TRANSCRIPT
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
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
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
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
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
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
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
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
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
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
12
• Logic flow of a while statement: while(expression) statement;
next statement
Operation of the while Loop
statement
expression
0
next statement
0
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
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
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
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 (;)
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
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
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
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
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!
22
• Common mistake
if (number % 2 = 0) { printf("%d is an odd ", number); } printf("number\n");
The if statement 4/5
Should be ==
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!
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
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
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
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.
• 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!
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
• 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
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
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
• 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
• 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
• 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
• 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
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.
• 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
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.
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
41
switch(op)
{
case ‘+’:
printf(“%f”, N1+N2);
break;
case ‘-’:
printf(“%f”, N1-N2);
break;
default:
printf(“ neither + nor - operator”) ;
}
Example: switch statement
#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.