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

EST102: Programming in C: Control Structures

The document discusses different types of control structures in C programming including selection statements like if/else and switch statements as well as iteration statements like for loops. Selection statements allow selective execution of code based on conditions while iteration statements allow repeated execution of code. The document provides syntax and examples for each type of control structure.

Uploaded by

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

EST102: Programming in C: Control Structures

The document discusses different types of control structures in C programming including selection statements like if/else and switch statements as well as iteration statements like for loops. Selection statements allow selective execution of code based on conditions while iteration statements allow repeated execution of code. The document provides syntax and examples for each type of control structure.

Uploaded by

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

EST102 : Programming in C

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.

6.2 Selection statements


In this section, we explore several types of selection statements that allow a computer to
make choices.

6.2.1 One-way selection statement


The simplest form of selection is the if statement. This type of control statement is also
called a one-way selection statement, because it consists of a condition and just a single
block of statements. Here is the syntax for the if statement:
if(condition)
{
<block of statements>
}
If condition evaluates to True, the block of statements is run. Otherwise, control proceeds
to the next statement following the entire selection statement. The following code snippet
tests whether a variable is positive or not.

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.

6.2.2 Two-way selection statement


The if-else statement is the most common type of selection statement. It is called a
two-way selection statement, because it directs the computer to make a choice between two
alternative courses of action. Here is the C syntax for the if-else statement:
if(condition)
{
<block of statements-1>
}
else
{
<block of statements-2>
}
First the condition is tested. If it evaluates to True, then block of statements-1 will
be executed. Otherwise block of statements-2 will be executed. Since the condition
must be True or False, exactly one of the alternatives will be executed. The alternatives
are called branches, because they are branches in the flow of execution. See the following
example which checks if a person is major or minor.
if(age>=18)
printf("You are a major");
else
printf("You are a minor");
It is possible to nest (i.e., embed) if-else statements, one within another. This is called
two level nesting. There are several forms of two-level nesting. The most general form is
if(condition1)
{
if(condition2)
statement1;
else
72 CHAPTER 6. CONTROL STRUCTURES

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");
}

6.2.3 Multi-way selection statement


Sometimes there are more than two possibilities and we need more than two branches. The
process of testing several conditions and responding accordingly can be described in code
by a multi-way selection statement. This can be achieved in two ways:

6.2.3.1 if-else if-else ladder


This is also called if-else if-else staircase. The syntax is given below:
if(condition-1)
{
<block of statements-1>
}
else if(condition-2)
{
<block of statements-2>
}
.
.
.
6.2. SELECTION STATEMENTS 73

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);

6.2.3.2 switch statement


C has a built-in multiple-branch selection statement, called switch, which successively tests
the value of an expression against a list of values. When a match is found, the statements
associated with that value are executed. The general form of the switch statement is
switch(expression)
{
case value1:
block-1
break;
case value2:
block-2
break;
case value3:
block-3
break;
.
.
.
default:
block-default
}
74 CHAPTER 6. CONTROL STRUCTURES

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.

2. The case values should be constants. Variables are not allowed.

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!");
}

Here, the block of statements


printf("First alphabet");
break;

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.

6.3 Iteration Statements


In C, and all other modern programming languages, iteration statements (also called loops)
allow a set of instructions to be repeatedly executed. Each repetition of the set of statements
is known as a pass or an iteration. There are two types of loops – those that repeat an
action a predefined number of times (definite iteration) and those that perform the action
until a pre-determined condition becomes false (conditional iteration).

6.3.1 for loop


The for loop generally implements definite iteration. This type of loop increments or
decrements the value of a variable called loop-variable each time the loop is repeated. The
general form of the for statement is
for(initialization;condition;update)
{
block of statements
}
The initialization is an assignment statement that is used to set the loop control vari-
able. The condition is a relational expression that determines when the loop exits. The
update defines how the loop control variable changes each time the loop is repeated. The
block of statements associated with the loop is called loop body. The condition is tested
at the beginning of each pass through the loop and the loop body continues to execute
as long as the condition is True. Once the condition becomes False, program execution
resumes with the statement following the for loop.
76 CHAPTER 6. CONTROL STRUCTURES

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.

6.3.1.1 for loop variations


The previous discussion described the most common form of the for loop. However, several
variations of the for loop are allowed that increase its power, flexibility, and applicability
to certain programming situations.
One of the most common variations is to allow two or more variables to control the loop.

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.

Example 6.3. Consider the portion of a program:


main( )
{
int i = 1;
for(;i <= 10;)
{
printf("%d\n", i);
i = i + 1 ;
}
}

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

6.3.2 while loop


The while statement is used to carry out looping operations, in which a group of statements
is executed repeatedly, as long as some condition is satisfied. The general form of the while
statement is
while(condition)
{
<block of statements>
}
The form of this statement is almost identical to that of the one-way selection statement.
However, the use of the reserved word while instead of if indicates that the sequence of
statements might be executed many times, as long as the condition remains True.

Example 6.5. Suppose we want to display the consecutive digits 0, 1, 2, · · · ,9 with


one digit on each line. This can be accomplished with the following program.
#include<stdio.h>
main()
{
int digit = 0;
while(digit <= 9)
{
printf("%d\n", digit);
digit++;
}
}

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.

6.3.3 do-while loop


As we have seen, for and while loops test the loop condition at the beginning of the loop.
For this reason they are called entry-controlled loops. On the other hand, the do-while
loop is an exit controlled loop and checks its condition at the end of the loop. This means
that a do-while loop always executes at least once. The general form of the do-while
loop is
do
{
<block of statements>
}while(condition);
The do-while loop iterates until condition becomes False.
6.4. JUMP STATEMENTS 79

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);

6.3.4 Nested loops


It is possible to embed a loop inside another loop. The enclosing loop is called outer loop
and the other loop is called inner loop. For each iteration of the outer loop, the inner loop
executes to completion (all the iterations are performed). The following code prints first 10
multiples of numbers from 1 to 5.
#include <stdio.h>
main()
{
int i,j;
for(i=1;i<=5;i++) //outer loop
{
for(j=1;j<=10;j++) //inner loop
printf("%d ",i*j);
printf("\n");
}
}

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

6.4 Jump statements


The loop statements provide the capability of conditional branching, i.e., taking branches
based on the outcome of testing a condition. C has four statements that perform uncon-
ditional branching: return, goto, break and continue. We postpone the treatment of
return until the discussion of functions. Other three are discussed below:
80 CHAPTER 6. CONTROL STRUCTURES

6.4.1 goto statement


The goto statement is used to alter the normal sequence of program execution by transfer-
ring control to some other part of the program. In its general form, it is written as
goto label;
where label is an identifier that is used to label the target statement to which control will
be transferred. Control may be transferred to any other statement within the program.
The target statement must be labeled, and the label must be followed by a colon. Thus,
the target statement will appear as
label: statement
In this context, it is to be noted that no two statements can have the same label.
Example 6.7. The following code fragment prints the numbers from 1 to 100 using the
goto and a label:
x = 1;
loop1:
printf("%d ",x);
x++;
if(x <= 100)
goto loop1;

6.4.2 break statement


The break statement has two uses. You can use it to terminate a case in the switch
statement. You can also use it to force immediate termination of a loop. Any statement
inside the loop following the break will be neglected and the control goes out of the loop.
break stops the current iteration and skips the succeeding iterations (if any) and passes
the control to the first statement outside the loop. This is illustrated in the following code:
#include<stdio.h>
main()
{
int num;
for(num=1;num<5;num++)
{
if(num%2==0)
{
printf("%d is even\n",num);
break;
}
printf("The number is %d\n",num);
}
printf("Outside the loop\n");
6.5. PROGRAMMING EXAMPLES 81

}
This code produces the output:
The number is 1
2 is even
Outside the loop

6.4.3 continue statement


The continue statement is used to bypass the remainder of the current iteration through
a loop. The loop does not terminate when a continue statement is encountered. Rather,
the remaining loop statements are skipped and the computation proceeds directly to the
next pass through the loop. See the code below:
#include<stdio.h>
main()
{
int num;
for(num=1;num<5;num++)
{
if(num%2==0)
{
printf("%d is even\n",num);
continue;
}
printf("The number is %d\n",num);
}
printf("Outside the loop\n");
}
The code above produces the output:
The number is 1
2 is even
The number is 3
4 is even
Outside the loop

6.5 Programming examples


Program 6.11. To find the absolute value of an integer.

#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);
}

Program 6.12. To check if the input number is a multiple of 7.

#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);
}

Program 6.13. To check if the input character is an alphabet.

#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);
}
}

Program 6.14. To find the smallest of two numbers.

#include <stdio.h>
main()
{
6.5. PROGRAMMING EXAMPLES 83

int num1, num2;


printf("Enter any two numbers:\n");
scanf("%d %d", &num1, &num2);
if(num1 < num2)
printf("%d is minimum\n", num1);
else
printf("%d is minimum\n", num2);
}

Program 6.15. To determine the maximum of three numbers.

#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

amt = (50*0.5) + ((units-50)*0.75);


else // units <= 250 but >150
amt = (50*0.5) + (100*0.75) + ((units-150)*1.20);
if(amt>300)
surcharge = amt*0.20;
bill = amt+surcharge;
printf("Electricity bill is Rs. %.2f\n", bill);
}
Program 6.17. To input marks of five subjects of a student and then determine the grade
according to following grade rule:
Percentage Grade
≥ 90 S
≥ 80 but < 90 A
≥ 70 but < 80 B
≥ 60 but < 70 C
≥ 50 but < 60 D
≥ 40 but < 50 E
< 40 F

#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

2. if year is divisible by 100, then it should be divisible by 400 too

The second condition is equivalent to writing

2. year is divisible by 400

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

printf("Largest number is: %d\n",big);


}

Program 6.22. To print the factorial of a number.

#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);
}

Program 6.23. To check if the input number is a prime or not.

#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

whose value is equal to the sum of its factors.


#include<stdio.h>
main()
{
int n,sum=0,i;
printf("Enter a number\n");
scanf("%d",&n);
for(i=1;i<=n/2;i++)
{
if(n%i==0)
sum=sum+i;
}
if(sum==n)
printf("%d is a perfect number\n",n);
else
printf("%d is not a perfect number\n",n);
}
Program 6.25. To determine the sum of n input numbers.

#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);
}
}

Program 6.28. To determine the LCM of two numbers.

#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);
}

Program 6.29. To determine the HCF of two numbers.

#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);
}

Program 6.30. To add the digits of a number.

#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);
}

Program 6.31. To print the reverse of a number.

#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);
}

Program 6.32. To check if a number is palindrome or not.

#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);
}

Program 6.33. To check if a number is an Armstrong number or not. An n digit number


is an Armstrong number if it is equal to the sum of the nth power of its digits. For example,
153 is an Armstrong number as 153 = 13 + 53 + 33 . [Since 153 is a three digit number, we
take the cube of each digit.]
#include <stdio.h>
#include<math.h>
int main()
{
int number, num, remainder, result = 0, n=0;
printf("Enter a number\n");
scanf("%d", &number);
92 CHAPTER 6. CONTROL STRUCTURES

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

Program 6.35. To print the first n terms of Fibonacci series.

#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;
}
}
}

Program 6.36. To print the prime numbers in a given range.

#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");
}
}

You might also like