0% found this document useful (0 votes)
12 views20 pages

PC - Unit - 2

The document provides an overview of selection and repetition statements in C programming, detailing the use of if, switch, while, for, and do-while statements. It explains the syntax and flow of these control statements, including examples and flowcharts for better understanding. Additionally, it covers nested statements and the use of break and continue within loops.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views20 pages

PC - Unit - 2

The document provides an overview of selection and repetition statements in C programming, detailing the use of if, switch, while, for, and do-while statements. It explains the syntax and flow of these control statements, including examples and flowcharts for better understanding. Additionally, it covers nested statements and the use of break and continue within loops.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 20

Selection Statements – if and switch statements,

Repetition statements – while, for, do-while statements,


Loop examples,
other statements related to looping – break, continue, goto,
Simple C Programming examples.

Decision statements (or) selection statements (or) conditional statements:


C language possesses decision-making capabilities by supporting the following statements:
If statement
Switch statement
These statements are popularly known as decision-making statements. Since these statements
control the flow of execution, they are also known as control statements.
Decision making with if statement
The if statement is a powerful decision-making statement and is used to control the flow of
execution of statements. It is basically a two-way decision statement and is used in conjunction
with an expression. It takes the following form:
If (test-expression)
It allows the computer to evaluate the expression first and then, depending on whether the
value of the expression is true or false, it transfers the control to a particular statement.
The if statement may be implemented in different forms depending on the complexity of
conditions to be tested. The different forms are:
 simple – if statement
 if – else statement
 nested – if else statement
 else – if ladder
 switch statement
1. Simple – if statement
The general form of a simple if statement is
Syntax :
if (condition)
{
Statement-block;
}
Statement-x;
The statement-block may be a single statement or a group of statements. If the condition is
true, the statement-block will be executed; otherwise the statement-block will be skipped and
the execution will jump to the statement-x;
Note: When the condition is true, both the statement-block and the statement-x are executed in
sequence.

Flow chart
True Con False
diti
on?

Statement (s)

Program /* checking whether a number is greater than */


main ( )
{
int a;
printf (“enter a number”);
scanf (“%d”, &a);
if (a>50)
{
printf (‘%d is greater than 50”, a);
}
}
Output
1) enter a number 60 2) enter a number 20
60 is greater than 50 no output.

2. if … else statement
The if … else statement is an extension of simple if statement. It takes the following general
form
Syntax:
if (condition)
{
True block statement(s)
}
else
{
False block statement(s)
}
statement-x

If the condition is true, then the true-block statement(s), immediately following the if
statements are executed.: otherwise, the false-block statements are executed. In either case,
either true-block or false-block will be executed, not both. In both cases, the control is
transferred subsequently to the statement-x.
Flow chart
True False
Con
diti
on?

True block False block


statement(s) statement (s)
Program
/* checking for even (or) odd number */
main ( )
{
int n;
printf (“enter a number”);
scanf (“%d”, &n);
if (n%2 ==0)
printf (‘%d is even number”, n);
else
printf( “%d is odd number”, n”);
}
Output
1) enter a number 10 2) enter a number 5
10 is even number 5 is odd number

3. Nested if - else statement


If---else statement inside another if---else statement is called as nested if---else statement.
When a series of decisions are involved, we may have to use more than one if…else statement
in nested form.
Syntax:
if (condition1)
{
if (condition2)
{
stmt1;
}
else
{
stmt2;
}
}

else
{
if (condition3)
stmt3;
else
stmt4;
}

Flow chart
True Con False
diti
on1

True Con False True Con False


ditio diti
n2 on3

Stmt1 Stmt2 Stmt3 Stmt4

Program /* largest of 3 numbers */


main ( )
{
int a,b,c;
printf (“enter 3 numbers”);
scanf (“%d%d%d”, &a, &b, &c);
if (a>b)
{
I f (a>c)
printf (‘%d is largest”, a);
else
printf (‘%d is largest”, c);
}
else
{
if (b>c)
printf (‘%d is largest”, b);
else
printf (‘%d is largest”, c);
}
}
Output
enter 3 numbers = 10 20 30
30 is largest

4. Else – if ladder
This is the most general way of writing a multi-way decision. A multi-way decision is a chain of
ifs in which the statement associated with else is an if. It takes the following general form
Syntax
if (condition1)
stmt1;
else if (condition2)
stmt2;
-----
else if (condition n)
stmnt;
else
stmt x ;
flow chart

True Con False


ditio
n1?

True Con False


ditio
Stmt1 n2?
------
Stmt2

True Cond False


ition
n?

Stmt n Stmt x

Program /* finding roots of quadratic equation */


#include <math.h>
main ( )
{
int a,b,c,d;
float r1, r2
printf (“enter a,b,c values”);
scanf (“%d%d%d”, &a, &b, &c);
d= b*b – 4*a*c
if (d>0)
{
r1 = (-b+sqrt(d)) / (2*a);
r2 = (-b-sqrt(d)) / (2*a);
printf (“root1 = %f, root2 == %f, r1, r2);
}
else if (d= = 0)
{
r1 = -b / (2*a);
r2 = -b/ (2*a);
printf (“root1 = %f, root2 == %f, r1, r2);
}
else
printf (‘roots are imaginary”);
}
Output
1) enter a,b, c values : 1 4 3
Root 1 = -1
Root 2 = -3
2) enter a,b, c values : 1 2 1
Root 1 = -1
Root 2 = -1
3) enter a,b, c values : 1 2 3
roots are imaginary

Switch statement
C has a built-in multiway decision statement known as switch. It is used to select one among
multiple decisions. The switch statement tests the value of a given variable (or expression)
against a list of case values and when a match is found, a block of statements associated with
that case is executed.

Syntax
switch (expression)
{
case value1 : stmt1;
break;
case value2 : stmt2;
break;
------
default : stmt – x;
}
Flow chart

Switch
(expres
sion)

Exp =value1 Stmt1

Exp =value2
Stmt2
|
|
default Stmt-x

The expression is an integer expressions or characters. Value1, value2 are constats or


constant expressions (evaluable to an integral constant) and are known as case labels. Each of
these values should be unique with in a switch statement. There is no need to put braces
around these blocks. Note that case labels end with a colon( : )
When the switch is executed, the value of the expression is successfully compared
against the values value-1,valu-2,---. If a case is found whose values match with value of the
expression, then the block of statements that follows the case are executed.
The break statement at the end of each block signals the end of a particular case and
causes exit from the switch statement, transferring the control to the statement-x following the
switch.
The default is an optional case. When present, it will be executed if the value of the
expression does not match with any of the case values. If not present, no action takes place if all
matches fail and the control goes to the statement-x.
Program
main ( )
{
int n;
printf (“enter a numbers”);
scanf (“%d”, &n);
switch (n)
{
case 0 : printf (“zero”)
break;
case 1 : printf (‘one”);
break;
default : printf (‘wrong choice”);
}
}
Output
enter a number
1
one
It i1s possible to nest the switch statements. That is, a switch may be part of a case statement.
ANSI C permits 15 levels of nesting.
Some key rules for using switch statement:
1. The switch expression must be an integral type.
2. Case labels must be constants or constant expressions.
3. Case labels must be unique. No two labels have the same value.
4. Case labels must end with colon( : ).
5. The break statement transfers the control out of the switch statement.
6. The break statement is optional. That is, two or more case labels may belong to the
same statements.
7. The default label is optional. If present, it will be executed when the expression does not
find a matching case label.
8. Threre can be at most one default label.
9. The default may be placed anywhere but usually placed at the end.
10. It is permitted to nest switch statements
Loop control statements
1,2,3,4,6,10,13,14,21,25,27,28,35,38,40,41,44,46,47,49,50,51,57,59,
Looping or iterative statements are used for running a particular set of code for any number of
times. Iterative statements consist two parts—head and body. The head of the statement
decides the number of times the body of the statements are to be executed.
In looping, a sequence of statements are executed until some conditions for the termination of
the loop are satisfied.
A looping process, in general, would include the following four steps:
1. Setting and initialization of a condition variable.
2. Test for a specified value of the condition variable for execution of the loop
3. Execution of the statements in the loop.
4. Incrementing or decrementing the condition variable.
The C language provides three constructs for performing loop operations.
They are
for loop
while loop
do-while loop
for loop
The for loop is an entry-controlled loop that provides loop control structure. The general form
of the for loop is
Syntax
for (initialization ; condition ; increment / decrement)
{
body of the loop
}
Flow chart

False
Initialization Increment/
condition decrement

True

Body of the loop


for statement contains 3 parts
initialization is usually an assignment statement that is used to set the loop control variable
The condition is a relational expression that determines when the loop will exit.
The increment/decrement part defines how the loop control variable will change each time
loop is repeated
loop continues to execute as long as the condition is true
Once the condition is false, program continues with the next statement after for loop.

The execution of the for statement is as follows


1) Initialisation of the control variable is done first, using assignemnt statements such as i=1
and count=0. The variables i and count are known as loop-control variabels.
2) The value of the control variable is tested using the test-condition. The test-condition os a
relational expression, such as i<10 that determines when the loop will exit. If the condtiion is
true, the body of the loop is executed; otherwise the loop is terminated and the execution
continues with the statement that immediately follows the loop.
3) When the body of the loop is executed, the control is transfered back to the for statemetn
after evaluating the last staement in the loop. Now the control variable is incremented using an
assignement statement such as i=i+1 and the new value of the control variable is again tested
to see whether it satisfies the loop condition. If the condition is satisfied, the body of the loop is
again executed. This process continues till the value of the control variable fails to satisfy the
test-condition.
Program
main( )
{ Output
int k; 1
2
for (k = 1; k<5; k++)
3
{
4
printf (”%d”,k);
5
}
}
Additional features of for loop
 More than on variable can be initialized at a time in the for statement
Ex: for(i=1 , j=0; i<10; i++)
Note that the initialization section has two parts i=1 and j=0 seperated by comma.

 Like the initialization section, the increment section may also have more than one part.
The multiple arguments in the increment section are separated by commas.
Ex: for(i=1 , j=10; i <= j; i++, j--)

 Further, the test-condition may have any compound relation and the testing need not be
limited only to the loop control variable.
Ex:
sum = 0;
for( i = 1 ; i < 20 && sum < 100 ; ++i)
{
sum=sum + i;
}

 Another unique aspect of for loop is that one or more sections can be omitted, if
necessary.
Ex:
m = 5;
for( ; m != 100 ; )
{
m = m + 5;
}
Here both initialization and increment sections are omitted in the for statement. The
initilisation has been done before the for statement and the control variable is incremented
inside the loop. In such cases the sections are left blank. However, the semicolons separating
the sections must remain. If the test-condtion is not present, the for statement sets up an
infinite loop.
Nesting of for loops
Nesting of loops, that is, one for statement within another for statement, is allowed in C. For
example two loops can be nested as shown bellow
-----------------------------------
------------------------------------
for( i = 1 ; i < 10 ; ++i)
{
----------------------
---------------------
for( j = 1; j != 5; ++j)
{
-----------------------
-----------------------
}
}
------------------------------
-----------------------------

while loop
The simplest of all the looping structures in C is the while statement.
Syntax
while (condition)
{
body of the loop
}
The while is an entry-controlled loop statement. The condition is evaluated and if the condition
is true, then the body of the loop is executed. After execution of the body, the test-condition is
once again evaluated and if it is true, the body is executed once again. This process of repeated
execution of the body continues until the test-condition finally becomes false and the control is
transferred out of the loop. On exit, the program continues with the statement immediately
after the body of the loop.
Flow chart initialization

Is False
expressio
n?

True

Body of the loop

Incr/ dec

Intialization is done before the loop


Loop continues as long as the condition is true
Incriminations and decrementation part is done within the loop
Program
main( )
{ Output
int k; 1
2
k = 1;
3
while (k< = 5)
4
{
5
printf (”%d”,k);
k++;
}
}

do-while loop
The while loop construct, makes a test of condition before the loop is executed. Therefore, the
body of the loop may not be executed at all if the condition is not satisfied at the very first
attempt. In some situations it might be necessary to execute the body of the loop before the
test is performed. Such situations can be handled with the help of the do- while statement.
Syntax
Initialization
do
{
body of the loop
inc/ dec
} while (condition);
On reaching the do statement, the program proceeds to evaluate the body of the loop first. At
the end of the loop, the condition in the while statement is evaluated. If the condition is true,
the program continues to evaluate the body of the loop once again. This process continues as
long as the condition is true. When the condition becomes false, the loop will be terminated
and the control goes to the statement that appears immediately after the while statement.
Since the condition is evaluated at the bottom of the loop, the do---while construct provides an
exit-controlled loop and, therefore, the body of the loop is always executed atleast once.

Flow chart
initialization

Body of the loop

Incr/ dec

True Is
expressio
n?

Flase

Program
Output
main( ) 1
{ 2
int k; 3
4
5
k = 1;

do
{
printf (”%d”,k);
k++;
} while (k == 5);
}

Other statements related to loops


break
continue
goto

1)break (jumping out of a loop)


An early exit from a loop can be accomplished by using the break statement or goto statement.
break statement can be used within while, do-while, for and switch statement. The use of break
in loops is illustrated in following fig:

Summary:
It is a keyword used to terminate the loop (or) exit from the block
The control jumps to next statement after the loop (or) block
‘break is used with for, while, do-while and switch statement
When break is used in nested loops then only the innermost loop is terminated
When a break statement is encountered inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop. When the loops are
nested, the break would only exit from the loop containing it. That is, the break will exit only a
single loop.
Program
main( )
{ int i; Output
for (i=1; i<=5; i++) 1
2
{
3
printf (”%d”, i);
if (i= =3)
break;
}
}
2) continue (skipping a part of a loop)
Like the break statement, C supports another similar statement called the continue
statement. However, unlike the break statement that causes the loop to be terminated, the
continue, as the name implies, causes the loop to be continued with the next iteration after
skippin any statements in between. The continue statement tells the compiler, “skip the
following statements and continue with the next iteration”.
It is a keyword used for continuing the next iteration of the loop
It skips the statements after the continue statement
It is used with for, while and do-while

Syntax
{
Stmt1;
Stmt2;
continue;
Stmt3;
Stmt4;
}
Program Output
1
main( )
3
{
4
int i;
5
for (i=1; i<=5; i++)
{
if (i= =2)
continue,
printf(“%d”, i)
}
}
3) goto
C supports the goto statement to branch unconditionally from one point to another in the
program. The goto requires a label in order to identify the place where the branch is to be
made. A label is any valid name, and must be followed by a colon( : ) . The label is placed
immediately before the statement where the control is to be transferred. The general form of
goto is shown in fig

Forward jump backward jump


Syntax
goto label; label :stmt
---- ----
---- ----
---- ----
label : stmt goto label;

The label : can be anywhere in the program either before or after the goto label; statement.
During running of a program when a statement like goto begin; is met, the flow of control
jumps to the statement immediately following the label begin. This happens unconditionally.
Note that a goto breaks the normal sequential execution of the program. If the label: is
before the statement goto label; a loop will be formed and some statements will be executed
repeatedly. Such a jump is known as a backward jump. On the other hand, if the label: is placed
after the goto label; some statements will be skipped and the jump is known as a forward
jump.
Program
main( ) Output
Hello
{
you
printf(’Hello”);
goto l1;
printf(”How are”);
l1: printf(”you”);
}

You might also like