JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
1. Write a code to reverse a number
#include<stdio.h>
int main() {
//Initialization of variables where rev='reverse=0'
int number, rev = 0, store, left;
//input a numbers for user
printf("Enter the number\n");
scanf("%d", & number);
store = number;
//use this loop for check true condition
while (number > 0) {
//left is for remider are left
left = number % 10;
//for reverse of no.
rev = rev * 10 + left;
//number /= 10;
number = number / 10;
}
//To show the user value
printf("Given number = %d\n", store);
//after reverse show numbers
printf("Its reverse is = %d\n", rev);
return 0;
}
2. Write the code to find the Fibonacci series upto the nth term.
#include<stdio.h>
int main() {
int n = 10;
int a = 0, b = 1;
// printing the 0th and 1st term
printf("%d, %d", a, b);
int nextTerm;
// printing the rest of the terms here
for (int i = 2; i < n; i++) {
nextTerm = a + b;
a = b;
b = nextTerm;
printf("%d, ", nextTerm);
}
return 0;
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
}
3. Write code of Greatest Common Divisor
// The code used a recursive function to return gcd of p and q
int gcd(int p, int q)
{
// checking divisibility by 0
if (p == 0)
return q;
if (q == 0)
return p;
// base case
if (p == q)
return p;
// p is greater
if (p > q)
return gcd(p-q, q);
else
return gcd(p, q-p);
}
// Driver program to test above function
int main()
{
int p = 98, q = 56;
printf("GCD of %d and %d is %d ", p, q, gcd(p, q));
return 0;
}
4. Write code of Perfect number
#include<stdio.h>
int main() {
// Initialization of variables
int number, i = 1, total = 0;
// To take user input
printf("Enter a number: ");
scanf("%d", & number);
while (i < number) {
if (number % i == 0) {
total = total + i;
i++;
}
}
//to condition is true
if (total == number)
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
//display
printf("%d is a perfect number", number);
//to condition is false
else
//display
printf("%d is not a perfect number", number);
return 0;
}
5. Write code to Check if two strings are Anagram or not
#include<stdio.h>
int main()
{
//Initializing variables.
char str[100];
int i;
int freq[256] = {0};
//Accepting inputs.
printf("Enter the string: ");
gets(str);
//Calculating frequency of each character.
for(i = 0; str[i] != '\0'; i++)
{
freq[str[i]]++;
}
printf("The non repeating characters are: ");
for(i = 0; i < 256; i++)
{
if(freq[i] == 1)//Finding uniques charcters and printing them.
{
printf(" %c ", i);
}
}
return 0;
}
6. Write code Check if the given string is Palindrome or not
#include<stdio.h>
#include <string.h>
int main()
{
//Initializing variable.
char str[100];
int i,length=0,flag=0;
//Accepting input.
printf("Enter the string : ");
gets(str);
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
length=strlen(str);
//Initializing for loop.
for(i=0;i<length/2;i++)
{
//Checking if string is palindrome or not.
if(str[i]==str[length-i-1])
flag++;
}
//Printing result.
if(flag==i)
printf("String entered is palindrome");
else
printf("String entered is not palindrome");
return 0;
}
7. Write code to Calculate frequency of characters in a string
#include<stdio.h>
int main() {
//Initializing variables.
char str[100];
int i;
int freq[256] = {
0
};
//Accepting inputs.
printf("Enter the string: ");
gets(str);
//Calculating frequency of each character.
for (i = 0; str[i] != '\0'; i++) {
freq[str[i]]++;
}
//Printing frequency of each character.
for (i = 0; i < 256; i++) {
if (freq[i] != 0) {
printf("The frequency of %c is %d\n", i, freq[i]);
}
}
return 0;
}
8. Write code to check if two strings match where one string contains wildcard characters
#include<stdio.h>
#include<string.h>
bool check(char *str1, char * str2) ;// declaration of the check() function
int main()
{
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
char str1[100],str2[100];
printf("Enter first string with wild characters : ");
gets(str1);
printf("Enter second string without wild characters : ");
gets(str2);
test(str1,str2);
return 0;
}
bool check(char *str1, char * str2)
{
// checking end of both the strings
if (*str1 == '\0' && *str2 == '\0')
return true;
// comparing the characters of both the strings and wild characters(*)
if (*str1 == '*' && *(str1+1) != '\0' && *str2 == '\0')
return false;
// checking wild characters(?)
if (*str1 == '?' || *str1 == *str2)
return check(str1+1, str2+1);
if (*str1 == '*')
return check(str1+1, str2) || check(str1, str2+1);
return false;
}
// test() function for running test cases
void test(char *str1, char *str2)
{
check(str1, str2)? puts(" Yes "): puts(" No ");
9. Write a code for bubble sort
#include<stdio.h>
/* Function to print array */
void display(int arr[], int size) {
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Main function to run the program
int main() {
int array[] = {
5,
3,
1,
9,
8,
2,
4,
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
7
};
int size = sizeof(array) / sizeof(array[0]);
printf("Before bubble sort: \n");
display(array, size);
int i, j, temp;
for (i = 0; i < size - 1; i++) {
// Since, after each iteration righmost i elements are sorted
for (j = 0; j < size - i - 1; j++)
if (array[j] > array[j + 1]) {
temp = array[j]; // swap the element
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
printf("After bubble sort: \n");
display(array, size);
return 0;
}
10. How is the merge sort algorithm implemented?
#include<stdio.h>
void mergeSort(int[], int, int);
void merge(int[], int, int, int);
void display(int arr[], int size) {
int i;
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
void main() {
int a[10] = {
11,
9,
6,
19,
33,
64,
15,
75,
67,
88
};
int i;
int size = sizeof(a) / sizeof(a[0]);
display(a, size);
mergeSort(a, 0, size - 1);
display(a, size);
}
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
void mergeSort(int a[], int left, int right) {
int mid;
if (left < right) {
// can also use mid = left + (right - left) / 2
// this can avoid data type overflow
mid = (left + right) / 2;
// recursive calls to sort first half and second half subarrays
mergeSort(a, left, mid);
mergeSort(a, mid + 1, right);
merge(a, left, mid, right);
}
}
void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
// create temp arrays to store left and right subarrays
int L[n1], R[n2];
// Copying data to temp arrays L[] and R[]
for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
// here we merge the temp arrays back into arr[l..r]
i = 0; // Starting index of L[i]
j = 0; // Starting index of R[i]
k = left; // Starting index of merged subarray
while (i < n1 && j < n2) {
// place the smaller item at arr[k] pos
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
// Copy the remaining elements of L[], if any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
// Copy the remaining elements of R[], if any
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
11. Write to code to check whether a given year is leap year or not.
#include <stdio.h>
int main() {
int year;
scanf("%d", & year);
if (year % 400 == 0)
printf("%d is a Leap Year", year);
else if (year % 4 == 0 && year % 100 != 0)
printf("%d is a Leap Year", year);
else
printf("%d is not a Leap Year", year);
return 0;
}
12. Find non-repeating characters in a string
#include<stdio.h>
int main()
{
//Initializing variables.
char str[100]="prepinsta";
int i;
int freq[256] = {0};
//Calculating frequency of each character.
for(i = 0; str[i] != '\0'; i++)
{
freq[str[i]]++;
}
printf("The non repeating characters are: ");
for(i = 0; i < 256; i++)
{
if(freq[i] == 1)//Finding uniques charcters and printing them.
{
printf(" %c ", i);
}
}
return 0;
}
13. Write a code to replace a substring in a string.
#include<stdio.h>
#include<string.h>
int main() {
char str[256] = "prepinsta", substr[128] = "insta", replace[128] = "ster ", ou
tput[256];
int i = 0, j = 0, flag = 0, start = 0;
str[strlen(str) - 1] = '\0';
substr[strlen(substr) - 1] = '\0';
replace[strlen(replace) - 1] = '\0';
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
// check whether the substring to be replaced is present
while (str[i] != '\0')
{
if (str[i] == substr[j])
{
if (!flag)
start = i;
j++;
if (substr[j] == '\0')
break;
flag = 1;
}
else
{
flag = start = j = 0;
}
i++;
}
if (substr[j] == '\0' && flag)
{
for (i = 0; i < start; i++)
output[i] = str[i];
// replace substring with another string
for (j = 0; j < strlen(replace); j++)
{
output[i] = replace[j];
i++;
}
// copy remaining portion of the input string "str"
for (j = start + strlen(substr); j < strlen(str); j++)
{
output[i] = str[j];
i++;
}
// print the final string
output[i] = '\0';
printf("Output: %s\n", output);
} else {
printf("%s is not a substring of %s\n", substr, str);
}
return 0;
}
14. Write a code for Heap sort.
#include<stdio.h> // including library files
int temp;
void heapify(int arr[], int size, int i)//declaring functions
{
int max = i;
int left = 2*i + 1;
int right = 2*i + 2;
if (left < size && arr[left] >arr[max])
max= left;
if (right < size && arr[right] > arr[max])
max= right;
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
if (max!= i)
{
// performing sorting logic by using temporary variable
temp = arr[i];
arr[i]= arr[max];
arr[max] = temp;
heapify(arr, size, max);
}
}
void heapSort(int arr[], int size)// providing definition to heap sort
{
int i;
for (i = size / 2 - 1; i >= 0; i--)
heapify(arr, size, i);
for (i=size-1; i>=0; i--)
{
// swaping logic
temp = arr[0];
arr[0]= arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}
}
void main() // defining main()
{
int arr[] = {58, 134, 3, 67, 32, 89, 15, 10,78, 9};
// array initializing with their elements.
int i;
int size = sizeof(arr)/sizeof(arr[0]);
heapSort(arr, size);
printf("printing sorted elements\n"); // printing the sorted array
for (i=0; i<size; ++i)
printf("%d\n",arr[i]);
}
15. Write a code to replace each element in an array by its rank in the array
#include<stdio.h>
int main(){
int arr[] = { 100, 2, 70, 12 , 90};
int n = sizeof(arr) / sizeof(arr[0]);
int temp[n];
for(int i=0; i<n; i++)
temp[i] = arr[i];
//sort the copied array
for(int i=0; i<n; i++){
for(int j=i+1; j<n; j++){
int x = temp[i];
temp[i] = temp[j];
temp[j] = x;
}
}
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(temp[j]==arr[i])
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
{
arr[i] = j+1;
break;
}
}
}
for(int i=0; i<n; i++)
printf("%d ", arr[i]);
}
16. Write a code to find circular rotation of an array by K positions.
#include<stdio.h>
int main()
{
int size;
printf("Size of array: ");
scanf("%d",&size);
int arr[size];
printf("Enter the elements ");
for(int a=0;a<size;a++)
scanf("%d",&arr[a]);
int n;
printf("Enter the index from where you want your array to rotate ");
scanf("%d",&n);
printf("Array: \n");
for (int a = 0; a < size; a++) {
printf("%d ", arr[a]);
}
for(int a = 0; a < n; a++) { int b, temporary; temporary = arr[size-1]; for(b =
size-1; b > 0; b--)
{
arr[b] = arr[b-1];
}
arr[0] = temporary;
}
printf("\n");
printf("New Array: \n");
for(int a = 0; a< size; a++){
printf("%d ", arr[a]);
}
return 0;
}
17. Write a code to find non-repeating elements in an array.
#include<stdio.h>
// Main function to run the program
int main()
{
int arr[] = {21, 30, 10, 2, 10, 20, 30, 11};
int n = sizeof(arr)/sizeof(arr[0]);
int visited[n];
for(int i=0; i<n; i++){
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
if(visited[i]==0){
int count = 1;
for(int j=i+1; j<n; j++){
if(arr[i]==arr[j]){
count++;
visited[j]=1;
}
}
if(count==1)
printf("%d "arr[i]);
}
}
return 0;
}
18. Write a code to check for the longest palindrome in an array.
#include<stdio.h>
#include<limits.h>
int ispalindrome(int n){
int rev=0, temp = n;
while(temp>0){
int rem = temp%10;
rev = rev*10 + rem;
temp /= 10;
}
if(n==rev)
return 1;
return 0;
}
int main(){
int arr[] = {1, 121, 55551, 545545, 10111, 90};
int n = sizeof(arr)/sizeof(arr[0]);
int res = INT_MIN;
for(int i=0; i<n; i++){
if(ispalindrome(arr[i]) && res<arr[i])
res = arr[i];
if(res==INT_MIN)
res = -1;
printf("%d ",res);
}
19. Write a code to find the factorial of a number.
#include<stdio.h>
int main ()
{
int num = 5, fact = 1;
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
// Can't calculate factorial of a negative number
if(num < 0)
printf("Error");
else
{
for(int i = 1; i <= num; i++)
fact = fact * i;
}
printf("Fact %d: %d",num, fact);
}
// Time complexity: O(N)
// Space complexity: O(1)
20. Write the code to for Armstrong number
#include
#include
// Armstrong number is any number following the given rule
// abcd... = a^n + b^n + c^n + d^n + ...
// Where n is the order(length/digits in number)
// Example = 153 (order/length = 3)
// 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
// Example = 1634 (order/length = 4)
// 1634 = 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634
// number of digits in a number is order
int order(int x)
{
int len = 0;
while (x)
{
len++;
x = x/10;
}
return len;
}
int armstrong(int num, int len){
int sum = 0, temp, digit;
temp = num;
// loop to extract digit, find power & add to sum
while(temp != 0)
{
// extract digit
digit = temp % 10;
// add power to sum
sum = sum + pow(digit,len);
temp /= 10;
};
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
return num == sum;
}
// Driver Code
int main ()
{
int num, len;
printf("Enter a number: ");
scanf("%d",&num);
// function to get order(length)
len = order(num);
// check if Armstrong
if (armstrong(num, len))
printf("%d is Armstrong", num);
else
printf("%d is Not Armstrong", num);
21. Write a program to find the sum of Natural Numbers using Recursion.
#include<stdio.h>
int getSum(int sum,int n)
{
if(n==0)
return sum;
return n+getSum(sum,n-1);
}
int main()
{
int n, sum = 0;
scanf("%d",&n);
printf("%d",getSum(sum, n));
return 0;
}
// Time complexity : O(n)
// Space complexity : O(1)
// Auxilary space complexity : O(N)
// Due to function call stack
22. Write a program to add Two Matrices using Multi-dimensional Array.
#include<stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
printf("Enter elements of 2nd matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}
// adding two matrices
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}
// printing the result
printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}
return 0;
}
23. Write a Program to Find the Sum of Natural Numbers using Recursion.
#include
Numbers(int n);
int main() {
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
printf("Sum = %d", addNumbers(num));
return 0;
int addNumbers(int n) {
if (n != 0)
return n + addNumbers(n - 1);
else
return n;
24. Write code to check a String is palindrome or not?
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
#include
#include
// A function to check if a string str is palindrome
voids isPalindrome(char str[])
{
// Start from leftmost and rightmost corners of str
int l = 0;
int h = strlen(str) - 1;
// Keep comparing characters while they are same
while (h > l)
{
if (str[l++] != str[h--])
{
printf("%s is Not Palindrome", str);
return;
}
}
printf("%s is palindrome", str);
}
// Driver program to test above function
int main()
{
isPalindrome("abba");
isPalindrome("abbccbba");
isPalindrome("geeks");
return 0;
}
25. Write a program for Binary to Decimal to conversion
#include<stdio.h>
int main()
{
int num, binary_val, decimal_val = 0, base = 1, rem;
printf("Insert a binary num (1s and 0s) \n");
scanf("%d", &num); /* maximum five digits */
binary_val = num;
while (num > 0)
{
rem = num % 10;
decimal_val = decimal_val + rem * base;
//num/=10;
num = num / 10 ;
//base*=2;
base = base * 2;
}
//display binary number
printf("The Binary num is = %d \n", binary_val);
//display decimal number
printf("Its decimal equivalent is = %d \n", decimal_val);
return 0;
}
26. Write a program to check whether a character is a vowel or consonant
#include
int main()
{
char c;
int isLowerVowel, isUpperVowel;
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
printf("Enter an alphabet: ");
scanf("%c",&c);
//To find the corrector is lowercase vowel
isLowerVowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
//To find the character is Upper case vowel
isUpperVowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
// compare to charector is Lowercase Vowel or Upper case Vowel
if (isLowerVowel || isUpperVowel)
printf("%c is a vowel", c);
//to check character is alphabet or not
elseif((c >= 'a' && c= 'A' && c <= 'Z'))
prinf("\n not a alphabet\n");
else
printf("%c is a consonant", c);
return 0;
}
27. Write a code to find an Automorphic number
#include<stdio.h>
int checkAutomorphic(int num)
{
int square = num * num;
while (num > 0)
{
if (num % 10 != square % 10)
return 0;
// Reduce N and square
num = num / 10;
square = square / 10;
}
return 1;
}
int main()
{
//enter value
int num;
scanf("%d",&num);
//checking condition
if(checkAutomorphic(num))
printf("Automorphic");
else
printf("Not Automorphic");
return 0;
}
28. Write a code to find Find the ASCII value of a character
/* C Program to identify ASCII Value of a Character */
#include
#include
int main()
{
char a;
printf("\n Kindly insert any character \n");
scanf("%c",&a);
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
printf("\n The ASCII value of inserted character = %d",a);
return 0;
}
29. Write a code to Remove all characters from string except alphabets
#include <stdio.h>
int main()
{
//Initializing variable.
char str[100];
int i, j;
//Accepting input.
printf(" Enter a string : ");
gets(str);
//Iterating each character and removing non alphabetical characters.
for(i = 0; str[i] != '\0'; ++i)
{
while (!( (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || str[i] == '\
0') )
{
for(j = i; str[j] != '\0'; ++j)
{
str[j] = str[j+1];
}
str[j] = '\0';
}
}
//Printing output.
printf(" After removing non alphabetical characters the string is :");
puts(str);
return 0;
}
30. Write a code to Print the smallest element of the array
#include < stdio.h >
int getSmallest(int arr[], int len)
{
// assign first array element as smallest
int min = arr[0];
// linearly search for the smallest element
for(int i=1; i < len; i++)
{
// if the current array element is smaller
if (arr[i] < min)
min = arr[i];
}
return min;
}
int main()
{
int arr[] = {5, 8, 7, 2, 12, 4};
// get the length of the array
int len = sizeof(arr)/sizeof(arr[0]);
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
printf("The smallest : %d", getSmallest(arr, len));
}
31. Write a code to Reverse the element of the array
#include < stdio.h>
void printReverse(int arr[], int len){
for(int i = len - 1; i >= 0; i--)
printf("%d ", arr[i]);
}
int main()
{
int arr[] = {10, 20, 30, 40, 50, 60};
int len = sizeof(arr)/sizeof(arr[0]);
printf("Array in Reverse:\n");
printReverse(arr, len);
return 0;
}
32. Write a code to Sort the element of the array
#include < stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int array[], int size)
{
int i, j, min_idx;
// Loop to iterate on array
for (i = 0; i < size-1; i++)
{
// Here we try to find the min element in array
min_idx = i;
for (j = i+1; j < size; j++)
{
if (array[j] < array[min_idx])
min_idx = j;
}
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
// Here we interchange the min element with first one
swap(&array[min_idx], &array[i]);
}
}
/* Display function to print values */
void display(int array[], int size)
{
int i;
for (i=0; i < size; i++)
{
printf("%d ",array[i]);
}
printf("\n");
}
// The main function to drive other functions
int main()
{
int array[] = {50, 30, 10, 90, 80, 20, 40, 70};
int size = sizeof(array)/sizeof(array[0]);
selectionSort(array, size);
display(array, size);
return 0;
}
33. Write a code to Sort the element of the array without sort method
#include < stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int array[], int size)
{
int i, j, min_idx;
// Loop to iterate on array
for (i = 0; i < size-1; i++)
{
// Here we try to find the min element in array
min_idx = i;
for (j = i+1; j < size; j++)
{
if (array[j] < array[min_idx])
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
min_idx = j;
}
// Here we interchange the min element with first one
swap(&array[min_idx], &array[i]);
}
}
/* Display function to print values */
void display(int array[], int size)
{
int i;
for (i=0; i < size; i++)
{
printf("%d ",array[i]);
}
printf("\n");
}
// The main function to drive other functions
int main()
{
int array[] = {50, 30, 10, 90, 80, 20, 40, 70};
int size = sizeof(array)/sizeof(array[0]);
selectionSort(array, size);
display(array, size);
return 0;
}
34. Write a code to Replace a Substring in a string
#include< stdio.h>
#include< string.h>
int main() {
char str[256] = "prepinsta", substr[128] = "insta", replace[128] =
"ster ", output[256];
int i = 0, j = 0, flag = 0, start = 0;
str[strlen(str) - 1] = '\0';
substr[strlen(substr) - 1] = '\0';
replace[strlen(replace) - 1] = '\0';
// check whether the substring to be replaced is present
while (str[i] != '\0')
{
if (str[i] == substr[j])
{
if (!flag)
start = i;
j++;
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
if (substr[j] == '\0')
break;
flag = 1;
}
else
{
flag = start = j = 0;
}
i++;
}
if (substr[j] == '\0' && flag)
{
for (i = 0; i < start; i++)
output[i] = str[i];
// replace substring with another string
for (j = 0; j < strlen(replace); j++)
{
output[i] = replace[j];
i++;
}
// copy remaining portion of the input string "str"
for (j = start + strlen(substr); j < strlen(str); j++)
{
output[i] = str[j];
i++;
}
// print the final string
output[i] = '\0';
printf("Output: %s\n", output);
} else {
printf("%s is not a substring of %s\n", substr, str);
}
return 0;
}
35. Write a code to Remove space from a string
#include< stdio.h>
using namespace std;
// Function to remove all spaces from a given string
void removeSpaces(char *str)
{
// To keep track of non-space character count
int count = 0;
// Traverse the provided string. If the current character is not a space,
//move it to index 'count++'.
for (int i = 0; str[i]; i++)
if (str[i] != ' ')
str[count++] = str[i]; // here count is incremented
str[count] = '\0';
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
}
// Driver program to test above function
int main()
{
char str[] = "P re p i n sta ";
removeSpaces(str);
printf("%s", str);
return 0;
}
36. Write a code to Count Inversion
#include < stdio.h >
int _mergeSort(int arr[], int temp[], int left, int right);
int merge(int arr[], int temp[], int left, int mid,int right);
/* This function sorts the
input array and returns the
number of inversions in the array */
int mergeSort(int arr[], int array_size)
{
int temp[array_size];
return _mergeSort(arr, temp, 0, array_size - 1);
}
/* An auxiliary recursive function
that sorts the input array and
returns the number of inversions in the array. */
int _mergeSort(int arr[], int temp[], int left, int right)
{
int mid, inv_count = 0;
if (right > left) {
/* Divide the array into two parts and
call _mergeSortAndCountInv()
for each of the parts */
mid = (right + left) / 2;
/* Inversion count will be sum of
inversions in left-part, right-part
and number of inversions in merging */
inv_count += _mergeSort(arr, temp, left, mid);
inv_count += _mergeSort(arr, temp, mid + 1, right);
/*Merge the two parts*/
inv_count += merge(arr, temp, left, mid + 1, right);
}
return inv_count;
}
/* This funt merges two sorted arrays
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
and returns inversion count in the arrays.*/
int merge(int arr[], int temp[], int left, int mid,int right)
{
int i, j, k;
int inv_count = 0;
i = left; /* i is index for left subarray*/
j = mid; /* j is index for right subarray*/
k = left; /* k is index for resultant merged subarray*/
while ((i <= mid - 1) && (j <= right)) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
}
else {
temp[k++] = arr[j++];
/* this is tricky -- see above
explanation/diagram for merge()*/
inv_count = inv_count + (mid - i);
}
}
/* Copy the remaining elements of left subarray
(if there are any) to temp*/
while (i <= mid - 1)
temp[k++] = arr[i++];
/* Copy the remaining elements of right subarray
(if there are any) to temp*/
while (j <= right)
temp[k++] = arr[j++];
/*Copy back the merged elements to original array*/
for (i = left; i <= right; i++)
arr[i] = temp[i];
return inv_count;
}
// Driver code
int main()
{
int n ;
scanf("%d", &n);
int arr[n];
for(int i=0; i<="" pre="" style="box-sizing: border-box;">
37. Write a code to find consecutive largest subsequence
#include < stdio.h>
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
#include < stdlib.h>
//call back function
int compare(const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int findLongestConseqSeq(int arr[], const int n)
{
int length = 1;
int longestConsecutiveSeq = 1;
int i =0;
//sort arr elements using qsort inbuilt function
qsort( arr,n, sizeof(int), compare);
for ( i = 0; i < n - 1; i++) {
if(arr[i] == arr[i+1]) {
continue;
}
else if (arr[i] + 1 == arr[i + 1]) {
length++;
}
else {
length = 1;
}
longestConsecutiveSeq = (longestConsecutiveSeq > length)?
longestConsecutiveSeq: length;
}
return longestConsecutiveSeq;
}
int main()
{
int arr[] = {2,5,7,7,8,8,9,4,10,12,3,6};
const int N = sizeof(arr)/sizeof(arr[0]);
const int longestConsecutiveSeq = findLongestConseqSeq(arr, N);
printf("Longest Consecutive Sequence is %d",longestConsecutiveSeq);
return 0;
}
38: Write a Program to Find out the Sum of Digits of a Number.
int main ()
{
int num, sum = 0;
printf("Enter any num: ");
scanf("%d",&num);
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
//loop to find sum of digits
while(num!=0){
sum += num % 10;
num = num / 10;
}
//output
printf("Sum: %d",sum);
return 0;
}
// Time complexity : O(N)
// Space complexity : O(1)
39: Write a Program to Find out the Power of a Number
// pow function is contained in math.h library
#include<stdio.h>
#include <math.h>
int main()
{
double base = 2.3;
double exp = 2.1;
double result;
// calculates the power
result = pow(base, exp);
// %lf used for double
printf("%lf ^ %lf = %lf\n", base, exp, result);
// following can be used for precision setting
printf("%.1lf ^ %.1lf = %.2lf", base, exp, result);
return 0;
}
40: Write a Program to Find out the Sum of Digits of a Number.
#include
int main ()
{
int num, sum = 0;
printf("Enter any num: ");
scanf("%d",&num);
//loop to find sum of digits
while(num!=0){
sum += num % 10;
num = num / 10;
}
//output
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
printf("Sum: %d",sum);
)
return 0;
}
// Time complexity : O(N)
// Space complexity : O(1
41: Write a Program to Add two Fractions
#include<stdio.h>
int main()
{
//for initialize variables
int numerator1, denominator1, numerator2, denominator2, x, y, c, gcd_no;
//To take user input of numerators and denominators
printf("Enter the numerator for 1st number : ");
scanf("%d",&numerator1);
printf("Enter the denominator for 1st number : ");
scanf("%d",&denominator1);
printf("Enter the numerator for 2nd number : ");
scanf("%d",&numerator2);
printf("Enter the denominator for 2nd number : ");
scanf("%d",&denominator2);
//numerator
x=(numerator1*denominator2)+(denominator1*numerator2);
//denominator
y=denominator1*denominator2;
// Trick part. Reduce it to the simplest form by using gcd.
for(c=1; c <= x && c <= y; ++c)
{
if(x%c==0 && y%c==0)
gcd_no = c;
}
//To display fraction of givien numerators and denominators
printf("(%d / %d) + (%d / %d) = (%d / %d)", numerator1, denominator1, numerator2,
denominator2, x/gcd_no, y/gcd_no);
return 0;
}
42: Write a Program to Find the Largest Element in an Array.
// C Program to find largest element in an array
#include<stdio.h>
int getLargest(int arr[], int len)
{
// assign first array element as largest
int max = arr[0];
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
// linearly search for the largest element
for(int i=1; i max)
max = arr[i];
}
return max;
}
int main()
{
int arr[] = {20, 5, 35, 40, 10, 50, 15};
// get the length of the array
int len = sizeof(arr)/sizeof(arr[0]);
printf("The Largest element is: %d", getLargest(arr, len));
}
// Time complexity: O(N)
// Space complexity: O(N)
43: Write a Program to Find the Roots of a Quadratic Equation
#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
void findRoots(int a, int b, int c)
{
if (a == 0) {
printf("Invalid");
return;
}
int d = b * b - 4 * a * c;
double sqrt_val = sqrt(abs(d));
if (d > 0) {
printf("Roots are real and different \n");
printf("%f\n%f", (double)(-b + sqrt_val) / (2 * a),(double)(-b - sqrt_val) / (2 * a));
}
else if (d == 0) {
printf("Roots are real and same \n");
printf("%f", -(double)b / (2 * a));
}
else // d < 0
{
printf("Roots are complex \n");
printf("%f + i%f\n%f - i%f", -(double)b / (2 * a), sqrt_val/(2 * a), -(double)b / (2 *
a), sqrt_val/(2 * a));
}
}
int main()
{
int a = 1, b = 4, c = 4;
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
findRoots(a, b, c);
return 0;
}
44: Write a Program to Find the Prime Factors of a Number.
#include<stdio.h>
void primefactor(int num) {
printf("Prime factors of the number : ");
for (int i = 2; num > 1; i++) {
while (num % i == 0) {
printf("%d ", i);
num = num / i;
}
}
}
int main() {
int num;
printf("Enter the positive integer: ");
scanf("%d", &num);
primefactor(num);
return 0;
}
45: Write a Program to Convert Digits to Words.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void convert_to_words(char* num)
{
int len = strlen(num);
/* Base cases */
if (len == 0) {
fprintf(stderr, "empty string\n");
return;
}
if (len > 4) {
fprintf(stderr,
"Length more than 4 is not supported\n");
return;
}
char* single_digits[] = { "zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine" };
char* two_digits[]= { "", "ten", "eleven","twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen" };
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
char* tens_multiple[] = { "", "", "twenty", "thirty", "forty", "fifty", "sixty",
"seventy", "eighty", "ninety" };
char* tens_power[] = { "hundred", "thousand" };
printf("\n%s: ", num);
if (len == 1) {
printf("%s\n", single_digits[*num - '0']);
return;
}
while (*num != '\0') {
if (len >= 3) {
if (*num - '0' != 0) {
printf("%s ", single_digits[*num - '0']);
printf("%s ", tens_power[len - 3]);
}
--len;
}
else {
if (*num == '1') {
int sum = *num - '0' + *(num + 1) - '0';
printf("%s\n", two_digits[sum]);
return;
}
else if (*num == '2' && *(num + 1) == '0') {
printf("twenty\n");
return;
}
else {
int i = *num - '0';
printf("%s ", i ? tens_multiple[i] : "");
++num;
if (*num != '0')
printf("%s ",
single_digits[*num - '0']);
}
}
++num;
}
}
int main(void)
{
convert_to_words("9459");
return 0;
}
46: Write a Program to Find the Factorial of a Number using
Recursion.
int getFactorial(int num)
{
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
if(num == 0)
return 1;
return num * getFactorial(num-1);
}
int main ()
{
int num = 7;
int fact = getFactorial(num);
printf("Fact %d: %d",num, fact);
}
47: Write a Program to Reverse an Array
#include <stdio.h>
void printReverse(int arr[], int len){
for(int i = len - 1; i >= 0; i--)
printf("%d ", arr[i]);
}
int main()
{
int arr[] = {10, 20, 30, 40, 50, 60};
int len = sizeof(arr)/sizeof(arr[0]);
printf("Array in Reverse:\n");
printReverse(arr, len);
return 0;
}
48. Write code to check if two strings match where one string contains wildcard characters
#include
#include
bool check(char *str1, char * str2) ;// declaration of the check() function
int main()
{
char str1[100],str2[100];
printf("Enter first string with wild characters : ");
gets(str1);
printf("Enter second string without wild characters : ");
gets(str2);
test(str1,str2);
return 0;
}
bool check(char *str1, char * str2)
{
// checking end of both the strings
if (*str1 == '\0' && *str2 == '\0')
return true;
// comparing the characters of both the strings and wild characters(*)
if (*str1 == '*' && *(str1+1) != '\0' && *str2 == '\0')
return false;
// checking wild characters(?)
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
if (*str1 == '?' || *str1 == *str2)
return check(str1+1, str2+1);
if (*str1 == '*')
return check(str1+1, str2) || check(str1, str2+1);
return false;
}
// test() function for running test cases
void test(char *str1, char *str2)
{
check(str1, str2)? puts(" Yes "): puts(" No ");
49: Write a Program to find out the Spiral Traversal of a
Matrix.
#include <stdio.h>
#define r 4
#define c 4
int main()
{
int a[4][4] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
int i, left = 0, right = c-1, top = 0, bottom = r-1;
while (left <= right && top <= bottom) {
/* Print the first row
from the remaining rows */
for (i = left; i <= right; ++i) {
printf("%d ", a[top][i]);
}
top++;
/* Print the last column
from the remaining columns */
for (i = top; i <= bottom; ++i) {
printf("%d ", a[i][right]);
}
right--;
/* Print the last row from
the remaining rows */
if (top <= bottom) { for (i = right; i >= left; --i) {
printf("%d ", a[bottom][i]);
}
bottom--;
}
/* Print the first column from
the remaining columns */
JAI SHRIRAM ENGINEERING COLLEGE
TIRUPPUR – 638 660
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC & Accredited by NAAC and NBA (CSE and ECE)
if (left <= right) { for (i = bottom; i >= top; --i) {
printf("%d ", a[i][left]);
}
left++;
}
}
return 0;
}
50. Write a code to find Fibonacci Series using Recursion
//Fibonacci Series using Recursion
#include
int fibo(int n)
{
if (n <= 1)
return n;
return fibo(n-1) + fibo(n-2);
}
int main ()
{
int n = 9;
printf("%d", fib(n));
getchar();
return 0;
}