Control Structures in C
Control structures in C are used to control the execution flow of a program and are
classified into selection, iteration, and jump statements.
1 Selection (Decision) Control Structures
Used to make decision or select .
if
→ Executes code when condition is true.
Example 1: WAP to generate which is greater number
#include <stdio.h>
int main()
{ a is greater than b
int a = 10, b = 5;
if (a > b)
{
printf("a is greater than b");
}
return 0;
}
if–else
→ Chooses between two blocks based on condition.
Example 2: WAP to check number is odd or even
#include <stdio.h>
Number is Odd
int main() {
int num = 7;
if (num % 2 == 0) {
printf("Number is Even");
} else {
printf("Number is Odd");
}
return 0;
}
Prepared By: [Link] Chand
else if ladder
→ Checks multiple conditions sequentially
Example:
#include <stdio.h>
int main()
{
float marks;
printf("Enter your marks (0-100): ");
scanf("%f", &marks); Output:
if(marks >= 60 && marks <= 100) Enter your marks (0-100): 72
First Division
{
printf("First Division\n");
}
else if(marks >= 50 && marks < 60)
{
printf("Second Division\n");
}
else if(marks >= 40 && marks < 50)
{
printf("Third Division\n");
}
else if(marks >= 0 && marks < 40)
{
printf("Fail\n");
}
else {
printf("Invalid marks entered!\n");
}
return 0;
}.
switch
→ Selects one case from many based on expression.
Prepared By: [Link] Chand
#include <stdio.h>
int main() {
int day = 2;
switch(day) {
case 1: printf("Sunday"); break;
Monday
case 2: printf("Monday"); break;
case 3: printf("Tuesday"); break;
default: printf("Invalid day");
}
return 0;
}
2️ Iteration (Looping) Control Structures
Control loops are used to repeat a block of code; for is used when iterations are known, while
when iterations are unknown, and do–while when the loop must execute at least once.
for loop
When number of iterations is known in advance
When working with arrays or fixed range
When counter-controlled loop is needed
Example1
#include <stdio.h>
int main()
12345
{
int i;
for(i = 1; i <= 5; i++)
{
printf("%d ", i);
}
return 0;
}
Prepared By: [Link] Chand
Example 2: Table of 3 3x1=3
#include <stdio.h> 3x2=6
int main() 3x3=9
{ 3 x 4 = 12
int i; 3 x 5 = 15
3 x 6 = 18
printf("Multiplication Table of 3:\n");
3 x 7 = 21
for (i = 1; i <= 10; i++)
3 x 8 = 24
{
3 x 9 = 27
printf("3 x %d = %d\n", i, 3 * i);
3 x 10 = 30
}
return 0;
Example 3:WAP to display the given pattern
12345
1234
123
12
1
Sloution:
Outer loop(i) → controls rows (5 to 1)
Inner loop(j) → prints numbers from 1 up to current row number
#include <stdio.h>
int main()
{
int i, j;
for(i = 5; i >= 1; i--)
Prepared By: [Link] Chand
{
for(j = 1; j <= i; j++)
{
printf("%d", j);
}
printf("\n");
}
return 0;
}
Example 4:WAP to display the given pattern
1
12
123
1234
12345
Sloution:
Outer loop(i) → controls rows (1 to 5)
Inner loop(j) → prints numbers from 5 up to current row number
#include <stdio.h>
int main()
{
int i, j;
for(i = 1; 1<=i; i++)
{
for(j = 1; j <= i; j++)
{
printf("%d", j);
}
printf("\n");
}
return 0;
}
Example 6:WAP to display the given pattern
*****
****
Prepared By: [Link] Chand
***
**
*
Sloution:
Outer loop(i) → controls rows (5 to 1)
Inner loop(j) → prints numbers from 1 up to current row number
#include <stdio.h>
int main()
{
int i, j;
for(i = 5; i >= 1; i--)
{
for(j = 1; j <= i; j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Example 7:WAP to display the given pattern
1
22
333
4444
55555
Solution:
#include <stdio.h>
int main()
{
int i, j;
for(i = 1; i <= 5; i++)
{
for(j = 1; j <= i; j++)
Prepared By: [Link] Chand
{
printf("%d", i);
}
printf("\n");
}
return 0;
}
Prepared By: [Link] Chand
while loop
Uses case
When number of iterations is unknown
When loop depends on a condition
When reading input until a condition becomes false
Examples (situations):
Reading input until user enters 0
Looping until file end is reached
Example 1: WAP to display natural numbers up to 5.
#include <stdio.h>
int main()
{
int i = 1;
while(i <= 5)
{
12345
printf("%d ", i);
i++;
}
return 0;
}
Example 2: WAP to find factorial number of 5
#include <stdio.h>
Prepared By: [Link] Chand
int main()
{
n fact = fact × n
int n = 5, fact = 1;
5 1×5=5
while(n > 0) 4 5 × 4 = 20
{ 3 20 × 3 = 60
fact = fact * n; 2 60 × 2 = 120
n-- ; 1 120 × 1 = 120
}
printf("Factorial = %d", fact);
return 0;
}
Example 3: WAP to calculate sum of digits of a given number.
#include<stdio.h>
int main()
{
int n,s=0,r;
If you asked product of digits then you
printf("Enter any number\t"); need to change S=P as a variable and
inside while
scanf("%d",&n);
You need to change P=P*r
while (n!=0)
Others same
{
r = n%10; // for find reminder
s = s+r; // gives new value of sum in every step
n = n/10; //new value of digit after exact division of iteration
}
printf("Sum of digits is %d\n",s);
return 0; Output
} Enter any number 657
Sum of digits is 19
Prepared By: [Link] Chand
Example 3: WAP to get reverse number using while loop
#include <stdio.h>
int main()
{
int num, reverse = 0, remainder;
printf("Enter a number: ");
scanf("%d", &num);
while(num != 0)
{
remainder = num % 10; // Get last digit
Output:
reverse = reverse * 10 + remainder; // Append digit to reverse
Input:
num = num / 10; // Remove last digit
Enter a number: 12345
}
printf("Reversed number = %d\n", reverse); Output:
return 0; Reversed number = 54321
}
Example 4: WAP to get Palindrome number (reverse जस्तै तर उल्टो सल्
ु टो बाट हे र्ाा उस्तै number आउनु पर्यो )
#include <stdio.h>
int main()
{
int num, original, reverse = 0, remainder;
printf("Enter a number: ");
scanf("%d", &num);
original = num; // Store the original number
while(num != 0)
{
remainder = num % 10;
reverse = reverse * 10 + remainder;
num = num / 10;
Prepared By: [Link] Chand
}
// Check if original number and reversed number are the same
if(original == reverse) {
printf("%d is a palindrome number.\n", original);
} else {
printf("%d is not a palindrome number.\n", original);
}
return 0;
}
Example 4: WAP to Check given number is Armstrong number of not ?
Solution : Armstrong number = The sum of its digits raised to the power of the number of digits
is equal to the number itself. i.e. 123 = 13+23+33=36 which is not arm strong because 13+23+33
≠123 . If we take 153 then 13+53+33=153 so it is armstrong number.
Program:
#include <stdio.h>
int main()
{
int num, original, sum = 0;
printf("Enter a 3-digit number: ");
scanf("%d", &num);
original = num; // to store original value of 3 digit number
while(num != 0)
{
int digit = num % 10;
sum += digit * digit * digit; // cube directly
num /= 10;
}
if(sum == original)
{
Prepared By: [Link] Chand
printf("%d is an Armstrong number.\n", original);
}
else
printf("%d is not an Armstrong number.\n", original);
return 0;
}
do–while loop
The do–while loop is used when the loop must execute at least once before checking the
condition.
Use cases:
When loop body must execute at least once
When user interaction is required first
When displaying menu at least once
Example::Password retry systems
Example 1 :print output natural number upto 5
#include <stdio.h>
int main()
{
int i = 1;
do
12345
{
printf("%d ", i);
i++;
} while(i <= 5);
return 0;
}
Example 2 :Print output sum of natural number
#include <stdio.h>
int main()
{
Prepared By: [Link] Chand
int num, i = 1, sum = 0;
Enter a number: 5
printf("Enter a number: ");
Sum = 15
scanf("%d", &num);
do
{
sum = sum + i;
i++;
} while(i <= num);
printf("Sum = %d", sum);
return 0;
}
3 Jump Control Structures
break
Terminates loop or switch statement.
Use cases:
To terminate loop early
When required condition is met
To exit from infinite loop
break is used to immediately terminate a loop
Example:
#include <stdio.h>
int main()
{
int i;
for(i = 1; i <= 10; i++) 1234
{
if(i == 5)
break;
printf("%d ", i);
}
Prepared By: [Link] Chand
return 0;
}
continue
Use cases:
To skip current iteration
When certain condition should be ignored
Skips current iteration and continues loop.
Continue is used to skip the current iteration and continue with the next one.
Examples:
Skip negative numbers
Skip invalid input
Ignore a specific value during loop
Example: WAP to skip number 3 out of 5 natural number
#include <stdio.h>
int main()
int i;
for(i = 1; i <= 5; i++)
{ 1245
if(i == 3)
continue;
printf("%d ", i);
return 0;
Prepared By: [Link] Chand
goto
goto is used to transfer control to a labeled statement within the same function, mainly for error
handling or exiting nested loops.
Used (Use cases):
To exit deeply nested loops quickly.
For error handling in low-level or system programs.
When code logic becomes simpler using a jump
Example:
#include <stdio.h> Output1 :
int main() Enter a number: 5
{ You entered a positive number.
int num; Program finished.
printf("Enter a number: "); Output2 :
scanf("%d", &num); Enter a number: -3
if (num < 0) Program finished.
goto end;
printf("You entered a positive number.\n");
end:
printf("Program finished.\n");
return 0;
}
Return
Return is used to terminate a function and optionally return a value to the calling function.
Used (Use cases):
To send a value back to the calling function.
To terminate a function.
To end program execution when used in main()
Prepared By: [Link] Chand
Example : WAP to find the sum of two numbers using return value
#include <stdio.h>
int add(int a, int b)
return a + b;
int main()
Sum = 8
{
int sum = add(5, 3);
printf("Sum = %d", sum);
return 0;
While vs do-while?
→ do-while executes at least once.
If vs switch?
→ if checks conditions, switch checks fixed values.
Break vs continue?
→ Break exits loop, continue skips iteration.
Array in C Programming
An array is a collection of elements of the same data type stored in memory locations.
It allows you to store multiple values under a single variable name.
Example:
int marks[5]; // Array to store 5 integers
Prepared By: [Link] Chand
Here, marks can store 5 integer values like marks[0], marks[1], ..., marks[4].
Features of Arrays
1. All elements are of same data type.
2. Array index starts from 0(zero).
3. The size of the array must be known at compile time (for static arrays).
Syntax
data_type array_name[size];
Example:
int numbers[10]; // Declares an integer array of size 10
float marks[5]; // Declares a float array of size 5
char name[20]; // Declares a char array (string) of size 20
How to Initialize an Array
1. At the time of declaration:
int numbers[5] = {10, 20, 30, 40, 50};
2. Without specifying size:
int numbers[] = {1, 2, 3, 4, 5}; // Size automatically 5
Types :
1. One-Dimensional (1D) Array
Definition: A 1D array stores elements in a single row.
Syntax: data_type array_name[size];
Example 1: Store marks of 5 students and calculate total marks.
#include <stdio.h>
int main()
{
int marks[5] = {50, 60, 70, 80, 90}; Output:
int total = 0;
for(int i = 0; i < 5; i++) Total Marks = 350
{
total += marks[i];
}
Prepared By: [Link] Chand
printf("Total Marks = %d\n", total);
return 0;
}
Example 2: WAP to display number from 10 to 90 using array
#include <stdio.h>
int main()
{
int arr[80]; // array to store 80 numbers
int i, num = 10;//start number (kati number dekhi print gara vanx tei)
// Store numbers from 10 to 90
for(i = 0; i < 90; i++)
{
arr[i] = num;
num += 1;// kati le increase garne ta number lai tyo dinx
}
// Print array elements
for(i = 0; i < 90; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
Example 3: WAP to display average of n numbers:
Solution:
#include <stdio.h>
int main()
{
int n, i;
float sum = 0, average, a[1000];
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d numbers:\n", n);
for(i = 0; i < n; i++)
{
scanf("%f", &a[i]);
sum =sum+ a[i];
}
average = sum / n;
Prepared By: [Link] Chand
printf("Average = %f", average);
return 0;
}
Example 3: WAP to find the greatest number among user required numbers.
Solution:
#include <stdio.h>
int main()
{
int n, i,a[1000],max; //max chahi greatest ko lagi
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d numbers:\n", n);
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
max = a[0]; // Assume first element is greatest
for(i = 1; i < n; i++)
{
if(a[i] > max)// smallest vanema just sign change > to <//
{
max = a[i];
}
}
printf("Greatest number = %d", max);
return 0;
}
Prepared By: [Link] Chand
Example 4: WAP to display in Ascending order (sorting numbers from smallest to largest).
#include <stdio.h>
int main()
{
Output:
int arr[5], i, j, temp; Enter 5 numbers:
5
printf("Enter 5 numbers:\n"); 2
8
for(i = 0; i < 5; i++) 1
4
{
scanf("%d", &arr[i]); Output:
} Numbers in Ascending Order:
1 2 4 5 8
// Sorting in ascending order
for(i = 0; i < 5; i++)
{
for(j = i + 1; j < 5; j++)
{
if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
printf("Numbers in Ascending Order:\n");
for(i = 0; i < 5; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
Prepared By: [Link] Chand
2. Two-Dimensional (2D) Array
Definition: A 2D array stores elements in rows and columns (like a table).
Syntax: data_type array_name[rows][columns];
Example 1: Display 2×2 Matrices
#include <stdio.h>
int main()
int matrix[2][2],i,j;
printf("Enter elements of 2x2 matrix:\n");
// Input matrix elements
for(i = 0; i < 2; i++)
for(j = 0; j < 2; j++)
scanf("%d", &matrix[i][j]);
printf("The 2x2 Matrix is:\n");
// Display matrix
for(i = 0; i < 2; i++)
for(j = 0; j < 2; j++)
Prepared By: [Link] Chand
{
Output:
printf("%d ", matrix[i][j]); Enter elements of 2x2 matrix:
} 1234
The 2x2 Matrix is:
printf("\n");
12
}
34
return 0;
Example 2: Matrix addition of 3×2 matrices Output:
#include <stdio.h> Enter two matrix data:
int main()
{
1
int i,j,a[3][2],b[3][2],sum[4][3];
printf(“Enter two matrix data:\n”);
2
// Add two matrices
3
for( i = 0; i < 3; i++)
{
4
for( j = 0; j < 2; j++)
{
5
Scanf(“%d%d”,&a[i][j],&b[i][j]);
sum[i][j] = a[i][j] + b[i][j];
} 6
}
7
printf("Sum of Matrix:\n");
for(i = 0; i < 3; i++) 8
{
for(j = 0; j < 2; j++) 9
{
printf("%d\t ", sum[i][j]); 10
}
printf("\n"); 11
}
12
return 0;
} Sum Matrix:
8 10
12 14
16 18
Prepared By: [Link] Chand
Example 3: Multiplication of two matrix(3*2 matrix)
#include <stdio.h>
#include<math.h>
int main()
int A[3][2], B[2][3], C[3][3],i,j,k;
// Input Matrix A (3x2)
printf("Enter elements of 3x2 matrix A:\n");
for(i = 0; i < 3; i++)
for(j = 0; j < 2; j++)
scanf("%d", &A[i][j]);
// Input Matrix B (2x3)
printf("Enter elements of 2x3 matrix B:\n");
for(i = 0; i < 2; i++)
for(j = 0; j < 3; j++)
Prepared By: [Link] Chand
scanf("%d", &B[i][j]);
// Initialize result matrix C to 0
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
C[i][j] = 0;
// Matrix multiplication
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
for(k = 0; k < 2; k++)
C[i][j] += A[i][k] * B[k][j];// C[i][j] + yasle sum ko kam garx yo vaneko C[i][j]=C[i][j]+A[i][k] * B[k][j] yasto vannu eutai ho
Prepared By: [Link] Chand
} Output:
Enter elements of 3x2 matrix A:
2
// Display result
23
printf("Resultant 3x3 Matrix:\n");
3
for(i = 0; i < 3; i++) 4
{ 5
6
for(j = 0; j < 3; j++)
Enter elements of 2x3 matrix B:
{ 7
printf("%d ", C[i][j]);//for horizontal display 8
9
}
5
printf("\n");// for vertical display
4
} 3
return 0; Resultant 3x3 Matrix:
129 108 87
}
41 40 39
65 64 63
Prepared By: [Link] Chand
String
String is stored in contiguous memory.
Ends with \0 (null character).
Index starts from 0.
It is actually a character array.
Common String Functions (#include <string.h>) + #include<ctype.h>
Function Purpose
strlen(str) Find length of string
strcpy(a,b) Copy string
strcat(a,b) Join two strings
strcmp(a,b) Compare two strings
toupper(str[i]) For upper case convert
tolower(str[i]) For lower case convert
Example:Convert Lower case to Upper case
#include <stdio.h>
#include <ctype.h>
int main()
{
char text[] ;
int i;
printf(“Enter your String:\n”);
gets(text);
for(i = 0; text[i] != '\0'; i++)
{
text[i] = toupper(text[i]); // if asked lower replace upper by lower
}
Prepared By: [Link] Chand
printf("Uppercase : %s", text); // Output: What you type as a input same display in uppercase
return 0;
}
3. Character Array (String)
Definition: Character arrays are used to store strings.
Syntax: char array_name[size];
Example 1: Store and print a name
#include <stdio.h>
Output:
int main()
{ Name: Ro Hit
char name[20] = "RO Hit";
printf("Name: %s\n", name);
return 0;
}
Example 2: Check given word is Palindrome or not.
#include<stdio.h>
#include<string.h>
int main()
char str[100],rev[100];
int i,j,len;
printf("Enter your string:\t");
scanf("%s",str);
len=strlen(str);
i=0;
j=len-1;
while(j>=0)
rev[i]=str[j];
Prepared By: [Link] Chand
i++;
OutPut:
j--; Enter your string:madam
String is a Pallindrome!!
}
Or
rev[i]='\0';
Enter your string:Rohit
if(strcmp(str,rev)==0) Not a Pallindrome!!
printf("String is a Pallindrome!!");
else
printf("Not a pallindrome!!");
Example 3: lower to upper case conversion
#include <stdio.h>
#include<ctype.h>
int main()
{
char str[1000];
int i;
printf("Enter Your lowercase String :\t");
fgets(str,1000,stdin); You can use :
for(i=0;str[i]!='\0';i++) If part हटाएर सिधै for loop सित्र str[i]=toupper(str[i]) गना
सकिन्छ र toupper replaced by tolower which is used for to
{
convert upper case to lower case others remaining same
if(str[i]>='a'&& str[i]<='z')
OR,
str[i]=str[i]-32;
If part राखेरै गर्ने हो भने upper case बाट lower case convert गर्ाा
}
a िो ठाउँ मा A & z िो ठाउमा Z र -32 िो ठाउमा +32 put गने |
Prepared By: [Link] Chand
printf("Converted Uppercase String is :%s\t",str);
return 0;
}
Output:
Enter Your lowercase String: nobel
Converted Uppercase String is:NOBEL
If you have any Queries: you can asked 9862463329 Whatsapp Freely
Prepared By: [Link] Chand