EST102: Programming in C: Control Structures
EST102: Programming in C: Control Structures
Chapter 6
Control structures
Narasimhan T.
6.1 Introduction
Chapter 5 essentially sheds light on the sequencing programming construct in which program
instructions execute (only) once in that order. Now we move to more advanced constructs
like selection and looping which allow for selective execution as well as repeated execution
of program instructions.
70
6.2. SELECTION STATEMENTS 71
if(x > 0)
{
printf("%d is positive",x);
}
It is possible to combine multiple conditions using logical operator. The following code
snippet tests whether a number x is a single digit number or not.
if(x > 0 && x < 10)
printf("%d is a positive single digit number",x);
When there is only a single statement associated with the if, then the pair of braces can
be omitted as written in the code above.
statement2;
}
else
{
if(condition3)
statement3;
else
statement4;
}
It is possible that statement1, statement2 etc. could be if-else statements themselves.
Then it is called multilevel nesting.
An example of two level nesting is given below which checks the nature (zero, positive or
negative) of an input value x.
if(x==0)
printf("You entered a zero now");
else
{
if(x>0)
printf("You entered a positive value");
else
printf("You entered a negative value");
}
else if(condition-n)
{
<block of statements-n>
}
else
{
<default block of statements>
}
The conditions are evaluated from the top downward. As soon as a True condition is found,
the statements associated with it are executed and the rest of the ladder is bypassed. If
none of the conditions are True, the final else block is executed. That is, if all other
conditional tests fail, the default block of statements is executed. There is no limit of
the number of else if statements, but the last branch has to be an else statement. The
following code compares two variables and prints the relation between them.
if(x < y)
printf("%d is less than %d", x, y);
else if(x > y)
printf("%d is greater than %d", x, y);
else
printf("%d is equal to %d", x, y);
The value of expression is tested against the values, value1, value2 etc. one after
another. When a match is found, the block associated with that case is executed until the
break statement or the end of the switch statement is reached. The default-block is
executed if no matches are found.
The following points are noteworthy regarding a switch statement:
1. The expression must evaluate to an integer type. Thus, you can use character or
integer values in the cases, but floating-point expressions are not allowed. If character
constants are used in the switch statement, they are to be enclosed within quotes and
are automatically converted to integers as decided by the ASCII.
3. Even if there are multiple statements to be executed in each case there is no need to
enclose them within a pair of braces (unlike if and else).
4. Technically, the break statements inside the switch statement are optional. If the
break statement is omitted, execution will start from the first matching case and
continue on into the succeeding case statements (even if they are not matching cases)
until either a break or the end of the switch is reached.
5. You can have a switch as part of the block associated with a case of another switch.
The enclosed switch is called inner switch and the enclosing switch is called outer
switch.
6. No two case values within a switch should be identical. Nevertheless, an outer switch
can have case constants that are in common with those of the inner switch.
7. The default case may appear anywhere within the switch statement – it need not
necessarily be placed at the end.
8. The default is optional, and if it is not present, no action takes place if all matches
fail.
9. It is possible to associate the same set of block with multiple cases. For example,
consider the following code snippet.
switch(ch)
{
case 'a':
case 'A':
printf("First alphabet");
break;
case 'b':
case 'B':
printf("Second alphabet");
break;
case 'c':
6.3. ITERATION STATEMENTS 75
printf("Third alphabet");
break;
default:
printf("wish you knew what are alphabets!");
}
is associated with two case values 'a' and 'A'. If ch is assigned the character 'a',
then the case ‘a’ is satisfied and since there are no statements to be executed in this
case the control automatically reaches the next case i.e. case ‘A’ and executes all the
statements in this case.
10. Every statement in a switch must belong to some case or the other. If a statement
doesn’t belong to any case, the compiler won’t report an error. However, the statement
would never get executed.
Example 6.1. In the following program, a for loop is used to print the numbers 1 through
100 on the screen:
#include<stdio.h>
main()
{
int x;
for(x=1;x<=100;x++)
printf("%d ",x);
}
Here the loop variable x is initially set to 1 and then compared with 100. Since x is less
than 100, printf() is called and the loop iterates. This causes x to be increased by 1
and again tested to see if it is still less than or equal to 100. If it is, printf() is called.
This process repeats until x is greater than 100, at which point the loop terminates.
Example 6.2. In the following code fragment, variables x and y control the loop:
for(x=0, y=0; x+y < 10; ++x)
{
scanf("%d",&y);
y+=2;
.
.
.
}
Commas separate the two initialization statements. Each time the loop repeats, x is
incremented and y’s value is set by keyboard input. Even though y’s value is set by
keyboard input, y must be initialized to 0 so that its value is defined before the first
evaluation of the conditional expression.
Another interesting trait of the for loop is that the three pieces of the loop definition
need not be present. For example, this loop will run until the user enters 123:
for(x=0; x != 123; )
scanf("%d", &x);
6.3. ITERATION STATEMENTS 77
Notice that the update portion of the for definition is blank. This means that each time
the loop repeats, x is tested to see if it equals 123. If the input is 123, the loop condition
becomes False and the loop terminates.
A third variation of for loop is to take the initialization of the loop control variable outside
the for statement.
Here, neither the initialisation, nor the update is done in the for statement, but still the
two semicolons are necessary.
Yet another variation is to combine the update and condition parts of the for loop
definition. See the code below:
main( )
{
int i;
for(i = 0;i++ < 10;)
printf("%d\n",i);
}
Here, the comparison as well as the increment is done through the same statement, i++ <
10. Since the statement involves the post increment operator, i is first compared with 10,
then followed by the actual increment.
It is really interesting that all the three components of the for loop definition viz.
initialization, test and update can be left blank, although the two semicolons should still
be put. What you end up with, is known as an infinite loop, i.e., a loop which runs forever
(unless there is a break statement in the loop body).
Example 6.4. When the conditional expression is absent, it is assumed to be True. Thus
the following loop runs forever.
for(;;)
printf("This loop will run forever.\n");
78 CHAPTER 6. CONTROL STRUCTURES
Like for loops, while loops check the test condition at the beginning of the loop, which
means that the body of the loop will not execute if the condition is false to begin with.
Example 6.6. The following do-while loop reads numbers from the keyboard until it finds
a number less than or equal to 100:
do
{
scanf("%d", &num);
}while(num > 100);
For each value of the outer loop variable i, the inner loop variable j runs from 1 to 10.
Thus, the above code produces the following output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
}
This code produces the output:
The number is 1
2 is even
Outside the loop
#include<stdio.h>
main()
82 CHAPTER 6. CONTROL STRUCTURES
{
int num,abs;
printf("Enter any number\n");
scanf("%d",&num);
abs=num;
if(num<0)
abs=num*-1;
printf("The absolute value of %d is %d\n",num,abs);
}
#include <stdio.h>
main()
{
int n;
printf("Enter an integer\n");
scanf("%d", &n);
if(n%7 == 0)
printf("%d is divisble by 7\n",n);
else
printf("%d is not divisble by 7\n",n);
}
#include <stdio.h>
main()
{
char ch;
printf("Enter any character: ");
scanf("%c", &ch);
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
printf("%c is an alphabet\n",ch);
}
else
{
printf("%c is not an alphabet\n",ch);
}
}
#include <stdio.h>
main()
{
6.5. PROGRAMMING EXAMPLES 83
#include <stdio.h>
main()
{
int num1, num2, num3, large;
printf("Enter any two numbers:\n");
scanf("%d %d %d", &num1, &num2, &num3);
if(num1 > num2)
large=num1;
else
large=num2;
if(num3>large)
large=num3;
printf("The largest among %d, %d and %d is %d\n",num1,num2,num3,large);
}
Program 6.16. To calculate the electricity bill of a customer. The tariff slabs are as
follows:
For first 50 units, | 0.50/unit
For next 100 units, | 0.75/unit
For next 100 units, | 1.20/unit
For total units above 250, | 1.50/unit
An additional surcharge of 20% is added to the bill if the amount exceeds | 300.
#include <stdio.h>
main()
{
int units;
float amt, bill, surcharge=0;
printf("Enter total consumed units\n");
scanf("%d", &units);
if(units > 250)
amt = units*1.50;
else if(units <= 50) //first 50 units
amt = units * 0.50;
else if(units <= 150) // 150 = first 50 + next 100
84 CHAPTER 6. CONTROL STRUCTURES
#include <stdio.h>
main()
{
int m1, m2, m3, m4, m5;
float per;
printf("Enter five subjects marks\n");
scanf("%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5);
per = (m1 + m2 + m3 + m4 + m5) / 5.0;
if(per >= 90)
printf("Grade A\n");
else if(per >= 80)
printf("Grade B\n");
else if(per >= 70)
printf("Grade C\n");
else if(per >= 60)
printf("Grade D\n");
else if(per >= 50)
printf("Grade E\n");
else
printf("Grade F\n");
}
Program 6.18. To determine whether an year is a leap year or not.
An year is a leap year if any of the following two conditions are true:
1. year is divisible by 4 but not by 100
6.5. PROGRAMMING EXAMPLES 85
as a number divisible by 400 is also divisible by 100. This logic results in the following code:
#include<stdio.h>
main()
{
int year;
printf("Enter the year");
scanf("%d",&year);
if (((year%4==0) && (year%100!=0)) || (year%400==0))
printf("%d is a leap-year\n",year);
else
printf("%d is not a leap-year\n",year);
}
Program 6.19. To solve a quadratic equation.
#include <stdio.h>
#include <math.h>
main()
{
float a, b, c, determinant, root1,root2, real, imaginary;
printf("Enter coefficients a, b and c: ");
scanf("%f %f %f",&a, &b, &c);
determinant = b*b-4*a*c;
if(determinant > 0)
{
root1 = (-b+sqrt(determinant))/(2*a);
root2 = (-b-sqrt(determinant))/(2*a);
printf("root1 = %f and root2 = %f\n",root1 , root2);
}
else if(determinant == 0)
{
root1 = root2 = -b/(2*a);
printf("root1 = root2 = %f\n", root1);
}
else
{
real = -b/(2*a);
imaginary = sqrt(-determinant)/(2*a);
printf("root1 = %f+%f i and root2 = %f-%f i\n", real, imaginary,
real, imaginary);
86 CHAPTER 6. CONTROL STRUCTURES
}
}
Program 6.20. To find the gross salary of an employee in a company, where the pay rules
are as follows : If the basic salary is less than | 15000, then HRA is 10% of basic salary
and DA is 110% of basic pay. Otherwise, the employee will receive an HRA of | 2000 and
DA will be 120% of basic salary.
#include<stdio.h>
main()
{
float bp,gs,da,hra;
printf("Enter basic salary\n");
scanf("%f",&bp);
if(bp<15000)
{
hra=bp*10/100;
da=bp*110/100;
}
else
{
hra=2000;
da=bp*120/100;
}
gs=bp+hra+da;
printf("Gross salary is Rs. %f\n",gs);
}
Program 6.21. To determine the largest in a list of n numbers entered by the user.
#include<stdio.h>
main()
{
int n,num,i,big;
printf("Enter the value of n\n");
scanf("%d",&n);
printf("Enter the first number\n");
scanf("%d",&num);
big=num;
for(i=1;i<=n-1;i++)
{
printf("Enter the next number\n");
scanf("%d",&num);
if(big<num)
big=num;
}
6.5. PROGRAMMING EXAMPLES 87
#include <stdio.h>
main()
{
int n, i;
long fact = 1; // for large numbers, factorial will be huge
printf("Enter a non negative integer\n");
scanf("%d",&n);
for(i=1; i<=n; i++)
fact *= i;
printf("Factorial of %d is %ld\n", n, fact);
}
#include <stdio.h>
main()
{
int n, i, flag;
printf("Enter a positive integer\n");
scanf("%d",&n);
if(n==1)
printf("1 is neither prime nor composite\n");
else
{
flag=1;
for(i=2;i<=n/2;i++)
{
if(n%i==0)
{
flag=0;
break;
}
}
if(flag==1)
printf("%d is a prime number\n",n);
else
printf("%d is not a prime number\n",n);
}
}
Program 6.24. To check if a number is perfect number or not. A perfect number is one
88 CHAPTER 6. CONTROL STRUCTURES
#include <stdio.h>
main()
{
int n, sum = 0, c, value;
printf("Enter the number of integers you want to add\n");
scanf("%d", &n);
printf("Enter %d integers\n",n);
for (c=1;c<=n;c++)
{
scanf("%d", &value);
sum = sum + value;
}
printf("Sum of entered integers is %d\n",sum);
}
Program 6.26. To find the sum of all odd numbers in a list of n numbers entered by the
user.
#include <stdio.h>
main()
{
int i,n,sum=0,num;
printf("Enter how many numbers you want to enter\n");
scanf("%d", &n);
for(i=0;i<n;i++)
{
6.5. PROGRAMMING EXAMPLES 89
printf("Enter a number\n");
scanf("%d",&num);
if(num%2!=0)
sum += num;
}
printf("Sum of all odd numbers in the list you entered is %d\n",sum);
}
Program 6.27. To determine the average of list of numbers entered by the user. The
user will terminate the input with a -1.
#include<stdio.h>
main()
{
int count=0,num,sum=0;
float average;
printf("Enter a number\n");
scanf("%d",&num);
while(num!=-1)
{
count++;
sum+=num;
printf("Enter next number\n");
scanf("%d",&num);
}
if(count>0)
{
average=sum/count;
printf("The average of the entered numbers is %f\n",average);
}
}
#include <stdio.h>
main()
{
int i, num1, num2, max, lcm;
printf("Enter any two numbers to find LCM\n");
scanf("%d %d", &num1, &num2);
max = (num1>num2) ? num1 : num2;
i = max;
while(1)
{
if(i%num1==0 && i%num2==0)
{
90 CHAPTER 6. CONTROL STRUCTURES
lcm = i;
break;
}
i += max;
}
printf("LCM of %d and %d is %d\n", num1, num2, lcm);
}
#include <stdio.h>
main()
{
int i, num1, num2, min, hcf=1;
printf("Enter any two numbers to find HCF: ");
scanf("%d %d", &num1, &num2);
min = (num1<num2) ? num1 : num2;
for(i=1; i<=min; i++)
{
if(num1%i==0 && num2%i==0)
hcf = i;
}
printf("HCF of %d and %d is %d\n", num1, num2, hcf);
}
#include <stdio.h>
main()
{
int n,num,sum = 0;
printf("Enter a number\n");
scanf("%d", &num);
n=num;
while(num!=0)
{
sum += num % 10;
num = num / 10;
}
printf("Sum of digits of %d is %d\n", n, sum);
}
#include <stdio.h>
main()
{
6.5. PROGRAMMING EXAMPLES 91
int n,num,reverse = 0;
printf("Enter a number to find reverse\n");
scanf("%d", &n);
num=n;
while(n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
printf("Reverse of %d is %d\n", num, reverse);
}
#include <stdio.h>
main()
{
int n,num,reverse = 0;
printf("Enter a number to find reverse\n");
scanf("%d", &n);
num=n;
while(n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
if(reverse==num)
printf("%d is a palindrome\n", num);
else
printf("%d is not a palindrome\n", num);
}
num = number;
while(num != 0) // to find the number of digits
{
num /= 10;
n++;
}
num = number;
while (num != 0)
{
remainder = num%10;
result += pow(remainder,n);
num /= 10;
}
if(result == number)
printf("%d is an Armstrong number\n",number);
else
printf("%d is not an Armstrong number\n",number);
}
Program 6.34. To print the Fibonacci series whose terms are less than or equal to an
user input limit.
#include <stdio.h>
main()
{
int prev1, prev2, next, limit;
printf("Enter the limit\n");
scanf("%d", &limit);
if(limit==0)
printf("0");
else
{
prev1=0;
prev2=1;
printf("%d %d ",prev1,prev2);
next=prev1+prev2;
while(next<=limit)
{
printf("%d ",next);
prev1=prev2;
prev2=next;
next=prev1+prev2 ;
}
}
}
6.5. PROGRAMMING EXAMPLES 93
#include <stdio.h>
main()
{
int prev1, prev2, next, n, i;
printf("Enter the number of terms\n");
scanf("%d", &n);
if(n==1)
printf("0");
else if(n==2)
printf("0 1");
else
{
prev1=0;
prev2=1;
printf("%d %d ",prev1,prev2);
for(i=3;i<=n;i++)
{
next=prev1+prev2;
printf("%d ",next);
prev1=prev2;
prev2=next;
}
}
}
#include <stdio.h>
main()
{
int low, high, i,j, flag;
printf("Enter the lower and upper bounds of the range\n");
scanf("%d %d", &low, &high);
printf("Prime numbers between %d and %d are\n", low, high);
for(i=low;i<=high;i++)
{
flag=1;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
{
flag=0;
break;
}
94 CHAPTER 6. CONTROL STRUCTURES
}
if(flag==1)
printf("%d ",i);
}
}
Program 6.37. To print the Armstrong numbers in a given range.
#include <stdio.h>
#include <math.h>
main()
{
int low, high, i, num, remainder, n,result;
printf("Enter the bounds of the range\n");
scanf("%d %d", &low, &high);
printf("Armstrong numbers between %d an %d are\n", low, high);
for(i=low;i<=high;i++)
{
n = 0;
result = 0;
num = i;
while(num != 0)
{
num /= 10;
n++;
}
num = i;
while(num != 0)
{
remainder = num % 10;
result += pow(remainder, n);
num /= 10;
}
if(result == i)
printf("%d ", i);
}
}
Program 6.38. To compute the sum of the following series upto n terms:
x2 x4 x6
1+ + + + ······
2 4 6
#include<stdio.h>
#include<math.h>
main()
6.5. PROGRAMMING EXAMPLES 95
{
int n,x,i;
float sum=1.0;
printf("Enter the number of terms and the value of x\n");
scanf("%d %d",&n,&x);
for(i=1;i<n;i++)
sum+=(pow(x,2*i))/(2*i);
printf("The sum of the series is %f\n",sum);
}
Program 6.39. To compute the sum of the following series upto n terms:
x2 x4 x6
1− + − + ······
2 4 6
#include<stdio.h>
#include<math.h>
main()
{
int n,x,i;
float sum=1.0;
printf("Enter the number of terms and the value of x\n");
scanf("%d %d",&n,&x);
for(i=1;i<n;i++)
sum+=pow(-1,i)*(pow(x,2*i))/(2*i);
printf("The sum of the series is %f\n",sum);
}
Program 6.40. To compute the sum of the following series upto n terms:
1 + (1 + 2) + (1 + 2 + 3) + · · · · · · + (1 + 2 + 3 + · · · · +n)
#include<stdio.h>
main()
{
int i,j,n,sum=0;
printf("Enter the number of terms\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
sum+=j;
}
printf("Sum is %d\n",sum);
}
96 CHAPTER 6. CONTROL STRUCTURES
Program 6.41. To print the following pattern by inputting the number of lines to be
printed.
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
#include <stdio.h>
main()
{
int i, j, n;
printf("Enter the number of lines\n");
scanf("%d",&n);
for(i=n;i>=1;i--)
{
for(j=1;j<=i;j++)
printf("%d ",j);
printf("\n");
}
}
Program 6.42. To print the following pattern by inputting the number of lines to be
printed.
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
#include <stdio.h>
main()
{
int i, j, n;
printf("Enter the number of lines\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=i;j<=n;j++)
printf("%d ",j);
printf("\n");
}
}
6.5. PROGRAMMING EXAMPLES 97
Program 6.43. To print the following pattern by inputting the number of lines to be
printed.
5
4 5
3 4 5
2 3 4 5
1 2 3 4 5
#include <stdio.h>
main()
{
int i, j, n;
printf("Enter the number of lines\n");
scanf("%d",&n);
for(i=n;i>=1;i--)
{
for(j=i;j<=n;j++)
printf("%d ",j);
printf("\n");
}
}
Program 6.44. To print the following pattern by inputting the number of lines to be
printed.
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
#include <stdio.h>
main()
{
int i, j, n;
printf("Enter the number of lines\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=i;j>=1;j--)
printf("%d ",j);
printf("\n");
}
}
98 CHAPTER 6. CONTROL STRUCTURES
Program 6.45. To print the following pattern by inputting the number of lines to be
printed.
1 2 3 4 5 6 7
1 2 3 4 5
1 2 3
1
#include<stdio.h>
main()
{
int i, j, n;
printf("Enter the number of lines\n");
scanf("%d",&n);
for(i=2*n-1;i>=1;i-=2)
{
for(j=1;j<=i;j++)
printf("%d ",j);
printf("\n");
}
}
Program 6.46. To print the following pattern by inputting the number of lines to be
printed.
1
0 1
1 0 1
0 1 0 1
#include <stdio.h>
main()
{
int i, j, n;
printf("Enter the number of lines\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=i;j>=1;j--)
printf("%d ",j%2);
printf("\n");
}
}
Program 6.47. To print the following pattern by inputting the number of lines to be
printed.
6.5. PROGRAMMING EXAMPLES 99
1
234
56789
#include<stdio.h>
main()
{
int i, j, n, c, k=1;
printf("Enter the number of lines\n");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
for(j=n-i; j>=1; j--)
printf(" ");
for(c=1; c<=2*i-1; c++)
printf("%d",k++);
printf("\n");
}
}
Program 6.48. To print the following pattern by inputting the number of lines to be
printed.
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
#include<stdio.h>
main()
{
int i, j, n;
printf("Enter the number of lines\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=n;j>i;j--)
printf(" ");
for(j=1;j<=i;j++)
printf("%d ",j);
printf("\n");
}
}
Program 6.49. To print the following pattern by inputting the number of lines to be
printed.
100 CHAPTER 6. CONTROL STRUCTURES
1
123
12345
1234567
123456789
1234567
12345
123
1
#include<stdio.h>
main()
{
int i, j, k, n;
printf("Enter the number of lines\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=i;j<n;j++)
printf(" ");
for(k=1;k<(i*2);k++)
printf("%d",k);
printf("\n");
}
for(i=n-1;i>=1;i--)
{
for(j=n;j>i;j--)
printf(" ");
for(k=1;k<(i*2);k++)
printf("%d",k);
printf("\n");
}
}
Program 6.50. To print the following pattern by inputting the number of lines to be
printed.
*********
*******
*****
***
*
#include <stdio.h>
main()
{
6.5. PROGRAMMING EXAMPLES 101
int i, j, k, n;
printf("Enter the number of lines\n");
scanf("%d",&n);
for(i=n;i>=1;i--)
{
for(j=n;j>i;j--)
printf(" ");
for(k=1;k<(i*2);k++)
printf("*");
printf("\n");
}
}
Program 6.51. To print the following pattern by inputting the number of lines to be
printed.
A
AB
ABC
ABCD
ABCDE
#include <stdio.h>
main()
{
int i, n;
char j;
printf("Enter the number of lines\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j='A';j<='A'+i;j++)
printf("%c",j);
printf("\n");
}
}
Program 6.52. To print the following pattern by inputting the number of lines to be
printed.
EEEEE
DDDD
CCC
BB
A
102 CHAPTER 6. CONTROL STRUCTURES
#include <stdio.h>
main()
{
int i, j, n;
printf("Enter the number of lines\n");
scanf("%d",&n);
for(i=n;i>=1;i--)
{
for(j=1;j<=i;j++)
printf("%c",'A' + i-1);
printf("\n");
}
}