Pranav - Final Assignment
Pranav - Final Assignment
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;
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.
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.
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.
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();
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;
}
Output:
Discussion:
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);
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
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;
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];
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]++;
}
}
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
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);
}
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;
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.
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.
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
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.
Source Code:
#include<stdio.h>
#include<stdlib.h>
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: “);
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;
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 ->
Assignment 18:
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
Pop operation
Program Code :
#include<stdio.h>
#include<stdlib.h>
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);
}
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
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;
};
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);
}
}
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
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.
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:
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();
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 :
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.
Algorithm:
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 α
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
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