0% found this document useful (0 votes)
20 views

Control Statements

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

Control Statements

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

Control Statements

Nawaraj Paudel
Citizen College
Pokhara University
Control Statements (1/2)
• A control statement is a statement that causes C
statement(s) to execute in a manner that doesn’t relate to
the order it appears in the source code. These statements
help to jump from one part of the program to another. The
control transfer may be conditional or unconditional.
• Types of control statements:
– Selection statements: These are also known as branching,
decision making, or conditional statements. These statements
execute program statement(s) depending upon a given condition.
C supports two selection statements: if and switch. There are
different forms of if statements: if only, if-else-if, and if-else-if
ladder.
2
Control Statements (2/2)
– Repetition statements: When there is a need of executing a
task a specific number of times until a termination condition is
met, we use iteration statements. These statements are also
called looping statements or iterative statements. C provides
three ways of writing iterative statements. They are while , do-
while , and for.
– Jump statements: For the transfer of control from one part to
another, C also supports various jump statements. These are
break, continue, goto, and return.

3
The if only statement (1/3)
• Allows your program to execute a single statement, or a
block of statements enclosed between braces, if a given
condition is true. Its general form or syntax is:
if (expression)
statement
• If expression evaluates to true (any non-zero value),
statement is executed. If expression evaluates to false
(0), statement is not executed. In either case, execution
then passes to whatever code follows the if statement.
• Expression can be any valid C expression and statement
can be simple or compound or even another control
statement.
4
The if only statement (2/3)

False expression

True

Body of if
Flow-chart

Statement following
if body

5
The if only statement (3/3)

if (x > y) assigns the value of x to y only if x is


y = x; greater than y. If x is not greater than
y, no assignment takes place.

if (letter == 'A')
printf("The first capital\n");
printf("After if\n");

if the value of letter is 'A‘, the text The first


capital is printed otherwise not. The last
statement After if always gets printed

Examples 6
The if else statement (1/3)
• When there is a need of executing a statement or
statement(s) if a condition matches and another
statement or statement(s) is to be executed otherwise,
then we use if–else statements. Its syntax is:
if(expression)
statement1
else
statement2
• If expression evaluates to true, statement1 is executed. If
expression evaluates to false, statement2 is executed.
Both statement1 and statement2 can be compound
statements or blocks.
7
The if else statement (2/3)
Using if-else, you can specify an action to be performed
both when the condition is true and when it is false

expression True

False

Body statement(s) of else Body statement(s) of if


Flow-chart

Statement following
else body
8
The if else statement (3/3)
Examples:

if (age >= 18)


printf("You can vote\n");
else
printf("You can’t vote\n");

if (x>y)

printf(“x is greatest”);

else
printf(“y is greatest”);

9
The if-else-if ladder statement (1/2)
• If we have the situation where there are different actions
that are executed depending upon different conditions with
same type of instance then if-else-if ladder is useful.
The conditions are evaluated from
if (expression) the top downward. As soon as a
statement; true condition is found, the
else if (expression) statement associated with it is
statement; executed and the rest of the ladder
else if (expression) is bypassed. If none of the
statement; conditions are true, the final else is
………… executed. If the final else is not
else present, no actions take place if all
statement; other conditions are false.
10
The if-else-if ladder statement (2/2)
char ch;
scanf("%c", &ch);
Flow-chart: Refer
if (ch >= 'a' && ch <= 'z') extra paper
printf("lowercase letter");
else if (ch >= 'A' && ch <= 'Z')
printf("uppercase letter");
else if (ch >= '0' && ch <= '9')
printf("a digit");
else if (ch==' '||ch=='\t'||ch=='\n')
printf("whitespace character");
else
printf("an unknown character");

11
The conditional operator (?:)
• It is ternary operator (demands 3 operands), and is used in
certain situations, replacing if-else statement. Its general form
is: exp1 ? exp2 : exp3;
• If exp1 is true, exp2 is executed and whole expression is
assigned with value of exp2. If the exp1 is false, then exp2 is
executed, and whole expression is assigned with exp2 value.
• For example, c = a > b ? a+b : a-b; and is equivalent to if(a>b)
c=a+b;
else
c=a-b;

12
Nested-if (1/2)
• The if statement (if only, if-else, if-else-if ladder) may
itself contain another if statement (if only, if-else, if-else-
if ladder) is known as nested if statement.
• We can write it as follows:
if (exp1)
if (exp2)
statement1
else
statement2
else
statement3

13
Nested-if (2/2)
Example:
if (x > y)
if (x > z)
printf("x is greater");
else
printf("z is greater");
else
if (y > z)
printf("y is greater");
else
printf("z is greater");

14
The switch Statement(1/4)
• switch is a multiple branch Syntax:

selection statement, which switch (expression)


{
successively tests the value of an case constant1:
expression against a list of integer statement(s)
break;
or character constants. When a case constant2:
match is found, the statement(s) statement(s)
break;
associated with that constant are ...
executed. case constantn:
statement(s)
• Useful when a variable or break;
default:
expression is tested for all the statement(s)
values it can assume and different }

actions are taken


15
The switch statement (2/4)
• The expression must evaluate to an integer type
• The value of expression is tested against the constants present in
the case labels
• When a match is found, the statement sequence, if present,
associated with that case is executed until the break statement or
the end of the switch statement is reached
• The statement following default is executed if no matches are
found
• The default is optional, and if it is not present, no action takes
place if all matches fail

16
The switch statement (3/4)
Exmaple1: Example2: Flow-chart: Refer
switch (choice) switch (n) { extra paper
{
case 1:
case 'r': case 2:
printf("RED"); printf(“1 or 2”);
break; break;
case 3:
case 'w':
case 4:
printf("WHITE");
printf(“3 or 4”);
break;
case 5:
case 'b': case 6:
printf("BLUE"); printf(“5 or 6?”);
break; printf(“or may be 3 or 4”);
default: default:
printf("Unknown"); printf(“Wrong case");
}
}
17
The switch statement (4/4)
• Things to remember with switch:
– A switch statement can only be used to test for equality of an
expression. We cannot check for other comparisons like <, <=,
>, >=
– switch expression must evaluate to an integral value
– No two case constants can be same
– Omission of a break statement causes execution to go to next
case label
– The default label is executed when no case constants matches
the expression value
18
Repetition Statements
• Repetition is the process of executing a group of
statements more than one time as long as some
condition remains true
• Repetition in C can be implemented using three
control statements: while, do – while, for
• These statements are also known as iteration or
looping statements

19
The while statement (1/5)
• Allows your program to execute a single statement, or a
block of statements enclosed between braces as long as a
given condition is true. Its general form is:
while (expression)
statement
• Here statement is executed as long as the expression
evaluates to true.
– First expression is evaluated
– If expression is nonzero (true), then statement is executed
and control is passed back to the beginning of the while
statement, otherwise control passes to next statement following
the while statement
20
The while statement (2/5)

Flow-chart

21
The while statement (3/5)
• As with if, expression can be any valid C expression and
statement can be simple or compound
• The statement inside the while loop must include some feature
that eventually alters the value of the expression, thus providing
a stopping condition for the loop

/* Prints hello world 10 times */


counter = 1; /* initialization */
while (counter <= 10) /* repetition condition */
{
printf("Hello World\n");
++counter; /* increment */
}
22
The while statement (4/5)
/* Prints digits 0 through 9 */
int digit = 0;
while (digit <= 9)
{
printf("%d\n", digit);
++digit;
}

/* Prints digits 9 through 0 */ More Examples


int digit = 9;
while (digit >= 0)
{
printf("%d\n", digit);
--digit;
}
23
The while statement (5/5)
int grade, counter;
int total;
float average;

total = 0;
counter = 1;
while (counter <= 10)
Example:
{ Calculation of
printf("Enter grade: "); average grade
scanf("%d", &grade);
total += grade;
++counter;
}
average = (float) total / 10;
printf("The average grade is %f", average);
24
The for statement (1/6)
• When we have the fixed number of iterations known then we use
for loop (normally, while loop is also possible). Its basic syntax is:
for( expr1; expr2; expr3 )
statement;
• First before loop starts, the initialization (expr1) is executed that
initializes the variable or variables in the loop.
• Second the condition (expr2) is evaluated, if it is true, the
statement (s) of the for loop will be executed.

25
The for statement (2/6)
• Finally, the increment/decrement (expr3) will be executed, and
the condition (expr2) will be evaluated, this continues until the
condition (expr2) is false, at which point control passes to next
statement following for loop.
• Example:
for (counter = 1; counter <= 10; counter++)
printf("Hello World\n");

26
The for statement (3/6)

Flow-chart:

27
The for statement (4/6)
/* Prints digits 0 through 9 */
for (digit = 0; digit <= 9; digit++)
printf("%d\n", digit);

/* Prints digits 9 through 0 */


for (digit = 9; digit >= 0; digit--)
printf("%d\n", digit);
More Examples:
/* Sum of first n natural numbers */
scanf("%d", &n);
sum = 0;
for (counter = 1; counter <= n; counter++)
sum += counter;
printf("The sum of first %d numbers is %d", n, sum);
28
The for statement (5/6)
• Comma operator can be used for multiple initialization
and multiple processing of loop control variables in for
statement
/* sum of numbers from 1 to n */
for (sum = 0, i = 1; i <= n; i++)
sum += i;

/*printing numbers from 1 to n, n to 1 simultaneously*/


for (i = 1, j = 10; i < n; i++, j--)
printf("%2d %2d\n", i, j);

29
The for statement (6/6)
• You can omit, any of the three expression of the for
statement. However, semicolons must be present. If your remove
all three expressions like for(; ;), it becomes infinite loop.
• You can also omit first expression and initialize it before
the loop as follows

int digit = 0;
for ( ; digit <= 9 ;digit++ )
printf("%d\n", digit);

30
The do-while statement (1/5)
• Similar to the while statement but condition for
repetition tested after the body of the loop is performed
do
statement
while (expr);
– First statement is executed, and expr is evaluated
– If the value of expr is nonzero (true), then control passes back
to the beginning of the do statement and process repeats itself
– When expr is zero (false), control passes to next statement
following the do-while statement
31
The do-while statement (2/5)
• Note that a semicolon is present after the closing parenthesis of
the expression
• Note that statement will always be executed at least once, since
the test for repetition does not occur until the end of the first pass
through the loop

32
The do-while statement (3/5)

Flow-chart:

33
The do-while statement (4/5)
• As with while, expr can be any valid C expression and
statement can be simple or compound.
counter = 1;
do {
printf("Hello World\n");
counter++;
} while (counter <= 10);

digit = 0;
do {
printf("%d\n", digit);
digit++;
} while (digit <= 9);
34
The do-while statement (5/5)
• The do-while is most appropriate when the statement(s)
associated with the loop must be executed at least once
• Example:

int n;
do
{
printf("Enter a number between 1 and 99: ");
scanf("%d", &n);
} while (n < 1 || n > 99);

35
Comparison of Three Loops
• Because of the features that are built into the for statement,
it is particularly well suited for loops in which the number
of passes is known in advance
• while loops are used when the no of times the statements
inside the loop to be executed is not known in advance
• Use do-while loop, when you want the loop body to
execute at least once for the first time regardless of the
outcome of condition
• for and while are called entry-controlled loops and do-
while is called exit-controlled loop.
36
Nested Loops
• Like selection statements, a loop can
be nested within another. for(i=0;i<10;i++) {
• The inner and outer loops need not be printf(“Hi”)
same. for(j=0;j<5;j+
+)
• It is essential, however, that one loop
printf(“Hello”);
be completely embedded within the
other—there can be no overlap. }
Example
• When one loop is nested inside
another loop, the inner loop is first
terminated and again restarted when
the first loop starts for the next
incremented value. The outer loop is
terminated last.
37
Nested Control Statements
• Nested control statements for (i = 1; i <= n; i++)
can also involve both loops if (i%3==0 || i%5 == 0)
and selection statements. printf("%d\n",i);
• Thus, a loop can be nested
within an selection Example
statement, and a selection
statement can be nested
within a loop.
• We can nest any control flow
statement (selection and
looping statement) within
another.
38
The break statement (1/2)
• The use of break statement causes the immediate
termination of a loop (for, while, or do-while) and switch
from the point of break statement.
• It then passage program control to the statement
following the loop or switch.
• In case of nested loops if break statement is in inner loop
only the inner loop is terminated.

39
The break statement (2/2)
for( int i=1; i<= 10; i++ ) {
if( i == 5 )
break;
printf(" i=%d”, i );
}
printf("oho char pachhi khai ta”);

Example

40
The continue statement (1/2)
• Skips the remaining statements in the body of a while,
for or do-while structure
– Proceeds with the next iteration of the loop
• while and do-while
– Loop-continuation test expression is evaluated immediately
after the continue statement is executed
• for
– Increment/decrement expression is executed, then the loop-
continuation test expression is evaluated immediately after the
continue statement is executed
41
The continue statement (2/2)
for(i=0;i<10;i++){
if(i>5&&i<8)
continue;
printf("%d\n",i);
}

Example

42
The goto Statement (1/2)
• The goto statement is used to alter the normal
sequence of program execution by transferring
control to some other part of the program.
• In its general form, the goto statement is written
as
goto label;
Where label is an identifier that is used to label
the target statement to which control will be
transferred.
43
The goto Statement (2/2)
• It is considered a harmful construct because it causes an
unconditional jump to a labeled statement.
Example
int num;
x: // this is label for goto
printf("\nEnter a positive number ");
scanf("%d",&num);
if(num < 0)
goto x; //this statement transfers the control to label x
printf("\nNumber = %d",num);

44

You might also like