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

Pranav - Final Assignment

The document provides an algorithm and source code to generate the prime factors of a given number. The algorithm involves taking a number as input, then using a for loop to iterate from 2 to half the number and check if each number is a factor. If it is a factor, it further checks if it is prime. Prime factors found are printed. The source code implements this by taking the number, initializing variables, then having a nested for loop to check for factors and primality using modulo. Prime factors found are printed. It outputs the prime factors of sample numbers correctly.

Uploaded by

Akash Bhagat
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)
101 views

Pranav - Final Assignment

The document provides an algorithm and source code to generate the prime factors of a given number. The algorithm involves taking a number as input, then using a for loop to iterate from 2 to half the number and check if each number is a factor. If it is a factor, it further checks if it is prime. Prime factors found are printed. The source code implements this by taking the number, initializing variables, then having a nested for loop to check for factors and primality using modulo. Prime factors found are printed. It outputs the prime factors of sample numbers correctly.

Uploaded by

Akash Bhagat
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/ 56

Assignment 1.

WAP to generate the prime factors of a number

Algorithm:
1. Input a number from user. Store it in some variable say num.
2. Run a loop from 2 to num/2, increment 1 in each iteration. The loop
structure should look like for(i=2; i<=num/2; i++).
You may think why loop from 2 to num/2? Because prime number starts from
2 and any factor of a number n is always less than n/2.
3. Inside the loop, first check if i is a factor of num or not. If it is a factor then
check it is prime or not.
4. Print the value of i if it is prime and a factor of num.

Source code:
#include <stdio.h>
int main()
{
int i, j, num, isPrime;

/* Input a number from user */


printf("Enter any number to print Prime factors: ");
scanf("%d", &num);

printf("All Prime Factors of %d are: \n", num);

/* Find all Prime factors */


for(i=2; i<=num; i++)
{
/* Check 'i' for factor of num */
if(num%i==0)
{
/* Check 'i' for Prime */
isPrime = 1;
for(j=2; j<=i/2; j++)
{
if(i%j==0)
{
isPrime = 0;
break;
}
}

/* If 'i' is Prime number and factor of num */


if(isPrime==1)
{
printf("%d, ", i);

1|Page
}
}
}

return 0;
}

Output:
Set-1:
Enter any number to print Prime factors: 24
All Prime Factors of 24 are:
2, 3,

Set-2:
Enter any number to print Prime factors: 100
All Prime Factors of 100 are:
2, 5,

Discussion:
1.afadfasdf
2.aadfasdf
3.asdfasdf
4.asdfasdf

2|Page
Assignment 2: WAP to interchange the values of two variables given by user
without using a third Variable.

Algorithm:
1. Two variables x and y and taken.
2. User is asked to enter the values of these variables.
3. Now comparison is made, if(x>y), if so then y is changed to x-y and x is
changed to x-y, and at last y is changed to x+y. Now x and y are storing
new values.
4. Now if (y>x), then x is changed to y-x, y is changed to y-x, and at last x is
changed to y+x.
5. New values are printed on the screen as output.
6. End.

Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
printf(“Enter value of X: “);
scanf(“%d”,&x);
printf(“Enter value of y: “);
scanf(“%d”,&y);
if(x>y)
{
y=x-y;
x=x-y;
y=x+y;
}
else
if(y>x)
{
x=y-x;
y=y-x;
x=y+x;
}
printf(“\nx=%d”,x);
printf(“\ny=%d”,y);
getch();
}

3|Page
Output:
Enter value of X: 14
Enter value of y: 23

x=23
y=14

Discussion:
Without using a third variable we are interchanging the values of two
variables.

Assignment 3:Hexadecimal Addition and Subtraction.


Algorithm:
Source code:
Discussion:

4|Page
Assignment 4: WRITE A C PROGRAM TO PRINT FIBONACCI SERIES UPTO
Nth TERM.

ALGORITHM:
STEP 1: Start
STEP 2: Declare variables i, a, b, show
STEP 3: Initialize the variables a=0, b=1 and show = 0
STEP 4: Enter the number of terms of Fibonacci series to be printed
STEP 5: Print first two terms of the series
STEP 6: Use loop for the following steps
a) show = a+b;
b) a=b;
c) b=show;
d) increase value of i each time by 1
e) print the value of show
STEP 7: End

Source code:
#include<stdio.h>
#include<conio.h>
int main()
{
int n, i, a=0, b=1, c;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("the Fibonacci series is: %d %d", a,b);
for(i=0; i<=n-2; i++)
{
c = a+b;
printf(" %d", c);
a=b;
b=c;
}
return 0;
}
Output:
Enter the value of n: 15
The Fibonacci series is: 0 1 1 2 3 5 8 13 21 34 55
89 144 233 377 610

Discussion:
1. The Fibonacci sequence is a set of numbers that starts with a one or a
zero, followed by a one, and proceeds based on the rule that each number is
equal to the sum of the preceding two numbers.

5|Page
2. The Fibonacci sequence is named for Leonardo Pisano (also known as
Leonardo Pisano or Fibonacci), an Italian mathematician who lived from 1170
– 1250.

3. Fibonacci numbers are of interest to biologists and physicists because


they are frequently observed in various natural objects and phenomena. The
branching pattern in trees and leaves, for example, and the distribution of
seeds in a raspberry are based on Fibonacci numbers.

Assignment 5: Binary to Decimal conversion.

Algorithm:
1. Take a binary number and store it in the variable num.
2. Initialize the variable decimal value to zero and variable base to 1.
3. Obtain the remainder and quotient of the binary number. Store the
remainder in the variable rem and override the variable number with quotient.
4. Multiply rem with variable base. Increment the variable decimal_val with
this new value.
5. Increment the variable base by 2.
6. Repeat the steps 3, 4 and 5 with the quotient obtained until quotient
becomes zero.
7. Print the variable s as output.
Source Code:
#include<math.h>
#include<conio.h>
#include<stdio.h>
int main()
{
int bin,i=0,s=0;
printf("Enter a binary number:");
scanf("%d",&bin);
while(bin!=0)
{
s=s+pow(2,i)*(bin%10);
bin=bin/10;
i++;
}
printf("The decimal equivalent is %d",s);
return 0;
}
6|Page
Output:
Enter a binary number: 1010
The decimal equivalent is 10
Enter a binary number: 1111
The decimal equivalent is 15

Discussion:
1. Binary number is the one which is made up of ‘1’ & ‘0’ only.
2. A decimal number is made up of ‘0’-‘9’.
3. Binary number is the only number which computers can read and
understand.
4. User usually enter number in decimal format, which is converted into its
corresponding binary number.

Assignment 6: Cosine Series

Algorithm:
1. First the computer reads the value of ‘x’ and ‘n’ from the user.
2. Then ‘x’ is converted to radian value.
3. Then using for loop the value of cos(x) is calculate.
4. Finally the value of Cos(x) is printed.

Source Code:

#include<stdio.h>
#include<conio.h>

int main()
{
int i, n;
float x, sum=1, t=1;
clrscr();

printf(" Enter the value for x : ");


scanf("%f",&x);

printf(" Enter the value for n : ");


scanf("%d",&n);

x=x*3.14159/180;

7|Page
/* Loop to calculate the value of Cosine */
for(i=1;i<=n;i++)
{
t=t*(-1)*x*x/(2*i*(2*i-1));
sum=sum+t;
}

printf(" The value of Cos(%f) is : %.4f", x, sum);


getch();
}

Output:

Enter the value for x : 30


Enter the value for n : 0
The value of Cos(0.523598) is : 1.0000

Discussion:

Assignment 7: WRITE A PROGRAM IN C WHICH WILL OUTPUT WHETHER A


WORD IS PALINDROME OR NOT.

ALGORITHM:
STEP 1: Read the word from the user, assign into an array
STEP 2: Set l=length of the word.
STEP 3: Set index variable i=0 and count=0.
STEP 4: Repeat STEP 4 until i=i/2.
STEP 5: if count=l/2
Print “Palindrome string”
If count not equals to l/2
Print “Not a Palindrome string”
STEP 6: End.

Source code:
#include <stdio.h>
#include <conio.h>
#include <string.h>

void main(){
char string1[20];
int i, length;
int count = 0;
char str[100];
clrscr();

8|Page
puts("Enter a string:");
gets(string1);

length = strlen(string1);

for(i=0;i < length/2 ;i++){


if(string1[i] != string1[length-i-1])
count++;

if (count==(length/2))
printf("%s is not a palindrome.", string1);

else
printf("%s is a palindrome.", string1);

getch();
}

Output:-

Output 1:
Enter a string:

Madam

Madam is a palindrome.

Output 2:
Enter a string:

Student

Student is not a palindrome.

Discussion:-

The above program can check whether a given word is palindrome or not.
A word is said to be palindrome if any two pairs of alphabets are same at both
end of the word and same distance from the middle. For e.g. “MADAM” is
palindrome word where as “STUDENT” is not a palindrome.

9|Page
Assignment 8: Write a program to count the total no. of vowels, consonant,
blank space from a text given as input.
Algorithm:
Step1: read the line.
Step2: i=0 until line[i]! =’\o’.
Step 3: take each character in i and start checking.
Step 4: (a) if it is vowel then increase ‘vowel’ by 1.
(b) if it is consonant then increase ‘consonant’ by 1.
(c) if there is blank space then increase ‘space’ by 1.
Step 5: END.

Source code:
#include <stdio.h>
#include<conio.h>

int main()
{
char line[100];
int i, vowels, consonants, spaces;

vowels = consonants = spaces = 0;

printf("Enter a line of string: ");


scanf("%[^\n]", line);

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


{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||
line[i]=='o' || line[i]=='u' || line[i]=='A' ||
line[i]=='E' || line[i]=='I' || line[i]=='O' ||
line[i]=='U')
{
++vowels;
}
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
{
++consonants;
}
else if (line[i]==' ')
{
++spaces;
10 | P a g e
}
}

printf("Vowels: %d",vowels);
printf("\nConsonants: %d",consonants);
printf("\nblank spaces: %d", spaces);

return 0;
}

Output:
Enter a line of string: my name is Pranav
Vowels: 5
Consonants: 8
Blank spaces: 3

Discussion:
In this program each character of the string is taken into the loop and
checked, different counters each for vowel, consonants, digits and white
spaces are declared. As soon as the loop encounters any of the vowel,
consonants, digits or white spaces, the respective counter variables
increments by 1.
Assignment 9: Write a program to print frequency of each letter in a text
given by the user as input.

Algorithm:
Step1:read the string.
Step2: i=0 until i<26
Source code:
#include <stdio.h>
#include <string.h>
#define MAX 100

int main()
{
char str[MAX];
int i, len;
int freq[26];

printf("Enter any string: ");


gets(str);

len = strlen(str);
11 | P a g e
for(i= 0; i< 26; i++)
{
freq[i] = 0;
}
for(i=0; i<len; i++)
{
if(str[i]>='a' && str[i]<='z')
{
freq[str[i] - 97]++;
}
else if(str[i]>='A' && str[i]<='Z')
{
freq[str[i] - 65]++;
}
}

printf("\nFrequency of all characters in the given string: \n");

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


{
if(freq[i] != 0)
{
printf("'%c' = %d\n", (i + 97), freq[i]);
}
}

return 0;

Output:
Enter any string:
frequency
Frequency of all characters in the given string:
'c' = 1
'e' = 2
'f' = 1
'n' = 1
'q' = 1
'r' = 1
'u' = 1
'y' = 1

12 | P a g e
Discussion:
This C Program counts the number of occurrence of each character ignoring
the case and prints them.

Assignment 10: write a program to take two different dates &find out number
of days in between these two days

Algorithm:
Source code:
#include<stdio.h>
#include<conio.h>
int day_of_month(int m,int y);
int main()
{
int d1,m1,y1,d2,m2,y2,total,x;
total=1;x=0;
printf("\n enter the first dates(dd-mm-yyyy):");
scanf("\n %d %d %d ",&d1,&m1,&y1);
printf("\n enter the second date(dd-mm-yyyy):");
scanf("\n %d %d %d",&d2,&m2,&y2);
x=day_of_months(m1,y1);

while(1)
{
total++;
d1++;
if(d1>x)
{
m1++;
d1=1;
if(m1>12)
{
m1=1;
y1++;

}
x=days-of-months(m1,y1)
}
if(d1==d2&&m1==m2&&y1==y2)
break;
}
13 | P a g e
printf("\n total no.of days is%d",total);
}
int days-of-month(int m,int y)
{
int z;
if(m==1||m==3||m==5||m==7||m==8||m==10||m==12)
z=31;
if(m==4||m==6||m==9||m==11)
z=30;
if(m==2)
{
z=28;
if(y%400==0)||(y%100!=0&&y%4==0))
z=29;
}
return z;
}

Output:
Enter first date(dd mm yyyy) : 02
05
2018

Enter second date(dd mm yyyy) : 12


12
2001
The no. of days b/w the 2 dates = 5985 days
Discussion:
In this c program we have calculated the difference between the given two
dates
Assignment 11: Write a program to read all the lines from a text file and print
the longest line with its length.
Algorithm:
Source code:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
FILE *fp;
14 | P a g e
int len, max=0,i,line,a[10]={0,0,0,0,0,0,0,0,0,0},j;
char ch,s[100],fname[20];
printf(“Enter file name:”);
gets(fname);
fp=fopen(fname,”r”);
if(fp==null)
{
printf(“\nError\n”);
exit(1);
}
while(fgets(s,99,fp)!=null)
{
printf(“%s\n”,s);
}
printf(“\n”);
rewind(fp);
ch=getc(fp);
while(ch!=EOF)
{
if(ch==’\n’)
{
line=line+1;
}
ch=getc(fp);
}
rewind(fp);
ch=getc(fp);
ch=getc(fp);
for(i=1;i<line;i++)
{
while(ch!=’\n’)
{
a[i]=a[i]+1;
ch=getc(fp);
}
if(a[i]>max)
max=a[i];
j=i;
}
ch=getc(fp);
}
15 | P a g e
printf(“\nLine no. which is maximum is %d having length %d”,j,max);
fclose(fp);
}
Output:
Discussion: Here the name of file containing some lines is entered by the
user. By this program firstly the whole content of the file if printed on the
screen. After that line by line comparison is done to find to find which line is
maximum? At last that line number along with its length is printed as the
output.

Assignment12: Write a program to inverse a square matrix of order ‘n’

Algorithm:
1. Order is asked to enter from the user.
2. Then a loop is executed to enter the elements of the matrix.
3. Then control is transferred to the determinant function, if determinant of
the entered matrix comes out to be 0(zero) then a message is generated
that inverse of the matrix is not possible. Else process of inversion
starts.
4. Now cofactor is been calculated for the matrix. Now this new matrix
(temp) which is generated is divided by the determinant and again
transposed it to find the inverse of the matrix.
5. Print the output(inverse of the matrix)
6. End
Source code:
#include<stdio.h>
#include<math.h>
float determinant(float [][25], float);
void cofactor(float [][25], float);
void transpose(float [][25], float [][25], float);
int main()
{
float a[25][25], k, d;
int i, j;
printf("Enter the order of the Matrix : ");
scanf("%f", &k);
printf("Enter the elements of %.0fX%.0f Matrix : \n", k, k);
for (i = 0;i < k; i++)
{
for (j = 0;j < k; j++)
{
16 | P a g e
scanf("%f", &a[i][j]);
}
}
d = determinant(a, k);
if (d == 0)
printf("\nInverse of Entered Matrix is not possible\n");
else
cofactor(a, k);
}
float determinant(float a[25][25], float k)
{
float s = 1, det = 0, b[25][25];
int i, j, m, n, c;
if (k == 1)
{
return (a[0][0]);
}
else
{
det = 0;
for (c = 0; c < k; c++)
{
m = 0;
n = 0;
for (i = 0;i < k; i++)
{
for (j = 0 ;j < k; j++)
{
b[i][j] = 0;
if (i != 0 && j != c)
{
b[m][n] = a[i][j];
if (n < (k - 2))
n++;
else
{
n = 0;
m++;
}
}
}
17 | P a g e
}
det = det + s * (a[0][c] * determinant(b, k - 1));
s = -1 * s;
}
}

return (det);
}

void cofactor(float num[25][25], float f)


{
float b[25][25], fac[25][25];
int p, q, m, n, i, j;
for (q = 0;q < f; q++)
{
for (p = 0;p < f; p++)
{
m = 0;
n = 0;
for (i = 0;i < f; i++)
{
for (j = 0;j < f; j++)
{
if (i != q && j != p)
{
b[m][n] = num[i][j];
if (n < (f - 2))
n++;
else
{
n = 0;
m++;
}
}
}
}
fac[q][p] = pow(-1, q + p) * determinant(b, f - 1);
}
}
transpose(num, fac, f);
}
18 | P a g e
void transpose(float num[25][25], float fac[25][25], float r)
{
int i, j;
float b[25][25], inverse[25][25], d;

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


{
for (j = 0;j < r; j++)
{
b[i][j] = fac[j][i];
}
}
d = determinant(num, r);
for (i = 0;i < r; i++)
{
for (j = 0;j < r; j++)
{
inverse[i][j] = b[i][j] / d;
}
}
printf("\n\n\nThe inverse of matrix is : \n");

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


{
for (j = 0;j < r; j++)
{
printf("\t%f", inverse[i][j]);
}
printf("\n");
}
}
Output:
Enter the order of the Matrix : 2
Enter the elements of 2X2 Matrix :
2
3
4
1

19 | P a g e
The inverse of matrix is :
-0.100000 0.300000
0.400000 -0.200000

Discussion:
Inverse of a matrix

Assignment 13: Write a program to arrange each row & column separately of
a square matrix in ascending order.

Algorithm:
Source code:
#include <stdio.h>

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

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


scanf("%d %d", &m, &n);
printf("Enter co-efficients of the matrix \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &array1[i][j]);
array2[i][j] = array1[i][j];
}
}
printf("The given matrix is \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
printf(" %d", array1[i][j]);
}
20 | P a g e
printf("\n");
}
printf("After arranging rows in ascending order\n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
for (k =(j + 1); k < n; ++k)
{
if (array1[i][j] > array1[i][k])
{
a = array1[i][j];
array1[i][j] = array1[i][k];
array1[i][k] = a;
}
}
}
}
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
printf(" %d", array1[i][j]);
}
printf("\n");
}
Output:
Enter the order of the matrix
3
3
Enter co-efficients of the matrix
3
2
1
5
7
4
8
6
9
The given matrix is
21 | P a g e
321
574
869
After arranging rows in ascending order
123
457
689
Discussion:

Assignment 14: write a program to perform insertion sort over a set of data &
display the sorted set of data in increasing order.

Algorithm:
Step 1: Repeat Steps 2 to 5 for K = 1 toN–1
Step 2: SET TEMP = ARR[K]
Step 3: SET J = K – 1
Step 4: Repeat while TEMP <= ARR[J] SET ARR[J + 1] = ARR[J] SETJ=J-1
[END OF INNER LOOP] Step 5: SET ARR[J + 1] = TEMP [END OF LOOP]
Step 6: EXIT

Source code:
#include <stdio.h>
#include <conio.h>
#define size 5
void insertion_sort(int arr[], int n);
void main()
{
int arr[size], i, n;
printf("\n Enter the number of elements in the array: ");
scanf("%d", &n);
printf("\n Enter the elements of the array: ");
for(i=0;i<n;i++)
{
scanf("%d", &arr[i]);
}
insertion_sort(arr, n);
printf("\n The sorted array is: \n");
for(i=0;i<n;i++)
printf(" %d\t", arr[i]);
22 | P a g e
getch();
}
void insertion_sort(int arr[], int n)
{
int i, j, temp;
for(i=1;i<n;i++)
{
temp = arr[i];
j = i-1;
while((temp < arr[j]) && (j>=0))
{
arr[j+1] = arr[j];
j--;
}
arr[j+1] = temp;
}
}

Output:
Enter the number of elements in the array: 6
Enter the elements of the array:
90
50
70
20
55
72
The sorted array is:
20 50 55 70 72 90

Discussion:
Insertion sort is a very simple sorting algorithm in which the sorted array (or
list) is built one element at a time.

Assignment 15: Write a program to perform shell sort.

Algorithm:
Shell_Sort(Arr, n)
Step 1: SET FLAG = 1, GAP_SIZE = N
Step 2: Repeat Steps 3 to 6 while FLAG = 1 OR GAP_SIZE>1
Step 3: SET FLAG = 0
23 | P a g e
Step 4: SET GAP_SIZE = (GAP_SIZE + 1) / 2
Step 5: Repeat Step 6 for I = toI<(N-GAP_SIZE)
Step 6: IF Arr[I + GAP_SIZE] > Arr[I] SWAP Arr[I + GAP_SIZE], Arr[I] SET
FLAG = 0
Step 7: END

Source code:
#include<stdio.h>
void main()
{
int arr[10]={-1};
int i, j, n, flag=1, gap_size, temp;
printf("\n Enter the number of elements in the array: ");
scanf("%d", &n);
printf("\n Enter %d numbers: ",n); // n was added
for(i=0;i<n;i++)
scanf("%d", &arr[i]);
gap_size = n;
while(flag == 1 || gap_size > 1)
{
Flag = 0;
gap_size = (gap_size + 1) /2;
for(i=0; i< (n - gap_size); i++)
{
if(arr[i+gap_size] < arr[i])
{
temp = arr[i+gap_size];
arr[i+gap_size] = arr[i];
arr[i] = temp;
flag = 0;
}
}
}
printf("\nThe sorted array is: \n");
for(i=0;i<n;i++)
{
printf(" %d\t", arr[i]);
}
}

24 | P a g e
Output:
Enter the number of elements in the array: 5
Enter 5 numbers: 33
55
21
87
31
The sorted array is: 21 31 33 55 8
Discussion:
In shell sort we arrange the elements of the array in the form of a table and
sort the columns (using insertion sort). We will repeat this arranging and
sorting each time with smaller number of longer columns in such a way that
at the end, there is only one column of data to be sorted.Hence atlast we get
our sorted elements by shell sort.

Assignment 16: WRITE A MENU DRIVEN C PROGRAM TO IMPLEMENT A


CIRCULAR QUEUE WITH THE FOLLOWING OPTIONS:-
I) INSERT
II) DELETE
III) DISPLAY
IV) EXIT

ALGORITHM:
A) TO INSERT IN CIRCULAR QUEUE
i) If rear=size-1 then
rear=0
else
rear=rear+1
ii) If front=rear then
Print(“circular queue overflows”)
iii) CQ[rear]= X
iv) If front=-1 then
Front =0
v) End

B) TO DELETE IN CIRCULAR QUEUE


i) If front= -1 then
Print (“circular queue underflows”)
ii) Return (CQ[front])
iii) If front = rear then
Front=rear=-1
iv) If front=size-1 then
front=0
else
25 | P a g e
front=front+1
v) End

Source code:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

struct Node
{
int Data;
struct Node* next;
}*rear, *front;

void delQueue()
{
struct Node *temp, *var=rear;
if(var==rear)
{
rear = rear->next;
free(var);
}
else
printf("\nQueue Empty");
}
void push(int value)
{
struct Node *temp;
temp=(struct Node *)malloc(sizeof(struct Node));
temp->Data=value;
if (front == NULL)
{
front=temp;
front->next=NULL;
rear=front;
}
else
{
front->next=temp;
front=temp;
front->next=rear;
}
}
void display()
{
struct Node *var=rear;
26 | P a g e
if(var!=NULL)
{
printf("\nElements are as: ");
while(var!=front)
{
printf("\t%d",var->Data);
var=var->next;
}
if(var==front)
{
printf("\t%d",var->Data);
}
printf("\n");
}
else
printf("\nQueue is Empty");
}
int main(int argc, char *argv[])
{
int i=0;
front=NULL;
printf(" \n1. Push to Queue");
printf(" \n2. Pop from Queue");
printf(" \n3. Display Data of Queue");
printf(" \n4. Exit\n");
while(1)
{
printf(" \nChoose Option: ");
scanf("%d",&i);
switch(i)
{
case 1:
{
int value;
printf("\nEnter a value to push into Queue: ");
scanf("%d",&value);
push(value);
display();
break;
}
case 2:
{
delQueue();
display();
break;
}
case 3:
27 | P a g e
{
display();
break;
}
case 4:
{
exit(0);
}
default:
{
printf("\nwrong choice for operation");
}
}
}
}

OUTPUT:
1. Push to Queue
2. Pop from Queue
3. Display Data of Queue
4. Exit
Choose Option: 1
Enter a value to push into Queue: 5
Elements are as : 5
Choose Option: 1
Enter a value to push into Queue: 6
Elements are as: 5 6
Choose Option:1
Enter a value to push into Queue: 2
Elements are as: 5 6 2
Choose option:2
Elements are as : 6 2
Choose option:4

DISCUSSION :
i. Allocate ONLY the new object or structure-type required.
ii. Insert the new allocation ANYWHERE you want in the queue.
Typically circular queues implement a linked-list design to manage the queue.
This allows you to "insert" an artifact (e.g. object or data-structure) anywhere
you like into a queue. This is very difficult within a linear queue (depending
on the reference implementation). Additionally memory management becomes
much easier to control and predominantly more efficient implementing a
circular queue.

Assignment 17: Reverse a singly linked list


28 | P a g e
Algorithm
Let us take three pointer variables P, q and r.
P references the linked list reversed so far, q points to
the linked list to be reversed and r points to the next node of q.
Initially, P=NULL; q=head; r=q->next;
while(all nodes have not been reversed )
{
Reverse
the node pointed by q.
q->next=P;
move P,
q, r forward by a node.
P=q;
q=r;
r=r->next;
}

Source Code:
#include<stdio.h>
#include<stdlib.h>

typedef struct node


{
int data;
struct node *next;
}node;

node *create(int);
void print(node *);
node *invert(node *);

int main()
{
node *head,*P;
int n;
printf(“Enter how many nodes? “);
scanf(“%d”,&n);
printf(“nEnter nodes: “);

head=create(n); //create function returns the address of first node


printf(“nOriginal Linked List: “);
print(head);

P=invert(head);
printf(“nnReversed Linked List: “);
print(P);
29 | P a g e
return 0;
}

node* create(int n)
{
node *head,*P;
int i;
head=(node*)malloc(sizeof(node));
head->next=NULL;
scanf(“%d”,&(head->data));
P=head;

//create subsequent nodes


for(i=1;i<n;i++)
{
P->next=(node*)malloc(sizeof(node));
//new node is inserted as the next node after P
P=P->next;
scanf(“%d”,&(P->data));
P->next=NULL;
}
return(head);
}

void print(node *P)


{
while(P!=NULL)
{
printf(“<- %d ->”,P->data);
P=P->next;
}
}

node *invert(node *head) //reverse a linked list pointed by head


{
node *P,*q,*r;

//initial values of P, q and r


P=NULL;
q=head;
r=q->next;

//until all nodes have reversed


while(q!=NULL)
{
q->next=P;
30 | P a g e
P=q;
q=r;

if(r!=NULL)
r=r->next;
}

return(P);
}

Output:
Enter how many nodes? 4
Enter nodes: 1
2
3
4
Original Linked List: <- 1 -><- 2 -><- 3 -><- 4 ->nnReversed Linked List: <- 4 -
><- 3 -><- 2 -><- 1 ->

Discussion: Reversing is linked list is nothing but to set reverse the


orientation of the pointers to print the content in backward direction or in
reverse order. No matter whether the elements are sorted or not, by the above
program the linked list can be reversed.

Assignment 18:

Assignment 21: WRITE A C-PROGRAM TO IMPLEMENT STACK USING LINK


LIST.

THEORY:
A stack is an ordered list in which all insertions and deletions are made at one
end, called the top. This means, in particular, that elements are removed from
the stack in the reverse order of that in which they were inserted into the
stack. Equivalently, we say that the last element to be into the stack will be
the first to be removed. For this reason stacks are sometimes referred to as
Last In First Out (LIFO) lists.

Algorithm:
 Push operation

stack_push (stk[ ],top.maxsize : item)

If (top = maxsize) then


Print “OVERFLOW”;
else
31 | P a g e
top+=1;
stk[top]:=item;
endif
End stack_push;

 Pop operation

stack_pop (stk[], top, maxsize : item)


If (top=-1) then
Print “UNERFLOW”;
else
if(top = maxsize) then
stk[top]:=item;
top-=1;
end if
End stack_pop;

Program Code :
#include<stdio.h>
#include<stdlib.h>

void push ();


void pop ();
void display();
main()
{
int n;
printf("\tMENU\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT\n");
do
{
printf("\nENTER YOUR CHOICE");
scanf("%d",&n);
switch(n)
{
case 1:
push();
break;

case 2:
pop();
break;

case 3:
display();
break;

32 | P a g e
case 4:
break;

default:
printf("Invalid choice\n");
break;
}
}

while(n!=4);
}

typedef struct node


{
int data;
struct node *link;
}
n;
n *top=NULL;

void push()
{
int item;
n *temp;
printf("ENTER THE ITEM\n");
scanf("%d", &item);
temp=(n*)malloc(sizeof(n));
temp->data=item;
temp->link=top;
top=temp;
}

void pop()
{
n *temp;
if(top==NULL)
printf("STACK IS EMPTY\n");
else
{
temp=top;
printf("THE ELEMENT DELETED=%d\n",temp->data);
top=temp->link;
free(temp);
}
}
33 | P a g e
void display()
{
n *save;
if(top==NULL)
printf("STACK IS EMPTY\n");
else
{
save=top;
printf("THE ELEMENTS OF THE STACK ARE:");
while(save!=NULL)
{
printf("%d\t",save->data);
save=save->link;
}
printf("\nTOPMOST ELEMENT =%d\n",top->data);
}
}

OUTPUT:
MENU
1. PUSH
2. POP
3. DISPLAY
4. EXIT
Enter your choice
1
Enter the item
2
Enter your choice
1
Enter the item
3
Enter your choice
2
The element is deleted=2

Enter your choice


3
Elements of the stack are=3
The top most element is=3
Enter your choice
2
The element is deleted=3
Enter your choice
3
Stack is empty
34 | P a g e
DISCUSSIONS:
a) STACK using LINKLIST is also known as growable stack because no full
condition is required because of dynamic allocation.

b) Inputs and Outputs of the program are traced for all 2 basic operations
of stack.

Assignment 22: Write a program to create a BST and perform insertion and
deletion operation on it.
Algorithm:
TreeNode insert(int data, TreeNode T) {
if T is NULL {
T = (TreeNode *)malloc(sizeof (Struct TreeNode));
(Allocate Memory of new node and load the data into it)
T->data = data;
T->left = NULL;
T->right = NULL;
} else if T is less than T->left {
T->left = insert(data, T->left);
(Then node needs to be inserted in left sub-tree.So,
recursively traverse left sub-tree to find the place
where the new node needs to be inserted)
} else if T is greater than T->right {
T->right = insert(data, T->right);
(Then node needs to be inserted in right sub-tree
So, recursively traverse right sub-tree to find the
place where the new node needs to be inserted.)
}
return T;
}
Source code:
#include <stdio.h>
#include <stdlib.h>

struct treeNode {
int data;
struct treeNode *left, *right;
};

struct treeNode *root = NULL;

/* create a new node with the given data */


struct treeNode* createNode(int data) {
struct treeNode *newNode;
newNode = (struct treeNode *) malloc(sizeof (struct treeNode));
newNode->data = data;
newNode->left = NULL;
35 | P a g e
newNode->right = NULL;
return(newNode);
}

/* insertion in binary search tree */


void insertion(struct treeNode **node, int data) {
if (*node == NULL) {
*node = createNode(data);
} else if (data < (*node)->data) {
insertion(&(*node)->left, data);
} else if (data > (*node)->data) {
insertion(&(*node)->right, data);
}
}

/* deletion in binary search tree */


void deletion(struct treeNode **node, struct treeNode **parent, int data) {
struct treeNode *tmpNode, *tmpParent;
if (*node == NULL)
return;
if ((*node)->data == data) {
/* deleting the leaf node */
if (!(*node)->left && !(*node)->right) {
if (parent) {
/* delete leaf node */
if ((*parent)->left == *node)
(*parent)->left = NULL;
else
(*parent)->right = NULL;
free(*node);
} else {
/* delete root node with no children */
free(*node);
}
/* deleting node with one child */
} else if (!(*node)->right && (*node)->left) {
/* deleting node with left child alone */
tmpNode = *node;
(*parent)->right = (*node)->left;
free(tmpNode);
*node = (*parent)->right;
} else if ((*node)->right && !(*node)->left) {
/* deleting node with right child alone */
tmpNode = *node;
(*parent)->left = (*node)->right;
free(tmpNode);

36 | P a g e
(*node) = (*parent)->left;
} else if (!(*node)->right->left) {
/*
* deleting a node whose right child
* is the smallest node in the right
* subtree for the node to be deleted.
*/

tmpNode = *node;

(*node)->right->left = (*node)->left;

(*parent)->left = (*node)->right;
free(tmpNode);
*node = (*parent)->left;
} else {
/*
* Deleting a node with two children.
* First, find the smallest node in
* the right subtree. Replace the
* smallest node with the node to be
* deleted. Then, do proper connections
* for the children of replaced node.
*/
tmpNode = (*node)->right;
while (tmpNode->left) {
tmpParent = tmpNode;
tmpNode = tmpNode->left;
}
tmpParent->left = tmpNode->right;
tmpNode->left = (*node)->left;
tmpNode->right =(*node)->right;
free(*node);
*node = tmpNode;
}
} else if (data < (*node)->data) {
/* traverse towards left subtree */
deletion(&(*node)->left, node, data);
} else if (data > (*node)->data) {
/* traversing towards right subtree */
deletion(&(*node)->right, node, data);
}
}

/* search the given element in binary search tree */


void findElement(struct treeNode *node, int data) {
if (!node)
return;
37 | P a g e
else if (data < node->data) {
findElement(node->left, data);
} else if (data > node->data) {
findElement(node->right, data);
} else
printf("data found: %d\n", node->data);
return;

void traverse(struct treeNode *node) {


if (node != NULL) {
traverse(node->left);
printf("%3d", node->data);
traverse(node->right);
}
return;
}

int main() {
int data, ch;
while (1) {
printf("1. Insertion in Binary Search Tree\n");
printf("2. Deletion in Binary Search Tree\n");
printf("3. Search Element in Binary Search Tree\n");
printf("4. Inorder traversal\n5. Exit\n");
printf("Enter your choice:");
scanf("%d", &ch);
switch (ch) {
case 1:
while (1) {
printf("Enter your data:");
scanf("%d", &data);
insertion(&root, data);
printf("Continue Insertion(0/1):");
scanf("%d", &ch);
if (!ch)
break;
}
break;
case 2:
printf("Enter your data:");
scanf("%d", &data);
deletion(&root, NULL, data);
break;
case 3:
printf("Enter value for data:");
scanf("%d", &data);
38 | P a g e
findElement(root, data);
break;
case 4:
printf("Inorder Traversal:\n");
traverse(root);
printf("\n");
break;
case 5:
exit(0);
default:
printf("u've entered wrong option\n");
break;
}
}
return 0;

}
Output:
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
Enter your choice:1
Enter your data:20
Continue Insertion(0/1):1
Enter your data:14
Continue Insertion(0/1):1
Enter your data:9
Continue Insertion(0/1):1
Enter your data:19
Continue Insertion(0/1):1
Enter your data:25
Continue Insertion(0/1):1
Enter your data:21
Continue Insertion(0/1):1
Enter your data:23
Continue Insertion(0/1):1
Enter your data:30
Continue Insertion(0/1):1
Enter your data:26
Continue Insertion(0/1):0
Resultant Binary Search Tree after insertion operation:
20
39 | P a g e
/ \
14 25
/ \ / \
9 19 21 30
\ /
23 26

1. Insertion in Binary Search Tree


2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
Enter your choice:4
Inorder Traversal:
9 14 19 20 21 23 25 26 30
1. Insertion in Binary Search Tree
2. Deletion in Binary Search Tree
3. Search Element in Binary Search Tree
4. Inorder traversal
5. Exit
Enter your choice:2
Enter your data:9

Delete node 9
20
/ \
14 25
\ / \
19 21 30
\ /
23 26
Discussion:
Binary Search Tree, is a node-based binary tree data structure which has
the following properties: The left subtree of a node contains only nodes with
keys lesser than the node's key. The right subtree of a node contains only
nodes with keys greater than the node's key.
Assignment: 23

40 | P a g e
Assignment 24: WRITE A PROGRAM IN C TO CALCULATE THE VALUE OF
4 1
∫2 𝑥 + (𝑥) 𝑑𝑥 . BY USING SIMPSON 1/3RD RULE. ASSUME THE NO. OF
INTERVALS TO BE 0.5

ALGORITHM:
In the source code below, a function f(x) = x+(1/x) has been defined. The
calculation using Simpson 1/3 rule in C is based on the fact that the small
portion between any two points is a parabola. The program follows the
following steps for calculation of the integral.
 As the program gets executed, first of all it asks for the value of lower
boundary value of x i.e. x0, upper boundary value of x i.e. xn and width of the
strip, h.
 Then the program finds the value of number of strip as n=( x n – x0 )/h
and checks whether it is even or odd. If the value of ‘n’ is odd, the program
refines the value of ‘h’ so that the value of ‘n’ comes to be even.
 After that, this C program calculates value of f(x) i.e ‘y’ at different
intermediate values of ‘x’ and displays values of all intermediate values of ‘y’.
 After the calculation of values of ‘c’, the program uses the following
formula to calculate the value of integral in loop.
Integral = *((y0 + yn ) +4(y1 + y3 + ……….+ yn-1 ) + 2(y2 + y4 +……….+ yn-2 ))
 Finally, it prints the values of integral which is stored as ‘ans’ in the
program.
If f(x) represents the length, the value of integral will be area, and if f(x) is
area, the output of Simpson 1/3 rule C program will be volume. Hence,
numerical integration can be carried out using the program below; it is very
easy to use, simple to understand, and gives reliable and accurate results.
f(x) = x+(1/x)

Source code:
#include<stdio.h>
#include<conio.h>
float f(float x)
{
return(1/(1+x));
}
void main()
{
int i,n;
float x0,xn,h,y[20],so,se,ans,x[20];
printf("\n Enter values of x0,xn,h: ");

41 | P a g e
scanf("%f%f%f",&x0,&xn,&h);
n=(xn-x0)/h;
if(n%2==1)
{
n=n+1;
}
h=(xn-x0)/n;
printf("\n Refined value of n and h are:%d %f\n",n,h);
printf("\n Y values: \n");
for(i=0; i<=n; i++)
{
x[i]=x0+i*h;
y[i]=f(x[i]);
printf("\n %f\n",y[i]);
}
so=0;
se=0;
for(i=1; i<n; i++)
{
if(i%2==1)
{
so=so+y[i];
}
else
{
se=se+y[i];
}

}
ans=h/3*(y[0]+y[n]+4*so+2*se);
printf("\n Final integration is %f",ans);

getch();
}
OUTPUT:
Enter values of x0,xn,h: 2 4 0.5
Refined value of n and h are: 4 0.500000
Y values:
0.333333
0.285714
0.250000
0.222222
0.200000
Final integration is 0.510847

42 | P a g e
Discussion:
Here we use Simpson’s 1/3rd composite rule to find out the definite integral.
At the “f” function we define the given function for integration. First we take
input lower limit a , upper limit b and no. of sub interval n. Then we calculate
the h. Then we calculate sum of the value of the function in the upper limit
and the lower limit. Then we use two loops, one for calculating the sum of
values of all odd ordinates another for sum of all even ordinates. Then use the
formula to get the desired result.

Assignment 25: WRITE A C-PROGRAM TO USE GAUSS-ELIMINATION


TECHNIQUE WITH PIVOTING TO FIND THE SOLUTION OF THE FOLLOWING
SYSTEM OF LINEAR EQUATION:
x+y+z=6
2x-y+3z=4
4x+5y-10z=13

Theory:
This method is mainly used to solve a set of ‘n’ linear equations. For the sake
of simplicity we consider three simultaneous equations in three unknowns:

a11x1 + a12x2 + a13x3 = b1


a21x1 + a22x2 + a23x3 = b2
a31x1 + a32x2 + a33x3 = b3

Where aij (I, j = 1, 2, 3) and bi (I = 1, 2, 3) are known constants.

By eliminating x1, x2 and x3 we will construct three pivotal equations, as:

a11x1 + a12x2 + a13x3 = b1


a22x2 + a23x3 = b2
a33x3 = b3

Where a33 = a33 – (a23 . a32) / a22

From these three equations we will find the value of x1, x2, x3 by this method.

Algorithm:
Here we use a two-dimensional array a[n][n] for keeping the value of the
coefficients of the unknown variables of the equations. Here we also use one
dimensional array x[n] for keeping the value of unknown variables.

STEP 1: initializations
STEP 2: for j=0 to n by 1do //taking the value of coefficient &the
constant term
read a[i][j] // in a two dimensions array

43 | P a g e
STEP 3: for k=0 to (n-1) by 1 do
STEP 4: for i=(k+1) to n by 1 d0
u = -(a[i][k] / a[k][k]) //determining the value of mij
end of for loop
STEP 5: for j=k to (n+1) by 1 do
a[i][j]+=u*(a[k][j])
end of for loop
repeat step 4 & 5
end of for loop
STEP 6: for i=(n-1) to 0 by -1 do
sum=0
for j=0 to (n-1-i) by 1 do
STEP 7: sum+= a[i][n-1-j]*x[n-1-j]
end of for loop
STEP 8: x[i] = (a[i][n]-sum)/(a[i][i]) //calculating the value of x, y, z and
store
//in the one dimension array
repeat step 7 & 8
end of for loop
STEP 9: print x[0], x[1], x[2] //print the value of x, y, z
STEP 10: exit.

Source code:
#include<stdio.h>
#include<conio.h>
void main()
{
float u,a[5][5],x[10],sum; // initializations
int n=3,i,j,k;

clrscr();

printf("\n Enter the 3 equations:");


for(i=0;i<n;i++)
{
printf("\n Enter coeff. of x, y, z, c of the eqn %d:",i+1);
for(j=0;j<=n;j++) //taking the value of coefficient &the
constant term
scanf("%f",&a[i][j]); //in a two dimensions array
printf("\n");
}

printf("\n The computation table:\n");


printf(" --------------------------------------------\n");
printf(" Step 1:\n");
for(i=0;i<n;i++)
{
44 | P a g e
for(j=0;j<n+1;j++)
printf("\t%.2f ",a[i][j]);
printf("\n");
}
for(k=0;k<n-1;k++)
{
printf("\n --------------------------------------------\n");
printf(" Step %d:\n",(k+2));
for(i=k+1;i<n;i++)
{
u = -(a[i][k] / a[k][k]); //determining the value of mij
for(j=k;j<n+1;j++)
a[i][j]+=u*(a[k][j]);
for(j=0;j<n+1;j++) //printing the computation table
printf(“\t%.2f ",a[i][j]);
printf("\n");
}
}
printf("\n --------------------------------------------\n");
printf("\n The pivotal equations are:\n");

for(i=0;i<n;i++)
{
for(j=0;j<n+1;j++) //printing the pivotal equations
{
if(j==0)
printf(" %.2fx +",a[i][j]);
else if(j==1)
printf(" %.2fy +",a[i][j]);
else if(j==2)
printf(" %.2fz",a[i][j]);
else
printf(" = %.2f ",a[i][j]);
}
printf("\n");
}
for(i=n-1;i>=0;i--)
{
sum=0;
for(j=0;j<n-1-i;j++) //calculating value of x, y, z & store
sum+=a[i][n-1-j]*x[n-1-j]; //in the one dimension array
x[i]=(a[i][n]-sum)/(a[i][i]);
}
printf("\n The solution is:\n");
for(i=0;i<n;i++) //print the value of x, y, z
{
if(i==0)
45 | P a g e
printf(" x = %f\n",x[i]);
else if(i==1)
printf(" y = %f\n",x[i]);
else
printf(" z = %f\n",x[i]);
}
getch();
}

Output :
Enter the 3 equations:
Enter the coeff. of x,y,z,c of the eqn 1:
1
1
1
6
Enter the coeff. of x,y,z,c of the eqn 2:
2
-1
3
4
Enter the coeff. of x,y,z,c of the eqn 3:
4
5
-10
13
The computation table:
--------------------------------------------
Step 1:
1.00 1.00 1.00 6.00
2.00 -1.00 3.00 4.00
4.00 5.00 -10.00 13.00
--------------------------------------------
Step 2:
0.00 -3.00 1.00 -8.00
0.00 1.00 -14.00 -11.00
--------------------------------------------
Step 3:
0.00 0.00 -13.67 -13.67
--------------------------------------------
The pivotal equations are:
1.00x + 1.00y + 1.00z = 6.00
0.00x + -3.00y + 1.00z=-8.00
0.00x + 0.00y + -13.67z=-13.67
The solution is:
x=2.000000
y=3.000000
46 | P a g e
z=1.000000

Discussion :

Gauss elimination will lead to a solution in a finite number of steps for


any set of equations provided the determinant of coefficients is not very small.

The necessary and sufficient condition for using this method is that all
diagonal elements should be non-zero known as pivots. When any of the
pivots vanishes, we can interchange the rows or columns in such a way that
none of the pivots are zero. If this is impossible, then the matrix is singular
and the system has no solution.

The disadvantages of using this method is –

1. The computational effort is approximately 2n3/3 arithmetic operations in


each elimination step.
2. The amount of book keeping necessary (such as row interchange) is
considerable.
3. The rounding errors may become quite large particularly for ill-
conditioned equations.
4. Any special structure in the matrix of coefficients is difficult to preserve
during elimination. Thus saving cannot be made in calculations if there are
many zero coefficients.

Assignment 26: Prim’s algorithm is to find minimum spanning tree.

Algorithm:

(* This algorithm finds the minimum spanning tree T from a graph G of n


vertices, with
the help of a adjacency matrix A. The elements of matrix A is defined below –

Aij = given weight of the edge connecting vertices Vi and Vj


α = if there is no edge between Vi and Vj *)

 Step 1: Construct the adjacency matrix A from graph G


 Step 2: Select vertex Vi (from row) and search the i-th row for the
minimum weight which was not previously selected. Locate the minimum
weight and select vertex Vj (from column) corresponding to the minimum
weight.

47 | P a g e
 Step 3: If (Vi-Vj) edge already exists in the spanning tree T then go to
step 2 and search the i-th row for the next minimum weight. Otherwise add
the edge (Vi - Vj) in the spanning tree T.
 Step 4: Vi = Vj
 Step 5: Repeat steps 2 to 5 until the spanning tree contains (n-1) edges.
 Step 6: Show the spanning tree T.
 Step 7:[Finished]

Example:

48 | P a g e
V1 V2 V3 V4 V5 V6
V1 α 1 α α 3 1
V2 1 α 7 α α 2
V3 α 7 α 6 α α
V4 α α 6 α 5 α
V5 3 α α 5 α 4
V6 1 2 α α 4 α

T (Minimum Spanning Tree

Source Code:

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],x[10],t=0,n,i,j,z,k,m=0,q,flag=0;
char p,r;
clrscr();
printf("\nEnter the number of vertices: ");
scanf("%d",&n);
for(i=0;i<n;i++)
a[i][i]=0;
for(i=0;i<n-1;i++)
49 | P a g e
for(j=i+1;j<n;j++)
{
printf("\nAny edge present between vertices %c and %c?(y/n): ",i+97,j+97);
p=getche();
if(p=='y')
{
printf("\nEnter the weight of the edge: ");
scanf("%d",&a[i][j]);
a[j][i]=a[i][j];
}
else
{
a[i][j]=0;
a[j][i]=0;
}
}
printf("\nEnter the starting vertex: ");
r=getche();
for(i=0;i<n;i++)
if(r==i+97)
break;
if(i>=n)
{
printf("\nInvalid vertex!!");
getch();
exit(1);
}
printf("\nResult:\n");
x[t++]=r-97;
for(i=0;i<n-1;i++)
{
z=100;
for(j=0;j<=i;j++)
{
for(k=0;k<n;k++)
{
flag=0;
if(a[x[j]][k]<z&&a[x[j]][k]!=0)
{
for(q=0;q<t;q++)
if(k==x[q])
50 | P a g e
{
flag=1;
break;
}
if(flag!=1)
{
z=a[x[j]][k];
x[t]=k;
}
}
}
}
m=m+z;
t++;
}
printf("%d",m);
getch();
}

Output:
Any edge present between vertices a and b?(y/n): y
Enter the weight of the edge: 3

Any edge present between vertices a and c?(y/n): y


Enter the weight of the edge: 4

Any edge present between vertices a and d?(y/n): y


Enter the weight of the edge: 5

Any edge present between vertices a and e?(y/n): n


Any edge present between vertices a and f?(y/n): y
Enter the weight of the edge: 7

Any edge present between vertices a and g?(y/n): n


Any edge present between vertices b and c?(y/n): n
Any edge present between vertices b and d?(y/n): n
Any edge present between vertices b and e?(y/n): n
Any edge present between vertices b and f?(y/n): y
Enter the weight of the edge: 8
51 | P a g e
Any edge present between vertices b and g?(y/n): y
Enter the weight of the edge: 9

Any edge present between vertices c and d?(y/n): n


Any edge present between vertices c and e?(y/n): y
Enter the weight of the edge: 8

Any edge present between vertices c and f?(y/n): n


Any edge present between vertices c and g?(y/n): y
Enter the weight of the edge: 10

Any edge present between vertices d and e?(y/n): y


Enter the weight of the edge: 9

Any edge present between vertices d and f?(y/n): y


Enter the weight of the edge: 10

Any edge present between vertices d and g?(y/n): n


Any edge present between vertices e and f?(y/n): y
Enter the weight of the edge: 11

Any edge present between vertices e and g?(y/n): n


Any edge present between vertices f and g?(y/n): n
Enter the starting vertex: f
Result:36

Discussion:
1. In this program the no. 100 represents the value for infinity, so 100 can not
be represent as real length for the length matrix.
2. Another method for finding the minimum spanning tree is Kruskal's
algorithm.

52 | P a g e
Assignment 27: Write a program to create an adjacency matrix for an
undirected graph and then traverse the graph through BFS.

Algorithm:
Step 1: SET STATUS = 1 (ready state)
for each node in G
Step 2: Enqueue the starting node A
and set its STATUS = 2
(waiting state)
Step 3: Repeat Steps 4 and 5 until
QUEUE is empty
Step 4: Dequeue a node N. Process it
and set its STATUS = 3
(processed state).
Step 5: Enqueue all the neighbours of
N that are in the ready state
(whose STATUS = 1) and set
their STATUS = 2
(waiting state)
[END OF LOOP]

BFS example
Let's see how the Breadth First Search algorithm works with an example. We use an undirected
graph with 5 vertices.

We start from vertex 0, the BFS algorithm starts by putting it in the Visited list and putting all its
adjacent vertices in the stack.

53 | P a g e
Next, we visit the element at the front of queue i.e. 1 and go to its adjacent nodes. Since 0 has
already been visited, we visit 2 instead.

Vertex 2 has an
unvisited adjacent vertex in 4, so we add that to the back of the queue and visit 3, which is at the
front of the queue.

Only 4 remains in the queue since the only adjacent node of 3 i.e. 0 is already visited. We visit it.
54 | P a g e
Since the queue is empty, we have completed the Depth First Traversal of the graph.

Source Code:
#include <stdio.h>
#define MAX 10
void breadth_first_search(int adj[][MAX],int visited[],int start)
{
int queue[MAX],rear = –1,front =– 1, i;
queue[++rear] = start;
visited[start] = 1;
while(rear != front)
{
start = queue[++front];
if(start == 4)
printf("5\t");
else
printf("%c \t",start + 65);
for(i = 0; i < MAX; i++)
{
if(adj[start][i] == 1 && visited[i] == 0)
{
queue[++rear] = i;
visited[i] = 1;
}
}
}
}
int main()
{
int visited[MAX] = {0};
int adj[MAX][MAX], i, j;
printf("\n Enter the adjacency matrix: ");
for(i = 0; i < MAX; i++)
for(j = 0; j < MAX; j++)
scanf("%d", &adj[i][j]);
breadth_first_search(adj,visited,0);
return 0;
55 | P a g e
}

Output:
Enter the adjacency matrix:

0 1 0 1 0
1 0 1 1 0
0 1 0 0 1
1 1 0 0 1
0 0 1 1 0

A B D C E

Discussion:
Breadth-first search (BFS) is a graph search algorithm that begins at the root node and
explores all
the neighbouring nodes. Then for each of those nearest nodes, the algorithm (Fig.
13.20) explores
their unexplored neighbour nodes, and so on, until it finds the goal.

56 | P a g e

You might also like