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

C - Control Statements and Loops

The document discusses different types of control statements in C programming including sequence, selection, and repetition statements. It covers if, if-else, nested if-else, switch, while, do-while and for loop statements providing syntax and examples of each. Decision making in C can be done using if, if-else-if, and switch statements while loops allow repeating blocks of code using while, do-while and for loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

C - Control Statements and Loops

The document discusses different types of control statements in C programming including sequence, selection, and repetition statements. It covers if, if-else, nested if-else, switch, while, do-while and for loop statements providing syntax and examples of each. Decision making in C can be done using if, if-else-if, and switch statements while loops allow repeating blocks of code using while, do-while and for loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Jyoti Chandnani

The Decision and Loop Control Statements


In any high-level language basically, there are three types of statements:
1. Sequence instruction
2. Selection decision instructions
3. Repetition or Loop instructions.

1. Sequence Instructions: means executing one statement after another, in the


same order in which they occur in the program file.
2. Selection Instructions: means executing different sections of code depending
on the condition. C provides three selection statements:
a. If
b. If…else
c. switch
3. Repetition or Loop Statements: Executing same section of code or block of
code more than once. Block of code either execute specified number of times
or while some condition is true. C provides three looping statements:
a. for
b. while
c. do….while

Decision Control Statements

Decision control statements causes a one time jump to a different part of the
program, depending on the condition or value of a variable. Decisions in C made in
several ways :

If Statement
It is used to execute a block of statements only if a condition is fulfilled.
Different forms of implementation of if-statement are :

1. Simple if statement
2. if..else
3. Nested if..else
4. Else if statement

1
Jyoti Chandnani

1. Simple if Statement : It is used to execute a block of code only if the


condition is true.
Syntax : if(condition)
Statement;
If more than one statement then the syntax will be :
if (condition)
{
Statements;
}
Statements ;

If the condition is true then the statements will be executed else the program
continues on the next statement after the conditional statement.

For eg :

If (a>5)
printf (“A is greater than 5”);

2. if…else statement
It is used when a different sequence of instructions are to be executed
depending on the logical value (True/false) of the condition evaluated.

Syntax :
If(condition)
{ Block -1 ; }
Else
{ Block -2 ; }

Block -3;

For eg : Write a program to print whether the given number is ever or odd;
main()
{
int x=9;
if (x%2 == 0)
printf(“number is even “);
else
printf(“number is odd “);
}

2
Jyoti Chandnani

3.Nested if … else Statements


Nested if means If..else inside the block of if or else.
Syntax :
If(condition 1 )
{
If(condition 2)
{ Block -1 }
Else
{ Block -2 }
}
Else { Block -3; }
Block -4;
If condition-1 is false then block-3 will be executed.

Example :
Write a program to calculate an Air ticket fare after discount, given the
following condition:
1. if passenger is below 14yrs- 50% disc on fare
2. if passenger is above 50yrs – 20%disc on fare
3. if passenger is above 14 and below 50 – 10%disc
Ans : //Program to calculate air fare

#include<stdio.h>
int main()
{
int age;
float fare=0;
printf("Enter age of the passenger \n");
scanf("%d",&age);
printf("Enter age of the passenger \n");
scanf("%f",&fare);
if(age<14)
fare=fare - 0.5*fare;
else
if(age<=50)
{ fare=fare-0.1 * fare; }
else
{ fare=fare - 0.2*fare; }
printf("\n Air ticket fare to be charged after discount is %.2f",fare);
}

3
Jyoti Chandnani

4.Else…if statements
Multiway decisions based on several conditions.
As soon as one of the condition is true, block of code associated with that
condition will be executed and no other condition will be evaluated.

Syntax :
If(condition)
{
Block -1;
}
Else if (condition)
{
Block -2;
}
…….
Else if(condition)
{
Block -n;
}
Else
{
Block - s
}

4
Jyoti Chandnani

Example
// program to calculate grade of student.

#include<stdio.h>
void main(){
float p;
printf("Enter Percentage of the Student\n:");
scanf("%f", &p);
if(p>=90)
printf("Grade is 'A'\n");
else if(p<90 && p>=70)
printf("Grade is 'B'\n");
else if(p<70 && p>=50)
printf("Grade is 'C'\n");
else if(p<50 && p>=35)
printf("Grade is 'D'\n");
else if(p<35 && p>=0)
printf("Student is Failed\n");
else
printf("Please Enter Valid Marks");
}

Switch statement :
This is same as else if statements. Its objective is to check several possible constant
values for an expression. Switch is used when the value of variable is smaller in
number.
Syntax :
switch (expression ) → int or char constant
{
case expression 1:
block of instructions;
break;
case expression 2:
block of instructions;
break;
case expression 3:
block of instructions;
break;
.
.
Default :
Block of instruction: }

5
Jyoti Chandnani

Example : # include<stdio.h>
int main( )
{
int i = 2 ;
switch ( i )
{
case 1 :
printf ( "I am in case 1 \n" ) ;
case 2 :
printf ( "I am in case 2 \n" ) ;
case 3 :
printf ( "I am in case 3 \n" ) ;
default :
printf ( "I am in default \n" ) ;
}
return 0 ; }

At times we may want to execute a common set of statements for multiple


cases. The following example shows how this can be achieved:
# include<stdio.h>
int main( )
{
char ch ;
printf ( "Enter any one of the alphabets a, b, or c " ) ;
scanf ( "%c", &ch ) ;
switch ( ch )
{
case 'a' :
case 'A' :
printf ( "a as in ashar\n" ) ;
break ;
case 'b' :
case 'B' :
printf ( "b as in brain\n" ) ;
break ;
case 'c' :
case 'C' :
printf ( "c as in cookie\n" ) ;
break ;
default :
printf ( "wish you knew what are alphabets\n" ) ;
} return 0; }

6
Jyoti Chandnani

Loop Control Statement

Loop control statements are used when block of code are to be executed fixed
number of times or depending on the condition if it’s true. C gives three types of
looping statements
1. While – used when number of iterations are not known.
2. Do… while – at least once the loop will be executed.
3. For loop – used when number of iterations are known.

While Loop : It is often the case in programming that you want to repeat something
a fixed number of times.

Syntax :
While(test condition)
{
Body of the loop;
Increment counter;
}

/* Calculation of simple interest for 3 sets of p, n and r */


# include<stdio.h>
int main( )
{
int p, n, count ;
float r, si ;
count = 1 ;
while ( count <= 3 )
{
printf ( "\nEnter values of p, n and r " ) ;
scanf ( "%d %d %f", &p, &n, &r ) ;
si = p * n * r / 100 ;
printf ( "Simple interest = Rs. %f", si ) ;
count = count + 1 ;
}
return 0;
}

7
Jyoti Chandnani

Note
• The statements within the while loop would keep getting executed− till the
condition being tested remains true.
• In place of the condition there can be any other valid expression. So − long as
the expression evaluates to a non-zero value the statements within the loop
would get executed.
• The condition being tested may use relational or logical operators as− shown
in the following examples:
while ( i <= 10 )
while ( i >= 10 && j <= 15 )
while ( j > 10 && ( b < 15 || c < 20 ) )

Write a program to enter numbers till the user wants. At the end it should display
the count of positive, negative and zeros entered.

Ans:
#include<stdio.h>
void main(){
int p,pos=0,neg=0,zero=0;
while(p!=100)
{
printf("Enter a number\n 100 to exit:\n");
scanf("%d", &p);

if(p>0)
pos++;
else if (p<0)
neg++;
else
zero++;
}
printf("Count of Positive numbers = %d \n ",pos);
printf("Count of Negative numbers = %d \n ",neg);
printf("Count of Zero numbers = %d \n ",zero);
}

8
Jyoti Chandnani

Do…while Loop

There is a minor difference between the working of while and do-while loops. This
difference is the place where the condition is tested. The while tests the condition
before executing any of the statements within the while loop. A do…while loop
execute statements at least once and then tests the condition.

Syntax:
Initialise counter
do
{
Body of the loop;
Increment counter;
} while(test counter using a condition);

/* Execution of a loop an unknown number of times */


# include<stdio.h>
int main( )
{
char another ;
int num ;
do
{
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
printf ( "square of %d is %d\n", num, num * num ) ;
printf ( "Want to enter another number y/n " ) ;
fflush ( stdin ) ; // to free the buffer
scanf ( "%c", &another ) ;
}while ( another == 'y' ) ;
return 0 ;
}

fflush( ). It is designed to remove or ‘flush out’ any data remaining in the buffer. The
argument to fflush( ) must be the buffer which we want to flush out. Here we have
used ‘stdin’, which means buffer related with standard input device, i.e., keyboard.

9
Jyoti Chandnani

For Loop

The for allows us to specify three things about a loop in a single line:
(a) Setting a loop counter to an initial value.
(b) Testing the loop counter to determine whether its value has reached the number
of repetitions desired.
(c) Increasing the value of loop counter each time the body of the loop has been
executed.

Syntax :
for(Initialise counter ;test counter using a condition ; Increment counter)
{
Body of the loop;
}

Example :
//Program to print numbers from 1 to 10

#include<stdio.h>
void main()
{
int x;
for(x=1 ; x<=10 ; x++)
{
printf("\t\t%d",x);
printf("\n");
}
printf("\n\nOut of the loop");
}

10
Jyoti Chandnani

The Nested Loops

The way if statements can be nested, similarly whiles and fors can also be nested. To
understand how nested loops work, look at the program given below

/* Demonstration of nested loops */


# include<stdio.h>

int main( )
{
int r, c, sum ;
for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */
{
for ( c = 1 ; c <= 2 ; c++ ) /* inner loop */
{
sum = r + c ;
printf ( "r = %d c = %d sum = %d\n", r, c, sum ) ;
}
}
return 0 ;
}

Forms of for loop:


1. for(;condition;increment) : means no initialization required
2. for(initialization;condition) : no running increment/decrement
3. for(initialization;increment/decrement) : it is required to test the condition
inside the loop statements else it results in the infinite loop
4. for(;;;) – initiasation is required to be done before the loop and condition
and increment to be done inside the body of the loop.
5. for(;condition; ) – initialisation before the loop and
increment/decrement inside the loop.

Multiple Initializations in the for Loop The initialization expression in the for loop can
contain more than one statement separated by a comma.
For example, for ( i = 1, j = 2 ; j <= 10 ; j++,i++)

11
Jyoti Chandnani

The GOTO Statement


Use a goto to take the control where you want. It alter the normal execution of the
program and take control anywhere in the program.
Syntax : goto label;

Label is an identifier that is used to label the statement to which control will be
transferred.
Syntax : label : statement

//Program to demonstrate goto statement


#include<stdio.h>
void main()
{
int x=2;
while(1)
{
printf("\t\t%d",x);
x=x+2;
if(x>=20)
goto outside; // taking control where label is defined
}
outside : // goto label definition
printf("\n\nOut of the loop");
}

The break Statement


The break Statement We often come across situations where we want to jump out of
a loop instantly, without waiting to get back to the condition. The keyword break
allows us to do this. When break is encountered inside any loop, control
automatically passes to the first statement after the loop.

12
Jyoti Chandnani

//program to check if the entered number is prime or not.

1. # include<stdio.h>
int main( )
{
int num, i ;
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
i=2;
while ( i <= num - 1 )
{
if ( num % i == 0 )
{
printf ( "Not a prime number\n" ) ;
break ;
}
i++ ;
}
if ( i == num )
printf ( "Prime number\n" ) ;
}

2. # include<stdio.h>
int main( )
{
int i = 1 , j = 1 ;
while ( i++ <= 100 )
{
while ( j++ <= 200 )
{
if ( j == 150 )
break ;
else
printf ( "%d %d\n", i, j ) ;
}
} return 0 ;
}

13
Jyoti Chandnani

The Continue Statement


When continue is encountered inside any loop, control automatically passes to the
beginning of the loop. A continue is usually associated with an if.
It is used to skip some part of the loop and to continue the execution with the next
loop iteration.

// demo for continue statement


#include<stdio.h>

int main( )
{
int i, j ;
for ( i = 1 ; i <= 2 ; i++ )
{
for ( j = 1 ; j <= 2 ; j++ )
{
if ( i == j )
continue ;
printf ( "%d %d\n", i, j ) ;
}
}
return 0 ;
}

14

You might also like