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

Module 2 (Programs)

Programs on if,if-else,else if ladder and looping statements

Uploaded by

ushashank720
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Module 2 (Programs)

Programs on if,if-else,else if ladder and looping statements

Uploaded by

ushashank720
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 135

CONTROL STRUCTURES

• A program is nothing but the execution of sequence of one or more instructions.


• Quite often, it is desirable to change the order of execution of statements based on
certain conditions or it involves a kind of decision making to see whether a particule
condition has occurred or not.
• Based on application, it is necessary
⮚To alter the flow of program
⮚Test the logical conditions
TYPES OF CONTROL STATEMENTS

• Decision making statements


⮚ if statement
⮚ Nested if statement
⮚ else if statement
⮚ Switch statement
• Loop control statements
⮚ while loop
⮚ for loop
⮚ do-while loop
CONTD...

• Conditional control(jump) statements


⮚Break statement
⮚Continue statement
• goto statements (unconditional jump)
DECISION MAKING AND BRANCHING

• C language possesses such decision making capabilities by supporting the following


statements:
• If statement
• Switch statement
• Conditional operator statement
• goto statement
• These statements are popularly known as decision making statements. Also known as control
statements.
DECISION MAKING

• The basic decision statement in the computer is the two way selection.
• The decision is described to the computer as conditional statement that can be answered TRUE or
FALSE.
• If the answer is TRUE, one or more action statements are executed.
• If answer is FALSE, the different action or set of actions are executed.
• Regardless of which set of actions is executed, the program continues with next statement.
• C language provides following two-way selection statements:
• if statement
• if – else statement
• Nested if else statement
• Cascaded if else (also called else-if ladder)
IF STATEMENT
IF...ELSE STATEMENT
NESTED IF .. ELSE STATEMENT
ELSE-IF LADDER OR CASCADED IF ELSE:
SWITCH STATEMENT

• C language provides a multi-way decision statement so that complex else-if statements


can be easily replaced by it. C language’s multi-way decision statement is called switch.
• General syntax of switch statement is as follows:
GOTO STATEMENT

• Goto is an unconditional branching statement.


• The syntax is as follows:
goto label;
Statement1;
Statement 2;
label:
Unit 2 (Part 2)
BRANCHING & LOOPING
Introduction
 Mostly C program is a set of instructions which are normally executed
sequentially in order , but sometimes we will have situations where we will
have to change the order of execution based on certain conditions or repeat a
group of statements until some conditions are met. Decision making
capability of C language is used in such situation (Control statements)
1. Simple IF statement
if(test expression)
{
Statement-block;
}
Statement x;
Write a C program to read the marks of a
student from the user and print his result as
PASS or FAIL . If the student has scored more
than 40 his result should be PASS . If he has
scored less than 40 his result should be FAIL.
#include <stdio.h>
void main( )
{
int marks; OUTPUT
printf("Enter your Marks : "); Enter your Marks : 33
scanf("%d", &marks); You Failed :(
if(marks < 40)
{
printf("You Failed :( \n");
}
if(marks >= 40)
{
printf("Congrats You Passed :)\n");
}
}
2. The if … else statement
if(test_expression)
{
True block statement(s)
}
else
{
False Block statement(s)
}
#include <stdio.h>
void main()
{
int marks;
OUTPUT
printf("Enter your Marks : ");
scanf("%d", &marks);
Enter your Marks : 55
Congrats You Passed :)
if(marks < 40)
{
printf("You Failed :(\n");
}
else
{
printf("Congrats You Passed :)\n");
}
}
Nested if… else statement
if( test condition 1)
{
if(test condition 2)
{
Statement 1;
}
else
{
Statement 2;
}
}
else
{
Statement 3;
}
Statement X;
C program to find largest of 3 numbers using nested if..else
void main()
{
int a=15,b=24,c=38;
if(a>b)
{
if(a>c)
{
printf("A is largest");
}
else
{
printf("C is largest");
}
}
else
{
if(b>c)
{
printf("B is largest");
}
else {
printf("C largest");
}
}
}
Write a C program to check if variable1 is equal to
variable2 or not. If not equal , then find out which of
variable1 or variable 2 is greater. Demonstrate this using
nested if else.
#include <stdio.h>

int main()

{ int var1, var2;

printf("Input the value of var1:"); OUTPUT


scanf("%d", &var1);
Input the value of var1:12
printf("Input the value of var2:");
Input the value of var2:21
scanf("%d",&var2);

if (var1 != var2) var1 is not equal to var2


{ printf("var1 is not equal to var2\n"); var2 is greater than var1
if (var1 > var2)

printf("var1 is greater than var2\n");

else

printf("var2 is greater than var1\n");

else

printf("var1 is equal to var2\n");

}
4. The else if ladder

if(condition_expression_One)
{
statement1;
}
else if (condition_expression_Two)
{
statement2;
}
else if (condition_expression_Three)
{
statement3;
}
else
{
statement4;
}
C Program to print grade of a student using else-if Ladder

1. Marks 90 and above : A grade


2. Marks between 70 to 89 : B grade
3. Marks between 50 to 69 : C grade
4. Marks less than 50 : fail
#include<stdio.h>

int main(){
int marks;
printf("Enter your marks between 0-100\n");
scanf("%d", &marks);
if(marks >= 90){ Output1:
printf("YOUR GRADE : A\n"); Enter your marks
}
96
else if (marks >= 70 && marks < 90)
{ YOUR GRADE : A
printf("YOUR GRADE : B\n"); Output 2:
}
Enter your marks
else if (marks >= 50 && marks < 70)
{ 35
printf("YOUR GRADE : C\n"); YOUR GRADE : Failed
}
else
printf("YOUR GRADE : Failed\n");
}
APPLICATION
PROGRAM
An electricity board charges the following rates for the use of electricity: for the first 200 units 80
paise per unit: for the next 100 units 90 paise per unit: beyond 300 units Rs. 1 per unit. All users are
charged a minimum of Rs. 100 as meter charge. If the total amount is more than 400, then an
additional surcharge of 15% of total amount is charged. Write a program to read the name of the
user, number of units consumed and print out the charges.
Algorithm
Step 1: [Start]
Begin Step 5:[Calculate the amount]
Step 2: [Input customer name] amount = amount/100
Read name amount = amount+100
Step 3: [Input unit consumed] Step 6: [Check if amount is greater than
Read n 400 then calculate additional charge of
15%]
Step 4: [Check units consumed to calculate the
amount] if amount > 400 then
if n < = 200 calculate amount amount + amount *
15/100
amount = n*80
end if
otherwise check if n > 200 and n <= 300 then
calculate Step 7: [Print total amount to be paid by
amount = 200 * 80
the customer]

amount = amount +(n-200) *90 Display amount


otherwise calculate Step 8: [Finished]
amount =(n-300)*100 Stop
amount = amount+100*90
amount = amount+200*80
end if
Flowchart
#include<stdio.h> else
void main() {
{ amount=(n-300)*100;
char name[20]; amount=amount+100*90;
int n; amount=amount+200*80;
float amount; }
amount=amount/100; //To convert into Rupees
printf("Enter the consumer name\n");
scanf("%s", name); amount=amount+100; // Additional 100 Rupees
printf("Enter no. of units consumed \n"); to be added
scanf("%d",&n); if(amount>400)
{
if (n<=200) amount=amount+amount*15/100;
{ }
amount=n*80; printf("Total amount to be paid is %.2f Rs\n",amount);
} }
else if(n>200 && n<=300)
{
amount=200*80;
amount=amount+(n-200)*90;
}
Output
Enter the consumer name :

Bhagya

Enter no. of units consumed

275

Total amount to be paid is = 327.50


switch statement
 Multiway decision statement
 Best used when number of alternatives increases
 switch statement tests the value of a given variable against a list of case values and when a
match is found a block of statement associated with that case is executed

switch(expression)
{
case label 1 : block1;
break;
case label 2 : block2;
break;
…………..
…………..
case label n : block n;
break;
default : default block;
break;
}
Lab Program
Design and Develop a program to solve simple computational problems using
arithmetic expressions and use of each operator leading to simulation of a
commercial calculator. (No built-in math function)
Algorithm
Step 1: Start the program

Step 2: Read the two numbers and the operator

Step 3: Evaluate option based on the operator with case statements

case ‘+’ : res = a + b

case ‘-’ : res = a - b

case ‘*’ : res = a * b

case ‘/’ : res = a/b

Step 4: if the entered case option is invalid code the print “Wrong Choice”

Step 5: Print the res

Step 6: Stop the program


Flowchart
#include<stdio.h> case '/': if(b!=0) res=a/b;
#include<conio.h> else
printf("Divide by zero error");
void main() break;
{
default: printf("Illegal operator\n");
float a,b,res;
break;
char op;
printf("Enter The Expression in form of }
op1 operator op2\n"); printf("Result is……\n");
scanf("%f%c%f",&a,&op,&b); printf("%f%c%f=%f",a,op,b,res);
switch(op)
}
{
case '+': res = a + b; break;
case '-‘: res = a-b; break;
case '*‘: res = a*b; break;
OUTPUT
Enter The Expression in form of op1
operator op2 :
4+5
Result is …….
4+5=9
Write a C program using control statements for the
following
1. To find largest of two numbers
2. To find maximum of three numbers
3.To check whether a number is positive, negative or zero
4. To print Number of Days in any Month entered by user
5. To check if a number entered is even or odd
6. Read a year as input and find out if it is a leap year or not
7. Read sides of triangle from the user and check if it is isosceles , equilateral or
scalene
8. Check if an entered character is vowel or consonant using i) switch ii) if
9. Check if entered number is divisible by 3 or 5 or not
goto statement
Syntax
goto label ;
……
……
……
label : statement;
Forward Jump Backward Jump
Write a C program to find sum of 10
natural numbers using goto
#include<stdio.h> Output :
void main() Sum= 55
{
int sum=0,i=0;
top : sum= sum+i;
i++;
if(i<=10)
goto top;
printf("sum = %d",sum);
}
Write a C program to check if a number
is Armstrong or not using goto
Armstrong number is a number that is equal
to the sum of cubes of its digits. For example 0,
1, 153, 370, 371 and 407 are the Armstrong
numbers.

Eg :
#include<stdio.h>
#include<math.h>
void main()
{
int n,sum,d1,d2,d3; OUTPUT:

printf(“Enter the number \n"); Enter the number : 153

scanf("%d",&n); Armstrong number

d3= n%10;
d2= (n/10)%10;
d1=n/100;
sum= pow(d1,3)+pow(d2,3)+pow(d3,3);
if(sum==n)
printf(“Armstrong number");
else
printf(" Not an armstrong number");
}
C Loop Constructs
Difference between the 3 loop constructs

for while do-while

When the condition When the condition When the condition


becomes false for very becomes false for very becomes false for very
first time , body of the first time , body of the first time ,Body of the
loop will not be executed loop will not be executed. loop will be executed at
least for one time

Syntax Syntax Syntax

Example Example Example


while loop
 A while loop in C programming
repeatedly executes a set of
statements as long as a given
condition is true
 When the condition is false the loop
will stop working
 SYNTAX:
while(expression)
{
Statements;
}
Output
#include <stdio.h>
int main () { value of a: 10
int a = 10; value of a: 11
while( a < 20 ) { value of a: 12
printf("value of a: %d\n", a); value of a: 13
a++; value of a: 14
} value of a: 15
return 0; value of a: 16
} value of a: 17
value of a: 18
value of a: 19
Write a program to accept a name and print
the name for a specified number of times
#include<stdio.h>
void main()
{ enter name
char name[30]; jim
int n ,i=0; enter the number of times to print the name
printf("enter name \n"); 3
scanf("%s",name); name is : jim
printf("enter the number of times name is : jim
to print the name \n");
name is : jim
scanf("%d",&n);
while(i<n)
{
printf("name is : %s \n",name);
i++;
}
}
Write a C program to find sum of given
series using while loop (1+2+3+… +n)
#include<stdio.h>

void main()
Output
{
enter n : 4
int n ,sum=0,i=0;
sum of the series is 10
printf("enter n : ");
scanf("%d",&n);
while(i<=n)
{
sum = sum+i;
i++;
}
printf("sum of the series is
%d",sum);
}
LAB PROGRAM – 4

Design and develop a C program to find the reverse of


an integer number NUM and check whether it is
PALINDROME or NOT. Implement a C program for the
developed algorithm that takes an integer number as
input and output the reverse of the same with
suitable messages. Ex: Num: 1234, Reverse: 4321, Not
a Palindrome.
#include <stdio.h> if (temp == rev)
int main() printf(“This number %d is a palindrome\n”,temp);
{ else
int n, rev = 0, digit, temp, rev; printf(“This number %d is not a palindrome\n”,temp);
printf("Enter an integer: \n”); return 0;
scanf("%d", &n); }
temp= n;
while( n!=0 ) OUTPUT
{ digit = n%10; Enter an integer :
rev = rev*10 + digit; 5678
n /= 10; Given number is 5678
} It‟s reverse is 8765
printf(“Given number is %d\n”,temp); This number 5678 is not a palindrome
printf(“It‟s reverse is %d\n”,rev);
Write a program to compute GCD & LCM
of 2 numbers
#include <stdio.h> while (remainder != 0)
void main() {
{ numerator = denominator;
int num1, num2, gcd, lcm, remainder, denominator = remainder;
numerator, denominator;
remainder = numerator % denominator;
}
printf("Enter two numbers\n");
gcd = denominator;
scanf("%d %d", &num1, &num2); lcm = num1 * num2 / gcd;
if (num1 > num2) printf("GCD of %d and %d = %d\n", num1, num2, gcd);
{ printf("LCM of %d and %d = %d\n", num1, num2, lcm);
numerator = num1; }
denominator = num2;
} OUTPUT
else
Enter two numbers
{ 30
numerator = num2;
40
denominator = num1; GCD of 30 and 40 = 10
}
LCM of 30 and 40 = 120
remainder = numerator % denominator;
do while
 A do...while loop is similar to a
while loop, except the fact that it is
guaranteed to execute at least one
time.
 Syntax
do
{
statement(s);
} while( condition );
Program to print the value of a from 10
to 19 using do while
#include <stdio.h> value of a: 10
int main () { value of a: 11

int a = 10; value of a: 12


do { value of a: 13
printf("value of a: %d\n", a); value of a: 14
a = a + 1; value of a: 15
}while( a < 20 ); value of a: 16
return 0; value of a: 17
} value of a: 18
value of a: 19
Lab Program 5
Design and Develop a C program to compute
sin(x) using Taylor series approximation and
compare with built-in library function and
display with appropriate messages.
#include<stdio.h> sum=sum+term;
#include <math.h> i=i+2;
#define pi 3.142 }
int main() while(fabs(term)>=0.00001);
{ printf(“The sine value is %f\n”,sum);
int i,degree; printf(“The sine value using built-in function is %f\n”,sin(x));
float x,sum=0,term,nume,deno; return 0;
printf("Enter the value of x in degree: "); }
scanf("%d", &degree);
x=degree*(pi/180); OUTPUT
nume = x ; Enter the value of x in degree: 45
deno = 1; The sine value is 0.707179
i = 2; The sine value using built-in function is 0.707179
do
{
term=nume/deno;
nume=-nume*x*x;
deno=deno*i*(i+1);
for loop
 A set of statements will be
executed for a set number of times
 Syntax :
for(exp1;exp2;exp3)
{
Statements;
}
 exp1: initialization of variable
exp2 : condition
exp3: increment / decrement
Write a program to print n numbers
using for loop
Write a program to print n numbers
#include<stdio.h>

void main() OUTPUT

{ int n; enter n 4

printf("enter n "); number is 1

scanf("%d",&n); number is 2

for(int i=1;i<=n;i++) number is 3

{ number is 4

printf("\n number is %d",i);


}
}
Write a C program to find factorial of a
given number using for loop
#include<stdio.h> OUTPUT
int main() enter n 5
{ int n,fact=1; factorial is 120
printf("enter n");
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
printf(“factorial is %d",fact);
return 0;
}
Write a C program to generate a fibonacci
series for a user entered value of n using for
loop
#include<stdio.h> for(i=3;i<=n;i++)
int main() {
{ fib3=fib1+fib2;
int n,fib1=0,fib2=1,i,fib3; printf("\t %d", fib3);
fib1= fib2;
printf("enter n"); fib2=fib3;
scanf("%d",&n); }
if(n<2) }
{ return 0;
printf("fibonacci series does not }
exist");
OUTPUT
}
enter n :9
else
{
Fib series : 0 1 1 2 3 5 8 13 21
printf(" \n Fib series : %d \t %d
",fib1,fib2);
JUMPS IN LOOPS
Break and continue: break and continue are unconditional control construct.
i. break
This statement is useful to terminate a loop and transfer control out of loop under special situations.
break statement works with while, do….while, for and switch statements. Following program syntax
diagrammatically represents the working mechanism of break statement.
NOTE:In switch statement if the break statement is missing then every case from the
matched case label till the end of the switch,including the default, is executed.
#include<stdio.h>
int main()
{
char grade;
printf("Enter your grade:\n");
grade=getchar();
switch(grade)
{
case 'A': printf("Excellent\n");
case 'B': printf("\n\n\nKeep it up!\n\nNo break statement\n\nHence all the case following this(but not the ones above this)
except the default case will get executed !\n\n");
case 'C': printf("\n\n\t\tCase C : Well done !\n\n");
case 'D': printf("\t\tCase D : You passed!\n\n");
case 'F': printf("\t\tCase E : Better luck next time\n\n\n");
default: printf("\t\tDefault Case : Invalid grade\n\n\n");
}
putchar(grade);
printf("\n\n\t\t\tCoding is Fun !\n\n\n");
return 0;
Example program for break statement
main() {
int i;
for(i=1;i<=5;i++)
{
if(i==3) {
break;
}
printf(“%d ”,i);
}

Output: 1 2
JUMPS IN LOOPS
Break and continue: break and continue are unconditional control construct.
ii. Continue
Statement is helpful to skip particular set of statements in loop body and to
continue execution from the beginning of loop.
Following syntax clearly depicts how control shifts to beginning of a loop on
finding continue statement
Example program for continue statement
main() {
int i;
for(i=1;i<=5;i++)
{
if(i==3)
{
continue;
}
printf(“%d ”,i);
}

Output: 1 2 4 5
goto statement
Syntax
goto label ;
……
……
……
label : statement;
Forward Jump Backward Jump
Write a C program to find sum of 10
natural numbers using goto
#include<stdio.h> Output :
void main() Sum= 55
{
int sum=0,i=0;
top : sum= sum+i;
i++;
if(i<=10)
goto top;
printf("sum = %d",sum);
}
return statement
► The return statement is used in a function to return a value to the calling function.
► The return statement can be written anywhere and often inside the function definition.
► Still, after the execution of the first return statement, all the other return statements will be terminated
and will be of no use.
► The reason why we have the two syntaxes for the return statement is that the return statement can be used
in two ways.
► First is that you can use it to terminate the execution of the function when the function is not returning any
value.
return;
⮚ Second, it is to return a value with function calls, and here, the datatype of expression should be the same
as the datatype of function.
⮚ return expression;
⮚ Here the expression can be any variable, number, or expression. All the return examples given below are
valid in C.
• return x;
• return 0;
• return x++;
• return(x+y);
Example: Using the return statement in void functions

#include<stdio.h>
void main()
{
Output:level1
printf("level1\n");
return;
printf("level2\n");
}
C Loop Constructs
Loop (Iterative) Statements

Definition of Loop: It is a programming structure used to repeatedly carry out a


particular instruction/statement until a condition is true. Each single repetition
of the loop is known as an iteration of the loop.

Three important components of any loop are:


1. Initialization (example: ctr=1, i=0 etc)
2. Test Condition (example: ctr<=500, i != 0 etc)
3. Updating loop control values (example: ctr=ctr+1, i =i-1)
Loop (Iterative) Statements (Contd…)
Pre-test and Post-test loops
Loops can be classified into two types based on the placement of test-condition.
• If the test-condition is given in the beginning such loops are called pre-test loops (also known as entry-
controlled loops).
• Otherwise if test condition is given at the end of the loop such loops are termed as post-test loops (or exit
controlled loops).
while loop
► It is a pre-test loop (also known as entry controlled loop).
► This loop has following syntax:

► In the syntax given above ‘while’ is a key word and condition is at beginning of the loop.
► If the test condition is true the body of while loop will be executed.
► After execution of the body, the test condition is once again evaluated and if it is true, the body
is executed once again.
► This process is repeated until condition finally becomes false and control comes out of the body
of the loop.
While loop
Output
#include <stdio.h>
int main () { value of a: 10
int a = 10; value of a: 11
while( a < 20 ) { value of a: 12
printf("value of a: %d\n", a); value of a: 13
a++; value of a: 14
} value of a: 15
return 0; value of a: 16
} value of a: 17
value of a: 18
value of a: 19
C program to print digits from 1 to 5
#include <stdio.h>
main()
{
int N=5, i=1; Output
1
2
3
while (i<=N) 4
{ 5
BMS
printf("%d\n", i);
i=i+1;
}
printf("BMS");
}
C program to calculate the sum from 1 to 5 using While
loop
#include <stdio.h> Output
main() Sum=15
{
int N=5, i=1, sum=0;

while (i<=N)
{
sum=sum+i;
i=i+1;
}
printf("Sum=%d",sum);
}
C program to calculate the sum from m to n using While loop
#include <stdio.h>
main()
{
int m, n, sum=0;
Input
Enter the value of m and n: 5 10
printf("Enter the value of m and n: "); Output
scanf("%d%d",&m,&n); Sum=45

while (m<=n)
{
sum=sum+m;
m=m+1;
}
printf("Sum=%d",sum);
}
Write a C program to find factorial of given number
#include <stdio.h>
main() {
int i, fact, n;

i=1;
fact=1;
printf("Enter the number to find Factorial: ");
scanf("%d",&n);

while(i<=n)
{
fact=fact*i;
i=i+1;
}

printf("Factorial=%d",fact);
}
Input
Enter the number to find Factorial: 4

Output
Factorial=24
Write a C program to find largest of five numbers
using ternary operator and while loop.

#include <stdio.h>
main()
Input
{
int i=1,large=-32768, num;
Enter the number: 12
Enter the number: 45
while (i<=5)
Enter the number: 38
{
Enter the number: 150
printf("\nEnter the number: ");
Enter the number: -2
scanf("%d",&num);
large=(num>large)?num:large;
Output
i++;
}
Largest=150
printf("Largest=%d",large);
}
Write a C program to read the numbers until -1 is encountered. Also
count the negative, positive and zeros entered by user.
#include <stdio.h> else
main()
zeros++;
{
printf("\nEnter the number: ");
int num;
int neg=0, pos=0, zeros=0;
scanf("%d",&num);
}
printf("\nEnter -1 to exit");
printf("\nEnter the number: "); printf("Count of Postive Numbers=%d\n",pos);
scanf("%d",&num); printf("Count of Negative Numbers=%d\n",neg);
while (num!=-1)
printf("Count of Zeros=%d",zeros);
{
}
if(num>0)
pos++;
else if (num<0)
neg++;
Write a program to accept a name and print
the name for a specified number of times
#include<stdio.h>
void main()
{ enter name
char name[30]; jim
int n ,i=0; enter the number of times to print the name
printf("enter name \n"); 3
scanf("%s",name); name is : jim
printf("enter the number name is : jim
of times to print the name \n");
name is : jim
scanf("%d",&n);
while(i<n)
{
printf("name
is : %s \n",name);
i++;
}
}
Write a C program to find sum of given
series using while loop (1+2+3+… +n)
#include<stdio.h>

void main()
Output
{
enter n : 4
int n ,sum=0,i=0;
sum of the series is 10
printf("enter n : ");
scanf("%d",&n);
while(i<=n)
{
sum =
sum+i;
i++;
}
printf("sum of the
series is %d",sum);
}
Design and develop a C program to find the reverse of
an integer number NUM and check whether it is
PALINDROME or NOT. Implement a C program for the
developed algorithm that takes an integer number as
input and output the reverse of the same with
suitable messages. Ex: Num: 1234, Reverse: 4321, Not
a Palindrome.
#include <stdio.h> if (temp == rev)
int main() printf(“This number %d is a palindrome\n”,temp);
{ else
int n, rev = 0, digit, temp, rev; printf(“This number %d is not a palindrome\n”,temp);
printf("Enter an integer: \n”); return 0;
scanf("%d", &n); }
temp= n;
while( n!=0 ) OUTPUT
{ digit = n%10; Enter an integer :
rev = rev*10 + digit; 5678
n /= 10; Given number is 5678
} It‟s reverse is 8765
printf(“Given number is %d\n”,temp); This number 5678 is not a palindrome
printf(“It‟s reverse is %d\n”,rev);
Write a program to compute GCD & LCM
of 2 numbers
#include <stdio.h> while (remainder != 0)
void main() {
{ numerator = denominator;
int num1, num2, gcd, lcm, remainder, denominator = remainder;
numerator, denominator;
remainder = numerator % denominator;
}
printf("Enter two numbers\n");
gcd = denominator;
scanf("%d %d", &num1, &num2); lcm = num1 * num2 / gcd;
if (num1 > num2) printf("GCD of %d and %d = %d\n", num1, num2, gcd);
{ printf("LCM of %d and %d = %d\n", num1, num2, lcm);
numerator = num1; }
denominator = num2;
} OUTPUT
else
Enter two numbers
{ 30
numerator = num2;
40
denominator = num1; GCD of 30 and 40 = 10
}
LCM of 30 and 40 = 120
remainder = numerator % denominator;
do…. while loop
do…. while loop: It is a post-test loop (also
called exit controlled loop) it has two keywords
do and while.

The General syntax:


C program to print digits from 1 to 5
#include <stdio.h>
main()
{ Output
int N=5, i=1; 1
2
do 3
{ 4
printf("%d\n", i); 5
i=i+1; BMS
} while (i<=N);

printf("BMS");
}
Program to print the value of a from 10
to 19 using do while
#include <stdio.h> value of a: 10
int main () { value of a: 11

int a = 10; value of a: 12


do { value of a: 13
printf("value of a: %d\n", a); value of a: 14
a = a + 1; value of a: 15
}while( a < 20 ); value of a: 16
return 0; value of a: 17
} value of a: 18
value of a: 19
Write a C program to find factorial of given number
#include <stdio.h>
main() {
int i, fact, n;

i=1; Input
fact=1; Enter the number to find
printf("Enter the number to find Factorial: Factorial: 4
");
scanf("%d",&n);

Output
do
{ Factorial=24
fact=fact*i;
i=i+1;
}
while(i<=n);
printf(“factorial= %d\n”,fact);
Write a C program to find sum of digits
in a given number
Write a C program to find sum of digits in a given number
#include <stdio.h>
void main()
{
int n, sum = 0, remainder;

printf("Enter an integer\n");
scanf("%d", &n);

do {
remainder = n % 10;
sum = sum + remainder;
n= n / 10;
}while (n != 0);

printf("Sum= %d", sum);}


Design and Develop a C program to compute
sin(x) using Taylor series approximation and
compare with built-in library function and
display with appropriate messages.
#include<stdio.h> sum=sum+term;
#include <math.h> i=i+2;
#define pi 3.142 }
int main() while(fabs(term)>=0.00001);
{ printf(“The sine value is %f\n”,sum);
int i,degree; printf(“The sine value using built-in function is %f\n”,sin(x));
float x,sum=0,term,nume,deno; return 0;
printf("Enter the value of x in degree: "); }
scanf("%d", &degree);
x=degree*(pi/180); OUTPUT
nume = x ; Enter the value of x in degree: 45
deno = 1; The sine value is 0.707179
i = 2; The sine value using built-in function is 0.707179
do
{
term=nume/deno;
nume=-nume*x*x;
deno=deno*i*(i+1);
for loop

It is another pre-test loop (also called entry controlled loop) that provides concise loop
control structure.
It has one keyword for.
One important aspect of for loop is all the three components of a loop (viz. initializing,
testing condition and updation (increment/decrement)) is given in the head of for loop.
General Syntax:

A set of statements will be executed for a set number of times


Flowchart of for loop
for loop (Contd…)
The execution of for statement is as follows.
1. In this loop first initialization of control variable is done first, using
assignments such as i=1, count=0. The variable i count are called loop control
variable.
2. The value of control variable is tested using the test condition. The test
condition is evaluated. If the condition is true, the body of the loop is executed;
otherwise loop will be terminated.
3. When the body of the loop is executed, the control transferred back to the for
statement to update the loop variable. And then condition is checked once
again. If condition is true once again body will be executed once again. This
process continues till the value of the control variable fails to satisfy the test
condition.
Program to print characters from ‘A’ to ‘Z’ using
loop
Output

#include <stdio.h>
int main()
{
char ch;
//Print characters from 'A' to 'Z'
for (ch = 'A'; ch <= 'Z'; ch++)
//there is a whitespace after %c so that the
//characters have spaces in between.
printf("%c ", ch);
return 0;
}
Program to generate multiplication table
#include <stdio.h> Output
int main()
{
Int number, i;
printf("Enter an integer: ");
scanf("%d", &number);
printf("Multiplication table of %d: \n", number);
for (i = 1; i <= 10; ++i) {
printf("%d * %d = %d \n", number, i, number * i);
}
return 0;
}
C program to print digits from 1 to 5
#include <stdio.h>
main()
{ Output

int N=5, i; 1
2

for(i=1;i<=N;i++) 3

{ 4

printf("%d\n", i); 5

} BMS

printf("BMS");
}
Write a C program to find factorial of given number
#include <stdio.h>
main() {
int i, fact, n;
Input
printf("Enter the number to find Factorial: "); Enter the number to find Factorial: 4
scanf("%d",&n);

fact=1; Output
for(i=1;i<=n;i++) Factorial=24
{
fact=fact*i;
}

printf("Factorial=%d",fact);
}
Write a program to print n numbers
using for loop
Write a program to print n numbers
#include<stdio.h>

void main() OUTPUT

{ int n; enter n 4

printf("enter n "); number is 1

scanf("%d",&n); number is 2

for(int i=1;i<=n;i++) number is 3

{ number is 4

printf("\n number is
%d",i);
}
}
Write a C program to generate a fibonacci
series for a user entered value of n using for
loop
#include<stdio.h>
int main()
{
int n = 9;
int a = 0, b = 1;

// printing the 0th and 1st term


printf("%d, %d ,",a,b);

int nextTerm;

// printing the rest of the terms here


for(int i = 2; i < n; i++){
nextTerm = a + b;
a = b;
b = nextTerm;

printf("%d, ",nextTerm);
}

return 0;
Difference between While, Do-While and For loop
Nested Loops
► A nested loop means a loop statement inside another loop statement. That is why
nested loops are also called “loop inside loops“.
► We can define any number of loops inside another loop.
Nested for Loop
► Nested for loop can be used to control the number of times that a particular set of
statements will be executed.
► Another outer loop could be used to control the number of times that a whole loop is
repeated.
NOTE:
⮚ Loops should be properly indented so that a reader can easily determine which
statements are contained within each of the statement.
⮚ Although this feature will work with any loop such as while,do-while and for,it is most
commonly used with the for loop,because this is easiest to control.
Nested for Loops(Contd…)

for(initialization;condition;increment)
{
for(initialization;condition;increment)
{
//Statement of inside loop
}
// Statement of outer loop
}
C Program to Print Pyramids and Patterns
Half Pyramid of *
#include <stdio.h>
int main()
{
*
int i, j;
**
for (i = 1; i <=5; i++)
***
{
****
for (j = 1; j <= i; j++) {
*****
printf("* ");
}
printf("\n");
}
return 0;
}
Half Pyramid of Numbers
#include <stdio.h>
int main()

1 {

12 int i, j;

123 for (i = 1; i <=5;i++)


{
1234
for (j = 1; j <= i; j++)
12345
{
printf("%d ", j);
}
printf("\n");
}
return 0;
}
#include <stdio.h>

Pascal's Triangle int main()


{
int n=6, s, i, j,coef;
for (i = 0; i < n; i++){
1
for (s = 1; s <n - i; s++)
1 1
1 2 1
printf(" ");
1 3 3 1 for (j = 0; j <= i; j++)
1 4 6 4 1
{
1 5 10 10 5 1
if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;
printf("%d ", coef);
}
printf("\n");
}
return 0;
}
Floyd's Triangle
#include <stdio.h>
int main() {
int i, j, number = 1;
1
for (i = 1; i <= 4; i++) {
23
for (j = 1; j <= i; j++) {
456
printf("%d ", number);
7 8 9 10
number++;
}
printf("\n");
}
return 0;
}

You might also like