Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

CHAPTER - 4

Control Structures in C

4.1 Introduction
As the name suggests the "Control Instruction" enables us to specify the order in which the
various instructions in a program are to be executed by the computer. In other words the control
instructions determine the "flow of control" in a program. There are 4 types of control
instructions in C. They are:
 Sequence Control Instruction
 Selection or Decision Control Instruction
 Repetition or Loop Control Instruction
 Case Control Instruction

The sequential structure consists of a sequence of program statements that are executed one after
another in order. The selective structure consists of a test for a condition followed by alternative path
that the program can follow. The repetitive structure consists of program statements that are
repeatedly executed while some condition hold true. In case control structure, among multiple cases,
only one condition will executed that hold the condition true.

Selection or Decision Control Instruction (Condition Expression)


The statements that make selection of settlements to be executed are called selection statement or
branching statement. The conditional expression is mainly used for decision making. In subsequent
sections, the various structures of the control statements and their expression are explained. The
following statements are used to perform the task of the conditional operations

i) if statement: The "if" statement is used to express conditional expressions. If the given
condition is true then it will execute the statements; otherwise it will execute optional
statements. The braces { and } are used to group declarations and statements into compound
statement or a block.

Syntax:
if(condition)
{
//set of stmt1
………………
………………
}
//set of stmt2
…………………
…………………

- If the condition is true set of statement stmt1 is executed and then after only statement set
stmt2 are executed otherwise statement set stmt1 are skipped and directly statement set stmt2
is executed.

Example:
#include <stdio.h>
#include <conio.h>

int main()
{
int marks;
clrscr();
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 1

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


printf("Enter marks of a student\n");
scanf("%d",&marks);
if(marks>35)
{ //if the condition marks>35 is true this message is displayed in monitor
printf("Student is passed\n");
}
if(marks<35)
{ //if the condition marks>35 is true this message is displayed in monitor
printf("Student is Failed:\n");
}
getch();
eturn 0;
}

ii) if..else statement: In this case, either of the two statement is executed depending upon the value
of the expression. The first statement is executed if the expression is true; otherwise the else
statement is executed.

Syntax:
if(condition)
{
//statement set1
}
else
{
//statement set2
}

Example: WAP to find a number which is even or odd.


#include <stdio.h>
#include <conio.h>
int main()
{
int n;
clrscr();
printf("Enter a number\n");
scanf("%d",&n);
n = n%2;
if(n==0)
printf("The number is even\n");
else
printf("The number is odd \n");
getch();
return 0;
}

Example: A program to read any two numbers from the keyboard and to display the larger
value.
#include <stdio.h>
#include <conio.h>
void main()
{
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 2

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


float x,y;
clrscr();
printf("Enter first number:");
scanf("%f",&x);
printf("Enter second number:");
scanf("%f",&y);
if(x>y)
printf("Larger value is %f",x);
else
printf("Larger value is %f",y);
getch();

iii) Nested if- else statements: The if..else statement which is again inside if..else statements, is
called nested if..else statements which are as follows.

Syntax: 1
if (expression)
{
if(expression)
{

} Syntax: 2
else
{ if(expression)
if(expression)
} __________
} else
else __________
{ else
if(expression) _____________
{

}
else
{
}
}

Example: WAP to find the largest number among 3 numbers.


#include <stdio.h>
#include <conio.h>
void main()
{
float x,y,z;
clrscr();
printf("Enter first number:");
scanf("%f",&x);
printf("Enter second number:");
scanf("%f",&y);
printf("Enter third number:");
scanf("%f",&z);
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 3

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


if(x>z)
{
if(x>y)
printf("Largest value is %f",x);
else
printf("Largest value is %f",y);
}
if(z>x)
{
if(z>y)
printf("Largest value is %f",z);
else
printf("Largest value is %f",y);
}
getch();
}

Example: WAP to find the largest value among four numbers.


#include <stdio.h>
#include <conio.h>
void main()
{
float a,b,c,d;
clrscr();
printf("Enter any four numbers:");
scanf("%f %f %f %f",&a,&b,&c,&d);
if(a>b)
{
if(a>c)
{
if(a>d)
printf("Largest value is %f",a);
else
printf("Largest value is %f",d);
}
}
if(c>a)
{
if(c>b)
{
if(c>d)
printf("Largest value is %f",c);
else
printf ("Largest value is %f",d);
}
}
if(b>a)
{
if(b>c)
{
if(b>d)
printf("Largest value is %f",b);
else
printf("Largest value is %f",d);
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 4

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


}
}

getch();
}

iv) “if … else if” ladder: In else if ladder (or multi-way conditional statements), the condition
expression is evaluated in order. If any of these expressions is formed to be true, the statement
associated with it is executed and this terminates the whole chain. If none of the expression is
true then the statement associated with final else is executed.

Syntax:
if(condition)
{

}
else if
{

else if
{

}
else
{
//default statement
}

Example:
#include <stdio.h>
#include <conio.h>

int main()
{
int marks;
clrscr();
printf("Enter marks of a student\n");
scanf("%d",&marks);
if(marks>60)
{
printf("Student is passed in first division:\n");
}
else if(marks>45)
{
printf("Student is passed in second division:\n");
}
else if(marks>32)
{
printf("Student is passed in third division:\n");
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 5

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


}
else
{
printf("Student is failed:\n");
}
getch();
return 0;
}

Example: An electricity board charges according to following rates.


For the first 100 units---------------Rs. 40 per unit
For the next 200 units---------------Rs. 50 per unit
Beyond 300 units---------------------Rs. 60 per unit
All users are charged meter charge also, which is also Rs. 50. Write a program to read the
number of unis consumed, and print out the charges.

#include<stdio.h>
#include<conio.h>
#define meter_charge 50
void main()
{
int units;
float amt,amt_rupees=0;
clrscr();
printf("\n***Electricity Amount calaulating program***\n");
printf("How many units of electricity used?");
scanf("%d",&units);
if(units>300)
amt_rupees=(units-300)*60+200*50+100*40;
else if(units>100)
amt_rupees=(units-100)*50+100*40;
else
amt_rupees=units*40;
amt=amt_rupees+meter_charge;
printf("\nThe payable amount is %.2f",amt);
getch();
}

Assignments
 Write a program to calculate the income tax and net salary having following condition.
If salary>=9000 income tax is 40% of salary
If salary>=7500 and salary<=8999 then income tax is 30% of salary
If salary<=7499 then income tax is 20% of salary

Note: WAP to find the largest and smallest number among 3 user entered numbers.
#include <stdio.h>
#include <conio.h>
void main()
{
int a, b, c, x, y;
clrscr();
printf("Enter any three numbers:");
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 6

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


scanf("%d%d%d",&a, &b, &c);
x = a>b?(a>c?a:c):(b>c?b:c);
printf("The largest number is:%d”, x);

y = a<b?(a<c?a:c):(b<c?b:c);
printf("The largest number is:%d”, y);
getch();
}

Case Control Instruction (Switch-Case statement)


The switch statement is a special decision maker that tests whether expression matches one of the
numbers of constant values, and braces accordingly. In switch statements, the float values are not
used i.e. only the integer and characters are in use. Note that the sequential arrangement of cases is
not necessary. The syntax of suitable statement is:

Syntax:-
switch(variable)
{
case 1:
//statement set1
……………..
break;

case 2:
//statement set2
……………..
break;

case n:
//statement set_N
……………………
break;
default:
//default statement set
…………..
break;
}

Example: WAP to determine whether a user entered number is Odd or Even.


#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("Enter any number\n");
scanf("%d",&a);
a=a%2;
switch(a)
{
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 7

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


case 0:
printf("The number is even\n");
break;

default:
printf("The number is odd");
}
getch();
return 0;
}

Example: WAP to find the day on entering a number less than or equal to 7.
#include<stdio.h>
#include<conio.h>

int main()
{
int day;
clrscr();
printf("Enter numeric day of the week:\n");
scanf("%d",&day);
switch(day)
{
case 1:
printf("Day is Sunday\n");
break;

case 2:
printf("Day is Monday\n");
break;

case 3:
printf("Day is Tuesday\n");
break;

case 4:
printf("Day is Wednsday\n");
break;

case 5:
printf("Day is Thursday\n");
break;

case 6:
printf("Day is Friday\n");
break;

case 7:
printf("Day is Saturday\n");
break;

default:
printf("Your choice is wrong!!!!!!!!");
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 8

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


break;
}
getch();
return 0;
}

Q. Write a program to calculate value of Celsius to Fahrenheit and vice-versa.


#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
float celcius,farenheit;
int choice;
clrscr();
printf("***Temperature converting program***\n");
printf("1) celcius to farenheit\n");
printf("2) farenheit to celcius\n");
printf("3) Exit\n");
printf("Enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter the value of celcius:");
scanf("%f",&celcius);
farenheit=(celcius-9/5)+32;
printf("Your equivalent farenheit is
%.2f",farenheit);
break;
case 2:
printf("Enter the value of farenheit:");
scanf("%f",&farenheit);
celcius=(farenheit-32)+5/9;
printf("Your equivalent celcius is %.2f",celcius);
break;
case 3:
exit(0);
default:
printf("Invalid choice");
}//end switch-case
getch();
}//end main()

Q. Write a program to calculate area or perimeter of a rectangle.


#include<stdio.h>
#include<conio.h>
void main()
{
float length,breadth,Area,P;
int choice;
clrscr();
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 9

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


printf("Enter the value of length & breadth:");
scanf("%f %f",&length,&breadth);
printf("\n ***Area & Perimeter calculating program***\n");
printf("1> Area\n");
printf("2> Perimeter\n");
printf("Enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
Area=length*breadth;
printf("The area is %f",Area);
break;
case 2:
P=2*(length+breadth);
printf("The Perimeter is %f",P);
break;
}//end-switch case
getch();
}//end main()

Assignment: Write a program using switch case to calculate area and circumference of a circle.

Repetition or Loop Control Statements


The computer has the ability to perform a set of instructions repeatedly. This involves repeating
some portion of a program either for a specified number of times or until a given condition is
satisfied. This repetitive operation is done a loop control statement.

Suppose we need to display the natural number series 1 2 3 and suppose we do not know about loop
then probably we will draw a flowchart-1. Here to print 1 2 3 you used the statements “X=x+1 and
print value of x” three
times. If you would
have to print 1 2 3
4….100 then you
would have to write the
above statements 100
times. Do you think it
is a tedious task? Yes
of course it is a tedious
job. But don’t be afraid,
here Dennis Ritchie has
developed a tool called
loop to solve this
problem. C has
provided you a
mechanism to repeat
X=x+1 and print ‘x’ till
you want.
Take a look at the
flowchart-2.

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 10

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


There are three methods for generating repetition of a certain part of the program
 for statement
 while statement
 do…while statement

a) for loop: The for loop is mostly used loop for repetitive structure and is an entry control loop.
The for loop consists of three expressions. The first expression issued to initialize the index
value, the second to check whether the loop is to be continued again and third to change the
index value for further repetition.

Syntax: for(initialization; test condition;


increment or decrement)

Example: for( count = 0; count < 5; count++)

Example: A program to display the numbers from 0 to 10 using for loop.


#include <stdio.h>
void main()
{
int i=0;
clrscr();
for(i=0;i<=10;i++)
printf("%d\n",i);
getch();
}

Example: WAP to print all even numbers from 0 to 20.


#include <stdio.h>
#include <conio.h>
void main()
{
int i=0;
clrscr();
for(;i<=20;)
{
printf("%d\t",i);
i=i+2;
}
getch();
}

Example: WAP to count all the integers greater than 100 and less than 200 that are divisible by
7. Also find the sum of these numbers.
#include <stdio.h>
#include <conio.h>
void main()
{
int i, count=0, sum=0;
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 11

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


clrscr();
for(i=101;i<200;i++)
{
if (i%7 ==0)
{
sum = sum + i;
count = count + 1;
}
}
printf("The sum is = %d\n",sum);
printf("The count is = %d",count);
getch();
}

Example: A program to create the multiplication table of a number.


#include <stdio.h>
#include <conio.h>
void main()
{ int a,b,c;
clrscr();
printf("Enter a number:");
scanf("%d",&a);
for(b=1;b<=10;b++)
{
c=a*b;
printf("\n%d * %d=%d",a,b,c);
}
getch();
}

Nested Loops: If we define loop insides a loop, such loops are called nested loops. For example:
for(i=0;i<10;i++)
{
for(j=0;j<5;j++) //nested loop
{
…………
}
}

b) while loop statement: The second type of loop statement is while loop. While loop first checks
whether the initial condition is true or false and finding it to be true, it will enter the loop and
execute the statement. Thus, it is also an entry control loop (perform pre-test).

Syntax:
initialization;
while(test condition)
{
Statement 1;

Statement n;
increment or decrement;
}

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 12

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


Difference between for loop and while loop
for Loop while Loop
1 It is definite loop i.e. exact number of 1 It may be definite and may not be definite.
iterations.
2 The loop expression is within a one block. 2 The loop expression is scattered throughout the
program.
3 It is used the keyword for. 3 It is use the keyword while.
4 For example: 4 For example:
void main() void main()
{ int n; { int n=10;
for(n=0;n<10;n++) while(n!=0)
printf("Nepal"); { printf("Nepal");
} n--; }

Q. Program to print 10 natural numbers.


void main()
{ int number=1;
while(number<=10)
{
printf("%d\t",number);
number++;
}
getch();
}

Q. Write a program to find factorial using while loop.


#include<stdio.h>
#include<conio.h>
void main()
{ long int fact;
int n,k;
clrscr();
printf("\n FACTORIAL USING WHILE LOOP\n");
printf("Enter the number:");
scanf("%d",&n);
fact=1;
k=n;
while(n>1)
fact=fact*n--;
printf("Factorial of %d is %ld",k,fact);
getch();
}

OR
Q. Program to calculate factorial using while loop.
#include<stdio.h>
#include<conio.h>
void main()
{
int a=1,n;
long float fact=1;
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 13

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


clrscr();
printf("Enter the value for n:");
scanf("%d",&n);
while(a<n)
{ a++;
fact*=a;
}
printf("Factorial of given no. is: %.2lf",fact);
getch();
}

c) do…while loop statement: The do...while loop is another repetitive loop used in C programs.
Differ from the for loop and while loop, the do…while loop is an exit control (post-test) loop.
Thus, the while loop tests the condition before executing any of the statements inside the while
loop but the do…while loop test the condition after executing the statements. This means that
the do…while would execute its statements at least one even if the condition fails for first time
itself. The while loop on the other hand will not execute its statements if the condition fails for
the first times.

Syntax:
do
{
Statement 1;
...
Statement n;
}
while(condition);

Difference between while loop and do-while loop


while Loop do-while Loop
1 The while loop is entry controlled loop. 1 The do-while loop is exit control loop.
2 It has a keyword while. 2 It has two keyword do and while.
3 Loop is not terminated with semicolon. 3 Loop is terminated with a semicolon.
4 It doesn't execute the body of loop until and 4 Body of the loop will always executed at least
unless the condition is true. once since the test condition is not checked until
the end of the loop.
5 Example: Print “Hello” 5 Example: Print “Hello”

void main() void main()


{ {
int i=0; int i=0;
while (i>=4) do
{ {
printf(“Hello \n”); printf(“Hello \n”);
i++; i++;
} }
} while (i>=4);
}
Output: Noting will display. Output: Hello

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 14

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


Example: A program to find the sum of odd numbers using do..while loop.
#include <stdio.h>
#include<conio.h>
void main()
{
int n,sum=0,i=1;
clrscr();
printf("Enter the value of n:");
scanf("%d",&n);
do
{
sum+=i;
i+=2;
}while(i<=n);
printf("The sum of odd number is %d",sum);
getch();
}

Breaking control statements

A. Continue statement
Continue statement is used to bypass the execution of the statements inside the loop. In some
situations we want to jump to the next iterations of the loop the loop by ignoring the execution of
statements specified within the body of loop. The keyword “continue” allows us to do this. When
the keyword is encountered inside the loop, control automatically passes to the next iteration of
the loop. A continue specified using if () statement. As an example, consider the following
program:

Example:
main()
{
int i;
for (i =1; i<=5;i++)
{
If (i==3)
continue;
printf(“%d”,i);
}
getch();
}

The output of the following program would be: 1 2 4 5


Thus, continue statement is used to skip a part of the body of loop and continue with next
iteration. Note that when the value of i equal to 3, the continue statement takes the control to the
next iteration by passing the execution of the printf() statement. consider another program:

Example:
main()
{
int n, sum=0;
printf(“enter a number and press 0 to stop:”);
do
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 15

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


{
Scanf(“%d”,&n);
If (n<0)
continue;
sum = sum +n;
}while (n!=0);
Printf(“The sum of positive number = %d”,sum);
getch();
}

The output of the program would be: enter a number and press 0 to stop: 1 2 – 3 4 -5 0
The sum of positive number is = 7. Note that the negative numbers are not added to the sum
because when the value of n is less than 0 (i.e. negative) the continue statement bypass the
execution of the sum = sum +n.

B. Break Statement
The break statement is used as a statement inside the body of loop. Generally the break statement
is associated with a condition specified with if () statement. As soon as the condition evaluates
within if (), the execution of break statement takes the control outside the loop and therefore
stops the further iterations of the loop. As an example, consider the following program:

Example:
void main() In this program, when i=3, the
{ execution of the break
int i; statement terminates the loop
for (i =1; i<=5;i++) and the output of the program
{ would be:
Printf(“%d”,i); 123
If (i==3)
Loop terminates here
break;
In the above program, the
}
printf(“%d”,i); is placed
printf(“\n loop terminates here”);
before break .
getch();
}

Do you think that placing printf(“%d”,i); statement after break statement will make a difference?
Here is the program:

Example: In this program, when i=3, the


void main()
break statement terminates the
{
loop and the program control
int i;
is jumped out from the loop
for (i =1; i<=5;i++)
without executing the
{
printf(“%d”,i); statement. The
If (i==3)
output of the program would
break;
Printf(“%d”,i); be:
} 12
printf(“\n loop terminates here”); Loop terminates here
getch();
}

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 16

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


Consider another program, to understand break statement.
Example:
main()
{
int n, sum=0;
printf(“enter numbers:”);
while(1)
{
Scanf(“%d”,&n);
If (n<0)
break;
sum = sum +n;
}
Printf(“The sum of positive number is = %d”,sum);
getch();
}

This program invites the user to enter positive numbers. It also finds the summation of these
numbers. As soon as user enters a negative number, the loop is terminated by the break
statement. Let us take a look at the sample output: Enter numbers: 1 2 3 4 5 -1
Sum of positive numbers is = 15

Q. What is the similarity and difference between break and continue statements?
 Similarity: Both break and continue are jump statements.
 Difference: The break statement terminates the entire loop execution whereas continue
statement terminates single pass of the loop.

C. goto statement
The goto statement is used to alter the program execution sequence by transferring the control to
some other part of the program.

Q. Program to demonstrate the usage of goto statement.

#include <stdio.h>
void main()
{
int a,b;
printf("Enter two numbers:");
scanf("%d %d",&a,&b);
if(a>b)
goto output1;
else
goto output2;
output1:
printf("Largest value=%d",a);
goto stop;
output2:
printf("Largest value=%d",b);
goto stop;
stop:
;
}

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 17

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


LAB SESSION

A. For loop Programs

Q. A program to find the sum and the average of given numbers.


#include <stdio.h>
void main()
{
int n,i;
float sum=0.0,a,average;
clrscr();
printf("How many numbers you want?");
scanf("%d",&n);
for(i=0;i<=n-1;i++)
{
printf("Enter a number:");
scanf("%f",&a);
sum+=a;
}
average=sum/n;
printf("Sum=%f",sum);
printf("\nAverage= %f",average);
getch();
}

Q. A program to display the Fibonacci series.


Method-I: Method-II:
#include <stdio.h> void main()
#include <conio.h> {
void main() int n, a=1, b=1, c, i;
{ printf(“How many terms?”);
int scanf(“%d”,&n);
fibo,fibo1=0,fibo2=1,num,i; printf(“%d\t%d”, a, b);
clrscr(); for(i=1; i<=n-2; i++)
printf("How many terms?"); {
scanf("%d",&num); c=a+b;
printf("%d\t%d",fibo1,fibo2); printf(“%d\t”,c);
for(i=2;i<num;i++) a=b;
{ b=c;
fibo=fibo1+fibo2; }
fibo1=fibo2; getch();
fibo2=fibo; }
printf("\t%d",fibo);
}
getch();
}

Q. If two numbers n1 & n2 are input through the keyboard. WAP to find sum of those
numbers which is exactly divisible by 5 between n1 and n2.
void main()
{
int n1, n2, sum=0, i;
printf(“enter n1 & n2”);
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 18

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


scanf(“%d%d”,&n1, &n2);
for(i=n1; i<=n2; i++)
{
if(i%5==0)
sum=sum+i;
}
printf(“required sum=%d”,sum);
getch();
}

Q. If an integer is input through the keyboard, WAP to find its factorial.


void main()
{ Write the same program using break statement.
int n, i, long fact=1; void main () 1 1
printf(“enter a {
number”); int i, n, fact=1;
scanf(“%d”, &n); printf(“enter a number”);
if(n==0) scanf(“%d”, &n);
printf(“factorial=1”); i=1;
else while(1)
{ {
for(i=1; i<=n; i++) fact=fact*i;
fact=fact*i; i++;
printf(“the factorial of if(i>n)
%d is %d”, n, fact); break;
} }
getch(); printf(“factorial=%d”,fact);
} }

Q. A program to generate number in pyramid format.


#include<stdio.h>
void main()
{
int p,q,a,k,l;
clrscr();
printf("\nEnter the value for pyramid:");
scanf("%d",&a);
for(p=1;p<=a;p++) /*for a row implement*/
{
for(q=a;q>p;q--) /*for the space(s)*/
printf(" ");
for(k=1;k<=p;k++) /*for previously printed
number*/
printf("%d",k);
for(l=p-1;l>=1;l--) /*for printing new nos.*/
printf("%d",l);
printf("\n");
}
getch();
}

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 19

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


B. While loop program

Q. Write a program to check whether the given number is prime number or not.

Method-I:
#include <stdio.h> Method-II:
#include <conio.h> main()
void main() {
{ int n, i, c=0;
int num,i; printf(“enter a number”);
clrscr(); scanf(“%d”&n);
printf("Enter the number:"); i=2;
scanf("%d",&num); while(i<=n-1)
i=2; {
while(i<=num-1) if(n%i==0)
{ c++;
if (num%i==0) i++;
{ }
printf("Not a prime no"); if(c==0)
break; printf(“The number is prime”);
} else
i++; printf(“The number is
} composite”);
if(i==num) getch();
printf("Prime number"); }
getch();
}

Q. If a 4 digit number is input through the keyboard. WAP to check whether it is palindrome
or not. Hind: A number is palindrome if it is equal to its reverse. For example: 4224 is palindrome
but 4223 is not palindrome. To check whether a number is palindrome or not, first we should find the
reverse of a number and check whether it is equal to its reverse or not.
Method-II:
Method-I: main()
void main() {
{ int n, rev=0, y, d;
int n, rev=0, y, d; printf(“enter a no”);
printf(“enter a number”); scanf(“%d”,&n);
scanf(“%d”,&n); y=n;
y=n;
while(n!=0) while(1)
{ {
d=n%10; d=n%10;
rev=rev*10+d; rev=rev*10+d;
n=n/10; n=n/10;
} if(n==0)
break;
if(y==rev) }
printf(“the number is palindrome”);
else
printf(“the number is not palindrome”);
getch();
}
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 20

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


Q. WAP to print all ASCII values & their equivalent characters using a while loop.
void main()
{
int i;
i=0;
while(i<=255)
{
printf(“%d\t%c”,i,i);
i++;
}
getch();
}

PROGRAMMING EXAMPLES OF NESTED LOOP

Q. WAP to print the following output:


1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

void main()
{
int i, j;
for(i=1; i<=5; i++)
{
for(j=1; j<=i; j++)
printf(“%d\t”,j);
printf(“\n”);
}
getch();
}

Q. WAP to print the following output:


1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
main()
{ LOGIC
int i, j; Note: printf(“%d”, i);
for(i=5; i>=1; i--) 5 5 5 5 5
{ 4 4 4 4
for(j=1; j<=i; j++) 3 3 3
printf(“%d\t”,j); 2 2
printf(“\n”); 1
}
getch();
}
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 21

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


Q. WAP to print the following output
A B C D E D C B A
A B C D D C B A
A B C C B A
A B B A
A A

void main()
{
int i=1, b=0, x, v;
x=69; /*ASCII value of E */
while(i<=5) /*for five lines*/
{
j=65; /*ASCII value of A*/
v=x; /*assign x to v*/
while(j<=v)
{
printf(“%c”, j); /*print ASCII character of j*/
j++;
}
if(i==1)
v--;
k=1;
while(k<=b)
{
printf(“ “); /*for blank*/
k++;
}
b=2*i-1;
while(v>=65)
{
printf(“%c”, v);
v--;
}
printf(“\n”);
x--;
i++;
}
getch();
}

Q. WAP to print the following output:


1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
void main()
{
int i, j, m;
for(i=1; i<=5; i++)
{
for(j=1; j<=5; j++)
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 22

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


{
m=i*j;
printf(“%d”,m);
}
}
}

Q. WAP to print following output:


1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5

void main()
{
int p, q, m, n=5; /*n for no. of lines (5 lines)*/
for(p=1; p<=n; p++)
{
for(q=1; q<=n-p; q++) /*to print space*/
printf(“ “);
m=p;
for(q=1; q<=p; q++) /*to print numbers*/
{
printf(“%d”,m);
m=m+1;
}
m=m-2;
for(q=1; q<p; q++)
{
printf(“%d”,m);
m--;
}
}

Q. WAP to find: sum= 1 + 2/2! + 3/3! + ………………….. + n/n!


main()
{
int n, fact, i, j, sum=0;
printf(“enter the last term”);
scanf(“%d”, &n);
i=1;
while(i<=n)
{
fact=1; j=1;
while(j<=i)
{
fact=fact*j;
j++;
}
sum=sum + i/fact;
i++;
}
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 23

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


getch();
}

Q. WAP to print prime numbers between ranges given by user.


void main()
{
int n1, n2, i, j, c;
printf(“enter the range”);
scanf(“%d %d”, &n1, &n2);
i=n1;
while(i<=n2)
{
j=2; c=0;
while(j<=i-1) //Note: Trace the program for n1=5 & n2=100
{
if(i%j==0)
c++;
}
if(c==0)
printf(“%d”, i);
i++;
}
getch();
}

Q. WAP to compute exponential series: 1 + x + x2/2! + x3/3! + ……………… + xn/n!


void main()
{
int i, n, fact;
float x, sum=1;
printf(“enter value of x & n”);
scanf(“%f %d”, &x, &n);
i=1;
while(i<=n)
{
fact=1;
j=1;
while(j<=i)
{
fact=fact*j;
j++;
}
sum=sum + pow(x, i)/fact;
i++;
}
printf(“sum=%f”, sum);
}

Exercise: WAP to compute the


 sine series: x – x3/3! + x5/5! – x7/7! + ……… xn/n!
 cosine series: 1 – x2/2! + x4/4! – x6/6! + ……………… + xn/n!
 WAP to display all Armstrong numbers between a given range.
 WAP to find the factorial of all numbers between a range of two given numbers.
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 24

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


 WAP to check whether a number is Armstrong or not
 WAP to display all perfect numbers between a range given by user.

Q. WAP to check whether a no. is perfect or not.


void main()
{ Note: If the sum of exact
int n, sum=1; i=2; dividers of a given number
printf(“enter a number”); is equal to the original
scanf(“%d”, &n); number, then such number
while(1) is called a perfect number.
{
if(n%i==0) For example:
sum=sum+i; 28 = 1+2+4+7+14 = 28.
if(i==n/2) Therefore, 28 is a perfect
break; number.
i++;
}
if(n==sum)
printf(“the number is perfect number”);
else
printf(“the number is not a perfect number”);
getch();
}

Q. WAP to calculate the binary equivalent of a decimal number


void main()
{
int n, base=1, r, y;
long int sum=0;
printf(“enter a decimal number”);
scanf(“%d”, &n);
y=n;
while(1)
{
r=n%2;
sum=sum+r*base;
base=base*10;
n=n/2;
if(n==0)
break;
}
printf(“The binary equivalent of %d is %d”, y, sum);
getch();
}

Q. WAP to print the following output:

1
2 3
4 5 6
7 8 9 10

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 25

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


void main()
{
int i, j, k, l, s;
s=20;
for(i=1, k=1; i<5; i++)
{
for(l=1; l<=s; l++)
printf(“ “);
s=s-2;
for(j=1; j<=i; j++, k++)
printf(“%d”, k);
printf(“\n”);
}
getch();
}

Exercise: WAP to print the following Pascal’s Triangle

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Exercise: WAP to read two integers n1 & n2 and display sum of even & odd numbers between the
two nos. separately.

Q. WAP to read an integer no. & add the individual digits contained in it until the final sum is
a single digit. For e.g. if the number is
n=35876, then
3+5+8+7+6=29
2+9=11
1+1=2
void main()
{
long int n;
int r, sum=0;
scanf(“%d”, &n);
do
{
sum=0;
do
{
r=n%10;
sum=sum+r;
n=n/10;
} while(n!=0);
n=sum;
} while(sum/10!=0);
printf(“%d”, sum);
getch();
}
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 26

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


Q. WAP to compute & print the following terms:

12+22/3, 22+32/4, 32+42/5, 52+62/7, 62+72/8

main()
{
int l, i;
float t;
l=1
while(i<=5)
{
t= pow(i, 2)+pow((i+1), 2)/(float)(i+2);
printf(“%f\t”, t);
l++;
}
getch();
}

Q. WAP to print Floyd’s triangle. A Floyd’s triangle is a right angled triangular array of
numbers arranged as follow:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

void main()
{
int i, j, n=1;
for(i=1; i<=5; i++)
{
for(j=1; j<=i; j++)
printf(“%d”, n++);
printf(“\n”);
}
getch();
}

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 27

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)

You might also like