0% found this document useful (0 votes)
16 views27 pages

CP Unit 2

This document outlines the various types of control statements in C programming, including decision-making, conditional, and loop control statements. It details the structure and syntax of if, if-else, nested if-else, switch statements, and different loop types such as while, do-while, and for loops. Additionally, it explains the properties and usage of these control structures with examples and flowcharts for better understanding.

Uploaded by

v lokesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views27 pages

CP Unit 2

This document outlines the various types of control statements in C programming, including decision-making, conditional, and loop control statements. It details the structure and syntax of if, if-else, nested if-else, switch statements, and different loop types such as while, do-while, and for loops. Additionally, it explains the properties and usage of these control structures with examples and flowcharts for better understanding.

Uploaded by

v lokesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

UNIT-2

Types of Control Statements in C

The primary types of control statements in C are:

 Decision-making control statements


1. Simple if statement
2. If-else statements
3. Nested if-else statements
4. else-if ladder

 Conditional statements

 Goto statements in C

 Loop control statements in C


1. While Loop
2. Do-while Loop
3. For Loop

Control Structures

Program Control Structure: The structure of the program which decides the order of
program statements execution is called ‘control structure’. There are three types of
control structures.

1. Sequence: In this control structure, the instructions are executed linearly from
top to bottom
2. Selection: This control structure makes decision according to some predefined
condition.
3. Iteration: This control structure executes certain instructions repeatedly
until the desired condition is satisfied.
Conditional (selection) Statements:
The conditional statements are mainly used for Decision Making. There are 3 ways
of statements
a). Single –way selection b). Two-way selection c). Multi-way selection

Single-way selection: Simple-if Statement: The if statement is a decision making


statement. It is used to control the flow of execution of the statements and also
used to test logically whether the condition is true or false. It is always used in
conjunction with condition. If the condition is true, then the True statements are
executed. The 'True statements' may be a single statement or group of statements.
If the condition is false then the true statements are not executed, instead the
program skip past it. The condition is given by the relational operator like ==, !=,
<=, >=, etc.

Flow-chart for simple-


if
The general form of
If statement

if(conditional-statement) Test True


{
statement-block; conditio
}
statement-x;
nal
expressi
Statement-x
on

False Statement block

Next statements
Properties of if statement:
*. If the condition is true, then the simple or compound condition statements are
executed.\
*. If the condition is false, it does not do anything.
*. The condition is parenthesis and must be evaluated as true (non-zero value) or
false (zero).
*. If the compound structure is provided, it must be enclosed in opening and closing
braces.
The following program illustrates the use of if statement.(null else)
/* Program to check whether the entered number is less
than 25*/ #include<stdio.h>
main()
{
int i;
printf("\nEnter the number < 10. ");
scanf("%d",&i);
if(i<10)
printf("\nThe entered number %d is < 10", i);
}

Two-way selection: if-else Statement:

If-Else Statements: The if…..else statement is extension of the simple if


statement.
It is basically two way decision making statement and always used in conjunction
with condition. It is used to control the flow of execution and also used to carry
out the logical test and then pickup one of the two possible actions depending on
the logical test.
Flow-chart for if-else
The general form of If-else statement

if(conditional-statement)
False
{ Te True
statement-block1; st
} conditional
Statement block
else expression
{
Statement-xStatement block
statement-block2;
}
statement x;

Next statements
Example : Program to find floating point input using if-else statement.
#include<stdio.h>
main()
{
float years,
seconds; int life;
printf("Input you age in years : ");
life=scanf("%f",&years
); if(life==0)
printf("The input is not a floating-point
number.\n"); else
{
seconds=years*365*24*60*60;
printf("You have lived for %f seconds\n",seconds);
}
getch();
}

Nested If-Else Statements


When a series of if..else statements are occurred in a program, we can write
an entire if..else statement in another if..else statement called nesting, and the
statement is called nested if.statement
The general form of
Flow-chart for Nested-if-else
Nested-If-else statement

if(conditional-expression 1)
{
if(conditional-expression 2) False T True
{
statement-1;
e
} st
else conditional
{ expression-1
statement-2;
}
}
else
{
statement-2; F T True
}
al e
statement x;
se st
Statement block
conditional
expression-2

Statement block Statement block

Statement-x

Next statements
/* Write a Program to read experience and cadre and display salary through
Monitor */ #include<stdio.h>
main()
{
int ch, expr;
printf("Enter 1 for principal: ");
printf("Enter 2 for Professor: ");
printf("Enter 3 for Asst-
professor: "); scanf("%d”,&ch);
printf("Enter your experience:");
scanf("%d”,&exp);
if(ch==1)
if(exp>10)
printf("Salry is
30000:"); else
printf("Salary is 25000\
n"); else if(ch==2)
if(exp>6)
printf("Salry is
23000:"); else
printf("Salary is 20000\
n"); else if(ch==3)
if(exp>3)
printf("Salry is
16000:"); else
printf("Salary is 12000\n");
else
printf(“Entered choice is
Invalid”); getch();
}

The if…else Ladder:


There is another way of putting ifs together when multipath decisions are involved.
A multipath decision is a chain of ifs in which the statement associated with each
else is an if. Nested if statement can become quite complex. If there are more than
three alternatives and indentation is not consistent, it may be different for us to
determine the logical structure of the if statement.
Flow-chart for else-if Ladder

True Test False


conditional
expression-1
if (conditional- Statement -1 Test
True False
expresion 1) conditional
expression-2
statement-- Statement -2 Test
True False
1 conditional
expression-3
else if Statement -3 Test
True False
(conditional- conditional
expression-4

Statement -n dfefault statement


expresion 2)
statement--2
else if
(conditional-
expresion 3)
statement--3
else if
(conditional-
expresion n)
statement--n
else
default statement;

statement--x;
/* Program that reads marks in 3 subjects, calculate average marks and assigns
grade as per following specifications */
If marks Then Grade
>=90 A
75-90 B
60-75 C
50-60 D
<50 Fail

#include<stdio.h>
main()
{
float m1 ,m2 ,m3 ,average;
printf(“Enter the marks in three
subjects\n”); scanf(“%d%d%d”,&m1,
&m2, &m3); average=(m1+m2+m3);
printf (“Average marks are:%f\n”,
average); if(average>=90)
printf (“Grade is A \n”);
else if (average>=75 &&
average<90) printf (“Grade is B \
n”);
else if (average>=60 &&
average<75) printf (“Grade is C \
n”);
else if (average>=50 &&
average<60) printf (“Grade is
D \n”);
else
printf(“Fail \
n”); getch();
}

The Switch Statement


The switch statement is used to pickup or executes a particular group of
statements from several available groups of statements. It allows us to make a
decision from the number of choices.

It is a multi-way decision statement, it tests the value of 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.
Example : Program to print the Today‟s name of the Day by using switch case
statement. #include<stdio.h>
#include<conio.h>
main()
{
int i,n;
printf("Enter a Number : ");
scanf("%d",&n);
switch(n)
{
case 1 :
printf("Today is Monday”);
break;
case 2 :
printf("Today is
Tuesday”); break;
case 3 :
printf("Today is
Wednesday”); break;
case 4 :
:

case 5
p
r
i
n
t
f
(
"
T
o
d
a
y

i
s

T
h
u
r
s
d
a
y

)
;

b
r
e
a
k
;

printf("Today is Friday”);
brea
k; case 3 :
printf("Today is Saturday”);
break;
default:
printf("Invalid
Day”); break;
}
getch();
}

Nested Switch() Case

'C' supports the nested switch( ) statements. The inner switch( ) statement can be a
part of an outer switch( ) statement. The inner and outer switch ( ) case constants
may be same. No conflict arises even if they are same.
Rules for writing switch() statement:
*. The expression in switch statement must be an integer value or a character
constant.
*. No real numbers are used in an expression.
*. Each case and default blocks must be terminated with break statements.
*. The default is optional and can be placed anywhere, but usually placed at end.
*. The case keyword must terminate with colon (:)
*. No two case constants are identical.
*. The case labels must be constants.
*. The switch can be nested.

Repetition / Iteration / Loops


The loop is defined as the block of statements which are repeatedly
executed for certain number of times. There are two types of loop statements are
available: Those loops which check the test condition at the entry level itself,
and the other checks test condition at the exit level.
The loop in a program consists of two parts, one is body of the loop and
another is control statement. The control statement is used to test the
condition and then directs the repeated execution of the statements in the
body of the loop. Any looping statement would include-
1. Initialization of a condition variable.
2. Test the control statement.
3. Executing the body of the loop depending on the condition.
4. Updating the variable.
There available loop structures available in „C‟ is –while, do..while, for , nested
loops

while loop : Repeats a statement or group of statements while a given condition


is true. It tests the condition before executing the loop body.
for loop : Executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable.
do...while loop : It is more like a while statement, except that it tests the
condition at the end of the loop body.
nested loops :You can use one or more loops inside any other while, for, or do
while loop.

The while Loop/Pretest Loop:


The while loop is an entry controlled loop statement, means the condition is
evaluated first and if it is true, then the body of the loop is executed. After
executing the body of the loop, the condition is once again evaluated and if it is
true, the body is executed once again, the process of repeated execution of the
body of the loop continues until the condition finally becomes false and the
control is transferred out of the loop.

Syntax: /* Addition of natural numbers upto 5 using while


Initialization
loop */

while #include<stdio.h>
{ False main()
............. Condition {
Body of the int i,
loop sum=0;
True
............. while(i<=
} 5)
Body of the Loop
{
sum=sum+
i; i++;
}
printf("The sum of numbers upto 5 is %d:",sum);
}

Explanation: Here, first evaluates whether 'i' is less than or equal to 5. At first i=1 so the
codition is true, now sum is added with the value of 'i' and get sum as one, then 'i' is
incremented by 1, then it evaluates the condition again. This process is going on till the
condition is false. When the condition is false the printf() statement is executed and
displays the result.
do-while Loop / Posttest Loop :
It is also repetitive control structure and executes the body of the loop once
irrespective of the condition, and then it checks the condition and continues the
execution until the condition becomes false.
The statements within the body of the loop is executed once, then it evaluates for
the condition, if it is true, then it executes body until the condition becomes false.

Initialization /* Addition of natural numbers upto 5 using do-while loop


*/
Syntax:
Body of the Loop #include<stdio.h>
do{ main()
{ {
............. int i, sum=0;
Body of the do
loop {
Condition
............. True sum=sum+i;
}while(condition i++;
) False }while(i<=5);
printf("The sum of numbers upto 5 is %d:",sum);
}

Explanation: In the above program the value of i is evaluated as 1 and value of sum is
initialized as 0. In this program the do..while is executed tje body and calculates the sum and
increment the i value by 1 until the condition satisfies i<=10. Then prints sum value as
output.
The do...while command strcure

for Loop
The for loop is another repetitive control structure, and is used to execute set
of instructions repeatedly until the condition becomes false.
The assignment, incrementation or decrementation and condition checking
is done in for statement only, where as other control structures are not
offered all these features in one statement.
For loop has three parts
1. Initialize counter.
2. Test condition is used to initialize counter variable.
3. Increment/decrement is used to increment or decrement counter variable.

Example : Program to print n


Initialization numbers using
for..loop structure.
/* Program to print n numbers */
Syntax: #include<stdio.h
> void main()
Body of the Loop
for(initialization; {
condition;incre/decrement int i,n;
{ Increment/Decrement
clrscr();
............. printf("Enter a number :");
Body of the loop scanf("%d",&n);
............. for(i = 0; i<n; i= i+1)
}
Condi {
tion
Tr printf("The numbers are %d \n",i);
ue }
getch();
False
}
Explanation: In the above program prints the n numbers on the screen, using for
loop the n value can be supplied by the user. i.e., if we give n as 5 it prints
0,1,2,3,4,5 if we gives 10 it prints 0,1,2............................................9 and so
on.
Comparison between while and do while

S. While do..While
No
1 This is the top tested This is the bottom tested
loop loop
2 The condition is first It executes body once,
tested if the condition after it checks the
os true then the block condition, if it is true the
is executed until the body is executed until
condition becomes the condition becomes
false false.
3 Loop will not be Loop is executed atleast
executed if the once even through the
condition is false condition is false.

Nesting of for Loop


Like if statement for loop also nested. The loop within the loop is called nested
loop. In nested for loops two or more for statements are included in the body of
the loop. The number of iterations in this type of structure will be equal to the
number of iterations in the outer loop multiplied by the number of iterations in the
inner loop.
Example :

/* Program using nesting of for loops */


#include<stdio.h>
main()
{
int i,j;
for(i=1;i<=3;i++)
{
printf("\n");
for(j=1;j<=3;j++)
printf("%d\t",j);
}
}
Additional features of for loop.
1. We can initialize more than one variable at
a time. Example: for (i=1, j=1; i<=10;i+
+)
2. One or more section of for loop may be omitted, if
necessary Example: for(; i<=100;)
3. The test condition may have any compound relation
Example: for(i=1;i<10 && sum <100; j++)
{
Sum=sum+j;
}
Loop Control Statements
Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed.
C supports the following control statements.
1) break 2) continue 3) goto

The Break Statement


The break statement is used to terminate the loop. When the keyword break is
used inside any 'C' loop, control automatically transferred to the first
statement after the loop.
When the break statement is encounted inside a loop, the loop is immediately
exited and the program continues with the statement immediately following the
loop.
Syntax: break;
A break is usually associated with an if statement. /* Program using break
statement */
Example : Program to print the number upto 5 using break
statement. #include<stdio.h>
main ()
{
int i;

for(i=1;i<=10;i++)
{
if(i==6)
break; /* break statement
*/ printf("%d", i);
}
}

The Continue Statement


In some situations, we want to take the control to the beginning of the loop,
bypassing the statements inside the loop which have not yet been executed,
for this purpose the continue is used. When the statement continues is
encountered inside any 'C' loop control automatically passes to the beginning
of the loop.
Syntax: continue
Like break statement the continue statements also associate with if statement.
/* Program to calculate the sum of the given positive
numbers */ #include<stdio.h>
main
{
int i,n,sum=0;
for(i=1;i<=5;i++)
{
printf("Enter any number \n");
scanf("%d",&n);
if(n<0)
continue;
els
e
sum=sum+

}
n;

printf("Sum is. %d",sum);


}

S.N break continue


o
1 Break statement takes the Continue statement takes the
control to the outside of the control to the beginning of
loop. the loop.
2
It is also used in switch This can be used only in loop
statement statement
3
This is also associated with if
Always associated with if condition
condition in loops
Goto Statement
C' provides the goto statement to transfer control unconditionally from one
place to another place in the program.
A goto statement can cause program control almost anywhere in the program
unconditionally.
The goto statement requires a label to identify the place to move the execution.
A label is a valid variable name and must be ended with colon (:).
Example : /* Program using goto
statement */ #include<stdio.h>
main ()
{
int a, b;
printf("\nEnter the
numbers"); scanf("%d
%d",&a,&b); if(a==b)
goto vahini;
else
{
printf("\n A and B are not
equal"); exit(0);
}
vahin
i:
printf("A and B are equal");

The Infinite Loop


A loop becomes an infinite loop if a condition never becomes false. The for loop
is traditionally used for this purpose. Since none of the three expressions that form
the 'for' loop are required, you can make an endless loop by leaving the conditional
expression empty.

#include <stdio.h>

int main () {

for( ; ; ) {
printf("This loop will run forever.\n");
}

return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have
an initialization and increment expression, but C programmers more commonly
use the for(;;) construct to signify an infinite loop.

NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.

You might also like