0% found this document useful (0 votes)
50 views15 pages

Coding Questions IN C

Uploaded by

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

Coding Questions IN C

Uploaded by

khushi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Coding Questions IN C

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

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

Write code of Perfect number


#include
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)
//display
printf("%d is a perfect number",number);
//to condition is false
else
//display
printf("%d is not a perfect number",number);

return 0;
}

Write code to Check if two strings are Anagram or not


#include

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

Write code Check if the given string is Palindrome or


not
#include
#include

int main()
{
//Initializing variable.
char str[100];
int i,length=0,flag=0;

//Accepting input.
printf("Enter the string : ");
gets(str);
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;
}

Write code to Calculate frequency of characters in a


string
#include

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

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


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

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

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

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

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

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

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

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;

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

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])
{
arr[i] = j+1;
break;
}
}
}

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


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

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

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

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

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

Write a code to find the factorial of a number.


#include<stdio.h>
int main ()
{
int num = 5, fact = 1;

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

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

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

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

Write a program to add Two Matrices using Multi-


dimensional Array.
#include
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);

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

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;

Write code to check a String is palindrome or not?


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

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

Write a program to check whether a character is a


vowel or consonant
#include
int main()
{
char c;
int isLowerVowel, isUpperVowel;
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;
}

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

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

printf("\n The ASCII value of inserted character = %d",a);


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

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

You might also like