0% found this document useful (0 votes)
3 views158 pages

Chapter 5 Control Structure

Chapter 5 discusses control structures in programming, which manage the flow of execution in a program through sequential, selective, and repetitive structures. It explains how sequential structures execute instructions linearly, selective structures allow decision-making based on conditions, and repetitive structures enable the execution of instructions multiple times. The chapter also covers various control statements in C, including if-else statements, switch statements, and loops.

Uploaded by

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

Chapter 5 Control Structure

Chapter 5 discusses control structures in programming, which manage the flow of execution in a program through sequential, selective, and repetitive structures. It explains how sequential structures execute instructions linearly, selective structures allow decision-making based on conditions, and repetitive structures enable the execution of instructions multiple times. The chapter also covers various control statements in C, including if-else statements, switch statements, and loops.

Uploaded by

mahendrarokaya21
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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

executed only once.

• 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

some conditions) structure.


Control Structure
• A control structure is a block of code that manages the flow of
execution in a program.
• Control structures dictate the order in which statements are executed
based on certain conditions.
• Types of control structures:
• Sequential Structure
• Selection Structure (Conditional Statements)
• Repetition Structure (Loops)
Sequential Structure
• A sequentially structured program executes all instructions line by line
until the end of the program is reached. All the instructions are
executed only once and none of the instructions are skipped.
• The default structure is where statements are executed one after the
other in sequence.
Sequential Structure
• An example of sequential program is shown below. The program will
display the sum of two numbers entered by the user.
Algorithm C code
1. Start the program. #include<stdio.h>
2. Read two numbers. void main(){
3. Add those numbers. int a,b,c;
scanf("%d%d",&a,&b);
4. Display the result.
c = a + b;
5. End the program printf("%d",c);
}
Selective Statement
• A selective structure allows to make decisions using a logical test and
branch to some part of the program depending upon the outcome of
the test.
• The logical test enables us to take one of two possible actions
because the result of the logical test will either be true or false.
• If the test result is true, some instructions are executed, otherwise
some other instructions are executed and after that the normal flow
of the program resumes. The process is called branching and the
statement that causes it is called control statement.
The program determines whether a number entered by the user is odd or even.

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:

while(i < 10) Hello World


Hello World
{ Hello World
Hello World
printf("Hello World\n"); Hello World
i=i+1; Hello World
Hello World
} Hello World
Hello World
return 0; Hello World

}
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.

Syntax: statement-2; else


if(test-condition-1) } {
{ } statement-4
if(test-condition-2) else }
{ { }
statement-1; if(test-condition-3) statement-x
} {
else statement-3;
{ }
Flowchart structure
else… if Ladder:
• A multipath decision is a chain of 'if's' in which the statement associated with each else is an if and last else
if’s else part contain only else.
• The conditions are evaluated from the top to bottom. As soon as true condition is found, the statement
associated with it is executed and the control is transferred to statement-x(skipping the rest of ladder) when
all the conditions become false, then the final else containing the default statement will be executed.
• Syntax:
if(condition-1)
Statement-1;
else if(condition-2)
Statement -2;
else if(condition-n)
Statement -n;
else
Default Statement; Statement -x;
Switch statement:
• A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and
the variable being switched on is checked for each switch case.
The following rules apply to a switch statement –
1. The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which
the class has a single conversion function to an integral or enumerated type.
2. You can have any number of case statements within a switch. Each case is followed by the value to be compared to
and a colon (:).
3. The constant-expression for a case must be the same data type as the variable in the switch, and it must be a
constant or a literal.
4. When the variable being switched on is equal to a case, the statements following that case will execute until a break
statement is reached.
5. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following
the switch statement.
6. Not every case needs to contain a break. If no break appears, the flow of control will follow through to subsequent
cases until a break is reached.
7. A switch statement can have an optional default case, which must appear at the end of th switch. The default case
can be used for performing a task when none of the cases is true. No break is needed in the default case
Syntax:
switch(expression)
{
case constant-expression-1 : statement(s);
break;
case constant-expression-2 : statement(s);
break;
...
case constant-expression-n : statement(s);
break;
default : statement(s);
}
Problem discussions
C program calculate the absolute value of an integer using if statement.
# include<stdio.h >
void main( )
{
int numbers; Output:
clrscr(); Type a number: -10
The absolute value is 10
printf (“Type a number:”);
scanf (“%d”, & number);
if (number < 0)
{
number = – number;
}
printf (“\nThe absolute value is % d ”, number);
getch(); }
C Program to check equivalence of two
numbers using if statement
#include<conio.h>
#include<stdio.h>
void main()
{
Output:
int m,n;
enter two numbers:12 12
clrscr();
two numbers are equal
printf(" \n enter two numbers:");
scanf(" %d %d", &m, &n);
if(m-n= = 0)
printf(" \n two numbers are
equal");
getch();
} Note: if statement will execute one statement below to it by default. if we
want to execute more than one statement, then those all statements we have
to group in open and close Curly brackets { and }.
C program to read any number as input through the keyboard and find out whether
it is Odd Number or Even Number.
#include<stdio.h>
#include<conio.h>
void main()
{
int n; Output:
clrscr(); Enter the Number 24
printf("Enter the Number");
This is Even Number
scanf("%d",&n);
if(n%2==0)
{
printf(“\nThis is Even Number");
}
else
{
printf(“\nThis is Odd Number");
}
getch(); }
C program to find biggest among two numbers using if else.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter the two Number"); OUTPUT:
scanf("%d%d",&a,&b); Enter the two Number 12 13
if(a>b) The number 13 is bigger.
{
printf("The number a=%d is bigger”, a);
}
else
{
printf("The number b=%d is bigger”,b);
}
getch();
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
scanf(“%d”,&x);
if (x < 0)
printf(“\n the no. u entered is negative”);
else
{
if (x == 0)
printf(“\nthe no. u entered is 0”);
else
printf(“\nthe no. u entered is positive”);
}
getch();
}
C Program to print grade of a student using If Else Ladder 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> printf("The number %d is divisible by


int main() 5 but not by 11.\n", num);
{ }
int num; else
// Input the number {
printf("Enter a number: "); printf("The number %d does not
satisfy the condition.\n", num);
scanf("%d", &num); }
// Check divisibility conditions return 0;
if (num % 5 == 0 && num % 11 != 0) }
{
WAP to read a character from keyboard. Convert it to uppercase if it is lower case and vice versa

#include <stdio.h> // Convert to lowercase by adding 32 to the ASCII value


int main() { ch = ch + 32;
char ch; printf("Converted to lowercase: %c\n", ch);
// Input a character } else {
printf("Enter a character: "); // Handle non-alphabetic characters
scanf("%c", &ch); printf("The character '%c' is not an alphabetic character.\n",
ch);
// Check if the character is lowercase (ASCII range: 97-122)
}
if (ch >= 'a' && ch <= 'z') {
// Convert to uppercase by subtracting 32 from the ASCII
value return 0;
ch = ch - 32; }
printf("Converted to uppercase: %c\n", ch);
}
// Check if the character is uppercase (ASCII range: 65-90)
else if (ch >= 'A' && ch <= 'Z') {
WAP to check a number odd or even using bitwise operator.
#include <stdio.h>
int main() { Explanation
int num; Bitwise AND (&):
The binary representation of numbers ends in 0 for even
// Input the number numbers and 1 for odd numbers. For example:4 (even) in
printf("Enter a number: "); binary: 0100, and 4 & 1 is 0.5 (odd) in binary: 0101, and 5 & 1 is
scanf("%d", &num); 1.
By performing num & 1:If the result is 1, the number is [Link]
// Use bitwise AND to check if the last bit is 1 the result is 0, the number is even.
if (num & 1) {
printf("%d is an odd number.\n", num);
} else {
printf("%d is an even number.\n", num);
}
return 0;
}
WAP to find the second largest number among three variables.

#include <stdio.h> else {


int main() { second_largest = num3;
int num1, num2, num3, second_largest; }
// Input three numbers // Output the second largest number
printf("Enter three numbers: "); printf("The second largest number is: %d\n", second_largest);
scanf("%d %d %d", &num1, &num2, &num3); return 0;
// Logic to find the second largest number }
if ((num1 > num2 && num1 < num3) || (num1 > num3 && num1 < num2))
{
second_largest = num1;
}
else if ((num2 > num1 && num2 < num3) || (num2 > num3 && num2 < num1))
{
second_largest = num2;
}
WAP to find largest among three number using binary minus operator.

#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:

•Input two characters (alphabets).


•Find their positions in the alphabet (ASCII values).
•Subtract the ASCII values of the two characters to get the number of characters between them.
•The number of characters between the two will be the absolute difference minus 1.

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

if (char2 >= 'a' && char2 <= 'z') { return 0;

char2 = char2 - 32; // Convert to uppercase }

}
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

Note: if condition fails very first time the body of the


loop will not be executed.
Note: even if condition fails first time but body of
loop will execute minimum one time.
Contd…
• There are three loops in C programming:
1. for loop
2. while loop
3. do...while loop
for Loop
• for loop in C programming is a repetition control structure that allows
programmers to write a loop that will be executed a specific number
of times. for loop enables programmers to perform n number of steps
together in a single line.
• Syntax:
for (initialize expression; test expression; update expression) Example:
{
// for(int i = 0; i < n; ++i)
// body of for loop {
// printf("Body of for loop which will execute till n");
} }
Working of for loop
• In for loop, a loop variable is used to control the loop.
• Firstly we initialize the loop variable with some value, then check its
test condition.
• If the statement is true then control will move to the body and the
body of for loop will be executed.
• Steps will be repeated till the exit condition becomes true. If the test
condition will be false then it will stop.
Contd…
• Initialization Expression: In this expression, we assign a loop variable
or loop counter to some value. for example: int i=1;
• Test Expression: In this expression, test conditions are performed. If
the condition evaluates to true then the loop body will be executed
and then an update of the loop variable is done. If the test expression
becomes false then the control will exit from the loop. for example,
i<=9;
• Update Expression: After execution of the loop body loop variable is
updated by some value it could be incremented, decremented,
multiplied, or divided by any value.
For loop flowchart
Example:
// C program to print Hello World 10 times • Output
#include <stdio.h> Hello World
Hello World
int main() Hello World
{ Hello World
int i = 0; Hello World
for (i = 1; i <= 10; i++) Hello World
{ Hello World
printf( "Hello World\n"); Hello World
} Hello World
return 0; Hello World
}
Problems using for loop
• WAP to calculate the sum of first n natural numbers.
• WAP to find sum and average of n numbers given by user.
• WAP Program to find Factorial of a Number.
• WAP to generate Fibonacci series upto n terms entered by user.
• WAP to print “Nepal is beautiful” n times, where n is given by user.
• WAP for generating multiplication table for the given number using C
for loop
Example: C Program to calculate the sum of first n natural numbers.
#include <stdio.h>
#include<conio.h> void main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when n is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
getch();
}
Program to find sum and average of n numbers given by user

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

4 ) As mentioned above, the counter variable can be decremented as well. In


the below example the variable gets decremented each time the loop runs
until the condition num>10 returns false. for(num=20; num>10; num--)
Nested for in C
#include <stdio.h>
void main()
{ 0, 0
0, 1
for (int i=0; i<2; i++) 0, 2
{ 0, 3
for (int j=0; j<4; j++) 1, 0
1, 1
{ 1, 2
printf("%d, %d\n",i ,j); } 1, 3
}
getch();
}
In the above example we have a for loop inside another for loop,
this is called nesting of loops.
While loop
Flowchart:
• while loop has one control condition, and executes as
long the condition is true. The condition of the loop is
tested before the body of the loop is executed; hence it
is called an entry-controlled loop.
• Syntax:
Initialization of loop variable;
while (condition)
{
//body of loop statement(s);
updation of loop variable;
}
Contd…
• Working:
step1: The loop variable is initialized with some value and then it has
been tested for the condition.
step2: If the condition returns true then the statements inside the body
of while loop are executed else control comes out of the loop.
step3: The value of loop variable is incremented/decremented then it
has been tested again for the loop condition.
Problems:
• Write a program to Calculate sum of digits using while loop.
• Write a program to generate Fibonacci Sequence Up to a Certain
Number using while loop.
• Write a program to find reverse of a number entered by user.
• WAP to check whether a given number is palindrome or not
C program to Calculate sum of digits using while
loop.
#include<stdio.h>
void main() {
int a, s;
printf("Enter value of a: ");
scanf("%d",&a);
s = 0;
while(a > 0)
{
s = s + (a%10); a = a / 10;
}
printf("Sum of digits: %d",s); getch();
}
C program to generate Fibonacci Sequence Up to a Certain Number

#include <stdio.h> t1 = t2; // Update t1 to t2


int main() t2 = nextTerm; // Update t2 to nextTerm
{ i = i + 1; // Increment the counter
int t1 = 0, t2 = 1, nextTerm = 0, n, i = 0; }
printf("Enter a positive number: "); return 0; // Ensure the program returns 0
scanf("%d", &n); }
printf("Fibonacci Series: ");
while (i < n)
{ // Use i < n to generate 'n' terms
printf("%d, ", t1); // Print the current term (t1)
nextTerm = t1 + t2; // Calculate the next term
Program to reverse given number
#include<stdio.h>
#include<conio.h>
void main()
{
int num, rem, rev=0;
clrscr();
printf("Enter number: ");
scanf("%d", &num);
while(num!=0)
{
rem = num%10; OUTPUT:
rev = rev*10 + rem; Enter number: 523
Reverse is 325
num = num/10;
}
printf("Reverse is %d", rev);
getch();
Palindrome number
#include <stdio.h> number
int main() }
{
int num, originalNum, reversedNum = 0, remainder; // Check if the number is a palindrome
// Input the number if (originalNum == reversedNum) {
printf("Enter a number: "); printf("%d is a palindrome.\n", originalNum);
scanf("%d", &num); } else {
originalNum = num; // Store the original number printf("%d is not a palindrome.\n", originalNum);
// Reverse the number using a while loop }
while (num != 0) {
remainder = num % 10; // Get the last digit return 0;
reversedNum = reversedNum * 10 + remainder; //
Build the reversed number
}
num /= 10; // Remove the last digit from the
do while
• d o-while loop: is an exit controlled loop i.e. the condition is checked at the end of loop. It means the
statements inside do-while loop are executed at least once even if the condition is false. Do-while loop is an
variant of while loop.

Syntax:
Initialization of loop variable;
do
{
statement 1; statement 2; …………. statement n;
updation of loop variable;
}while (condition);

NOTE: We have to place semi-colon after the While condition.


Flowchart
Contd…
Working:
1. First we initialize our variables, next it will enter into the Do While loop.
2. It will execute the group of statements inside the loop.
3. Next we have to use Increment and Decrement Operator inside the loop
to increment or decrements the value.
4. Now it will check for the condition. If the condition is True, then the
statements inside the do while loop will be executed again. It will continue
the process as long as the condition is True.
5. If the condition is False then it will exit from the loop.
Using do while loop
• WAP to calculate factorial of n.
• Write a C program to print the sum of all even and odd numbers up to
n.
• Program to add floating numbers until the user enters zero.
• Program to check an entered number a palindrome or not.
Palindrome: Numbers like 0,1,2,11,44,121,222,242,345543 are called as Palindrome Numbers. The
original number and reverse of the numbers are same.
C program to calculate factorial value using do while.

#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.

#include <stdio.h> for (i = 1; i <= n; i++) {


result *= m; // Multiply m n times
int main() { }
int m, n, i; // Output the result
long long result = 1; // Use long long to handle large results printf("%d to the power of %d is: %lld\n", m, n, result);
}
// Input base (m) and exponent (n) else
printf("Enter the base (m): "); {
scanf("%d", &m); printf(“Please enter positive power”);
printf("Enter the exponent (n): "); }
scanf("%d", &n); return 0;
if(n>0) }
{

// 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: 65415 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: 65415 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.

cos(x)= 1- x2/2!+x4/4!- x6/6!+ …. upto nth terms


#include <stdio.h> result -= term; // Subtract the negative terms
#include <math.h> }
int main() { }
double x, result = 1.0, term; // Output the result
int n; printf("cos(%.2lf) using %d terms = %.8lf\n", x, n, result);
printf("Enter the angle in radians: "); // Using built-in cos() function for comparison
scanf("%lf", &x); printf("cos(%.2lf) using built-in cos() function = %.8lf\n", x,
cos(x));
printf("Enter the number of terms in the series: ");
scanf("%d", &n);
return 0;
for (int i = 1; i < n; i++) {
}
int power = 2 * i; // Even powers (2, 4, 6, ...)
long long fact = 1;
for (int j = 1; j <= power; j++) {
fact *= j;
}
term = pow(x, power) / fact;
if (i % 2 == 0) {
result += term; // Add the positive terms
} else {
Pattern Generation in C
Using Nested Loop
Rectangle Pattern

***** 12345 ABCD


***** 12345 ABCD
***** 12345 ABCD
***** 12345 ABCD

Star Number Alphabets


Algorithm
• Algorithm to print rectangular star pattern using loop
Take the number of rows(N) and columns(M) of rectangle as input
from user using scanf function.
• We will use two for loops to print rectangular star pattern.
• Outer for loop will iterate N times. In each iteration, it will print one row of
pattern.
• Inner for loop will iterate M [Link] one iteration, it will print *, number or
characters in a row.
Rectangle Pattern(Star)
#include <stdio.h>
int main() {
int i, j, rows, col;
printf("Enter row and column");
scanf("%d%d", &rows,&col);
for (i = 1; i <=rows; ++i)
{
for (j = 1; j <= col; ++j)
This is the matrix representation of the
{
rectangle star pattern. The row
printf”*”); numbers are represented by i whereas
} column numbers are represented by j.
printf("\n");
}
return 0;
}
Write a code to generate following pattern
12345
12345
12345
12345
Rectangle Pattern(Number)
#include <stdio.h>
int main() {

int i, j, rows, col;

printf("Enter row and column\t");

scanf("%d %d", &rows,&col);

for (i = 1; i <=rows; i++)// for(i=1;i<=rows;i++)


{

for (j = 1; j <= col;j++) // for(i=1;i<=col;i++)


{

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

scanf("%d %d", &rows,&col);


A B C D E
A B C D E
for (i = 1; i <= rows; ++i) {

for (j = 0; j <col; ++j) {

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

for (j = 0; j < col; ++j) {

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;

// first loop is for printing the rows


for (i = rows; i >= 1; i--) {
for ( k = 1; k <= i; k++)
{
printf("*");
}
printf("\n");
}
return 0;
}
C program to print right half pyramid pattern
of number
#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 ", j);
}
printf("\n");
}
return 0;
}
Write C code to generate following pattern.
#include <stdio.h>

int main()
{
int rows = 5, i,j;

// first loop is for printing the rows


for (i = rows; i >= 1; i--) {
for ( j = 1; j <= i; j++)
{
printf(“%d“,j);
}
printf("\n");
}
return 0;
}
C program to print right half pyramid pattern
of alphabets
#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("%c ", 'A'+j-1);
}
printf("\n");
}
return 0;
}
Write C code to realize the following pattern.
#include <stdio.h>

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;

// first loop is for printing the rows


for (int i = 1; i <= rows; i++) {

// loop for printing leading whitespaces


for (j = 1; j <=(rows - i); j++)
{
printf(" ");
}
// loop for printing continious numbers
for ( k = 1; k <= i; k++)
{
printf("%d",k );
}
printf("\n");
}
return 0;
}
Write C code to generate the 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(“%d“,k);
}
printf("\n");
}
return 0;
}
How to generate following output?
#include <stdio.h>

int main()
{
int rows = 5, i,j,k;

// first loop is for printing the rows


for (int i = 1; i <= rows; i++) {

// loop for printing leading whitespaces


for (j = 1; j <=(rows - i); j++) {
printf(" ");
}

// loop for printing continious numbers


for ( k = 1; k <= i; k++) {
printf("%c",'A'+k-1 );
}
printf("\n");
}
return 0;
}
How to generate following output?
#include <stdio.h>

int main()
{
int rows = 5, i,j,k;

// first loop is for printing the rows


for (int i = rows; i>= 1; i--)
{

// loop for printing leading whitespaces


for (j = 1; j <=(rows - i); j++) {
printf(" ");
}

// loop for printing continious numbers


for ( k = 1; k <= i; k++) {
printf("%c",'A'+k-1 );
}
printf("\n");
}
return 0;
}
Full Pyramid In C

for ( i = 1; i <= rows; i++) {


// loop for printing leading whitespaces
for (j = 1; j <=(rows - i); j++)
{
printf(" "); Here k runs from 1 to 2*i-1 because
} for i=2, we require 3 stars to print,
// loop for printing continous numbers for i=3, we require 5 stars to print,
for ( k = 1; k <= 2*i-1; k++) { for i=I, we require 2*i-1 stars to print
printf("*");
}
printf("\n");
}
Full Pyramid with Star
#include <stdio.h> }
int main() // loop for printing continious numbers
{ for ( k = 1; k <= 2*i-1; k++) {
int rows = 5, i,j,k; printf("*");
// first loop is for printing the rows }
for ( i = 1; i <= rows; i++) { printf("\n");
// loop for printing leading whitespaces }
for (j = 1; j <=(rows - i); j++) return 0;
{ }
printf(" ");
Full Pyramid with Number
#include <stdio.h> }
int main() // loop for printing continious numbers
{ for ( k = 1; k <= 2*i-1; k++) {
int rows = 5, i,j,k; printf(“%d“,k);
// first loop is for printing the rows }
for ( i = 1; i <= rows; i++) { printf("\n");
// loop for printing leading whitespaces }
for (j = 1; j <=(rows - i); j++) return 0;
{ }
printf(" ");
Full Pyramid with Alphabets
#include <stdio.h> }
int main() // loop for printing continious numbers
{ for ( k = 1; k <= 2*i-1; k++) {
int rows = 5, i,j,k; printf(“%c“,’A’+k-1);
// first loop is for printing the rows }
for ( i = 1; i <= rows; i++) { printf("\n");
// loop for printing leading whitespaces }
for (j = 1; j <=(rows - i); j++) return 0;
{ }
printf(" ");
Write C code to generate the 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 continious numbers
for ( k = 1; k <= 2*i-1; k++) {
printf("*");
}
printf("\n");
}
return 0;
}
Write C code to generate the pattern

for ( i =rows; i >=1; i--) {


// loop for printing leading whitespaces
for (j = 1; j <=(rows - i); j++)
{
printf(" ");
}
// loop for printing continious numbers
for ( k = 1; k <= 2*i-1; k++) {
printf(“ %d",k); // printf(“%c”,’A’+k);
}
printf("\n");
}
Rhombus Pattern
#include <stdio.h>
int main()
{
int rows = 5, i,j,k;
// first loop is for printing the rows
for ( i =1; i <=rows; i++) {
// loop for printing leading whitespaces
for (j = 1; j <=rows-i; j++)
{
printf(" ");
}
rows=5 // loop for printing continious numbers
for i=1, space=4 for ( k = 1; k <= rows; k++)
for i=2, space=3 {
for i=3, space=2 printf("%c",'A'+k-1);
for i=4, space=1 }
for i=5, space=0 printf("\n");
so for i=i, space=rows-i }
return 0;
}
Floyd's Triangle #include <stdio.h>

int main()
{
int rows = 4;
int n = 1;

// outer loop to print all rows


for (int i = 1; i <=rows; i++)
{

// inner loop to print alphabet in each row


for (int j = 1; j <= i; j++) {
printf("%d ", n);
n=n+1;
}
printf("\n");
}
return 0;
}
Pascal’s Triangle
C program to generate
#include <stdio.h> // Print each value in the row dynamically
int main() { for (j = 0; j <= i; j++) {
int rows,space,i,j; printf("%d ", value); // Print the current value
printf("Enter the number of rows for Pascal's
Triangle: "); // Update the value dynamically for the next
scanf("%d", &rows); position
for (i = 0; i < rows; i++) { value = value * (i - j) / (j + 1);
int value = 1; // Initialize the first value of the }
row to 1 printf("\n"); // Move to the next row
}
// Print leading spaces for alignment
for ( space = 1; space <= rows - i - 1; space++) { return 0;
printf(" ");
}
}
Write a program to generate the following
pattern
P
Pu
PuL
PULC
PuLcH
PULCHO
pulcHoW
PULCHOWK
Code #include <stdio.h>

int main() {
char str[] = "PULCHOWK"; // The string to be printed
int i, j;
char result;

// Loop to print each row, limiting i to the length of the string


for (i = 1; i <= 8; i++) {
for (j = 0; j < i && j < 8; j++) { // Ensure j doesn't go out of bounds
if (j % 2 == 0) {
// For even index (j), make the letter uppercase
result = str[j] - 32; // Convert to uppercase
} else {
// For odd index (j), make the letter lowercase
result = str[j] + 32; // Convert to lowercase
}
printf("%c", result);
}
printf("\n"); // Newline after each row
}

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

for (i = 0; i <= 7; i++) { // Loop to print each row }


for (j = 0; j <= i; j++) { // Loop to print characters up to printf("\n"); // Newline after each row
the current row number }
if (i%2!= 0)
{ return 0;
printf("%c",str[j]); }
}
else{

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

// Loop for each row k += 2; // Increase the number of characters


for (i = 0; i < 5; i++) { in each row
putchar('\n'); // Move to the next row
// Print spaces for alignment
for (j = 0; j < 5 - i - 1; j++) { }
putchar(' ');
return 0;
}
}
End Of chapter 5

You might also like