Instruction Set Architecture 2
Download
Report
Transcript Instruction Set Architecture 2
Algorithms and Computing
Lecture 3
Control Statements
By
Dr. M. Tahir Khaleeq
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
2
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
3
The for statement
•
1/2
The general form of a for statement is:
for(expr1;expr2;expr3)statement;
Initialize
Test
Body of
the Loop
Increment
Ex.
N=0
N <= 10
N++
printf(“ N = %d”,N)
for(N = 0; N<=10; N++)
printf(“ %d”, N);
Output: 0 1 2 3 4 5 6 7 8 9 10
No
semi-colon (;)
4
The for statement
•
2/2
The for statement may be used as:
Initialize
semi-colons (;)
are necessary
Test
N=0;
for( ; N<=10 ; )
{
Put braces
if more than one
statements
in the for loop
printf(“ %d”, N);
N++;
}
Increment
5
Operation of the for Loop
•
Logic flow of a for statement:
for(expr1;expr2;expr3)statement;
next statement
expr1
expr2
0
0
statement
expr3
next statement
6
Using for
•
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);
}
}
Output
1 3 5 7 9 11 13 15 17 19
2 4 6 8 10 12 14 16 18 20
7
The while statement
1/4
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)
8
The while statement
•
2/4
The general form of a while statement is:
while(expression) statement;
Test
Body of
the Loop
Ex.
getche() == ‘a’
printf(“This character is a”)
No
semi-colon (;)
while(getche() == ‘a’)
printf(“This character is a”)
9
The while statement
•
3/4
The while statement may be used as:
Initialize
Put braces
if more than one
statements
in the while loop
Test
N=0;
No
while(N<=10)
semi-colons (;)
{
printf(“ %d”, N);
N++;
}
Increment
10
The while statement
4/4
• Common Mistakes in while is
extra semi-colon.
N=0;
Semi-colon marks the
end of the while-block
-- usual cause of infinite
loops
while(N<=10);
{
printf(“ %d”, N);
N++;
}
11
Operation of the while Loop
•
Logic flow of a while statement:
while(expression) statement;
next statement
expression
0
0
statement
next statement
12
Using while
•
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);
}
Output
arthdfi
character count is: 7
Press
Enter
13
Structure of The for and The while statements
•
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
expr1
expr2
0
0
statement
expr3
next statement
14
The do while statement
•
1/3
The general form of a do statement is:
do statement while(expression);
Body of
the Loop
Ex.
printf(“N = %d”, N)
N++
Test
N <= 10
do
No
semi-colon (;)
{ printf(“N = %d”, N);
N++;
} while(N<=10);
semi-colon (;)
15
The do while statement
•
2/3
The do while statement may be used as:
Initialize
N=0;
do
No
semi-colons (;)
{
Put braces
if more than one
statements
in the do while loop
printf(“ %d”, N);
N++;
Increment
} while(N<=10);
Test
semi-colon (;)
16
The do while statement
3/3
• The do while statement may be used as:
Increment
N=0;
do
{
printf(“ %d”, N);
N++;
} while(N<=10);
IMPORTANT!!
The increment is performed AFTER
the body of the loop
17
Operation of the do while Loop
•
The general form of a do statement is:
do statement while(expression);
next statement
statement
0
expression
0
next statement
18
The if statement
1/5
• 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.
19
The if statement
•
2/5
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.
20
The if statement
•
3/5
Common mistake
Do not put
semicolon here!
if (number % 2 != 0);
{
printf("%d is an odd ", number);
}
printf("number\n");
21
The if statement
•
4/5
Common mistake
Should be ==
if (number % 2 = 0)
{
printf("%d is an odd ", number);
}
printf("number\n");
22
The if statement
•
5/5
Common mistake
Do not put
“then” here!
if (number % 2 == 0)
{
printf("%d is an odd ", number);
}
printf("number\n");
23
Example
/* 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);
}
}
24
Exercise
•
1/2
Which of the following code fragments are equivalent?
A
if (number % 2 != 0)
{
printf("%d", number);
}
printf(” is odd\n");
B
if (number % 2 != 0)
printf("%d", number);
printf(” is odd\n");
C
if (number % 2 != 0)
{
printf("%d", number);
printf(” is odd\n");
}
25
Exercise
•
2/2
A and B are equivalent?
A
if (number % 2 != 0)
{
printf("%d", number);
}
printf(” is odd\n");
B
if (number % 2 != 0)
printf("%d", number);
printf(” is odd\n");
C
if (number % 2 != 0)
{
printf("%d", number);
printf(” is odd\n");
}
26
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.
Dangling else problem
•
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;
No semicolons
here!
Example: if else
/* 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);
}
}
29
Using else if
•
Find the minimum number out of three given integers
X,Y and Z.
#include <stdio.h>
void main(void){
int X,Y,Z,min;
Nested if-else
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);
}
Example: else if
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’);
}
31
Nested if statement
• 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.
32
The break 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
expr20
Using break
•
Read floating-point numbers from standard input:
– For each number X > 0 compute log10(X)
– Terminate the program when X <= 0.
#include <stdio.h>
“while (True)”
#include <math.h>
infinite loop
void main(void){
double X;
while(1){
printf(”Enter a number");
scanf("%f",&X);
Exit the cycle
if(X <= 0) break;
printf("log10(%f)=%f\n",X,log10(X));
}
}
The continue statement
• 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.
while(expr1){
statements1
if(expr2)continue;
statements2
}
next statement
while(expr1){
statements1
if(expr2==0){
statements2
}
}
next statement
Using continue
•
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);
}
}
Continue cycle
without 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.
Warning
•
•
•
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.
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.
39
The switch Statement
•
2/2
Structure of the switch statement:
switch(op)
Integer or character variable
or expression
{
case ‘a’:
Integer or character constant
statement;
break;
Statements are executed
default:
if switch variable op = ‘a’
statement;
}
Statements are executed
if no other case applies
40
Example: switch statement
switch(op)
{
case ‘+’:
printf(“%f”, N1+N2);
break;
case ‘-’:
printf(“%f”, N1-N2);
break;
default:
printf(“ neither + nor - operator”) ;
}
41
Complete Example
Declares that mark is a variable which
can contain a floating point number
#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");
}
}
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.