Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
561 views

Chapter 5 Control Structure in C PDF

Uploaded by

Yanendra Sah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
561 views

Chapter 5 Control Structure in C PDF

Uploaded by

Yanendra Sah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Control Structure in C-

controlling the program execution flow:


selection, repetition and branching-

1
What are control structures?
• Our programs so far consist of just a list of
commands to be done in order
– The program cannot choose whether or not to
perform a command
– The program cannot perform the same command
more than once
– Such programs are extremely limited!
• Control structures allow a program to base its
behavior on the values of variables

2
PROGRAM CONTROL
 Program begins execution at the main() function.
 Statements within the main() function are then
executed from top-down style, line-by-line.
 The order of the execution within the main() body
may be branched.
 Changing the order in which statements are executed
is called program control.
 Accomplished by using program control statements.
 So we can control the program flows.

3
PROGRAM CONTROL

 There are three types of program controls:


1. Sequence control structure.
2. Selection structures such as if, if-else, nested if,
if-if-else, if-else-if and switch-case-break-goto.
3. Repetition (loop) such as for, while and do-
while.
 Certain C functions and keywords also can be
used to control the program flows.

4
Control Structures

• Statements can be
executed in sequence
• One right after the other
• No deviation from the
specified sequence

5
PROGRAM CONTROL
 Take a look at the following example

Jump/branch to printf() Back to main() from printf()

6
PROGRAM CONTROL

float paidRate = 5.0, sumPaid, paidHours = 25; S1


sumPaid = paidHours * paidRate; S2
printf("Paid sum = $%.2f \n", sumPaid); S3
return 0; S4

 One entry point and one exit point.


 Conceptually, a control structure like this means a sequence
execution.

7
Control Structures
• A selection
structure can be
used
• Which statement
is executed is
selected by
whether the
expression is true
or false

8
PROGRAM CONTROL
Selection Control Structure

 Program need to select from the options given for


execution.
 At least 2 options, can be more than 2.
 Option selected based on the condition evaluation
result: TRUE or FALSE.

9
PROGRAM CONTROL
Selection: if, if-else, if-else-if

 Starting from the most basic if syntax,


if (condition) if (condition)
statement; { statements;}
next_statement; next_statement;

1. (condition) is evaluated.
2. If TRUE (non-zero) the statement is executed.
3. If FALSE (zero) the next_statement following the if statement
block is executed.
4. So, during the execution, based on some condition, some codes were
skipped.

10
Flowchart for the if statement

true
condition? statement

false

11
PROGRAM CONTROL
For example:
if (hours > 70)
hours = hours + 100;
printf("Less hours, no bonus!\n");

 If hours is less than or equal to 70, its value will remain unchanged and the printf() will
be executed.
 If it exceeds 70, its value will be increased by 100.

if(jobCode == '1')
{
carAllowance = 100.00;
housingAllowance = 500.00;
entertainmentAllowance = 300.00;
}
printf("Not qualified for car, housing and entertainment allowances!");

The three statements enclosed in the curly braces { } will only be executed if jobCode is equal
to '1', else the printf() will be executed.
12
The if-else statement
• The if-else statement chooses which of two
statements to execute
• The if-else statement has the form:
if (condition) statement-to-execute-if-true ;
else statement-to-execute-if-false ;
• Either statement (or both) may be a compound
statement
• Notice the semicolon after each statement

13
Flowchart for the if-else statement

true false
condition?

statement-1 statement-2

14
PROGRAM CONTROL
if (condition) if (condition)
statement_1; { a block of statements;}
else else
statement_2; { a block of statements;}
next_statement; next_statement;
Explanation:
1. The (condition) is evaluated.
2. If it evaluates to non-zero (TRUE), statement_1 is executed,
otherwise, if it evaluates to zero (FALSE), statement_2 is
executed.
3. They are mutually exclusive, meaning, either statement_1 is
executed or statement_2, but not both.
4. statements_1 and statements_2 can be a block of codes and
must be put in curly braces.

15
PROGRAM CONTROL
For example:
if(myCode == '1')
rate = 7.20;
else
rate = 12.50;

If myCode is equal to '1', the rate is 7.20 else, if


myCode is not equal to '1' the rate is 12.50.

Equal/not equal is not a value comparison, but a character comparison!!!

16
PROGRAM CONTROL
 The if-else constructs can be nested (placed one within another) to any depth.
 General forms: if-if-else and if-else-if.
 The if-if-else constructs has the following form (3 level of depth example),

if(condition_1)
if(condition_2)
if(condition_3)
statement_4;
else
statement_3;
else
statement_2;
else
statement_1;
next_statement;

17

PROGRAM CONTROL
In this nested form, condition_1 is evaluated. If it is zero
(FALSE), statement_1 is executed and the entire nested if
statement is terminated.
 If non-zero (TRUE), control goes to the second if (within the first
if) and condition_2 is evaluated.
 If it is zero (FALSE), statement_2 is executed; if not, control goes
to the third if (within the second if) and condition_3 is evaluated.
 If it is zero (FALSE), statement_3 is executed; if not, statement_4
is executed. The statement_4 (inner most) will only be executed if
all the if statement are TRUE.
 Again, only one of the statements is executed other will be
skipped.
 If the else is used together with if, always match an else with the
nearest if before the else.
 statements_x can be a block of codes and must be put in curly
braces.
18
PROGRAM CONTROL
 The if-else-if statement has the following form (3 levels example).

if(condition_1)
statement_1;
else if (condition_2)
statement_2;
else if(condition_3)
statement_3;
else
statement_4;
next_statement;
19
PROGRAM CONTROL
 condition_1 is first evaluated. If it is non zero (TRUE),
statement_1 is executed and the whole statement terminated
and the execution is continue on the next_statement.
 If condition_1 is zero (FALSE), control passes to the next else-
if and condition_2 is evaluated.
 If it is non zero (TRUE), statement_2 is executed and the
whole system is terminated. If it is zero (FALSE), the next
else-if is tested.
 If condition_3 is non zero (TRUE), statement_3 is executed; if
not, statement_4 is executed.
 Note that only one of the statements will be executed, others
will be skipped.
 statement_x can be a block of statement and must be put in
curly braces.
20
PROGRAM CONTROL
 If mark is less than 40 then grade 'F' will be
displayed; if it is greater than or equal to 40 but
less than 50, then grade 'E' is displayed.
 The test continues for grades 'D', 'C', and 'B'.
 Finally, if mark is greater than or equal to 80,
then grade 'A' is displayed.

21
The Switch Statement
• The switch statement provides
another way to decide which
statement to execute next switch ( expression ){
case value1 :
• The switch statement statement-list1
evaluates an expression, then case value2 :
attempts to match the result statement-list2
to one of several possible case value3 :
cases statement-list3
case ...
• The match must be an exact
match.
}

22
The Switch Statement

• Each case contains a


value and a list of switch ( expression ){
statements case value1 :
statement-list1
• The flow of control case value2 :
transfers to statement-list2
case value3 :
statement associated statement-list3
with the first case case ...
value that matches
}

23
Switch - syntax

• The general syntax of a switch statement is:

switch
switch ( expression ){
and
case value1 :
case
statement-list1
are
case value2 :
reserved
statement-list2
words
case value3 :
statement-list3
case ...
If expression
} matches value3,
control jumps
to here
The Switch Statement

• The break statement can be switch ( expression ){


used as the last statement in case value1 :
each case's statement list statement-list1
break;
• A break statement causes case value2 :
control to transfer to the end statement-list2
of the switch statement break;
case value3 :
• If a break statement is not statement-list3
used, the flow of control will break;
continue into the next case case ...

}
Switch Example

• Examples of the switch statement:


switch (option){
case 'A':
aCount++;
break;
case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
}
Switch – no breaks!!!

• Another Example:
switch (option){
case 'A': switch (option){
aCount++; case 'A':
break; aCount++;
case 'B': case 'B':
bCount++; bCount++;
break; case 'C':
case 'C': cCount++;
cCount++; }
break;
}
Switch - default
• A switch statement can have an optional default case
• The default case has no associated value and simply
uses the reserved word default
• If the default case is present, control will transfer to it
if no other case value matches
• If there is no default case, and no other value
matches, control falls through to the statement after
the switch
The switch Statement

• Switch
switch (option){
with case 'A':
aCount++;
default break;
case: case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
default:
otherCount++;
break;
}
switch Example
switch ( day )
{
case 0: printf (“Sunday\n”) ;
break ;
case 1: printf (“Monday\n”) ;
break ;
case 2: printf (“Tuesday\n”) ;
break ;
case 3: printf (“Wednesday\n”) ;
break ;
case 4: printf (“Thursday\n”) ;
break ;
case 5: printf (“Friday\n”) ;
break ;
case 6: printf (“Saturday\n”) ;
break ;
default: printf (“Error -- invalid day.\n”) ;
break ;
}
Why Use a switch Statement?
• A nested if-else structure is just as efficient as
a switch statement.
• However, a switch statement may be easier to
read.
• Also, it is easier to add new cases to a switch
statement than to a nested if-else structure.
To Switch or not to Switch
• The expression of a switch statement must result in an
integral type, meaning an integer (byte, short, int, long)
or a char
• It cannot be a boolean value or a floating point value
(float or double)
• The implicit boolean condition in a switch statement is
equality
• You cannot perform relational checks with a switch
statement
Iterations/Loops
• The purpose of a loop is to repeat the same action a number of
times
• We continue repeating the action until a terminating condition
is satisfied.
• This terminating condition is called a loop guard
• The loop guard is represented by a boolean expression in the
same way as the condition of an IF statement.
• Before the loop starts we initialise variables involved in the
loop
• In C there are a number of ways to represent loops
Repetition: The for statement
 Executes a code block for a certain number of times.
 The code block may have no statement, one statement or more.
 The for statement causes the for loop to be executed in a fixed number of
times.
 The following is the for statement form,

for(initial_value;condition(s);increment/decr
ement)
statement(s);
next_statement;

 initial_value, condition(s) and


increment/decrement are any valid C expressions.
 The statement(s) may be a single or compound C
statement (a block of code).
. 34
PROGRAM CONTROL
 The for loop flow chart should be something like the following.

Start

Evaluate initial_value

Do increment/ decrement

Evaluate Execute statement(s)


condition(s)

T
F

Stop

35
PROGRAM CONTROL
 A Simple for example, printing integer 1 to 10.
#include <stdio.h>
void main(void)
{
int nCount;
// display the numbers 1 to 10
for(nCount = 1; nCount <= 10; nCount++)
printf("%d ", nCount);
printf("\t");
}
Printf(“Press any key to continue . . . “);

36
PROGRAM CONTROL
 Its flow chart…
Start

nCount = 1

nCount++

nCount printf("…");
<=10?
T

Stop

37
PROGRAM CONTROL
 for loop is a very flexible construct.
 Can use the decrementing counter instead of
incrementing. For example,
for (nCount = 100; nCount > 0; nCount--)

 Can use counter other than 1, for example 3,


for(nCount = 0; nCount < 1000; nCount += 3)

 initial_value can be omitted if the test variable has been


initialized beforehand.
 However the semicolon must still be there. For example,
nCount=1;
for( ; nCount < 1000; nCount ++)

38
PROGRAM CONTROL
 The condition(s) expression that terminates the loop can
be any valid C expression.
 As long as it evaluates as TRUE (non zero), the for
statement continues to execute.
 Logical operators can be used to construct more complex
condition(s) expressions.

39
PROGRAM CONTROL

 The for statement(s) can be followed by a null (empty)


statement, so that task is done in the for loop itself.
 Null statement consists of a semicolon alone on a line. For
example,
for(count = 0; count < 20000; count++)
;
 This statement provides a pause (delay) of 20,000
milliseconds.

40
PROGRAM CONTROL
 We can also create an infinite or never-ending loop by
omitting all the expressions or by using a non-zero constant
for condition(s) as shown in the following two code snippets,

for( ; ; )
printf("This is an infinite loop\n");

 or

for( ; 1 ; )
printf("This is an infinite loop\n");

 In both cases, the message "This is an infinite


loop" will be printed repeatedly, indefinitely.
 All the repetition constructs discussed so far can be nested
to any degree.
41
While loops
• The most basic loop in C is the while loop.
• The general syntax of a while loop is
while( expression )
statement

The expression represents the loop guard.

• While it is true repeat the statement.


Terminate when the expression evaluates to false
Repetition: The while loop

 Executes a block of statements as long as a specified condition is TRUE.


 The general while loop construct,

while (condition)
statement(s);
next_statement;

 The (condition) may be any valid C expression.


 The statement(s) may be either a single or a compound
(a block of code) C statement.

43
PROGRAM CONTROL
 The while statement flow chart is shown below.

Start

Evaluate T Execute
condition statement(s)

Stop

44
PROGRAM CONTROL
 A simple example
// simple while loop example
#include <stdio.h>
int main(void)
{
int nCalculate = 1;
// set the while condition
while(nCalculate <= 12)
{
// print
printf("%d ", nCalculate);
// increment by 1, repeats
nCalculate++;
}
// a newline
printf("\n");
return 0;
}

45
PROGRAM CONTROL
 The same task that can be performed using the for statement.
 But, while statement does not contain an initialization
section, the program must explicitly initialize any variables
beforehand.
 As conclusion, while statement is essentially a for statement
without the initialization and increment components.
 The syntax comparison between for and while,

for( ; condition; ) vs while(condition)

46
PROGRAM CONTROL
 Just like for and if statements, while statements can also be
nested.
 The nested while example

47
www.tenouk.com, ©
PROGRAM CONTROL
 The nested for and while program example

48
Repetition: The do-while loop
 Executes a block of statements as long as a specified condition is true at
least once.
 Test the condition at the end of the loop rather than at the beginning, as
demonstrated by the for and while loops.
 The do-while loop construct is,
do
statement(s);
while (condition)
next_statement;

 (condition) can be any valid C expression.


 statement(s) can be either a single or compound (a block
of code) C statement.

49
PROGRAM CONTROL
 A flow chart for the do-while loop
 The statement(s) are
Start
always executed at least
once.
Execute  for and while loops
statement(s) evaluate the condition at
the start of the loop, so the
associated statements are
T not executed if the
Evaluate
condition
condition is initially
FALSE.
F

Stop
50
continue keyword

 continue keyword forces the next iteration to take place


immediately, skipping any instructions that may follow it.
 The continue statement can only be used inside a loop
(for, do-while and while) and not inside a switch-case
selection.
 When executed, it transfers control to the condition (the
expression part) in a while or do-while loop, and to the
increment expression in a for loop.
 Unlike the break statement, continue does not force the
termination of a loop, it merely transfers control to the
next iteration.

51
 continue keyword example
// using the continue in for structure
#include <stdio.h>
int main(void)
{
int iNum;
for(iNum = 1; iNum <= 10; iNum++)
{ // skip remaining code in loop only if iNum == 5
if(iNum == 5)
continue;
printf("%d ", iNum);
}
printf("\nUsed continue to skip printing the value 5\n");
return 0;
}

52
goto keyword
 The goto statement is one of C unconditional jump or
branching.
 When program execution encounters a goto statement,
execution immediately jumps, or branches, to the location
specified by the goto statement.
 The statement is unconditional because execution always
branches when a goto statement is came across, the
branching does not depend on any condition.
 However, using goto statement strongly not
recommended.
 Always use other C branching statements.
 When program execution branches with a goto statement,
no record is kept of where the execution is coming from.
53
• Syntax
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;

54
if(number < 0.0)
# include <stdio.h> goto jump;

int main() sum += number; // sum =


sum+number;
{
}
const int maxInput = 5;
int i;
jump:
double number, average,
sum=0.0;
average=sum/(i-1);
for(i=1; i<=maxInput; ++i) printf("Sum = %.2f\n", sum);
{ printf("Average = %.2f", average);
printf("%d. Enter a number: ",
i); return 0;
scanf("%lf",&number); }

55
break keyword
 Already discussed in switch-case constructs.
 The break statement terminates the execution of the nearest
enclosing loop or conditional statement in which it appears.
Control passes to the statement that follows the terminated
statement, if any.
 Used with the conditional switch statement and with the do, for,
and while loop statements.
 In loops, break terminates execution of the nearest enclosing do,
for, or while statement. Control passes to the statement that follows
the terminated statement, if any.
 Within nested statements, the break statement terminates only the
do, for, switch, or while statement that immediately encloses it.

56
Some loop programs
• 1: Read in 10 integers and output their sum
• 2: Read in 10 integers and output the largest
of them
• 3: Keep reading in integers until one is input
which is larger than 100
Sum of 10 Integers
#Include <stdio.h>
main()
{ int i, a,sum;
sum = 0;
for (i=0;I < 10; i++)
{ printf(“enter number \n”);
scanf(“%d”,&a);
sum = sum + a;
};
printf(“total is %d”,sum);
}
Largest of 10 Integers
#include <stdio.h>
main()
{ int i, a,max;
printf(“enter number \n”);
scanf(“%d”,&a);
max = a;
for (i=1;I < 10; i++)
{ printf(“enter number \n”);
scanf(“%d”,&a);
If (a > max) max = a;
};
printf(“largest is %d”,max);
Return 0;
}
Loop until one input is larger than 100
#Include <stdio.h>
main()
{ int a,

do
{ printf(“enter number \n”);
scanf(“%d”,&a);
};
while (a < 100)
printf(“The number which ended the loop is %d”,a);
}
While
#Include <stdio.h>
main()
{ int a,
a= 0;
while (a < 100)
{ printf(“enter number \n”);
scanf(“%d”,&a);
}
printf(“The number which ended the loop is %d”,a);
}
Example of a while loop
#include <stdio.h>
main()
{
int x
x = 2;
while(x < 1000)
{ printf("%d\n", x);
x = x * 2; }
}

This program repeatedly prints out powers of two until we


generate a number greater than or equal to 1000
The terminating condition is thus when the power of two equals
or exceeds 1000
loop questions
2: Use a Do while loop to calculate the minimum
of 100 integers being read in.
1: Write a program which continually reads in integers until
45 is read in

#include <stdio.h>
main()
{int x;
x =1;
while(x != 45)
{ printf(“enter no”);
scanf(“%d", &x);
}
}
Read until 45
#include <stdio.h>
main()
{int x;
do
{ printf(“enter no”);
scanf(“%d", &x);
}
while(x != 45) ;
}
More questions
• Read in 20 integers
and count the even
numbers
• Write a program to
calculate

N 100
Xn

N 1 ( X 2n )
Sum of function Example
#include <stdio.h> enum = n-1;
#include <math.h> denom = fac*pow(n,2);
If (denom == 0) printf(“sum not
main() defined”)
{ int n,i, fac; sum = sum + (enum/denom);
float enum,denom,sum;
sum = 0.0; };
for (n=1;n <= 100; n++) printf(“total %f”,sum);
{
fac = 1; }
for (i=1, i <=n, i++)
{ fac = fac*i;
}
Remember Loops Consist of
• Initialization
• Terminating Condition (Guard)
• Loop Body
• Terminating Action
• For Counted Loops Iterations use a For loop
• Otherwise use a while or a do while loop

You might also like