Chapter 5 Control Structure
Chapter 5 Control Structure
Chapter 5
Introduction
• In chapter 3 and 4, we have seen how programs are executed in a top to bottom order by
executing lines of code in same order as they are written in the program. The instructions are
• But, in larger programs, this may not always be true. Some part of the program may need to be
executed more than once and some part be skipped if some conditions are not met.
• To create more functional, there are three types of programming structure - the first one (in
above discussions) corresponds to sequential structure, the second repetitive (executing same
statements more than once) and finally the selective (executing different segments depending on
Algorithm
C code:
1. Start the program.
#include<stdio.h>
2. Read a number. void main(){
3. Divide the number by 2. int a;
4. If remainder at step 3 is 0, scanf("%d",&a);
the number is even. if(a%2)
Otherwise pritnf("The number is even");
the number is odd. else
5. End the program. printf("The number is odd");
}
Repetitive Structure
• A repetitive structure helps to execute group of instructions more than
once.
• The instructions to be executed more than once are placed inside the
repetitive structure and executed.
• If the number of execution is specified, the repetition should be stopped
after the repetition count reached that number and normal flow of the
program resumes.
• If the number of repetition is not known in priori, the group of instructions
are executed repeatedly until some condition is satisfied. In this case, a
selective structure is used to continue or terminate the repetitive
structure. This is also called looping.
Write a C program to print Hello World 10 timed using while loop
#include <stdio.h>
int main()
{
int i = 0; Output:
}
Branching Statement
• The C language programs follow a sequential form of execution of
statements.
• Many times it is required to alter the flow of sequence of
instructions/statements. C language provides statements that can
alter the flow of a sequence of instructions. These statements are
called as control statements/branching statements.
• To jump from one part of the program to another, these statements
help. The control transfer may be unconditional or conditional.
Conditional Branching statements:
• The conditional branching statements help to jump from one part of the program
to another depending on whether a particular condition is satisfied or not.
Generally they are two types of branching statements.
Two way selection:
Depending on the condition result either of one root will be followed. If condition
results to false then false root will be fallowed, if condition results to true than true
root will be fallowed.
Contd…
• Conditional Branching Statements in C:
• Simple if statement.
• if… else statement.
• Nested if…else statement
• else…if ladder
• switch statement
Simple If:
• It allows the computer to evaluate the expression/condition first and them
depending on whether the value of the expression/condition is "true" or "false",
it transfer the control to a particular statements.
• This point of program has two paths to flow, one for the true and the other for
the false condition. If condition becomes true than it executes statements written
in true block, if condition fails than true block will be skipped.
Syntax:
if(test-expression/condition)
{
True statement-block ;
}
statement-x;
Flowchart for If statement
The if-else statement:
• The if-else statement is an extension of the simple if statement. If the test
expression/condition is true, then true-block statements immediately following if
statement are executed otherwise the false-block statements are executed. In
other case, either true-block or false block will be executed, not both.
Syntax:
if(test-expression/condition)
{
true-block statements;
}
else
{
false-block statements;
}
statement-x ;
Nested if….else statement:
• C language supports if-else statements to test additional conditions apart from the initial test
expression.
• The if-else construct works in the same way as normal if statement nested if construct is also
know as if-else-if construct.
• When an if statement occurs within another if statement, then such type of is called nested if
statement.
#include<stdio.h> {
#include<conio.h> printf("YOUR GRADE : B\n");
void main() }
{ else if (marks >= 50 && marks < 70)
int marks; {
printf("Enter your marks between 0-100\n"); printf("YOUR GRADE : C\n");
scanf("%d", &marks); }
if(marks >= 90) else
{ {
printf("YOUR GRADE : A\n"); printf("YOUR GRADE : Failed\n");
} }
else if (marks >= 70 && marks < 90) getch(); }
}
C Program to create a simple calculator performs addition, subtraction,
multiplication or division depending the input from user.
#include<conio.h> case '-': printf("%d - %d = %d", firstOperand,
secondOperand, firstOperand-secondOperand);
# include <stdio.h>
break;
void main()
case '*': printf("%d* %d = %d", firstOperand,
{
secondOperand, firstOperand*secondOperand);
char operator;
break;
int firstOperand, secondOperand;
case '/': if(secondOperand==0) printf(“Divide by Zero
printf("Enter an operator (+, -, *, /): "); Error”);
scanf("%c", &operator); else
printf("Enter two operands: "); printf("%d / %d = %d", firstOperand, secondOperand,
firstOperand/secondOperand); break;
scanf("%d%d",&firstOperand, &secondOperand);
switch(operator) default: printf("Error! operator is not correct");
{ }
case '+': printf("%d+ %d= %d",firstOperand, getch(); }
secondOperand, firstOperand+secondOperand);
break;
WAP to display whether you are MALE of FEMALE given your gender (‘M’ or ‘F’) as
input.
#include <stdio.h> {
int main() { printf("You are FEMALE.\n");
char gender; }
// Input the character for gender else
printf("Enter your gender (M/F): "); {
scanf(" %c", &gender); printf("Invalid input. Please enter 'M' for Male or 'F' for
Female.\n");
// Check the input and display the result
}
if (gender == 'M' || gender == 'm')
return 0;
{
}
printf("You are MALE.\n");
}
else if (gender == 'F' || gender == 'f')
WAP to test a number entered by user whether it is divisible exactly by 5 but not by 11.
#include <stdio.h> {
largest = num3; // num3 is the largest
int main() { }
int num1, num2, num3; } else {
int largest; // num2 > num1
// Input three numbers if (num2 - num3 > 0) {
printf("Enter three numbers: "); largest = num2; // num2 is the largest
scanf("%d %d %d", &num1, &num2, &num3); } else {
// Compare num1 and num2 largest = num3; // num3 is the largest
if (num1 - num2 > 0) }
{ }
// num1 >= num2 // Print the result
if (num1 - num3 > 0) { printf("The largest number is: %d\n", largest);
largest = num1; // num1 is the largest return 0;
} }
else
To check vowel or consonant
#include <stdio.h> // evaluates to 1 if variable c is a uppercase
int main() { vowel
char c; uppercase_vowel = (c == 'A' || c == 'E' || c ==
'I' || c == 'O' || c == 'U');
int lowercase_vowel, uppercase_vowel;
printf("Enter an alphabet: "); // evaluates to 1 (true) if c is a vowel
scanf("%c", &c); if (lowercase_vowel || uppercase_vowel)
printf("%c is a vowel.", c);
// evaluates to 1 if variable c is a lowercase else
vowel
lowercase_vowel = (c == 'a' || c == 'e' || c == printf("%c is a consonant.", c);
'i' || c == 'o' || c == 'u'); return 0;
}
Enter an alphabet: G
G is a consonant.
WAP to read a year and determine if it is leap year or not.
• Rules for determining if a year is a leap year:
Why Do We Have Leap Years?
• If the year is divisible by 400, it is a leap year. The Earth takes approximately 365.2422 days to
• If the year is divisible by 100 but not by 400, it is not a leap year. orbit the Sun, which is roughly 365 days, 5 hours,
• If the year is divisible by 4 but not by 100, it is a leap year. 48 minutes, and 45 seconds. This discrepancy
• If the year is not divisible by 4, it is not a leap year. accumulates over time, and without leap years,
our calendar would slowly drift out of sync with
Example:
the Earth's revolutions around the Sun. By adding
Divisible by 400 → Leap Year:1600, 2000, 2400
a leap day every 4 years (with exceptions for
Divisible by 100 but not by 400 → Not a Leap Year:1700, 1800, 1900
years divisible by 100 but not 400), we keep the
Divisible by 4 but not by 100 → Leap Year:2020, 2024, 2028
calendar year synchronized with the Earth's orbit.
Not divisible by 4 → Not a Leap Year:2023, 2025, 2027
This method ensures that we do not lose track of
the seasons, and that they occur at approximately
the same time each year.
#include <stdio.h>
C code int main() {
int year;
// Input year from the user
Explanation:
printf("Enter a year: ");
[Link] program first asks the user to input a year.
[Link] checks if the year satisfies the leap year conditions: scanf("%d", &year);
1. If the year is divisible by 400, it is a leap year. // Check if the year is a leap year
2. If the year is divisible by 4 but not divisible by
100, it is a leap year. if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
{
3. Otherwise, the year is not a leap year.
[Link] program then prints whether the year is a leap printf("%d is a leap year.\n", year);
year or not. } else {
printf("%d is not a leap year.\n", year);
}
return 0;
}
WAP to enter two alphabets and display how many alphabets
lie between them.
Steps:
For example: If the input characters are 'A' and 'D', the characters between them are 'B' and 'C', so
the answer would be [Link] the input characters are 'B' and 'F', the characters between them are 'C',
'D', and 'E', so the answer would be 3.
Code
#include <stdio.h> else
int main() { {
char char1, char2; // If char2 is already uppercase, no change is needed
int diff; }
// Input two alphabets // Calculate the absolute difference between the ASCII values
printf("Enter two alphabets: "); if (char1 > char2) {
scanf("%c %c", &char1, &char2); diff = char1 - char2 - 1; // Calculate the number of alphabets
between
// Convert char1 to uppercase if it is lowercase
} else {
if (char1 >= 'a' && char1 <= 'z') {
diff = char2 - char1 - 1; // Calculate the number of alphabets
char1 = char1 - 32; // Convert to uppercase between
} else { }
// If char1 is already uppercase, no change is needed // Output the number of alphabets between the two
} printf("The number of alphabets between '%c' and '%c' is: %d\n",
// Convert char2 to uppercase if it is lowercase char1, char2, diff);
}
C – Loop control statements:
• During programming the programmer encounter situations, when a
block of code needs to be executed several number of times.
• A loop allows a program to repeat a group of statements, either any
number of times or until some loop condition occurs.
• It is convenient if the exact number of repetitions are known.
• Loop Consists of
• Body of the loop
• Control Statement
Contd…
• In C programing loops are basically categorized into two categories.
1. Entry control loop
2. Exit control loop
Entry Control loop: An entry control loop checks the condition at the
time of entry and if condition or expression becomes true then control
transfers into the body of the loop. Such type of loop controls entry to
the loop that’s why it is called entry control loop.
Exit Control Loop: An Exit Control Loop checks the condition for exit
and if given condition for exit evaluate to true, control will exit from the
loop body else control will enter again into the loop. Such type of loop
controls exit of the loop that’s why it is called exit control loop.
Flowchart
#include<stdio.h>
int main()
{
int i, n;
float sum=0, avg, num;
printf("Enter n: ");
scanf("%d", &n);
for(i=1;i<=n; i++)
Enter n: 4 ↲
{
printf("Enter number-%d:",i);
Enter number-1: 12 ↲
scanf("%f",&num);
Enter number-2: 21 ↲
sum = sum + num; Enter number-3: 14 ↲
} Enter number-4: 47 ↲
avg = sum/n; Sum is 94
printf("Sum is %f\n", sum); Average is 23.5
printf("Average is %f", avg);
return(0);
}
Example: C Program to find Factorial of a Number.
#include <stdio.h> else
#include<conio.h> void main() {
{ for(i=1; i<=n; ++i)
int n, i; {
unsigned long long factorial = 1; factorial *= i; // factorial =
printf("Enter an integer: "); factorial*i;
scanf("%d",&n); }
// show error if the user enters a negative printf("Factorial of %d = %llu", n, factorial);
integer }
if (n < 0) getch();
printf("Error! Factorial of a negative }
number doesn't exist.");
Example: Fibonacci series program in C language.
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, if ( c <= 1 )
21 next = c;
else
#include<stdio.h> {
#include<conio.h> next = first + second;
void main() {
first = second;
int n, first = 0, second = 1, next, c; second = next;
printf("Enter the number of terms\n"); }
scanf("%d",&n);
printf("%d\n",next);
printf("First %d terms of Fibonacci series are :- }
\n",n);
for ( c = 0 ; c < n ; c++ ) getch();
{ }
Program to print “Nepal is beautiful” n times, where n is given by user
#include<stdio.h> OUTPUT:
Enter n: 5
int main() Nepal is beautiful
{ Nepal is beautiful
Nepal is beautiful
int i, n;
Nepal is beautiful
printf("Enter n: "); Nepal is beautiful
scanf("%d", &n);
for(i=1;i<=n; i++)
{
printf(“Nepal is beautiful\n");
}
return(0);
}
Print a multiplication table for the given number using C for loop
#include<stdio.h>
int main()
{
Output:
int i,num,prod;
Enter a number: 5 ↲
printf("Enter a number: "); 5 * 1 =5
scanf("%d",&num); 5 * 2 =10
for(i=1;i<=10;i++) 5 * 3 =15
5 * 4 =20
{
5 * 5 =25
prod=i*num; 5 * 6 =30
printf("%d * %d= %d\n",num,i,prod)); 5 * 7 =35
} 5 * 8 =40
return 0; 5 * 9 =45
5 * 10 =50
}
Various forms of loop in C
1) Initialization part can be skipped from loop as shown below, the counter variable
is declared before the loop. int num=10; for (;num<20;num++)
Note: Even though we can skip initialization part but semicolon (;) before condition
is must, without which you will get compilation error.
2) Like initialization, you can also skip the increment part as we did below. In this
case semicolon (;) is must after condition logic. In this case the increment or
decrement part is done inside the loop. for (num=10; num<20; )
{
//Statements num++;
}
Contd…
3 ) This is also possible. The counter variable is initialized before the loop and
incremented inside the loop.
int num=10;
for (;num<20;)
{
//Statements num++;
}
Syntax:
Initialization of loop variable;
do
{
statement 1; statement 2; …………. statement n;
updation of loop variable;
}while (condition);
#include<stdio.h> do
#include<conio.h> {
void main() fact*=i; i++;
{ }
long int i,n,fact=1; /*variable while(i<=n);
declaration */ printf("Factorial = %ld\n",fact);
clrscr(); getch();
printf("Enter the value of n \n"); }
scanf("%ld", &n);
i=1;
Write a C program to print the sum of all even and odd numbers up to n.
#include<stdio.h> else
void main() s2=s2+i;
{ i++;
int n,s1=0,s2=0,i; }
printf("Enter Number : "); while(i<=n);
scanf("%d",&n); printf("\nSum of Even Numbers :
i=1; %d\n",s1);
do { printf("\nSum of Odd Numbers :
%d\n",s2);
if(i%2==0) getch();
s1=s1+i; }
Program to add floating numbers until the user enters zero
#include <stdio.h>
int main()
{ Output:
float number, sum = 0; Enter a number: 20.5
Enter a number: 50.5
do
Enter a number :40.1
{ Enter a number: 0
printf("Enter a number: ");
scanf("%f", &number); Sum=111.1
sum += number;
}
while(number != 0.0);
printf("Sum = %.2f",sum);
return 0;
}
Program to check an entered number a
#include<stdio.h> palindrome or not
#include<conio.h>
void main()
{
int num, rem, rev=0, orgi;
clrscr();
printf("Enter number: ");
scanf("%d", &num);
if(rev==orgi)
orgi= num;
{
do printf("PALINDROME");
{ }
rem = num%10; else
rev = rev*10 + rem; {
num = num/10; printf("NOT PALINDROME");
}
} while(num!=0);
getch();
}
Practice Session (5 B)
1. WAP to find mn. Where m and n are integers and must be given by user without
using built-in function.
2. WAP to find mn. Where m and n are integers and consider the value of n be
negative and 0 which is given by user without using built-in function.
3. WAP to count the number of digits in a number.
4. WAP to display the series: 1/2 2/3 3/4 4/5 …. n-1/n
5. WAP to evaluate the series S= 1+ 2*1 +3*2 +….+ n*n-1. where n is given by user.
6. WAP to create a hailstone series given a first number ‘x’ by user up to nth term.
example: if x=17, series will be: 17, 52, 26, 13, 40, 20…. So on
WAP to find mn. Where m and n are integers and must be given by user without using built-in
function.
// Calculate m^n
WAP to find mn. Where m and n are integers and must be given by
user without using built-in function.(considering positive/
negative/ zero)
• Explanation:
Positive Exponent:Multiply 𝑚 by itself 𝑛 times using a loop.
Negative Exponent:Compute 𝑚∣𝑛∣ (absolute value of 𝑛) and then take
the reciprocal to handle 𝑚−𝑛.
Zero Exponent: Directly return 1, as any number raised to the power of
0 is 1.
Floating-Point Result:double is used for the result to handle fractions
when 𝑛n is negative.
WAP to find mn. Where m and n are integers and must be given by user without using built-in
function.
#include <stdio.h> }
} else if (n < 0) {
int main() { for (i = 1; i <= -n; i++)// for making n positive
double m, result = 1.0; // Use double for fractional results if n is negative {
int n, i; result *= m; // Multiply m |n| times
}
// Input base (m) and exponent (n) result = 1.0 / result; // Take reciprocal for negative exponent
printf("Enter the base (m): "); } else {
scanf("%lf", &m); result = 1.0; // Any number to the power of 0 is 1
printf("Enter the exponent (n): "); }
scanf("%d", &n);
// Output the result
// Calculate m^n printf("%lf to the power of %d is: %lf\n", m, n, result);
if (n > 0) {
for (i = 1; i <= n; i++) { return 0;
result *= m; // Multiply m n times }
WAP to count the number of digits in a number.
• Explanation:
Input:
The user enters a number (positive or negative).
Negative Numbers:
Convert the number to its absolute value to handle negative input.
Special Case for Zero:
Zero has one digit, so it is handled explicitly.
Digit Counting:
The number is repeatedly divided by 10, removing the last digit each time, until it becomes 0.
A counter tracks how many divisions were performed.
Output:
The program prints the total number of digits.
Code
#include <stdio.h> if (num == 0) {
count = 1;
int main() { } else {
int num, count = 0; // Count the digits
while (num != 0) {
// Input the number num /= 10; // Remove the last digit
printf("Enter a number: "); count++; // Increment the count
scanf("%d", &num); }
}
// Handle negative numbers
if (num < 0) { // Output the result
num = -num; // Convert to positive printf("The number of digits is: %d\n", count);
}
return 0;
// Special case for 0 }
WAP to display the series: 1/2 ,2/3,3/4,4/5, …. n-
1/n
WAP to display the series: 1/2 ,2/3,3/4,4/5, …. n-
1/n
#include <stdio.h> // Display the series
printf("The series is:\n");
int main() { for (i = 1; i < n; i++)
int n, i; {
printf("%d/%d", i, i + 1);
// Input the value of n if (i < n - 1) {
printf("Enter the value of n: "); printf("\t"); // Add a tab space between terms
scanf("%d", &n); }
}
// Check if n is valid printf("\n");
if (n < 2) { }
printf("The series requires n >= 2.\n");
} return 0;
else }
{
Program to generate a series
Code
#include <stdio.h> sum += i * (i - 1);
int main() { }
int n, i; printf("The sum of the series is:
int sum = 1; %d\n", sum);
printf("Enter the value of n: "); return 0;
scanf("%d", &n); }
for (i = 1; i <= n; i++)
{
WAP to create a hailstone series given a first number ‘x’ by user up to nth term.
example: if x=17, series will be: 17, 52, 26, 13, 40, 20…. So on
Code
#include <stdio.h> if (x % 2 == 0) {
x = x / 2; // If x is even, divide by 2
int main() { } else {
int x, n, count = 1; x = 3 * x + 1; // If x is odd, multiply by 3 and add 1
}
// Input the first number x and the number of terms n printf("%d ", x); // Print the next term
printf("Enter the first number (x): "); count++; // Increment the term counter
scanf("%d", &x); }
printf("Enter the number of terms (n): "); printf("\n"); // Print a newline after the series is complete
scanf("%d", &n); return 0;
// Display the first term }
printf("Hailstone series: ");
printf("%d ", x);
// Generate the sequence up to nth term
while (count < n) {
UNCONDITIONAL CONTROL STATEMENTS:
• Unconditional branching is when the programmer forces the
execution of a program to jump to another part of the program.
• C Supports the following unconditional control statements:
1. BREAK
2. CONTINUE
3. GOTO
Break
• It is used to terminate a switch statement. BREAK is a keyword that
allows us to jump out of a loop instantly, without waiting to get back
to the conditional test.
• The break statement terminates the loop (for, while and do...while
loop) immediately when it is encountered. The break statement is
used with decision making statement such as if...else.
Syntax of break statement
break;
Contd…
• Where It’s Used: Primarily in loops (for, while, do-while) and switch
statements.
• Example:
#include <stdio.h> Output:
0
int main() { 1
for (int i = 0; i < 5; i++) { 2
if (i == 3) {
break; // Breaks the loop when i equals 3
}
printf("%d\n", i);
}
return 0;
}
The continue Statement
• The continue statement skips the current iteration of the loop and
proceeds to the next iteration.
Syntax: #include <stdio.h>
int main()
continue; {
for (int i = 0; i < 5; i++)
{
if (i == 3)
Output {
0 continue; // Skips printing 3
1 }
2 printf("%d\n", i);
4 }
return 0;
}
Example
Goto statement
• The goto statement transfers control to another part of the program
(a label). It’s a direct jump in the program’s flow.
• Syntax:
goto label:
• Use of goto statement is highly discouraged in any programming
language because it makes difficult to trace the control flow of a
program, making the program hard to understand and hard to modify.
Any program that uses a goto can be rewritten to avoid them
Example
#include <stdio.h>
int main() {
int i = 0; Output:
start: 0
if (i >= 5) 1
2
return 0; 3
printf("%d\n", i); 4
i++;
goto start; // Jumps back to start label
}
Comparison of break, continue, and goto
• break:
• Exits from loops or switch statements.
• Typically used when a condition is met.
• continue:
• Skips to the next iteration of the loop.
• Useful for skipping unwanted cases or conditions.
• goto:
• Transfers control to a labeled part of the program.
Avoid its overuse to keep code readable and maintainable.
Use Cases and Best Practices
• When to Use break:
• Exiting loops early when a condition is satisfied.
• Example: Searching for an item in a list.
• When to Use continue:
• Skipping unnecessary iterations in loops.
• Example: Filtering out unwanted values in a loop.
• When to Use goto:
• Rarely used in modern C programming due to readability concerns.
• It can be useful in error handling or breaking out of nested loops in complex
programs, but try to avoid it when possible.
Practice Session (5 C)
1. WAP to check whether the entered number is prime number or not.
2. WAP to read two integers n1 and n2. Display all the even numbers between
these two numbers. Also count the frequency of these even numbers.
3. WAP to check whether entered number is perfect number or not.
Hint: Perfect number, a positive integer that is equal to the sum of its proper divisors. The
smallest perfect number is 6, which is the sum of 1, 2, and 3. Other perfect numbers are 28,
496, and 8,128.
4. WAP to input 5 digit number and display its digits in words.
5. WAP to convert decimal number to binary number.
6. WAP to check the entered number is strong or not.
Strong number is a special number whose sum of the factorial of digits is equal to the original
number. For Example: 145 is strong number. Since, 1! + 4! + 5! = 145.
WAP to check whether the entered number is prime number
or not.
Code
#include <stdio.h> if (num % i == 0) {
#include <math.h> divisorCount++;
break;
int main() { }
int num, i, divisorCount = 0; }
printf("Enter a number: "); if (divisorCount == 0) {
scanf("%d", &num); printf("%d is a prime number.\n", num);
if (num <= 1) { } else {
printf("%d is not a prime number.\n", num); printf("%d is not a prime number.\n", num);
return 0; }
} return 0;
for (i = 2; i <= sqrt(num); i++) { }
WAP to read two integers n1 and n2. Display all the even numbers between these
two numbers. Also count the frequency of these even numbers
#include <stdio.h> for (i = n1; i <= n2; i++) {
int main() { if (i % 2 == 0) {
int n1, n2, i, count = 0, temp; printf("%d ", i);
printf("Enter two integers (n1 and n2): "); count++;
scanf("%d %d", &n1, &n2); }
if (n1 > n2) { }
temp = n1; printf("\nTotal even numbers: %d\n",
n1 = n2; count);
n2 = temp; return 0;
} }
printf("Even numbers between %d and %d
are:\n", n1, n2);
WAP to check whether a given number is perfect square or not.
#include <stdio.h> printf("%d is a perfect
int main() { number.\n", num);
int num, sum = 0, i; } else {
printf("Enter a number: "); printf("%d is not a perfect
number.\n", num);
scanf("%d", &num);
}
for (i = 1; i <= num / 2; i++) {
return 0;
if (num % i == 0) {
}
sum += i;
}
}
if (sum == num) {
Display digits to word
#include <stdio.h> break; break;
int main() { case 1: printf("One "); case 9: printf("Nine ");
int num, digit, i; break; break;
printf("Enter a 5-digit number: "); case 2: printf("Two "); }
scanf("%d", &num); break; }
if (num < 10000 || num > 99999) { case 3: printf("Three "); printf("\n");
break;
printf("Please enter a valid 5- }
digit number.\n"); case 4: printf("Four ");
return 0;
} else { break;
printf("The digits in words are: case 5: printf("Five ");
}
");
break;
for (i = 10000; i >= 1; i /= 10) {
case 6: printf("Six ");
digit = num / i;
break;
num = num % i;
case 7: printf("Seven ");
switch (digit) { break;
case 0: printf("Zero "); case 8: printf("Eight ");
WAP to convert decimal number to binary number.
#include <stdio.h> while (n > 0) {
r = n % 2;
int main() { b = b + r * p;
int n, r; p = p * 10;
int b = 0, p = 1; n = n/ 2;
printf("Enter a decimal number: "); }
scanf("%d", &n); printf("Binary equivalent: %d\n",
if (n == 0) { b);
printf("Binary equivalent: 0\n"); return 0;
return 0; }
}
WAP to check the entered number is strong or not.
#include <stdio.h> sum += fact;
int main() { temp /= 10;
int n, sum = 0, temp, digit, fact; }
printf("Enter a number: "); if (sum == n) {
scanf("%d", &n); printf("%d is a Strong number.\n",
temp = n; n);
while (temp > 0) { } else {
digit = temp % 10; printf("%d is not a Strong
number.\n", n);
fact = 1;
}
for (int i = 1; i <= digit; i++) {
return 0;
fact *= i;
}
}
Practice Session 5(D)
1. WAP to enter a number and add the digits till the sum of digits becomes a single
one. example: 65415 6
2. WAP to display all the prime numbers between n1 to n2 where n1 and n2 are
given by users.
3. WAP to display all Armstrong numbers in a certain range[from n1 to n2] given by
user.
4. WAP to compute the sine series.
sin(x)=x-x3/3! +x5/5!-x7/7!+….up to nth terms
5. WAP to compute the cosine series.
cos(x)= 1- x2/2!+x4/4!- x6/6!+ …. upto nth terms
6. WAP to display Armstrong number from 100 to 900.
7. WAP to add two binary numbers.
WAP to enter a number and add the digits till the sum of digits becomes
a single one. example: 65415 6
##include <stdio.h> num /= 10;
int main() { }
int num, digit_sum; num = digit_sum;
printf("Enter a number: "); }
scanf("%d", &num); printf("Final single-digit sum:
while (num >= 10) { %d\n", num);
digit_sum = 0; return 0;
while (num > 0) { }
digit_sum += num % 10;
WAP to display all the prime numbers between n1 to n2 where n1 and n2 are
given by users.
#include<stdio.h> flag = 0;
int main() { break;
int i, j, flag, n1, n2; }
printf("Enter n1 and n2: "); }
scanf("%d%d", &n1, &n2); if(flag == 1) {
printf("The prime numbers from %d to %d are:\n", n1, n2); printf("%3d ", i);
for(i = n1; i <= n2; i++) }
{ }
if(i < 2) { return 0;
continue; }
}
flag = 1;
for(j = 2; j <= i / 2; j++) {
if(i % j == 0) {
Armstrong number from n1 to n2
#include <stdio.h> int j = i;
#include <math.h> while (j != 0) {
rem = j % 10;
int main() { res += pow(rem, dig);
int n1, n2, num, orig, rem, res, dig; j /= 10;
printf("Enter n1 and n2: "); }
scanf("%d %d", &n1, &n2); if (res == i) {
printf("Armstrong numbers between %d and %d are:\n", printf("%d ", i);
n1, n2); }
for (int i = n1; i <= n2; i++) { }
orig = i; printf("\n");
res = 0; return 0;
dig = 0; }
while (orig != 0) {
orig /= 10;
dig++;
}
orig = i;
WAP to calculate the value of sine series, by summing first n terms of Maclaurin series.
(Hint: sin x = x – x3/3! + x5/5! – x7/7!+… )
#include <stdio.h> } else {
#include <math.h> sum = sum - pow(x, j) / fac;
int main() { }
float x, Q, sum = 0; }
int i, j, limit, fac; float sin_builtin = sin(x);
printf("Enter the value of x of sinx series (in degrees): "); printf("Sin(%0.1f) using Maclaurin series: %f\n", Q, sum);
scanf("%f", &x); printf("Sin(%0.1f) using built-in sin() function: %f\n", Q, sin_builtin);
printf("Enter the limit up to which you want to expand the series: "); return 0;
scanf("%d", &limit); }
Q = x;
x = x * (3.1415 / 180); // Convert x to radians
for (i = 1; i <= limit; i++) {
j = 2 * i - 1; // j takes values 1, 3, 5, 7, ...
fac = 1;
for (int k = 1; k <= j; k++) {
fac *= k;
}
if (i % 2 != 0) {
sum = sum + pow(x, j) / fac;
WAP to compute the cosine series.
printf("%d",j);
printf("\n");
return 0;
}
Write a code to generate the following
pattern.
11111
22222
for (i=1; i<=rows; i++) 33333
for(j=1; j<=cols;j++)
printf(“%d”,i); 44444
printf(“\n”);
55555
Note here: the content in each rows are same.
so have to simply print row number.
WAP to generate the following pattern
#include <stdio.h>
int main() { A B C D E
int i, j, rows, col; A B C D E
printf("Enter row and column\t"); A B C D E
printf("%c",j+65);
printf("\n");
return 0;
}
WAP to generate the following pattern
#include <stdio.h>
int main() { A A A A A
int i, j, rows, col; B B B B B
printf("Enter row and column\t"); C C C C C
D D D D D
scanf("%d %d", &rows,&col);
E E E E E
for (i = 0; i <rows; ++i) {
printf("%c",i+65);
printf("\n");
return 0;
}
Right Half Pyramid
C program to print right half pyramid pattern of star
#include <stdio.h>
int main() Here,
User can ask the no of rows as input from user
{
and the pattern as per the requirement can be
int rows = 5; generated
// first loop for printing rows
for (int i = 0; i < rows; i++) {
// second loop for printing character in each rows
for (int j = 0; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Write C code to generate following pattern.
#include <stdio.h>
int main()
{
int rows = 5, i,k;
int main()
{
int rows = 5, i,j;
int main()
{
int rows = 5, i,j,k;
for (int i = rows; i >= 1; i--) {
for ( j = 1; j <= i; j++) {
printf("%c",'A'+j-1);
}
printf("\n");
}
return 0;
}
Write C program code to generate following
pattern
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("%d ", i);
}
printf("\n"); Change
printf(“%d”,j); to printf(“%d”,i);
}
return 0;
}
Write C code to realize the following pattern.
#include <stdio.h>
int main()
{
int rows = 5, i,j;
for (int i = 1; i <=5; i++) {
for ( j = 1; j <= i; j++) {
printf("%c",'A'+i-1);
}
printf("\n");
}
return 0;
}
Left Half Pyramid Pattern in C
C program to print left half pyramid pattern of star
#include <stdio.h> }
int main() printf("\n");
{ }
int rows = 5,i, j,k; return 0;
// first loop is for printing the rows }
for (i = 1; i <= rows; i++) { Here,
// loop for printing leading whitespaces User can ask the no of rows as input from user
and the pattern as per the requirement can be
for ( j = 1; j < = (rows - i) ; j++)
generated
{
printf(" ");
}
// loop for printing * character
for (k = 1; k <= i; k++) {
printf("*");
Write C code to generate following pattern.
#include <stdio.h>
int main()
{
int rows = 5,i, j,k;
// first loop is for printing the rows
for (i = rows; i >= 1; i--)
{
// loop for printing leading whitespaces
for ( j = 1; j <= (rows - i) ; j++)
{
printf(" ");
}
// loop for printing * character
for (k = 1; k <= i; k++) {
printf("*");
}
printf("\n");
}
return 0;
}
How to generate output shown below?
#include <stdio.h>
int main()
{
int rows = 5, i,j,k;
int main()
{
int rows = 5, i,j,k;
int main()
{
int rows = 5, i,j,k;
int main()
{
int rows = 4;
int n = 1;
int main() {
char str[] = "PULCHOWK"; // The string to be printed
int i, j;
char result;
return 0;
Write code for following
P
PU
PuL Logic
if i%2!=0
PULC upper case
else
PulcH if (j%2==0)
upper case
PULCHO else
PulcHoW case
PULCHOWK
#include <stdio.h> {
// For odd index (j), make the letter lowercase
int main() { result = str[j] + 32; // Convert to lowercase
char str[] = "PULCHOWK"; // The string to be printed }
int i, j; printf("%c", result);
char result; }
if(j%2==0)
{
// For even index (j), make the letter uppercase
result = str[j]; // Convert to uppercase
}
else
Generate following pattern using unformatted
I/O
Programming
rogrammin
ogrammi
gramm
ram
a
Code
#include <stdio.h> for (j = i; j < =len-i ; j++) {
putchar(str[j]); /* Print each
int main() { character one by one*/
char str[] = "Programming"; }
int i, j; putchar('\n'); // Move to the next line
int len = 10; /*Fixed length of }
"Programming“*/
return 0;
// Loop for each line }
for (i = 0; i < len; i++) {
Write a program in C to generate following pattern using
unformatted input/ouput functions only.
Code
#include <stdio.h>
// Print the characters
int main() { for (j = 0; j < k; j++) {
char pattern[] = "NePaL"; putchar(pattern[i]);
int i, j, k = 1; }