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

Co Lab

The document is an index for a lab file submitted by a student named Yash Kumar Gola. The index contains 27 experiments related to programming fundamentals in C. The experiments cover topics like input/output, arithmetic operations, relational operators, logical operators, pattern printing, recursion, searching/sorting algorithms, strings, and matrices. Each experiment has a stated aim, theory, algorithm, code sample, and space for signatures.

Uploaded by

Yash Kumar
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)
44 views

Co Lab

The document is an index for a lab file submitted by a student named Yash Kumar Gola. The index contains 27 experiments related to programming fundamentals in C. The experiments cover topics like input/output, arithmetic operations, relational operators, logical operators, pattern printing, recursion, searching/sorting algorithms, strings, and matrices. Each experiment has a stated aim, theory, algorithm, code sample, and space for signatures.

Uploaded by

Yash Kumar
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
You are on page 1/ 56

DEPARTMENT OF

COMPUTER SCIENCE AND ENGINEERING


PROGRAMMING FUNDAMENTALS

CO 101
LAB FILE

SUBMITTED TO: SUBMITTED BY:


MISS ANUKRITI KAUSHAL YASH KUMAR GOLA

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:

1. Start the program.


2. Declare two integer variables, num1 and num2, to store the user's input.
3. Prompt the user to input the first integer and store it in num1.
4. Prompt the user to input the second integer and store it in num2.
5. Calculate the sum of num1 and num2 by adding them together, and store the result in a variable called
sum.
6. Display the value of sum as the output, which represents the sum of the two integers.
7. End the program.
CODE:

#include <stdio.h>

int main() {

int num1, num2, sum;

printf("Enter the first integer: ");

scanf("%d", &num1);

printf("Enter the second integer: ");

scanf("%d", &num2);

sum = num1 + num2;

printf("The sum of %d and %d is: %d\n", num1, num2, sum);

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

int num1, num2, num3, num4;

float average;

printf("Enter the first integer: ");

scanf("%d", &num1);

printf("Enter the second integer: ");

scanf("%d", &num2);

printf("Enter the third integer: ");

scanf("%d", &num3);

printf("Enter the fourth integer: ");

scanf("%d", &num4);

average = (num1 + num2 + num3 + num4) / 4.0;

printf("Average: %.2f\n", average);

return 0;

OUTPUT:
Experiment 3

AIM: Write a C program to implement Relational Operators.

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:

1. Start the program.


2. Declare two integer variables, num1 and num2, to store the user's input.
3. Prompt the user to input the first integer and store it in num1.
4. Prompt the user to input the second integer and store it in num2.
5. Perform relational operations between num1 and num2 using the following operators:
6. < (less than)
7. > (greater than)
8. <= (less than or equal to)
9. >= (greater than or equal to)
10. == (equal to)
11. != (not equal to
12. Display the results of each relational operation along with the corresponding operator and operands.
13. End the program.

CODE:

#include <stdio.h>

int main() {

int a = 3, b = 5;

printf("a == b is %d\n", a == b);

printf("a != b is %d\n", a != b);

printf("a > b is %d\n", a > b);

printf("a < b is %d\n", a < b);

printf("a >= b is %d\n", a >= b);

printf("a <= b is %d\n", a <= b);

return 0;

}
OUTPUT:
Experiment 4

AIM: Write a C program to implement Logical Operators.

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:

1. Start the program.


2. Declare two integer variables, num1 and num2, to store the user's input.
3. Prompt the user to input the first integer and store it in num1.
4. Prompt the user to input the second integer and store it in num2.
5. Perform a logical AND operation (num1 && num2) and display the result. If both num1 and num2 are
non-zero, the result is true (1); otherwise, it's false (0).
6. Perform a logical OR operation (num1 || num2) and display the result. If at least one of num1 and num2 is
non-zero, the result is true (1); otherwise, it's false (0).
7. Perform a logical NOT operation (!num1 and !num2) and display the results. The logical NOT operator
negates the value of the operand. If the operand is non-zero, the result is false (0); if the operand is zero,
the result is true (1).
8. End the program.
CODE:

#include <stdio.h>

int main() {

int p = 1, q = 0;

int result;

// Logical AND

result = p && q;

printf("p && q is %d\n", result);

// Logical OR

result = p || q;

printf("p || q is %d\n", result);

// Logical NOT

result = !p;

printf("!p is %d\n", result);

return 0;

}
OUTPUT:
Experiment 5

AIM: Write a C program to find the sum of a 3-digit number.

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

int number, sum = 0;

printf("Enter a 3-digit number: ");

scanf("%d", &number);

if (number >= 100 && number <= 999) {

int originalNumber = number;

while (number > 0) {

int digit = number % 10;

sum += digit;

number /= 10;

printf("The sum of the digits of %d is: %d\n", originalNumber, sum);

} else {

printf("Invalid input. Please enter a 3-digit number.\n");

return 0;}
OUTPUT:
Experiment 6

AIM: Write a C program to reverse a 3-digit number.

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

int inputNumber, reversedNumber = 0;

printf("Enter a 3-digit number: ");

scanf("%d", &inputNumber);

if (inputNumber >= 100 && inputNumber <= 999) {

int originalNumber = inputNumber;

while (inputNumber > 0) {

int digit = inputNumber % 10;

reversedNumber = (reversedNumber * 10) + digit;

inputNumber /= 10;

}printf("The reversed number of %d is: %d\n", originalNumber, reversedNumber);

} else {

printf("Invalid input. Please enter a 3-digit number.\n");

return 0;
}

OUTPUT:
Experiment 7

AIM: Write a C program to implement Bitwise Operators.

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:

● Bitwise AND (&):


● Symbol: &
● Description: Performs a bitwise AND operation between two integers. The result is 1 if and only if both
corresponding bits in the operands are 1. Otherwise, the result is 0.
● Bitwise OR (|):
● Symbol: |
● Description: Performs a bitwise OR operation between two integers. The result is 1 if at least one of the
corresponding bits in the operands is 1. If both bits are 0, the result is 0.
● Bitwise XOR (^):
● Symbol: ^
● Description: Performs a bitwise XOR (exclusive OR) operation between two integers. The result is 1 if the
corresponding bits in the operands are different (one is 0, and the other is 1). If both bits are the same, the
result is 0.
● Bitwise NOT (~):
● Symbol: ~
● Description: Performs a bitwise NOT operation on a single integer. It flips all the bits of the operand,
turning 0s into 1s and 1s into 0s.
● Left Shift (<<):
● Symbol: <<
● Description: Shifts the bits of an integer to the left by a specified number of positions. This is equivalent to
multiplying the integer by 2 raised to the power of the shift amount.
● Right Shift (>>):
● Symbol: >>
● Description: Shifts the bits of an integer to the right by a specified number of positions. For unsigned
integers, this is equivalent to dividing the integer by 2 raised to the power of the shift amount.
ALGORITHM:

1. Start the program.


2. Read the first integer num1 from the user.
3. Read the second integer num2 from the user.
4. Perform a bitwise AND operation between num1 and num2 and store the result in bitwiseAnd.
5. Perform a bitwise OR operation between num1 and num2 and store the result in bitwiseOr.
6. Perform a bitwise XOR operation between num1 and num2 and store the result in bitwiseXor.
7. Perform a bitwise NOT operation on num1 and store the result in
bitwiseNot1.

8. Perform a bitwise NOT operation on num2 and store the result in


bitwiseNot2.
9. Perform a left shift operation on num1 by 1 bit and store the result in
leftShift.
10. Perform a right shift operation on num1 by 1 bit and store the result in
rightShift.
11. Display the results of the bitwise operations as follows:
12. Print bitwiseAnd as "Bitwise AND (num1 & num2) = result".
13. Print bitwiseOr as "Bitwise OR (num1 | num2) = result".
14. Print bitwiseXor as "Bitwise XOR (num1 ^ num2) = result".
15. Print bitwiseNot1 as "Bitwise NOT (~num1) = result".
16. Print bitwiseNot2 as "Bitwise NOT (~num2) = result".
17. Print leftShift as "Left Shift (num1 << 1) = result".
18. Print rightShift as "Right Shift (num1 >> 1) = result".
19. End the program.
CODE:

#include <stdio.h>

int main() {

int a = 5, b = 3;

// Bitwise AND

int bitwiseAND = a & b;

printf("a & b is %d\n", bitwiseAND);

// Bitwise OR

int bitwiseOR = a | b;

printf("a | b is %d\n", bitwiseOR);

// Bitwise XOR

int bitwiseXOR = a ^ b;

printf("a ^ b is %d\n", bitwiseXOR);

// Bitwise left shift

int leftShift = a << 2;

printf("a << 2 is %d\n", leftShift);

// Bitwise right shift

int rightShift = a >> 1;

printf("a >> 1 is %d\n", rightShift);

return 0;

OUTPUT:
Experiment 8

AIM: Write a C program to implement Linear Search Algorithm.

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.

2. Declare a variable to store the element to be searched.

3. Input the element to be searched.

4. Initialize a new variable flag to tell if the element is found.

5. Iterate through the array using any loop.

6. Compare each element with the element to be searched.

7. If a match is found, set the flag=1 and use break statemen get out of the loop.

8. If the flag=1, display the element and its position.

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 n = sizeof(arr) / sizeof(arr[0]);

int searchElement;

printf("Enter the element to be searched: ");

scanf("%d", &searchElement);

int found = 0;

int position;

for (int i = 0; i < n; i++) {

if (arr[i] == searchElement) {

found = 1;

position = i;

break;
}

if (found) {

printf("Element %d found at position %d.\n", searchElement, position);

} else {

printf("Element %d not found in the array.\n", searchElement);

return 0;

OUTPUT:
Experiment 9

AIM: Write a C program to implement Binary Search Algorithm using recursion.

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:

1. Begin with a sorted array and a search key.


2. Initialize the start and end indices to cover the entire array.
3. While the start index is less than or equal to the end index: a. Calculate the middle index as the average
of the start and end indices. b. Compare the element at the middle index with the search key:
4. If they are equal, the search is successful; return the middle index.
5. If the element is greater than the key, update the end index to mid - 1 to search in the lower half.
6. If the element is less than the key, update the start index to mid + 1 to search in the upper half.
7. If the search key is not found in the array, return -1 to indicate that the element is not present.
8. End
CODE:

#include <stdio.h>

int binarySearch(int arr[], int low, int high, int searchElement) {

if (low <= high) {

int mid = low + (high - low) / 2;

if (arr[mid] == searchElement)

return mid;

if (arr[mid] > searchElement)

return binarySearch(arr, low, mid - 1, searchElement);

return binarySearch(arr, mid + 1, high, searchElement);

}return -1; // Element not found

int main() {

int arr[] = {10, 22, 30, 42, 55, 67, 78, 90};

int n = sizeof(arr) / sizeof(arr[0]);

int searchElement;

printf("Enter the element to be searched: ");

scanf("%d", &searchElement);

int result = binarySearch(arr, 0, n - 1, searchElement);


if (result != -1) {

printf("Element %d found at position %d.\n", searchElement, result);

} else {

printf("Element %d not found in the array.\n", searchElement);

}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

requirements of your program.

ALGORITHM:

1. Start

2. Declare string variables for each method: 'strScanf', 'strGets', and 'strFgets'.

3. Use 'scanf' to take input for 'strScanf' and store it.

4. Use 'gets' to take input for 'strGets' and store it.

5. Use 'fgets' to take input for 'strFgets' and store it.

6. Display the entered strings.

7. Exit

CODE:

#include <stdio.h>

#include <string.h>

int main() {

char strScanf[100], strGets[100], strFgets[100];

// Using scanf

printf("Enter a string using scanf: ");

scanf("%s", strScanf);

// Clear the input buffer

while (getchar() != '\n');

// Using gets

printf("Enter a string using gets: ");

gets(strGets);
// Using fgets

printf("Enter a string using fgets: ");

fgets(strFgets, sizeof(strFgets), stdin);

// Display the entered strings

printf("\nUsing scanf: %s\n", strScanf);

printf("Using gets: %s\n", strGets);

printf("Using fgets: %s\n", strFgets);

return 0;

OUTPUT:
Experiment 11

AIM: Write a Program to Print the following pattern

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

#include<stdio.h> int main(){

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

AIM: Write a C program to convert decimal to binary and vice versa.

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.

a. Initialize an empty string for the binary representation.

b. While the decimal number is greater than 0, do the following:

i. Find the remainder when dividing by 2 (0 or 1).

ii. Convert the remainder to a character and add it to the binary string.

iii. Divide the decimal number by 2.

c. Reverse the binary string to get the correct binary representation.

d. Return the binary string.

2. Implement a function `binaryToDecimal` that takes a binary string as input and returns its decimal representation
as an integer.

a. Initialize an integer variable to store the decimal number.

b. Iterate through the binary string from left to right:

i. For each character, multiply the current decimal number by 2.

ii. Add the integer value of the binary digit (0 or 1) to the decimal number.

c. Return 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>

// Function to convert decimal to binary

char* decimalToBinary(int decimal) {

static char binary[32];

int i = 0;

while (decimal > 0) {


binary[i] = (decimal % 2) + '0';

decimal /= 2;

i++;

if (i == 0) {

binary[i] = '0';

i++; }

binary[i] = '\0';

// Reverse the binary string

int left = 0;

int right = i - 1;

while (left < right) {

char temp = binary[left];

binary[left] = binary[right];

binary[right] = temp;

left++;

right--;

} return binary;

// Function to convert binary to decimal

int binaryToDecimal(const char* binary) {

int decimal = 0;

int length = strlen(binary);

for (int i = 0; i < length; i++) {

decimal = decimal * 2 + (binary[i] - '0');

return decimal;

int main() {

int choice, decimal;

char binary[32];

printf("Choose an option:\n");
printf("1. Decimal to Binary\n");

printf("2. Binary to Decimal\n");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter a decimal number: ");

scanf("%d", &decimal);

printf("Binary equivalent: %s\n", decimalToBinary(decimal));

break;

case 2:

printf("Enter a binary number: ");

scanf("%s", binary);

printf("Decimal equivalent: %d\n", binaryToDecimal(binary));

break;

default:

printf("Invalid choice. Please choose 1 or 2.\n");

} return 0;

OUTPUT:
Experiment 13

AIM: Write a C program to implement the switch-case statement.

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:

1. Declare an integer variable 'choice' to store the user's choice.


2. Display a menu of options for the user.
3. Take input from the user for 'choice.'
4. Implement a switch-case statement to perform actions based on the user's choice.
5. Display the result or perform the corresponding action.

CODE:

#include <stdio.h>

int main() {

int choice;

printf("Choose an option:\n");

printf("1. Print Hello\n");

printf("2. Print Goodbye\n");

printf("3. Print Welcome\n");

printf("4. Exit\n");

printf("Enter your choice (1-4): ");

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:

printf("Exiting the program.\n");


break;

default:

printf("Invalid choice. Please select a valid option.\n");

break;

} return 0;

OUTPUT:
Experiment 14

AIM: Write a C program to generate the Fibonacci sequence using recursion.

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

2. Implement a recursive function 'fibonacci' that takes an integer 'n' as input.

a. If 'n' is 0 or 1, return 'n' (base cases).

b. Otherwise, return the sum of 'fibonacci(n - 1)' and 'fibonacci(n - 2)'.

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>

// Recursive function to generate the Fibonacci sequence

int fibonacci(int n) {

if (n <= 1) {

return n; // Base cases: Fibonacci of 0 is 0, and Fibonacci of 1 is 1.

} else {

return fibonacci(n - 1) + fibonacci(n - 2);

int main() {

int terms;

printf("Enter the number of terms in the Fibonacci sequence: ");

scanf("%d", &terms);

if (terms <= 0) {

printf("Invalid input. Number of terms should be greater than 0.\n");

return 1; }

printf("Fibonacci sequence of %d terms: ", terms);

for (int i = 0; i < terms; i++) {

printf("%d ", fibonacci(i));


}

printf("\n");

return 0; }

OUTPUT:
Experiment 15

AIM: Write a C program to create an exponential function.

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:

1. Declare double variables 'base', 'exponent', and 'result'.

2. Prompt the user to enter the base and exponent values.

3. Use the 'pow' function to calculate the exponential value and store it in 'result'.

4. Display the result.

CODE:

#include <stdio.h>

#include <math.h>

int main() {

double base, exponent, result;

printf("Enter the base: ");

scanf("%lf", &base);

printf("Enter the exponent: ");

scanf("%lf", &exponent);

// Calculate the exponential value using the pow function

result = pow(base, exponent);

printf("The result of %.2lf^%.2lf is %.2lf\n", base, exponent, result);

return 0;

OUTPUT:
Experiment 16

AIM: Count the number of vowels in a given string.

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:

1. Initialize a counter variable to zero.


2. Use a loop to iterate through each character in the input string.
3. For each character, check if it's a vowel ('a', 'e', 'i', 'o', or 'u').
4. If it's a vowel, increment the counter variable by 1.
5. After looping through all characters, the counter variable will hold the count of vowels in the string.

CODE:

#include <stdio.h>

#include <string.h>

int main() {

char input[100];

int vowels = 0;

printf("Enter a string: ");

gets(input); // Input the string (Note: gets is not safe, consider using fgets)

for (int i = 0; i < strlen(input); i++) {

char currentChar = tolower(input[i]); // Convert character to lowercase for case insensitivity

if (currentChar == 'a' || currentChar == 'e' || currentChar == 'i' || currentChar == 'o' || currentChar == 'u') {

vowels++;

printf("Number of vowels in the string: %d\n", vowels);

return 0;

}OUTPUT:
Experiment 17

AIM: To check if a given string is a palindrome.

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:

1. Copy the input number in another variable to compare them later.


2. Next, we reverse the given number. To reverse the number, follow these steps:
i. Isolate the last digit of a number. The modulo operator (%) returns the remainder of a division
ii. Append lastDigit to reverse. reverse = (reverse * 10) + lastDigit.
iii. Remove the last digit from the number. number = number / 10.
iv. Iterate this process. while (number > 0)
3. Now we compare the reversed number with the original number.
4. If the numbers are the same, then the number is a palindrome, else it is not

CODE:

#include <stdio.h>

#include <string.h>

#include <stdbool.h>

bool isPalindrome(char *str) {

int start = 0;

int end = strlen(str) - 1;

while (start < end) {

if (str[start] != str[end]) {

return false; // It's not a palindrome

start++;

end--;

return true; // It's a palindrome

int main() {
char input[100];

printf("Enter a string: ");

gets(input); // Input the string (Note: gets is not safe, consider using fgets)

if (isPalindrome(input)) {

printf("The string is a palindrome.\n");

} else {

printf("The string is not a palindrome.\n");

return 0;

OUTPUT:
Experiment 18

AIM: To concatenate two strings in C.

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:

1. The two strings will be combined into one.


2. Using the gets() function, read two strings entered as gets(s1) and gets(s2).
3. Using the string library function strlen(s1), get the length of the string s1 and set it to j.
4. The for loop iterates across the for(i=0;s2[i]!='\0′;i++) structure. Append the characters of string s2 to the string
s1[i+j] until there are no more characters in the string s2. The string s2 is appended to the end of the string s1.
5. Print the s1 string, which has been concatenated.
CODE:

#include <stdio.h>

#include <string.h>

int main() {

char str1[100], str2[100];

printf("Enter the first string: ");

gets(str1); // Input the first string (Note: gets is not safe, consider using fgets)

printf("Enter the second string: ");

gets(str2); // Input the second string

strcat(str1, str2);

printf("Concatenated string: %s\n", str1);

return 0;

OUTPUT:
Experiment 19

AIM: Compare two strings in C.

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:

1. Initialize two character arrays (strings) for the input strings.


2. Read the two input strings.
3. Use the strcmp function to compare the two strings.
4. Check the result:
5. If the result is 0, the strings are equal.
6. If the result is positive, the first string is greater.
7. If the result is negative, the second string is greater.

CODE:

#include <stdio.h>

#include <string.h>

int main() {

char str1[100], str2[100];

printf("Enter the first string: ");

gets(str1); // Input the first string (Note: gets is not safe, consider using fgets)

printf("Enter the second string: ");

gets(str2); // Input the second string

int result = strcmp(str1, str2);

if (result == 0) {

printf("The strings are equal.\n");

} else if (result < 0) {

printf("The first string is smaller than the second string.\n");

} else {

printf("The first string is greater than the second string.\n");

return 0;

}
OUTPUT:
Experiment 20

AIM: To reverse a string in C.

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:

1. Initialize a character array (string) to store the input string.


2. Read the input string.
3. Initialize two pointers, one at the beginning of the string (start) and the other at the end (end).
4. Use a loop to swap characters at the start and end positions, moving towards the middle of the string, until the start
pointer is less than the end pointer.
5. After the loop, the string will be reversed.

CODE:

#include <stdio.h>

#include <string.h>

void reverseString(char *str) {

int start = 0;

int end = strlen(str) - 1;

while (start < end) {

// Swap characters at start and end

char temp = str[start];

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

printf("Reversed string: %s\n", str) ;

return 0;

OUTPUT:
Experiment 21

AIM: Convert a string from lowercase to uppercase and vice versa in C.

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:

1. Initialize a character array (string) to store the input string.


2. Read the input string.
3. Use a loop to iterate through the characters in the string.
4. Use the toupper function to convert a lowercase character to uppercase or the tolower function to convert an
uppercase character to lowercase.
5. Replace the original character in the string with the converted character.

CODE:

#include <stdio.h>

#include <ctype.h>

#include <string.h>

void toUppercase(char *str) {

for (int i = 0; i < strlen(str); i++) {

str[i] = toupper(str[i]);

int main() {

char str[100];

printf("Enter a string: ");

gets(str); // Input the string (Note: gets is not safe, consider using fgets)

toUppercase(str);

printf("Uppercase string: %s\n", str);

return 0;

}
OUTPUT:
Experiment 22

AIM:Program to add two 3x3 matrices in C.

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

int matrix1[3][3], matrix2[3][3], result[3][3];

// Input matrix1

printf("Enter elements of matrix1 (3x3):\n");

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

scanf("%d", &matrix1[i][j]);

// Input matrix2

printf("Enter elements of matrix2 (3x3):\n");

for (int i = 0; i < 3; i++) {


for (int j = 0; j < 3; j++) {

scanf("%d", &matrix2[i][j]);

// Perform matrix addition

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

result[i][j] = matrix1[i][j] + matrix2[i][j];

// Print the resulting matrix

printf("Resulting matrix (matrix1 + matrix2):\n");

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

printf("%d ", result[i][j]);

printf("\n");

return 0;

OUTPUT:
Experiment 23

AIM: Multiply two 3x3 matrices in C.

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

int matrix1[3][3], matrix2[3][3], result[3][3];

// Input matrix1

printf("Enter elements of matrix1 (3x3):\n");

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

scanf("%d", &matrix1[i][j]);

// Input matrix2

printf("Enter elements of matrix2 (3x3):\n");

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

scanf("%d", &matrix2[i][j]);

}
}

// Perform matrix multiplication

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

result[i][j] = 0;

for (int k = 0; k < 3; k++) {

result[i][j] += matrix1[i][k] * matrix2[k][j];

// Print the resulting matrix

printf("Resulting matrix (matrix1 * matrix2):\n");

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

printf("%d ", result[i][j]);

printf("\n");

return 0;

OUTPUT:
Experiment 24

AIM: To find the factorial of a number using recursion in C.

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:

1. Define a recursive function factorial that takes an integer n as an argument.


2. Check if n is equal to 1. If so, return 1 (base case).
3. If n is not 1, return n * factorial(n - 1), which calls the factorial function with a smaller value of n.
4. In the main function, read the input value of n and call the factorial function with this input.
5. Print the factorial result.

CODE:

#include <stdio.h>

// Recursive function to calculate factorial

int factorial(int n) {

if (n == 1) {

return 1; // Base case

} else {

return n * factorial(n - 1);

int main() {

int n;

printf("Enter a non-negative integer to find its factorial: ");

scanf("%d", &n);

if (n < 0) {

printf("Factorial is not defined for negative numbers.\n");

} else {

int result = factorial(n);

printf("Factorial of %d is %d\n", n, result);

}
return 0;

OUTPUT:
Experiment 25

AIM: Sort an array of integers using the Bubble Sort algorithm in C.

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>

void bubbleSort(int arr[], int n) {

int temp;

int swapped;

for (int i = 0; i < n - 1; i++) {

swapped = 0; // Reset the swapped flag for each pass

for (int j = 0; j < n - i - 1; j++) {

if (arr[j] > arr[j + 1]) {

// Swap arr[j] and arr[j+1]

temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

swapped = 1; // Mark that a swap occurred

}
if (swapped == 0) {

break; // If no swaps occurred in a pass, the array is already sorted

int main() {

int n;

printf("Enter the number of elements: ");

scanf("%d", &n);

int arr[n];

printf("Enter the elements:\n");

for (int i = 0; i < n; i++) {

scanf("%d", &arr[i]);

bubbleSort(arr, n);

printf("Sorted array:\n");

for (int i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\n");

return 0;

OUTPUT:
Experiment 26

AIM: Sort an array of integers using the Selection Sort algorithm in C.

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>

void selectionSort(int arr[], int n) {

int minIndex, temp;

for (int i = 0; i < n - 1; i++) {

minIndex = i; // Assume the current element is the minimum

for (int j = i + 1; j < n; j++) {

if (arr[j] < arr[minIndex]) {

minIndex = j; // Update the index of the minimum element

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

printf("Enter the number of elements: ");

scanf("%d", &n);

int arr[n];

printf("Enter the elements:\n");

for (int i = 0; i < n; i++) {

scanf("%d", &arr[i]);

selectionSort(arr, n);

printf("Sorted array:\n");

for (int i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\n");

return 0;

OUTPUT:
Experiment 27

AIM: Sort an array of integers using the Insertion Sort algorithm in C.

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>

void insertionSort(int arr[], int n) {

int i, key, j;

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

key = arr[i];

j = i - 1;

// Move elements of arr[0..i-1] that are greater than key

// to one position ahead of their current position

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j];

j = j - 1;

arr[j + 1] = key;

}
}

int main() {

int n;

printf("Enter the number of elements: ");

scanf("%d", &n);

int arr[n];

printf("Enter the elements:\n");

for (int i = 0; i < n; i++) {

scanf("%d", &arr[i]);

insertionSort(arr, n);

printf("Sorted array:\n");

for (int i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\n");

return 0;

OUTPUT:

You might also like