Вы находитесь на странице: 1из 66

NIT AGARTALA ,CSE DEPARTMENT

DATA STRUCTURE
ASSIGNMENT
Elementary Questions on C, string handling and Manipulation, Array
Manipulation, Recursion & Miscellaneous And Data Structure

Submitted by:
Bramha Prasad Jhariya
16UCS051
Section ‘A’
1. Elementary Questions on C
1.1 Write programs to print the following structure:
a. 0
01
011
0112

Answer:

#include <stdio.h>

int fibo(int n)

if(n>1)

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

else

return n;

void main(){

int lines,i,j;

printf("Enter Number of lines: ");

scanf("%d",&lines);

for(i=0;i<lines;i++){

for(j=0;j<=i;j++)

{
printf("%d ",fibo(j));
} printf("\n");

1
}

}
Output:
Enter Number of lines: 5
0
01
011
0112
01123

b. 1
11
121
1331
Answer:
#include <stdio.h>
int nCr(int n, int r){
if(n==0||r==0)return 1;//base
if(n==r)return 1;//base
if(r==1)return n;//base
return nCr(n-1,r-1) + nCr(n-1,r); //pascals identity
}
void main(){
int lines;
printf("Enter Number of lines: ");
scanf("%d",&lines);
int i,j;
for(i=0;i<lines;i++){
for(j=0;j<=i;j++)printf("%2d ",nCr(i,j));
printf("\n");
}
}

Output:
Enter Number of lines: 5
1

2
1 1
1 2 1
1 3 3 1
1 4 6 4 1

c. 1
12A
123AB
Answer:
#include <stdio.h>
void main(){
int lines;
printf("Enter the number of lines: ");
scanf("%d",&lines);
int i,j;
for(i=1;i <=lines;i++){
for(j=1;j<= i*2-1;j++){
if(j <=i)printf("%2d", j);
else printf("%2c", j + 'A'-i-1);
}
printf("\n");
}
}
Output:
Enter the number of lines: 5
1
12A
123AB
1234ABC
12345ABCD

d. 0
10
101

3
0101
01010
Answer:

#include <stdio.h>
void main(){
int rows;
printf("Enter Number of rows: ");
scanf("%d",&rows);
int i = 2,j,k;
for(j=1; j <=rows;j++){
for(k=1; k<=j;k++){
printf("%d ", i%2);
i++;
}printf("\n");
}
}
Output:
Enter Number of rows: 5
0
10
101
0101
01010

1.2 Write a program to check whether a number is Armstrong number or not


Answer:

#include <stdio.h>

#include <math.h>

void main(){

int n;

printf("Enter The Number: ");

4
scanf("%d",&n);

int digit = 1 + (int)log10(n);

int sum = 0;

int i = n;

while(i!=0){

sum += pow(i%10, digit);

i/=10;

(sum==n)?(printf("Your Number is Armstrong.")):(printf("Your Number is NOT


Armstrong.")) ;

Output: 1 Output:2

Enter The Number: 371 Enter The Number: 198

Your Number is Armstrong. Your Number is NOT Armstrong

1.3 Write a program to find the sum of the following series:


a. 1 + 3^2/3^3 + 5^2/5^3 + 7^2/7^3 + ….
Answer:
#include<stdio.h>
#include<math.h>
float series(int num)
{
int n=0,i=1;
float sum=0;
while(n!=num)
{
if(i%2!=0)
{
n++;

5
sum+=(pow(i,2)/pow(i,3));
}
i++;
}
return sum;
}

void main()
{
int num;
printf("Enter the number to print the sum:");
scanf("%d",&num);
printf("sum of series=%f\n",series(num));
}
Output:
Enter the number to print the sum:10
sum of series=2.133256

b. 1234/1+2+3+4 + 123/1+23 + 12/1+2 + 1


Answer:
#include <stdio.h>
#include <math.h>
int digitSum(long long int r)
{
return ((1+(long long int)log10(r))*(2+(long long int)log10(r)))/2 ;
}
void main(){
int n;
double sum = 0.0;
long long int bigNumber = 0;
printf("Enter the number of terms(max=9): ");
scanf("%d",&n);
int i =1;
while(i<=n)bigNumber = bigNumber * 10 + i++;
for(i=1; i <=n;i++){

6
sum += (double)bigNumber / digitSum(bigNumber);
bigNumber/=10;
}
printf("Sum of series is: %.5lf",sum);

}
Output:
Enter the number of terms(max=9): 9
Sum of series is: 3137362.13571

c. 1/2 – 2/3 + 3/4 - 4/5 + 5/6 - ….. n


Answer:
#include <stdio.h>
void main(){
int n;
printf("Enter the Number of Terms: ");
scanf("%d",&n);
int i = 1;
double sum = 0.0;
while(1){
sum += (double)i / (i+1) ;
if(i==n)break;
i++;
sum-= (double)i/(i+1);
if(i==n)break;
i++;
}
printf("Sum upto %d terms is: %lf",n,sum);

}
Output:
Enter the Number of Terms: 5
Sum upto 5 terms is: 0.616667

d. 5 + 50 + 505 + 5050 + 50505 +……n

7
Answer: #include <stdio.h>
void main()
{
int n;
printf("Enter the Number of terms(max = 19): ");
scanf("%d",&n);
int i;
unsigned long long sum=0;
unsigned long long term = 5;
for(i=1;i<=n;i++){
sum+=term;
if(i%2) term *= 10;
else term = term*10 + 5;
}
printf("Sum upto %d terms is: %llu",n,sum);

}
Output:
Enter the Number of terms(max = 19): 5
Sum upto 5 terms is: 56115
e. 1 + 12 + 123 + 1234 + ….. n
Answer:
#include <stdio.h>
void main(){
int n,i;
printf("Enter the number of terms: ");
scanf("%d",&n);
unsigned long long int sum=0;
unsigned long long int term = 0;
for(i=1;i<=n;i++){
term = term * 10 + i%10 ;
sum += term;
}
printf("Sum of series up to %d terms is: %llu",n,sum);
}

8
Output:
Enter the number of terms: 5
Sum of series up to 5 terms is: 13715

1.4 Write a program to create a binary calculator


Answer: #include <stdio.h>

#include <malloc.h>

int bin2dec(int n){

int dec=0,i;

int digit = 1+(int)log10(n);

for(i=0; i<digit;i++){

dec += n%10 * pow(2,i);

n/=10;

return dec;

int dec2bin(int n){

int bin=0,i,bits = 1 + (int)(log(n)/log(2));

char *res = (char *)malloc(sizeof(char)*(bits+1));

res[bits]='\0';

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

res[bits - i] = n%2 + '0';

n/=2;

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

bin = bin * 10 + (res[i-1]-'0');

9
return bin;

void main(){

int a,b,ch;

printf("Enter two binary number:\nA= ");

scanf("%d",&a);

printf("B= ");

scanf("%d",&b);

printf("Choose operation.\n1. Add\n2. difference\n3. Div\n4. Mult\nYour


choice: ");

scanf("%d",&ch);

switch(ch){

case 1:

printf("\t\t%d + %d = %d",a,b,dec2bin(bin2dec(a)+bin2dec(b)));

break;

case 2:

if(bin2dec(a)>bin2dec(b)){

printf("\t\t%d - %d = %d",a,b,dec2bin(bin2dec(a)-
bin2dec(b)));

}else{

printf("\t\t%d - %d = -%d",a,b,dec2bin(bin2dec(b)-
bin2dec(a)));

break;

case 3:

printf("\t\t%d / %d = %d",a,b,dec2bin(bin2dec(a)/bin2dec(b)));

10
break;

case 4:

printf("\t\t%d * %d = %d",a,b,dec2bin(bin2dec(a)*bin2dec(b)));

break;

default:

printf("Invalid option!");

Output

Enter two binary number:

A= 101

B= 101

Choose operation.

1. Add

2. difference

3. Div

4. Mult

Your choice: 1

101 + 101 = 1010

1.5 Write a program to create a digital clock


Answer: #include <stdio.h>

#include <conio.h>

#include <time.h>

void main()

11
{

time_t t;

while(!kbhit())

t=time(NULL);

printf("%s\n",ctime(&t));

getch();

Output:

//current time of system.

1.6 Write a program to convert a binary number to decimal number and vice-
versa.
Answer:
#include<stdio.h>
#include<math.h>

void btd()
{ int b,d=0,i=0;
printf("okay,give me the binary number...\n\t");
scanf("%d",&b);
while(b!=0)
{
d=d+(b%10)*pow(2,i);
i++;
b=b/10;
}
printf("\t%d is the decimal no. for given binary no.\n",d);
}

12
void dtb()
{
int b=0,d,i=0;
printf("okay give me the decimal no....\n\t");
scanf("%d",&d);

while(d!=0)
{
b= b+(d%2)*(int)(pow(10,i)+0.5) ; //As power function uses floating
point calculations which might be inaccurate for example 10^2=99.999
i++;
d=d/2;
}
printf("\t%d is the binary no. for given decimal no.\n",b);
}
void main()
{
int c;
printf("choose your option \n1.binary to decimal\n2.decimal to
binary\n");
scanf("%d",&c);
switch(c)
{
case 1:btd();break;
case 2:dtb();break;
default:printf("invalid input");
}
printf("want to continue press 1 otherwise any key\n");
scanf("%d",&d);
if(d==1)
main();
else
printf("thanks\n");
}

Output:

13
choose your option
1.binary to decimal
2.decimal to binary
1
okay,give me the binary number...
1011
11 is the decimal no. for given binary no.
want to continue press 1 otherwise any key
1
choose your option
1.binary to decimal
2.decimal to binary
2
okay give me the decimal no....
12
1100 is the binary no. for given decimal no.
want to continue press 1 otherwise any key
0
Thanks

1.7 Take two positive integers [x, p] from the user and compute an
approximate value of e^x, correct upto p bits after the decimal point.

∞ n 2 3
x x x
e x =∑ =¿ 1+ x + + +… ¿
n=0 n ! 2! 3 !
Answer:
#include<stdio.h>
#include<math.h>

int fact(int n)
{

if(n>1)
return n*fact(n-1);
else

14
return 1;
}

void main()
{

int x,p,i;
double ans=0;

printf("enter the value of x and p respectively\n");


scanf("%d%d",&x,&p);

for(i=0;i<34;i++)
{
ans=ans+pow(x,i)/fact(i);
}
printf("e^%d=%.*f",x,p,ans);
}
Output:
enter the value of x and p respectively
2
5
e^2=4.48478

1.8 Compute the ratio between two successive Fibonacci numbers F n+1/Fn in a
limiting sense (as n-> ∞), correct upto 20 bits after decimal point.
Answer:
#include<stdio.h>

double fibo(int n)
{
double i,temp,j=1,k=-1;

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

15
{ temp=j;
j=j+k;
k=temp;

}
return j;

}
void main()

{
int n;
printf("give me the value of n which tends to infinity\n");
scanf("%d",&n);
printf("Fn+1/Fn=%.*lf",20,fibo(n+1)/fibo(n));
}

Output:
give me the value of n which tends to infinity
100
Fn+1/Fn=1.61803398874989490000

1.9 Demonstrate the implementation and working of Call by value and Call by
reference.

Answer:

#include <stdio.h>

void swapv(int x, int y){

int temp;

temp = x;

x = y;

x = temp;

16
void swapr(int *x, int *y){

int temp;

temp = *x;

*x = *y;

*y = temp;

int main(void){

int a = 10;

int b = 20;

printf("Initially:\na=%d\nb=%d\n",a,b);

swapv(a,b);

printf("After call by Value:\na=%d\nb=%d\n",a,b); // No effect on a and b

swapr(&a,&b);

printf("After call by Reference:\na=%d\nb=%d\n",a,b); //Value of a and b is


swapped

return 0;

Output:

Initially:

a=10

b=20

After call by Value:

a=10

b=20

After call by Reference:

a=20

b=10

17
2. String handling and Manipulation
2.1 Write a program to find the frequency of a word in a given sentence.

Answer:

#include <stdio.h>

#include <string.h>

void main(){

char sentence[100000];

printf("Enter a sentence:\n");

gets(sentence);

int length = strlen(sentence);

printf("Enter word: \n");

char word[1000];

gets(word);

int wordlen = strlen(word);

int i=0;

int count=0;

while(i < length){

if(sentence[i]==word[0]){

if(i!=0 && sentence[i-1]!=' '){

i++;

continue;

int k=0;

int found = 1;

while(k< wordlen){

if(sentence[k+i]!=word[k]){

found = 0;

18
break;

k++;

if((i!=length-wordlen)&&sentence[k+i]!=' ')found = 0;

if(found)count++;

i++;

printf("Frequency of word \"%s\" is: %d\n",word,count);

Output:

Enter a sentence:

i am a student .i want to be a good student

Enter word:

student

Frequency of word "student" is: 2

2.2 Write a program to convert upper case letters into lower case letters and vice
versa without using library functions.

Answer :
#include <stdio.h>

void main ()

19
int c = 0;

char ch, s[1000];

printf("Input a string\n");

gets(s);

while (s[c] != '\0') {

ch = s[c];

if (ch >= 'A' && ch <= 'Z')

s[c] = s[c] + 32;

else if (ch >= 'a' && ch <= 'z')

s[c] = s[c] - 32;

c++;

}
printf("%s\n", s);
}

Output:

Input a string

my NAME IS my identity,Do YOU Understand

MY name is MY IDENTITY,dO you uNDERSTAND

2.3 Write a program to check whether a given string is palindrome string or not
without using library functions.
answer:
#include <stdio.h>
#include <string.h>

20
void main()
{
char string[25], reverse_string[25] = {'\0'};
int i, length = 0, flag = 0;

printf("Enter a string \n");


gets(string);
for (i = 0; string[i] != '\0'; i++)
{
length++;
}
for (i = length - 1; i >= 0 ; i--)
{
reverse_string[length - i - 1] = string[i];
}

for (flag = 1, i = 0; i < length ; i++)


{
if (reverse_string[i] != string[i])
flag = 0;
}
if (flag == 1)
printf ("%s is a palindrome \n", string);
else
printf("%s is not a palindrome \n", string);
}
Output:
Enter a string
i am ma i
i am ma i is a palindrome

2.4 Write a program to input a string and print unsuccessful if the string contains 2
consecutive vowels.
Answer : // This program prints "unsuccesful" when it encounters two
consecutive vowels in a string.
#include <stdio.h>
#include <string.h>
void main(){
char ch[10000];

21
printf("Enter a string:\n");
gets(ch);
int i = 0;
int flag,flag2;
for(i=0; i < strlen(ch)-1;i++){
flag =0;
flag2=0;
switch(ch[i]){
case 'a': case 'A': case 'e': case 'E': case 'i':
case 'I': case 'o': case 'O': case 'u': case 'U':
flag = 1;
break;
}
switch(ch[i+1]){
case 'a': case 'A': case 'e': case 'E': case 'i':
case 'I': case 'o': case 'O': case 'u': case 'U':
flag2=1;
break;
}
// prints unsuccessful if it contains two consecutive vowels
if(flag&&flag2){
printf("unsuccessful\n");
return 0;
} }
}
Output:1 Output:2
Enter a string: Enter a string:
i am an indian my destiny
unsuccessful

2.5 Write a program to concatenate two strings.


Answer:
#include <stdio.h>
int main()
{
char s1[100], s2[100], i, j;

printf("Enter first string: ");


gets(s1);

22
printf("Enter second string: ");
gets(s2);

for(i = 0; s1[i] != '\0'; ++i);

for(j = 0; s2[j] != '\0'; ++j, ++i)


{
s1[i] = s2[j];
}

s1[i] = '\0';
printf("After concatenation: %s", s1);
}
Output:
Enter first string: what is your name ?
Enter second string: Tell me
After concatenation: what is your name ?Tell me

2.6 Write a program to sort elements in Lexographical order (dictionary order).


Answer:

#include<stdio.h>
#include <string.h>

int main()
{
int i, j;
int n;
printf("Enter number of words: ");
scanf("%d",&n);
char str[n][50], temp[50];

printf("Enter %d words:\n",n);

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


scanf("%s[^\n]",str[i]);

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

23
for(j=i+1; j<n ; ++j)
{
if(strcmp(str[i], str[j])>0)
{
strcpy(temp, str[i]);
strcpy(str[i], str[j]);
strcpy(str[j], temp);
}
}

printf("\nIn lexicographical order: \n");


for(i=0; i<n; ++i)
{
puts(str[i]);
}

return 0;
}
Output:
Enter number of words: 5
Enter 5 words:
i am an indian citizen

In lexicographical order:
am
an
citizen
i
indian

2.7 Write a program to find the longest common substring in an array of strings.
Answer:
2.8 Write a program to simulate a credit card number validation scenario.
Answer:
#include <stdio.h>
#include <string.h>
int main(void){
char ch[20];
printf("Enter a credit card Number: ");

24
scanf("%s",ch);
int len = strlen(ch);
if(len >19||len<13){
printf("Invalid Card Number.\nIt must be between 13 to 19 digits.");
return 0;
}else{
// Luhn algo. starts from here.
int i,luhn=0;
for(i= len - 2;i >=0;i-=2){
ch[i] = 2 *( ch[i]-'0') +'0';
if(ch[i]-'0'>9){
ch[i]=ch[i]-9;
}
}
for(i=len-1;i>=0;i--){
luhn += ch[i]-'0';
}
if(luhn%10==0)printf("You Entered a VALID credit card number.");
else printf("Your credit card number is NOT valid.");
}
return 0;
}
Output:1 Output:2

Enter a credit card Number: 5105105105105100 Enter a credit card number:


4592001145464310

You Entered a VALID credit card number. Your credit card number is NOT
valid.

3. Array Manipulation
3.1 Write a program to sort an array without any function.
Answer:
#include <stdio.h>
int main(void){
int n;
printf("Enter the number of elements in array: ");
scanf("%d",&n);
int a[n];

25
printf("Enter your %d elements:\n",n);
int i=0,j=0;
while(i<n)scanf("%d",&a[i++]);
i =0;
printf("Before sorting array is:\n");
while(i<n)printf("%d ",a[i++]);
printf("\nAfter sorting in ascending order array is:\n");
for(i=0; i <n-1;i++){
int t = i;
for(j=i+1; j <n;j++){
if(a[j]<=a[t])t = j;
}
int temp = a[t];
a[t] = a[i];
a[i] = temp;
}
i=0;
while(i<n)printf("%d ",a[i++]);
return 0;
}
Output:
Enter the number of elements in array:
5
Enter your 5 elements:
19875
Before sorting array is:
19875
After sorting in ascending order array is:
15789
3.2 Write a program to find the second largest number in an array.
Answer:
#include <stdio.h>
int main(void){
int n;
printf("Enter the number of elements in array: ");
scanf("%d",&n);
int a[n];
printf("Enter your %d elements:\n",n);
int i=0,j=0;

26
while(i<n)scanf("%d",&a[i++]);
i =0;
for(i=n-1;i>= n-2;i--){
int t = i;
for(j=0;j< i;j++){
if(a[j]>=a[t])t=j;
}
int temp = a[t];
a[t] = a[i];
a[i] = temp;
}
printf("\nSecond Largest in array is: %d",a[n-2]);
return 0;
}
Output:
Enter the number of elements in array: 5
Enter your 5 elements:
13245

Second Largest in array is: 4


3.3 Write a program to delete a given element in an array and shift the elements
respectively.
Answer:
#include <stdio.h>
int main(void){
int n,target;
printf("Enter the number of elements in array: ");
scanf("%d",&n);
int a[n];
printf("Enter your %d elements:\n",n);
int i=0,j=0;
while(i<n)scanf("%d",&a[i++]);
printf("Enter the index of element you want to delete: ");
scanf("%d",&target);
if(target<0||target>=n){
printf("Incorrect index!");
return 0;
}else{
for(i=target;i <= n-2;i++){

27
a[i] = a[i+1];
}
printf("After deleting element at index %d array is:\n",target);
i=0;
while(i<n-1)printf("%d ",a[i++]);
}
return 0;
}
Output:
Enter the number of elements in array: 5
Enter your 5 elements:
12345
Enter the index of element you want to delete: 2
After deleting element at index 2 array is:
1245
3.4 Write a program to find the transpose of an array.
Answer:
#include <stdio.h>

void main()
{
static int array[10][10];
int i, j, m, n;

printf("Enter the order of the matrix \n");


scanf("%d %d", &m, &n);
printf("Enter the coefiicients of the matrix\n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &array[i][j]);
}
}
printf("The given matrix is \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{

28
printf(" %d", array[i][j]);
}
printf("\n");
}
printf("Transpose of matrix is \n");
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
printf(" %d", array[i][j]);
}
printf("\n");
}
}
Output:
Enter the order of the matrix
33
Enter the coefiicients of the matrix
123456789
The given matrix is
123
456
789
Transpose of matrix is
147
258
369

3.5 Write a program to find the lower and upper triangular matrix of a given MxN
matrix.
Answer:
#include <stdio.h>
int main(void){
int n,zero=0;
printf("Enter the order of square matrix: ");
scanf("%d",&n);
int a[n][n];
int i,j;
printf("Enter the elements of matrix row-wise:\n");

29
for(i=0;i<n;i++){
for(j=0;j<n;j++){
scanf("%d",&a[i][j]);
}
}
printf("Your matrix is:\n");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("%2d ",a[i][j]);
}
printf("\n");
}
printf("Lower triangular matrix is:\n");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(i<j)printf("%2d ",zero);
else printf("%2d ",a[i][j]);
}
printf("\n");
}
printf("Upper triangular matrix is:\n");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(i>j)printf("%2d ",zero);
else printf("%2d ",a[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Enter the order of square matrix: 3
Enter the elements of matrix row-wise:
123
456
789
Your matrix is:
1 2 3
4 5 6

30
7 8 9
Lower triangular matrix is:
1 0 0
4 5 0
7 8 9
Upper triangular matrix is:
1 2 3
0 5 6
0 0 9

3.6 Write a program to check whether a inputted matrix is symmetric or not.


Answer:
#include<stdio.h>

void main()
{
int a[10][10],at[10][10],k,i,j,m,n;
printf("enter the order of matrix:\n");
scanf("%d %d",&m,&n);
printf("enter the matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
at[i][j]=a[j][i];
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(at[i][j]!=a[i][j])
k=1;
}
}
if(k==1)

31
printf("not symmetric");
else
printf("symmetric");
}
Output:
enter the order of matrix:
33
enter the matrix:
123
245
356
symmetric

3.7 Write a program to interchange the diagonals of a MxN matrix with proper
validation
Answer :
#include <stdio.h>

void main ()
{
static int array[10][10];
int i, j, m, n, a;

printf("Enter the order of the matix \n");


scanf("%d %d", &m, &n);
if (m == n)
{
printf("Enter the co-efficients of the matrix\n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%dx%d", &array[i][j]);
}
}
printf("The given matrix is \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)

32
{
printf(" %d", array[i][j]);
}
printf("\n");
}
for (i = 0; i < m; ++i)
{
a = array[i][i];
array[i][i] = array[i][m - i - 1];
array[i][m - i - 1] = a;
}
printf("The matrix after changing the \n");
printf("main diagonal & secondary diagonal\n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
printf(" %d", array[i][j]);
}
printf("\n");
}
}
else
printf("The given order is not square matrix\n");
}

Output:

Enter the order of the matix

33

Enter the co-efficients of the matrix

198234557

The given matrix is

198

234

557

33
The matrix after changing the

main diagonal & secondary diagonal

891

234

755

4. Recursion & Miscellaneous:


4.1 Write a program to find the prime numbers with in a range using recursion.
Answer:

#include<stdio.h>

void prime(int i,int f,int j)

if(i%j&&j<i)

prime(i,f,j+1);

else if(j==i)

printf("%d ",i);

if(i<f)

return prime(i+1,f,2);

else if(i<f)

34
prime(i+1,f,2);

void main()

int i,f;

printf("enter the range \n");

scanf("%d%d",&i,&f);

prime(i,f,2);

}
Output:
enter the range
1 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
4.2 Implement recursion to reverse a sentence.
Answer:
#include <stdio.h>
#include <string.h>
void reverse(char ch[],int last,int first){
if(last==first)return;
char t = ch[first];
ch[first]= ch[last];
ch[last] = t;
reverse(ch,last-1,first + 1);
return;
}
int main(void){
char sen[100];
printf("Enter a sentence:\n");
gets(sen);
int l = strlen(sen);
reverse(sen,l-1,0);
printf("\nAfter reversing sentence is: \n");

35
puts(sen);
return 0;
}
Output:
Enter a sentence:
egaugnal teews a si ilagneb

After reversing sentence is:


bengali is a sweet language

4.3 Write a program to find the nth Fibonacci number in a Fibonacci sequence using
recursion.
Answer:

#include<stdio.h>

int fibo(int n)

if (n>2)

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

else

return (n-1);

int main()

{int n,c;

printf("enter the value of n\n");

scanf("%d",&n);

printf("asked term is %d\nwant to contnue(1/0)?\n",fibo(n));

36
scanf("%d",&c);

if(c)

main();

else

printf("thanks for using my program");

return 0;

Output:

enter the value of n

10

asked term is 34

want to contnue(1/0)?

enter the value of n

11

asked term is 55

want to contnue(1/0)?

thanks for using my program

4.4 Implement sorting algorithms like Bubble sort, Insertion sort and Selection sort
and compare the time taken by each algorithm.
Answer: #include <stdio.h>
#include <time.h>
#include<windows.h>
void swap(int *a,int *b){
int t = *a;
*a = *b;
*b = t;
return;
}

37
void bubbleSort(int n,int arr[]){
int i, j;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
Sleep(100);
swap(&arr[j], &arr[j+1]);

}
return;
}
void insertionSort(int n, int arr[]){
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i-1;
while (j >= 0 && arr[j] > key)
{
Sleep(100);
arr[j+1] = arr[j];
j = j-1;

arr[j+1] = key;
}
return;
}
void selectionSort(int n, int arr[]){
int i, j, min_idx;
for (i = 0; i < n-1; i++)
{
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
{
Sleep(100);

38
min_idx = j;

}
swap(&arr[min_idx], &arr[i]);

}
return;
}
int main(void){
int n,f;
printf("Enter the number of elements in array n: ");
scanf("%d",&n);
int a[n],b[n],i[n],s[n];
printf("Enter the elements of array: \n");
int j;
for(j=0;j<n;j++){
scanf("%d",&a[j]);
b[j]=i[j]=s[j]=a[j] ;
}
printf("\nYour array is:\n");
for(j=0;j<n;j++){
printf("%d ",a[j]);
}

clock_t t1,t2,t3,t4,t5,t6;
t1 = clock();
bubbleSort(n,b);
t2 = clock();
printf("\n\nOutcome of Bubble Sort:\n");
for(j=0;j<n;j++)printf("%d ",b[j]);
t3 = clock();
insertionSort(n,i);
t4 = clock();
printf("\n\nOutcome of Insertion Sort:\n");
for(j=0;j<n;j++)printf("%d ",i[j]);
t5 = clock();
selectionSort(n,s);
t6 = clock();
printf("\n\nOutcome of Selection Sort:\n");

39
for(j=0;j<n;j++)printf("%d ",s[j]);
printf("\nTime taken by algorithms in seconds is:\n");
printf("Bubble Sort : %.15lf",(double)(t2-t1)/CLOCKS_PER_SEC);
printf("\nInsertion Sort: %.15lf",(double)(t4-t3)/CLOCKS_PER_SEC);
printf("\nSelection Sort: %.15lf",(double)(t6-t5)/CLOCKS_PER_SEC);

return 0;
}
Output:
Enter the number of elements in array n: 5
Enter the elements of array:
99 9 894 45 21

Your array is:


99 9 894 45 21

Outcome of Bubble Sort:


9 21 45 99 894

Outcome of Insertion Sort:


9 21 45 99 894

Outcome of Selection Sort:


9 21 45 99 894
Time taken by algorithms in seconds is:
Bubble Sort : 0.685000000000000
Insertion Sort: 0.663000000000000
Selection Sort: 0.512000000000000

4.5 Find the value of the continued function, accurately upto ‘m’ decimal places:
#include<stdio.h>
#include<math.h>
int main(void)
{
float x,s=0;
int fact(int x);
int n,m,i,t=1;
printf("Enter the value of x , m & n\n");
scanf("%f%d%d",&x,&m,&n);

40
printf("x= %f\nm= %d\nNumber of terms to add = %d",x,m,n);
printf("\n\nSin(x)=");
for(i=1; i<=n; i++)
{
s=s+pow(-1,(i+1))*(pow(x,t))/((float)fact(t));
printf("x^%d/%d!",t,t);
if(i!=n){
if(i%2==0)
printf("+");
else
printf("-");
}
t=t+2;
}
printf("\nSum of series = %.*f",m,s);
return 0;
}
int fact(int x)
{
int i,f=1;
for(i=1; i<=x; i++)
f=f*i;
return(f);
}
Output:
Enter the value of x , m & n
236
x= 2.000000
m= 3
Number of terms to add = 6

Sin(x)=x^1/1!-x^3/3!+x^5/5!-x^7/7!+x^9/9!-x^11/11!
Sum of series = 0.909

4.6 There is an ancient cipher called the “Caesar’s Cipher” in which the encoding is
done by just jumping of steps. Write a program for encoding and decoding some
message, which will be provided in the form of string, with some clue. Hence
using it solve the following encoded message

41
CLUE = LUDN

CQRB VRPQC KN FXDA QRABC BCNY RW

Answer:
#include <stdio.h>
#include <string.h>
int main(void){
char ch[10000];
char ch1[10];
printf("Enter encrypted message: ");
gets(ch);
printf("Enter \"CLUE\": ");
gets(ch1);
int key = (-1)*( ch1[0]-'C');
int i,len = strlen(ch);
for(i=0;i<len;i++){
if(ch[i]==' '){
printf("%c",ch[i]);
continue;
}
if(ch[i]+key >= 'A'&&ch[i]+key <='Z')printf("%c",ch[i]+key);
else if(ch[i]+key >'Z')printf("%c",ch[i]+key-'Z'+'A'-1);
else if(ch[i]+key <'A')printf("%c",'Z'-('A'-ch[i]-key) + 1);
}
return 0;
}
Output:
Enter encrypted message: CQRB VRPQC KN FXDA QRABC BCNY RW
Enter "CLUE": LUDN
THIS MIGHT BE WOUR HIRST STEP IN

4.7 Create a header file of your own and find the perfect numbers with in a given
range

Answer: CODE
#include <stdio.h>

42
#include <math.h>
#include "myhead.h"
int main(void){
int a,b;
printf("Enter lower limit: ");
scanf("%d",&a);
printf("Enter upper limit: ");
scanf("%d",&b);
printf("Perfect numbers from %d to %d are as following..\n",a,b);
perfect(a,b);
return 0;
}
Header file(myhead.h)
int perfect(int n,int m )
{ int i,j,sum;
for(j=0;m>=n+j;j++)
{
i=1;
sum=0;
while(i<n+j)
{
if((n+j)%i==0)
sum+=i;
i++;
}
if(sum==n+j)
printf("%d ",n+j);
}
}

Output:
Enter lower limit: 1
Enter upper limit: 1000
Perfect numbers from 1 to 1000 are as following..
6 28 496

DATA STRUCTURE

43
1.write a program for stack representation using linked list.
Answer:

#include <stdio.h>

#include <malloc.h>

typedef struct stack {

int data;

struct stack *next;

} STACK;

typedef STACK *stack;

void printStack(stack head){

if(head==NULL){

printf("Stack is empty.");

return;

printf("From Top:\n");

while(head!=NULL){

printf("%d\n",head->data);

head = head->next;

return;

int peek(stack head){

if(head!=NULL)return head->data;

return 0;

int isEmpty(stack head){

44
if(head)return 0;

return 1;

stack pop(stack head){

if(head==NULL){

printf("Underflow condition.\n");return 0;

}else{

stack p = (stack)malloc(sizeof(STACK));

p = head;

head = head->next;

free(p);

return head;

stack push(stack head, int data){

stack p = (stack)malloc(sizeof(STACK));

if(head==NULL){

p->data = data;

p->next = NULL;

}else{

stack t = (stack)malloc(sizeof(STACK));

t = head;

p->data = data;

p->next = t;

head = p;

45
return head;

int main(void){

char ch = 'Y'; int data; int action;

stack head = (stack)malloc(sizeof(STACK));

head = NULL;

printf("Empty Stack created\n");

do{

printf("Choose a action.\n");

printf("1.Add data to stack(push())\n2.Delete data from stack(pop())\n3.Print top


stack(peek())");

printf("\n4.Check for empty stack(isEmpty())\n5.Print stack(printStack())");

printf("\nYour action: "); scanf("%d",&action); fflush(stdin);

switch(action){

case 1:

printf("Enter data: ");

scanf("%d",&data); fflush(stdin);

head = push(head,data);

break;

case 2:

head = pop(head);

break;

case 3:

if(head==NULL){

printf("Stack is empty.");

}else{

printf("Top element is: %d",peek(head));

46
}

break;

case 4:

if(isEmpty(head)){

printf("Stack is empty.");

}else{

printf("Stack has some elements.");

break;

case 5:

printf("Printing stack\n");

printStack(head);

break;

default:

printf("Wrong action.");

printf("\nWant more action?(y/n): ");

scanf("%c",&ch); fflush(stdin);

}while(ch=='Y'||ch=='y');

return 0;

Output:

Empty Stack created

Choose a action.

1.Add data to stack(push())

2.Delete data from stack(pop())

47
3.Print top stack(peek())

4.Check for empty stack(isEmpty())

5.Print stack(printStack())

Your action: 4

Stack is empty.

Want more action?(y/n): y

Choose a action.

1.Add data to stack(push())

2.Delete data from stack(pop())

3.Print top stack(peek())

4.Check for empty stack(isEmpty())

5.Print stack(printStack())

Your action: 1

Enter data: 12

Want more action?(y/n): y

Choose a action.

1.Add data to stack(push())

2.Delete data from stack(pop())

3.Print top stack(peek())

4.Check for empty stack(isEmpty())

5.Print stack(printStack())

Your action: 1

Enter data: 24

Want more action?(y/n): y

48
Choose a action.

1.Add data to stack(push())

2.Delete data from stack(pop())

3.Print top stack(peek())

4.Check for empty stack(isEmpty())

5.Print stack(printStack())

Your action: 3

Top element is: 24

Want more action?(y/n): y

Choose a action.

1.Add data to stack(push())

2.Delete data from stack(pop())

3.Print top stack(peek())

4.Check for empty stack(isEmpty())

5.Print stack(printStack())

Your action: 5

Printing stack

From Top:

24

12

Want more action?(y/n): y

Choose a action.

1.Add data to stack(push())

2.Delete data from stack(pop())

3.Print top stack(peek())

49
4.Check for empty stack(isEmpty())

5.Print stack(printStack())

Your action: 2

Want more action?(y/n): y

Choose a action.

1.Add data to stack(push())

2.Delete data from stack(pop())

3.Print top stack(peek())

4.Check for empty stack(isEmpty())

5.Print stack(printStack())

Your action: 5

Printing stack

From Top:

12

2.write a program for queue representation using linked list.


#include <stdio.h>

#include <malloc.h>

typedef struct que {

int data;

struct que *next;

} QUE;

typedef QUE *que;

void printQue(que head){

if(head==NULL){

printf("Queue is empty.");

50
return;

printf("Form First in\n");

while(head!=NULL){

printf("%d\n",head->data);

head = head->next;

return;

int peek(que head){

if(head!=NULL) return head->data;

return 0;

int isEmpty(que head){

if(head)return 0;

return 1;

que pop(que head){

if(head==NULL){

printf("Underflow condition.\n");return 0;

}else{

que p = (que)malloc(sizeof(QUE));

p = head;

head = head->next;

free(p);

51
return head;

que push(que head, int data){

que p = (que)malloc(sizeof(QUE));

p->next = NULL;

p->data = data;

if(head==NULL){

head = p;

}else{

que temp =head;

while(temp->next!=NULL){

temp=temp->next;

temp->next = p;

return head;

int main(void){

char ch = 'Y'; int data; int action;

que head = (que)malloc(sizeof(QUE));

head = NULL;

printf("Empty que created\n");

do{

printf("Choose a action.\n");

printf("1.Add data to que(push())\n2.Delete data from que(pop())\n3.Print first in


data(peek())");

printf("\n4.Check for empty que(isEmpty())\n5.Print que(printQue())");

52
printf("\nYour action: "); scanf("%d",&action); fflush(stdin);

switch(action){

case 1:

printf("Enter data: ");

scanf("%d",&data); fflush(stdin);

head = push(head,data);

break;

case 2:

head = pop(head);

break;

case 3:

if(peek(head)==-1){

printf("Que is empty.");

}else{

printf("First in Element is: %d",head->data);

break;

case 4:

if(isEmpty(head)){

printf("Queue is empty.");

}else{

printf("Queue has some elements.");

break;

case 5:

printf("Printing Queue\n");

53
printQue(head);

break;

default:

printf("Wrong action.");

printf("\nWant more action?(y/n): ");

scanf("%c",&ch); fflush(stdin);

}while(ch=='Y'||ch=='y');

return 0;

Output:

Empty que created

Choose a action.

1.Add data to que(push())

2.Delete data from que(pop())

3.Print first in data(peek())

4.Check for empty que(isEmpty())

5.Print que(printQue())

Your action: 1

Enter data: 12

Want more action?(y/n): y

Choose a action.

1.Add data to que(push())

2.Delete data from que(pop())

3.Print first in data(peek())

54
4.Check for empty que(isEmpty())

5.Print que(printQue())

Your action: 4

Queue has some elements.

Want more action?(y/n): y

Choose a action.

1.Add data to que(push())

2.Delete data from que(pop())

3.Print first in data(peek())

4.Check for empty que(isEmpty())

5.Print que(printQue())

Your action: 1

Enter data: 24

Want more action?(y/n): y

Choose a action.

1.Add data to que(push())

2.Delete data from que(pop())

3.Print first in data(peek())

4.Check for empty que(isEmpty())

5.Print que(printQue())

Your action: 2

Want more action?(y/n): y

Choose a action.

1.Add data to que(push())

55
2.Delete data from que(pop())

3.Print first in data(peek())

4.Check for empty que(isEmpty())

5.Print que(printQue())

Your action: 3

First in Element is: 24

Want more action?(y/n): y

Choose a action.

1.Add data to que(push())

2.Delete data from que(pop())

3.Print first in data(peek())

4.Check for empty que(isEmpty())

5.Print que(printQue())

Your action: 5

Printing Queue

Form First in

24

3.write a program in which contain singly linked list whose elements are of type
integer.now break these linked list into two linked list and one list contain all even node and
another contain all odd node.

Answer;

#include <stdio.h>

#include <malloc.h>

typedef struct node {

int data;

struct node *next;

56
} NODE;

typedef NODE *list;

void printList(list p){

while(p!=NULL){

printf("%d-> ",p->data);

p = p->next;

printf("NULL");

return;

list giveNode(int data){

list p = (list)malloc(sizeof(NODE));

p->data = data;

p->next = NULL;

return p;

int main(void){

int n;

char ch;

int data;

list head1 = (list)malloc(sizeof(NODE));

list head2 = (list)malloc(sizeof(NODE));

list head3 = (list)malloc(sizeof(NODE));

list temp = (list)malloc(sizeof(NODE));

list temp1 = (list)malloc(sizeof(NODE));

head1= NULL;

57
head2= NULL;

head3= NULL;

printf("Add data to list?(y/n)");

scanf("%c",&ch); fflush(stdin);

if(ch=='Y'||ch=='y'){

printf("Enter data: ");

scanf("%d",&n); fflush(stdin);

head1 = giveNode(n);

temp = head1;

printf("Add more data?(y/n)");

scanf("%c",&ch); fflush(stdin);

while(ch=='Y'||ch=='y'){

printf("Enter data: ");

scanf("%d",&n); fflush(stdin);

temp->next = giveNode(n);

temp = temp->next;

printf("Enter more data?(y/n)");

scanf("%c",&ch); fflush(stdin);

temp1 = head1;

if(temp1!=NULL&&temp1->next!=NULL){

head2 = giveNode(temp1->next->data);

temp = head2;

temp1 = temp1->next->next;

58
while(temp1!=NULL&&temp1->next!=NULL){

temp->next = giveNode(temp1->next->data);

temp1 = temp1->next->next;

temp = temp->next;

if(head1!=NULL)head3 = giveNode(head1->data);

temp = head3;

temp1 = head1->next;

if(temp1!=NULL&&temp1->next!=NULL){

temp->next = giveNode(temp1->next->data);

temp = temp->next;

temp1 = temp1->next->next;

while(temp1!=NULL&&temp1->next!=NULL){

temp->next = giveNode(temp1->next->data);

temp1 = temp1->next->next;

temp = temp->next;

printf("Printing original list:\n");

printList(head1);

printf("\n\nPrinting Even node list:\n");

printList(head2);

printf("\n\nPrinting Odd node list: \n");

printList(head3);

59
return 0;

Output:

Add data to list?(y/n)y

Enter data: 12

Add more data?(y/n)y

Enter data: 167

Enter more data?(y/n)y

Enter data: 17

Enter more data?(y/n)y

Enter data: 165

Enter more data?(y/n)y

Enter data: 1234

Enter more data?(y/n)n

Printing original list:

12-> 167-> 17-> 165-> 1234-> NULL

Printing Even node list:

167-> 165-> NULL

Printing Odd node list:

12-> 17-> 1234-> NULL

4. Write a C program for implementing Knuth-Morris- Pratt(KMP) pattern matching


algorithm

https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm

60
Answer:

#include <stdio.h>

#include <string.h>

#include <ctype.h>

int main()

char string[100], matchcase[20], c;

int i = 0, j = 0, index;

/*Scanning string*/

printf("Enter string: ");

do

fflush(stdin);

c = getchar();

string[i++] = tolower(c);

} while (c != '\n');

string[i - 1] = '\0';

/*Scanning substring*/

printf("Enter substring: ");

i = 0;

do

61
fflush(stdin);

c = getchar();

matchcase[i++] = tolower(c);

} while (c != '\n');

matchcase[i - 1] = '\0';

for (i = 0; i < strlen(string) - strlen(matchcase) + 1; i++)

index = i;

if (string[i] == matchcase[j])

do

i++;

j++;

} while(j != strlen(matchcase) && string[i] == matchcase[j]);

if (j == strlen(matchcase))

printf("Match found from position %d to %d.\n", index + 1, i);

return 0;

else

i = index + 1;

j = 0;

62
}

printf("No substring match found in the string.\n");

return 0;

Output:1

Enter string: national international sports

Enter substring: nat

Match found from position 1 to 1.

Output 2:

Enter string: national promotional

Enter substring: inter

No substring match found in the string.

5. Write a program to count the number of leaves in a binary tree.


Answer:

#include <stdio.h>

#include <malloc.h>

typedef struct node {

int data;

struct node *left;

struct node *right;

} NODE;

typedef NODE *tree;

63
int sum = 0;

tree givetree(int data){

tree q = (tree)malloc(sizeof(NODE));

q->right = NULL;

q->left = NULL;

q->data = data;

return q;

int getLeaf(tree p){

if(p->right ==NULL && p->left == NULL)sum++;

if(p->right!=NULL)getLeaf(p->left);

if(p->left!=NULL)getLeaf(p->right);

return sum;

int main(void){

/* *

/\

* *

/\

* *

/\

* *

*/

tree head = givetree(1);

head->right = givetree(2);

64
head->left = givetree(3);

head->right->left = givetree(4);

head->right->right = givetree(5);

head->right->left->left = givetree(4);

head->right->left->right = givetree(4);

if(head==NULL){

printf("There is not any tree.");

if(head->right==NULL&&head->left==NULL){

printf("There is no leaf only root.");

if(getLeaf(head) == 1){

printf("There is only one leaf in tree");

sum=0;

printf("There are %d leaves in tree ", getLeaf(head));

return 0;

Output:

There are 4 leaves in tree

6. Write a program in C for converting an Infix Expression to Prefix Expression. Program


should support for both parenthesized and free parenthesized expressions with the
operators: +, -, *, /, %( Remainder), ^ (Power) and alphanumeric operands.

Example : 5^E+D*(C^B+A) will result in to +*+A^BCD^E5

Answer:

65

Вам также может понравиться