Co Lab
Co Lab
CO 101
LAB FILE
23/CS/471
INDEX
S.No. Title Sign.
1. Write a C program to take input two integers and
print their sum.
2. Write a C program to take input four integers and
print their average
3. Write a C program to implement Relational
Operators.
4. Write a C program to implement Logical
Operators.
5. Write a C program to implement Logical
Operators.
6. Write a C program to find the sum of a 3-digit
number.
7. Write a C program to reverse a 3-digit number.
8. Write a program to implement Linear Search
Algorithm.
9. Write a program to implement Binary Search
Algorithm ( recursion).
10. Write a program to take input a String Using scanf,
gets and fgets
11. Write a Program to Print the following pattern
12. Write a Program to convert decimal to binary and
vice versa.
13. Write a Program to implement the switch case
statement.
14. Write a Program to generate the Fibonacci
sequence using recursion.
15. Write a Program to create an exponential function.
16. Write a Program to count the number of vowels in
a given string.
17. Write a Program to check if a given string is a
palindrome or not.
18. Write a Program for string concatenation.
19. Write a Program for string comparison.
20. Write a Program to compare two strings.
21. Write a Program to convert a string from lower
case to upper case and vice versa.
22. Program for the addition of two 3 x 3 matrices.
23. Program to multiply two 3 x 3 matrices
24. Program to find factorial of a number using
recursion.
25. Write a C program to sort an array using Bubble
sort.
26. Write a C program to sort an array using selection
sort.
27. Write a C program to sort an array using insertion
sort.
Experiment 1
AIM: Write a C program to take input two integers and print their sum.
THEORY: This program aims to create an interactive environment where the user is prompted to input two integer values.
Subsequently, the program calculates their sum and displays the result. It utilizes the 'scanf' function for input and 'printf' for
output.
ALGORITHM:
#include <stdio.h>
int main() {
scanf("%d", &num1);
scanf("%d", &num2);
return 0;
OUTPUT :
Experiment 2
AIM: Write a C program to take input four integers and print their average.
THEORY: This program is designed to capture four integer inputs from the user, compute their average, and display the
result. It employs the 'scanf' function for input and 'printf' for output.
ALGORITHM:
1. Start
2. Include the standard input-output library (stdio.h)
3. Declare integer variables num1, num2, num3, num4
4. Read four integers using scanf and store them in num1, num2, num3, num4
5. Calculate average = (num1 + num2 + num3 + num4) / 4.0
6. Print "Average: " followed by the value of average with two decimal places
7. Return 0 to the operating system
8. End
CODE:
#include <stdio.h>
int main() {
float average;
scanf("%d", &num1);
scanf("%d", &num2);
scanf("%d", &num3);
scanf("%d", &num4);
return 0;
OUTPUT:
Experiment 3
THEORY:Relational operators in C are used to compare two values or expressions and determine the relationship between
them. These operators return a boolean result, either true (1) or false (0), based on the comparison. Here's a brief
explanation of the commonly used relational operators in C:
● Less Than (<): This operator checks if the value on the left is less than the value on the right.
● Greater Than (>): This operator checks if the value on the left is greater than the value on the right.
● Less Than or Equal To (<=): This operator checks if the value on the left is less than or equal to the value
on the right.
● Greater Than or Equal To (>=): This operator checks if the value on the left is greater than or equal to the
value on the right.
● Equal To (==): This operator checks if the value on the left is equal to the value on the right.
● Not Equal To (!=): This operator checks if the value on the left is not equal to the value on the right.
ALGORITHM:
CODE:
#include <stdio.h>
int main() {
int a = 3, b = 5;
return 0;
}
OUTPUT:
Experiment 4
THEORY: This program first takes two integer inputs from the user and then demonstrates the logical AND, OR, and NOT
operations on these numbers. Depending on the input values, it will print whether each operation is true (1) or false (0).
The code takes two integer inputs from the user, then:
● Checks if both inputs are non-zero using && (logical AND).
● Checks if at least one input is non-zero using || (logical OR).
● Negates each input using ! (logical NOT).
ALGORITHM:
#include <stdio.h>
int main() {
int p = 1, q = 0;
int result;
// Logical AND
result = p && q;
// Logical OR
result = p || q;
// Logical NOT
result = !p;
return 0;
}
OUTPUT:
Experiment 5
THEORY:This program is a straightforward example of how to work with integer digits and perform a simple arithmetic
operation to calculate the sum. It's a useful exercise to understand basic integer manipulation in programming.
ALGORITHM:
1. Start
2. Declare an integer variable num to store the input number.
3. Declare an integer variable sum and initialize it to 0. This will store the sum of the digits.
4. Declare an integer variable rem to store the remainder when dividing num by 10.
5. Declare an integer variable i and initialize it to 1. This will keep track of the current digit's position.
6. Prompt the user to enter a number and store it in the variable num.
7. Initialize a while loop that continues until num becomes 0.
8. Inside the loop: a. Calculate the remainder when dividing num by 10 and store it in the variable rem. b. Add
rem to the sum. c. Print the current digit position and the digit itself. d. Increment i to move to the next digit
position. e. Update num by dividing it by 10, effectively removing the last digit.
9. After the loop, print the total sum of the digits stored in the sum variable.
10. End
CODE:
#include <stdio.h>
int main() {
scanf("%d", &number);
sum += digit;
number /= 10;
} else {
return 0;}
OUTPUT:
Experiment 6
THEORY: The provided C program reverses a positive integer. It does this by extracting the digits of the input number one by
one, constructing the reversed number, and finally displaying the reversed integer. The program utilizes a while loop to
repeatedly extract the last digit of the input number, add it to the reversed number, and then remove that digit from the
input number. This process continues until the input number becomes 0. Reversing a number is a fundamental concept in
programming and helps illustrate basic integer manipulation in C.
ALGORITHM:
1. Start
2. Declare an integer variable num to store the input number.
3. Declare an integer variable rev and initialize it to 0. This will store the reversed number.
4. Declare an integer variable rem to store the remainder when dividing num by 10.
5. Prompt the user to enter a number and store it in the variable num.
6. Initialize a while loop that continues until num becomes 0.
7. Inside the loop: a. Calculate the remainder when dividing num by 10 and store it in the variable rem. b.
Multiply rev by 10 and add rem to it. This effectively adds the current digit to the reversed number. c.
Update num by dividing it by 10, effectively removing the last digit.
8. After the loop, print the reversed number stored in the rev variable.
9. End
CODE:
#include <stdio.h>
int main() {
scanf("%d", &inputNumber);
inputNumber /= 10;
} else {
return 0;
}
OUTPUT:
Experiment 7
THEORY: Bitwise operators are used in computer programming to manipulate individual bits of data within variables,
typically integers. These operators perform operations at the binary level, meaning they work on the individual bits (0s and
1s) that make up the binary representation of a number. Here's an explanation of the common bitwise operators:
#include <stdio.h>
int main() {
int a = 5, b = 3;
// Bitwise AND
// Bitwise OR
int bitwiseOR = a | b;
// Bitwise XOR
int bitwiseXOR = a ^ b;
return 0;
OUTPUT:
Experiment 8
THEORY:This C program is designed to search for an element in an integer array. It first asks the user to input the number of
elements in the array and then prompts the user to enter each element. After receiving the search key, it calls the search
function, which uses a linear search approach to iterate through the array elements, looking for the key. If the key is found,
the function returns 1, indicating that the element is present in the array. If the key is not found after the loop completes,
the function returns -1 to indicate that the element is not in the array. The program then reports whether the element was
found or not.
ALGORITHM:
1. Declare an integer array and initialize it with some values of your choice.
7. If a match is found, set the flag=1 and use break statemen get out of the loop.
9. If the flag!=1, print a message indicating that the element was not found.
CODE:
#include <stdio.h>
int main() {
int arr[] = {10, 22, 30, 42, 55, 67, 78, 90};
int searchElement;
scanf("%d", &searchElement);
int found = 0;
int position;
if (arr[i] == searchElement) {
found = 1;
position = i;
break;
}
if (found) {
} else {
return 0;
OUTPUT:
Experiment 9
THEORY: Binary search is a fast and efficient algorithm used to find a specific element in a sorted array. It works by
repeatedly dividing the search range in half, eliminating the half in which the element cannot exist, and thus greatly reducing
the number of elements to be examined. This process continues until the element is found or the search range becomes
empty.
ALGORITHM:
#include <stdio.h>
if (arr[mid] == searchElement)
return mid;
int main() {
int arr[] = {10, 22, 30, 42, 55, 67, 78, 90};
int searchElement;
scanf("%d", &searchElement);
} else {
}return 0;
OUTPUT:
Experiment 10
AIM: Write a C program to take input for a string using scanf, gets, and fgets.
THEORY: This C program demonstrates how to input a string using three different methods: scanf, gets, and fgets.
scanf: scanf is used to input a string. It reads the input up to the first space or whitespace character, so it's not
suitable for inputting strings with spaces. This is a limitation of scanf.
gets: gets is used to input a string. It reads the entire line of input until it encounters a newline character.
It's useful for inputting strings with spaces. fgets: fgets is another method to input a string. It reads a
specified maximum number of characters or until a newline character is encountered, whichever
comes first. It's a safe way to input strings and allows you to control the number
of characters read.
Each method has its own advantages and limitations, and the choice of method depends on the specific
ALGORITHM:
1. Start
2. Declare string variables for each method: 'strScanf', 'strGets', and 'strFgets'.
7. Exit
CODE:
#include <stdio.h>
#include <string.h>
int main() {
// Using scanf
scanf("%s", strScanf);
// Using gets
gets(strGets);
// Using fgets
return 0;
OUTPUT:
Experiment 11
THEORY: Pattern printing in C involves the use of loops, such as for or while, to create specific shapes or structures using
characters or symbols. In the provided program, the user is prompted to input the number of rows for a right-angled
triangle pattern. The program then uses nested for loops to print the pattern, where the outer loop controls the number of
rows and the inner loop controls the number of characters printed in each row.
Patterns can vary in complexity, and their design is based on the specific requirements and goals of the program. By
understanding loop control and the desired pattern structure, you can create a wide range of patterns in C.
ALGORITHM:
1. Start
2. Declare integer variables for the number of rows (rows) and loop counters (i and j).
3. Prompt the user to enter the number of rows and store it in rows.
4. Use a for loop with i to iterate from 1 to rows (inclusive) for the rows.
5. Inside the outer loop, use another for loop with j to iterate from 1 to i (inclusive) for the columns in each row.
6. Print the desired character or symbol (e.g., "*") and a space for separation in the inner loop.
7. After printing the characters for one row, print a newline character to move to the next row.
8. Repeat steps 5-7 until the pattern is complete.
9. End
CODE:
Pattern 1 :#include<stdio.h>
int main(){
int n;
printf("enter number of rows:");
scanf("%d",&n);
for(int i=1;i<=n;i++){ for(int
j=1;j<=i;j++){ printf("*");
}
printf("\n");
}
return 0;
}
OUTPUT:
Pattern 2
#include<stdio.h>
int main(){
int n;
printf("enter number of rows:");
scanf("%d",&n);
for(int i=1;i<=n;i++){ for(int
j=n+1-i;j>0;j--){ printf("*");
}
printf("\n");
}
return 0; }
OUTPUT:
Pattern 3 #include<stdio.h>
int main(){
int n;
printf("enter number of rows:");
scanf("%d",&n);
for(int i=1;i<=n;i++){ for(int
j=1;j<=n-i+1;j++){ if(j==1 || i==1 ||
j==n-i+1){
printf("*");
}else{printf(" ");
printf("\n");
}
return 0;
}
OUTPUT:
Pattern 4
#include<stdio.h>
int main(){
int n;
printf("enter number of rows:");
scanf("%d",&n);
for(int i=1;i<=n;i++){ for(int
k=1;k<=n-i;k++){ printf(" ");
}
for(int j=1;j<=2*i-1;j++){ printf("*");
}
printf("\n");
}
return 0;
}
OUTPUT:
Pattern 5
int n;
printf("enter number of rows:");
scanf("%d",&n);
int a=2*n-1;
for(int i=1;i<=n;i++){ for(int
k=1;k<=i-1;k++){ printf(" ");
}
for(int j=a;j>0;j--){ if(j==1 || j%2!=0){
printf("*");
}else{ printf(" ");
}
}
a-=2;
printf("\n");
}
return 0;
}
OUTPUT:
Pattern 6
#include<stdio.h>
int main(){
int n;
printf("enter number of rows:");
scanf("%d",&n);
for(int i=1;i<=n;i++){ for(int
k=1;k<=n-i;k++){ printf(" ");
}
for(int j=1;j<=2*i-1;j++){ if(j==1 ||
j==2*i-1 || i==n){
printf("*");
}else{ printf(" ");
}
}
printf("\n");
}
return 0;
}
OUTPUT:
Experiment 12
THEORY: The provided C program converts a binary number entered by the user into its decimal equivalent. It achieves this
by iteratively extracting the rightmost digit, multiplying it by the corresponding positional value, and accumulating the result
to obtain the decimal representation. This process demonstrates the fundamental concept of binary-to-decimal conversion
in programming.
ALGORITHM:
1. Implement a function `decimalToBinary` that takes a decimal number as input and returns its binary representation
as a string.
ii. Convert the remainder to a character and add it to the binary string.
2. Implement a function `binaryToDecimal` that takes a binary string as input and returns its decimal representation
as an integer.
ii. Add the integer value of the binary digit (0 or 1) to the decimal number.
3. Take user input for either decimal to binary conversion or binary to decimal conversion.
4. Perform the conversion based on user choice.
5. Display the result.
CODE:
#include <stdio.h>
#include <string.h>
int i = 0;
decimal /= 2;
i++;
if (i == 0) {
binary[i] = '0';
i++; }
binary[i] = '\0';
int left = 0;
int right = i - 1;
binary[left] = binary[right];
binary[right] = temp;
left++;
right--;
} return binary;
int decimal = 0;
return decimal;
int main() {
char binary[32];
printf("Choose an option:\n");
printf("1. Decimal to Binary\n");
scanf("%d", &choice);
switch (choice) {
case 1:
scanf("%d", &decimal);
break;
case 2:
scanf("%s", binary);
break;
default:
} return 0;
OUTPUT:
Experiment 13
THEORY: The switch-case statement is used for multi-way decision-making in C. It evaluates an expression and matches it to
one of the specified cases. The program executes the code block associated with the matched case.
ALGORITHM:
CODE:
#include <stdio.h>
int main() {
int choice;
printf("Choose an option:\n");
printf("4. Exit\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Hello\n");
break;
case 2:
printf("Goodbye\n");
break;
case 3:
printf("Welcome\n");
break;
case 4:
default:
break;
} return 0;
OUTPUT:
Experiment 14
THEORY: The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. This
program demonstrates a recursive approach to generate the Fibonacci sequence.
ALGORITHM:
1. Start
3. Take user input for the number of terms in the Fibonacci sequence.
4. Generate and display the Fibonacci sequence using the 'fibonacci' function.
5. Exit
CODE:
#include <stdio.h>
int fibonacci(int n) {
if (n <= 1) {
} else {
int main() {
int terms;
scanf("%d", &terms);
if (terms <= 0) {
return 1; }
printf("\n");
return 0; }
OUTPUT:
Experiment 15
THEORY: This C program demonstrates the creation of an exponential function by raising a base number to an exponent
using the pow function from the math library. The user is prompted to enter the base and the exponent, and the program
calculates and displays the result of the exponentiation. The pow function simplifies the process of exponentiation in C,
making it a convenient way to create exponential functions in programming.
ALGORITHM:
3. Use the 'pow' function to calculate the exponential value and store it in 'result'.
CODE:
#include <stdio.h>
#include <math.h>
int main() {
scanf("%lf", &base);
scanf("%lf", &exponent);
return 0;
OUTPUT:
Experiment 16
THEORY: This C program counts the number of vowels in a user-input string. The user is prompted to enter a string, and the program
uses a while loop to iterate through each character in the string. For each character, it checks if it is a vowel (both uppercase and
lowercase) and increments a count variable if it is a vowel. After examining all characters in the string, the program prints the final count,
providing a simple way to determine the number of vowels in the input string. The program uses a loop to scan the string character by
character, making it a versatile approach for counting specific characters or patterns in a text input.
ALGORITHM:
CODE:
#include <stdio.h>
#include <string.h>
int main() {
char input[100];
int vowels = 0;
gets(input); // Input the string (Note: gets is not safe, consider using fgets)
if (currentChar == 'a' || currentChar == 'e' || currentChar == 'i' || currentChar == 'o' || currentChar == 'u') {
vowels++;
return 0;
}OUTPUT:
Experiment 17
THEORY: A palindrome is a string that reads the same forwards and backwards. To check if a string is a palindrome, you can
compare the characters from the beginning of the string with the characters from the end of the string. If they match for all
positions, the string is a palindrome.
ALGORITHM:
CODE:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int start = 0;
if (str[start] != str[end]) {
start++;
end--;
int main() {
char input[100];
gets(input); // Input the string (Note: gets is not safe, consider using fgets)
if (isPalindrome(input)) {
} else {
return 0;
OUTPUT:
Experiment 18
THEORY: To concatenate two strings in C, you can use the strcat function from the <string.h> library. The strcat function
appends the characters of the second string to the end of the first string. Make sure the first string has enough space to
accommodate the concatenated result.
ALGORITHM:
#include <stdio.h>
#include <string.h>
int main() {
gets(str1); // Input the first string (Note: gets is not safe, consider using fgets)
strcat(str1, str2);
return 0;
OUTPUT:
Experiment 19
THEORY: To compare two strings in C, you can use the strcmp function from the <string.h> library. The strcmp function
compares two strings and returns an integer value that indicates their relationship. If the result is 0, it means the strings are
equal. If the result is positive, the first string is greater. If the result is negative, the second string is greater.
ALGORITHM:
CODE:
#include <stdio.h>
#include <string.h>
int main() {
gets(str1); // Input the first string (Note: gets is not safe, consider using fgets)
if (result == 0) {
} else {
return 0;
}
OUTPUT:
Experiment 20
THEORY: This C program reverses a user-input string. It prompts the user to enter a string, calculates its length, and uses a
while loop to swap characters from both ends of the string, gradually moving towards the center. After the loop, the arr
array contains the reversed string, which is then printed as the "Reverse of the string." This program effectively
demonstrates the concept of string reversal by manipulating characters in the array, creating the reversed version of the
original string.
ALGORITHM:
CODE:
#include <stdio.h>
#include <string.h>
int start = 0;
str[start] = str[end];
str[end] = temp;
start++;
end--;
int main() {
char str[100];
printf("Enter a string: ");
gets(str); // Input the string (Note: gets is not safe, consider using fgets)
reverseString(str);
return 0;
OUTPUT:
Experiment 21
THEORY: String case conversion in C allows you to change the case of alphabetic characters within a string, either from
lowercase to uppercase or vice versa. It's a common text manipulation operation and is essential for tasks like formatting
text or making comparisons without considering case sensitivity.
ALGORITHM:
CODE:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
str[i] = toupper(str[i]);
int main() {
char str[100];
gets(str); // Input the string (Note: gets is not safe, consider using fgets)
toUppercase(str);
return 0;
}
OUTPUT:
Experiment 22
THEORY: This C program performs matrix addition, where the user is asked to input the number of rows and columns for two matrices.
The program then proceeds to input the elements for each matrix and adds the corresponding elements of the two matrices to form a
third matrix. Finally, the program displays the resulting sum matrix.
ALGORITHM:
1. Start
2. Declare integer variables r and c for the number of rows and columns in the matrices.
3. Prompt the user to enter the number of rows (r) and columns (c) for the matrices.
4. Initialize two 2D integer arrays, arr[r][c] and brr[r][c], to store the elements of the first and second matrices.
5. For the first matrix: a. Display "For the first array." b. Use nested loops to read and store the elements of the first matrix:
a. Iterate through each row (i) from 0 to r-1.
b. For each row, iterate through each column (j) from 0 to c-1.
c. Prompt the user to enter the element at row i and column j and store it in arr[i][j]. c. Display the elements of the
first matrix.
6. For the second matrix: a. Display "For the second array." b. Use nested loops to read and store the elements of the second
matrix, following the same procedure as in step 5 for the second matrix and storing the elements in brr[r][c]. c. Display the
elements of the second matrix.
7. Initialize a third 2D integer array sum[r][c] to store the sum of the two matrices.
8. Use nested loops to calculate the sum of corresponding elements of the first and second matrices and store them in sum[r][c]:
9. Display "SUM OF TWO MATRICES IS:" to indicate the start of the sum matrix.
10. Use nested loops to display the elements of the sum matrix:
a. Iterate through each row (i) from 0 to r-1.
b. For each row, iterate through each column (j) from 0 to c-1.
c. Print the element at sum[i][j].
11. End
CODE:
#include <stdio.h>
int main() {
// Input matrix1
scanf("%d", &matrix1[i][j]);
// Input matrix2
scanf("%d", &matrix2[i][j]);
printf("\n");
return 0;
OUTPUT:
Experiment 23
THEORY:This C program demonstrates matrix multiplication, a fundamental operation in linear algebra. It takes two 3x3 matrices, A and
B, as input from the user and computes their product, which is stored in matrix C. The program uses nested loops to perform the
multiplication, where each element of the result matrix C is obtained by summing the products of elements from matrices A and B.
ALGORITHM:
1. Start
2. Declare three integer matrices: A[3][3], B[3][3], and C[3][3] to store the input matrices and the result matrix,
respectively.
3. Use nested loops to input elements of matrix A from the user:
4. For each row i from 0 to 2:
5. For each column j from 0 to 2:
6. Prompt the user to enter an element and store it in A[i][j].
7. Use nested loops to input elements of matrix B from the user in a similar manner.
8. Initialize matrix C with zeros to prepare it for storing the result.
9. Use three nested loops to perform matrix multiplication:
10. For each row i from 0 to 2:
11. For each column j from 0 to 2:
12. Initialize C[i][j] to 0.
13. Use another loop with an index k to iterate from 0 to 2 for summation.
14. Update C[i][j] by adding the product of A[i][k] and B[k][j] to it.
15. Print the resulting matrix C as the product of A and B.
16. End
CODE:
#include <stdio.h>
int main() {
// Input matrix1
scanf("%d", &matrix1[i][j]);
// Input matrix2
scanf("%d", &matrix2[i][j]);
}
}
result[i][j] = 0;
printf("\n");
return 0;
OUTPUT:
Experiment 24
THEORY: The factorial of a non-negative integer n is the product of all positive integers from 1 to n. Factorial is often
denoted as n!. To find the factorial of a number using recursion, you can define a recursive function that breaks down the
problem into smaller subproblems, ultimately leading to the base case of 1. The base case is when n is 1, in which case the
factorial is 1. For any other value of n, you can calculate the factorial as n * factorial(n - 1) by recursively calling the function
with a smaller value of n.
ALGORITHM:
CODE:
#include <stdio.h>
int factorial(int n) {
if (n == 1) {
} else {
int main() {
int n;
scanf("%d", &n);
if (n < 0) {
} else {
}
return 0;
OUTPUT:
Experiment 25
THEORY: Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and
swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates
that the list is sorted.
ALGORITHM:
1. Start
2. Declare an integer variable n to store the number of elements in the array.
3. Prompt the user to enter the value of n.
4. Declare an integer array a with a size of n to store the elements.
5. Use a for loop to input the elements one by one:
6. For each index i from 0 to n-1:
7. Prompt the user to enter an element and store it in a[i].
8. Implement the Bubble Sort algorithm to sort the elements in ascending order:
9. Use two nested for loops for comparisons and swaps. The outer loop runs for n-1 iterations, and the inner loop
compares adjacent elements and swaps them if they are in the wrong order.
10. If no swaps are made during an iteration of the inner loop, set found to 1, indicating that the array is
sorted.
11. If found remains 1 after an outer loop iteration, exit the sorting process early.
12. Print the sorted array.
13. End
CODE:
#include <stdio.h>
int temp;
int swapped;
temp = arr[j];
arr[j + 1] = temp;
}
if (swapped == 0) {
int main() {
int n;
scanf("%d", &n);
int arr[n];
scanf("%d", &arr[i]);
bubbleSort(arr, n);
printf("Sorted array:\n");
printf("\n");
return 0;
OUTPUT:
Experiment 26
THEORY: Selection Sort is a simple sorting algorithm that repeatedly selects the minimum element from the unsorted part
of the array and moves it to the beginning of the sorted part of the array. The algorithm divides the input array into two
parts: the subarray of items already sorted and the subarray of items yet to be sorted.
ALGORITHM:
1. Start
2. Declare an integer variable n to store the number of elements in the array.
3. Prompt the user to enter the value of n.
4. Declare an integer array arr with a size of n to store the elements.
5. Use a for loop to input the elements one by one:
6. For each index i from 0 to n-1:
7. Prompt the user to enter an element and store it in arr[i].
8. Implement the Selection Sort algorithm to sort the elements in ascending order:
9. Use two nested for loops. The outer loop runs for n-1 iterations, representing the current position for selecting
the minimum element.
10. Inside the outer loop, initialize min to the maximum possible integer value (INT_MAX) and mindex to 0. These
variables will store the minimum element and its index within the unsorted portion of the array.
11. The inner loop starts from the current position i and iterates through the remaining unsorted
elements in the array.
12. For each element at index j, compare it with the current minimum (min). If it's smaller, update min and
mindex to the new minimum and its index.
13. After finding the minimum element within the unsorted portion, swap it with the element at the current
position i.
14. Print the sorted array.
15. End
CODE:
#include <stdio.h>
// Swap the minimum element with the current element (i-th position)
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
int main() {
int n;
scanf("%d", &n);
int arr[n];
scanf("%d", &arr[i]);
selectionSort(arr, n);
printf("Sorted array:\n");
printf("\n");
return 0;
OUTPUT:
Experiment 27
THEORY: Insertion Sort is a simple sorting algorithm that builds the final sorted array one item at a time. It is
much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.
However, it works well for small lists or lists that are almost sorted.
ALGORITHM:
1. Start
2. Declare an integer variable n to store the number of elements in the array.
3. Prompt the user to enter the value of n.
4. Declare an integer array arr with a size of n to store the elements.
5. Use a for loop to input the elements one by one:
6. For each index i from 0 to n-1:
7. Prompt the user to enter an element and store it in arr[i].
8. Implement the Insertion Sort algorithm to sort the elements in ascending order:
9. Use a for loop to iterate through the array, starting from the second element (index 1).
10. For each element at index i, store its value in the variable current.
11. Initialize an index j to i-1.
12. Use a while loop to compare current with the elements in the sorted portion of the array (from j to 0) and shift
elements to the right as long as they are greater than current and j is not negative.
13. Insert current into its correct position within the sorted portion by assigning it to arr[j+1].
14. Print the sorted array.
15.End
CODE:
#include <stdio.h>
int i, key, j;
key = arr[i];
j = i - 1;
arr[j + 1] = arr[j];
j = j - 1;
arr[j + 1] = key;
}
}
int main() {
int n;
scanf("%d", &n);
int arr[n];
scanf("%d", &arr[i]);
insertionSort(arr, n);
printf("Sorted array:\n");
printf("\n");
return 0;
OUTPUT: