Sei sulla pagina 1di 105

Wipro Elite Coding Statement

Q.1. Design a way to sort a list of positive integers in descending order based
on the frequency of elements.

Input:
Consists of two arguments
Size: no of elements
Arr: list of positive integers

Output:
Return a list of +ve integers sorted according to frequency of elements

Program:
#include<stdio.h>
int main()
{
intn,i,j,cnt=0,k=0,f=0;
scanf(“%d”,&n);
intarr[100],ele[100],count[100];
for(i=0;i<n;i++)
scanf(“%d”,&arr*i+);
for(i=0;i<n;i++)
{
if(arr[i]!=arr[i+1])
{
ele[k++]=arr[i];
}
}
k=0;
for(i=0;i<n;i++)
{
cnt=0;
for(j=0;j<n;j++)
{
if(ele[i]==arr[j])
{
cnt++;
}
}
if(cnt!=0)
count[k++]=cnt;
}
for(i=0;i<k;i++)
{
for(j=0;j<k;j++)
{
if(count[i]>=count[j])
{
int t=count[i];
count[i]=count[j];
count[j]=t;
int x=ele[i];
ele[i]=ele[j];
ele[j]=x;
}
}
}
for(i=0;i<k;i++)
{
if(count[i]==count[i+1])
{
int x=ele[i];
ele[i]=ele[i+1];
ele[i+1]=x;
}
}
for(i=0;i<k;i++)
for(j=0;j<count[i];j++)
{
printf(“%d “,ele*i+);

}
return 0;
}

Eg: size 19
arr = {1,2,2,3,3,3,4,4,5,5,5,5,6,6,6,7,8,9,10}
O/p:
{5,5,5,5,3,3,3,6,6,6,2,2,4,4,1,7,8,9,10}
Q.2. Mr.Woods, an electrician has made some faulty connections of eight
street lights in Timberland city. The connections are such that if the street
lights adjacent to a particular light are both ON (represented as 1) or are both
OFF (represented as 0), then that street light goes OFF the next night.
Otherwise, it remains ON the next night. The two street lights at the end of
the road have a single adjacent street light, so the other adjacent light can be
assumed to be always OFF. The state of the lights on a particular day is
considered for the next day and not for the same day.
Due to this fault, the people of the city are facing difficulty in during on the
road at night. So they have filed a complaint about this to the Head of the
Federal Highway Administration. Based on this complaint, the head has
asked for the report of the state of street lights after M Days.

Write an algorithm to output the state of the street lights after the given M
days.

Program:

#include<stdio.h>
Int cellcompete(int *cells, int day)
{
Int I,j;
For(i=0;i<day;i++)
{
Cells[-1]=0;
Cells[8]=0;
Int u[8];
For(int i=-1;i<9;i++)
{
U[i]=cells[i];
}
For(j=0;j<8;j++)
{
If(u[j-1]==u[j+1])
{
Cells[j]=0;
}
else
Cells[j]=1;
}
}
For(i=0;i<8;i++)
Printf(“%d”,,cells*i+);
}
int main()
{
Int cells[8],n,I;
For(i=0;i<8;i++)
Scanf(“%d”,&cells*i+);
Scanf(“%d”,&n);
Cellcompete(cells,n);
Return 0;
}

Q.3. Print the below pattern (half diamond using numbers)

Input:
3 4
Output:
3
44
555
6666
555
44
3

Input :
4 4
Output:
4
55
666
7777
666
55
4

Program:
#include
int main()
{
int i,j,s,N,count=0;
scanf(“%d%d”,&s,&N);
for(i=s;count<4;count++)
{
for(j=0;j<count+1;j++)
printf(“%d”,i);
printf(“\n”);
i=i+1;
}
for(i=s+N-2;count>0;count–)
{
for(j=0;j<count-1;j++)
printf(“%d”,i);
printf(“\n”);
i=i-1;
}
return 0;
}

Q.4. Print the following pattern (half diamond using numbers)

Input :
3
Output:
1
2*2
3*3*3
3*3*3
2*2
1

Input :
4
Output:
1
2*2
3*3*3
4*4*4*4
4*4*4*4
3*3*3
2*2
1

Program:
#include
int main()
{
int i,j,k,N,count=0;
scanf(“%d”,&N);
for(i=1;i<=N;i++)
{
k=1;
for(j=0;j<i;j++)
{
printf(“%d”,i);
if(k<i)
{
printf(“*”);
k=k+1;
}
}
printf(“\n”);
}
for(i=N;i>0;i–)
{
k=1;
for(j=0;j<i;j++)
{
printf(“%d”,i);
if(k<i)
{
printf(“*”);
k=k+1;
}
}
printf(“\n”);
}
return 0;
}

Q.5. Print the below pattern.

Input:
4
Output:
1
2*3
4*5*6
7*8*9*10
7*8*9*10
4*5*6
2*3
1

Program:
#include
int main() {
int i,j,count=1,n;
printf(“Enter a number\n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
if(j<i)
printf(“%d*”,count++);
else
printf(“%d”,count++);
} printf(“\n”);
}
count=count-n;
for(i=n;i>=1;i–)
{ for(j=1;j<=i;j++)
{
if(j<i)
printf(“%d*”,count++);
else
printf(“%d”,count++);
}
count=(count+1)-2*i;
printf(“\n”);
}
return 0;
}

Q.6. Print the following pattern.

Input:
3 4
Output:
3
44
555
6666
6666
555
44
3

Program:
#include<stdio.h>
int main()
{
int i,j,s,N,count=0;
scanf(“%d%d”,&s,&N);
for(i=s;count<4;count++)
{
for(j=0;j<count+1;j++)
printf(“%d”,i);
printf(“\n”);
i=i+1;
}
for(i=s+N-2;count>0;count–)
{
for(j=0;j<count-1;j++)
printf(“%d”,i);
printf(“\n”);
i=i-1;
}
return 0;
}

Q.7. Print the below pattern.

Input:
5
Output:
1
3*2
4*5*6
10*9*8*7
11*12*13*14*15

Program:
#include<stdio.h>
int main()
{
int i,j,k,l=1,N,d,r,count=0;
scanf(“%d”,&N);
for(i=1;i<=N;i++)
{
k=1;
d=i%2;
r=l+i-1;
for(j=0;j<i;j++)
{

if(d==0)
{
printf(“%d”,r);
r–;
if(k<i)
{
printf(“*”);
k=k+1;
}
l++;
continue;
}
printf(“%d”,l);
l++;
if(k<i)
{
printf(“*”);
k=k+1;
}
}
printf(“\n”);
}
return 0;
}

Q.8. Print the below pattern.

Input:
4
Output:
1*2*3*4*17*18*19*20
– -5*6*7*14*15*16
– – – -8*9*12*13
– – – – – -10*11

Program:
#include<stdio.h>
void pattern(int);
int main()
{
int n;
scanf(“%d”, &n);
pattern(n);
return 0;
}
void pattern(int n)
{
int i, j, k, s, a = 1,b = n*n + 1;
for (i = n; i >= 1; i–) {
for (s = 0; s < n – i; s++)
printf(“–“);
for (j = 0; j < i; j++)
printf(“%d*”, a++);
for (k = 0; k < i – 1; k++)
printf(“%d*”, b++);
printf(“%d\n”, b); // last b should without *
b -= 2*(i – 1);
}
}

Q.9. Print the below pattern.

Input:
3
Output:
333
313
323
333

Program:
#include<stdio.h>
int main()
{
int i, j, n, c=1;
scanf(“%d”, &n);
for(i=1; i<=n+1; i++)
{
for(j=1; j<=n; j++)
{
if(i!=1 && j==n-1)
{
printf(“%d “, c);
c++;
}
else
printf(“%d “, n);
}
printf(“\n”);
}
return 0;
}

Q.10. It is to remove the vowels in the given string and display the input
string without vowels (i.e. with only consonants).

Input:
TalentBattle
Output:
TlntBttl
Program:
#include <stdio.h>
int check_vowel(char);
int main()
{
char s[100], t[100];
int c, d = 0;
gets(s);
for(c = 0; s*c+ != ‘\0’; c++)
{
if(check_vowel(s[c]) == 0)
{
t[d] = s[c];
d++;
}
}
t*d+ = ‘\0’;
strcpy(s, t);
printf(“%s\n”, s);
return 0;
}
int check_vowel(char ch)
{
if (ch == ‘a’ || ch == ‘A’ || ch == ‘e’ || ch == ‘E’ || ch == ‘i’ || ch == ‘I’ || ch
==’o’ || ch==’O’ || ch == ‘u’ || ch == ‘U’)
return 1;
else
return 0;
}

Q.11. Program to sort elements by frequency in a given array is discussed


here. You need to print the elements of an array in the decreasing frequency
and if 2 numbers have same frequency then print the one which came first.
Input array:
{2,3,2,4,5,12,2,3,3,3,12}
Output array:
{3,3,3,3,2,2,2,12,12,4,5}
Program:

1. //Sort elements by frequency using sorting

#include<bits/stdc++.h>
using namespace std;
// struct to sort
struct ele
{
int count, index, val;
};
//sort with the values
bool comp1(struct ele a, struct ele b) {
return (a.val < b.val);
}
//sort by no of times or order
bool comp2(struct ele a, struct ele b) {
if (a.count != b.count) return (a.count < b.count);
else return a.index > b.index;
}
void freqSort(int arr[], int n)
{
struct ele element[n];
for (int i = 0; i < n; i++)
{
element[i].index = i;
element[i].count = 0;
element[i].val = arr[i]; }
/* maintain the same order */
stable_sort(element, element+n, comp1);
/* initialize count of first element as 1 */
element[0].count = 1;
/* how many times other elements appear*/
for (int i = 1; i < n; i++)
{
if (element[i].val == element[i-1].val)
{
element[i].count += element[i-1].count+1;
/* set previous as -1 to sort again*/
element[i-1].count = -1;
/* first index is maintained*/
element[i].index = element[i-1].index;
}
/* if previous element != curr
count=1 */
else element[i].count = 1;
}
/* sort with the help of count and order */
stable_sort(element, element+n, comp2);
for (int i = n-1, index=0; i >= 0; i–)
if (element[i].count != -1)
for (int j=0; j<element[i].count; j++)
arr[index++] = element[i].val;
}
// main
int main()
{
int t;
cin>>t;
for(int j=0;j<t;j++){
int n;
cin>> n;
int arr[n];
for (int i=0; i<n; i++)
cin>> arr[i];
freqSort(arr, n);
for (int i=0; i<n; i++)
cout << arr*i+ << ” “;
}
return 0;
}

2. // Sort elements by frequency using hashing

#include <bits/stdc++.h>
#include
using namespace std;

unordered_map<int, int> m2;

bool sort_by_value(const pair<int, int>& a, const pair<int, int>& b)


{
if (a.second == b.second)
return m2[a.first] < m2[b.first];
return a.second > b.second;
}
void sort_by_frequency(int a[], int n)
{
unordered_map<int, int> m;
vector<pair<int, int> > v;
for (int i = 0; i < n; ++i) {
m[a[i]]++;
if (m2[a[i]] == 0)
m2[a[i]] = i + 1;
}

copy(m.begin(), m.end(), back_inserter(v));


sort(v.begin(), v.end(), sort_by_value);

for (int i = 0; i < v.size(); ++i)


for (int j = 0; j < v[i].second; ++j)
cout << v*i+.first << ” “;
}
int main()
{
int n;
cout << “\nEnter the number of elements : “;
cin >> n;
int a[n];
cout << “\nInput the array elements : “;
for(int i = 0; i < n; i++)
{
cin >> a[i];
}

sort_by_frequency(a, n);

return 0;
}

3. Sort elements by frequency using BST

#include<bits/stdc++.h>
#include<iostream>
using namespace std;

struct BSTNode
{
struct BSTNode *left;
int data;
int freq;
struct BSTNode *right;
};

struct dataFreq
{
int data;
int freq;
};

int compare(const void *a, const void *b)


{
return ( (*(const dataFreq*)b).freq – (*(const dataFreq*)a).freq );
}

BSTNode* newNode(int data)


{
struct BSTNode* node = new BSTNode;
node->data = data;
node->left = NULL;
node->right = NULL;
node->freq = 1;
return (node);
}

BSTNode *insert(BSTNode *root, int data)


{
if (root == NULL)
return newNode(data);
if (data == root->data)
root->freq += 1;
else if (data < root->data)
root->left = insert(root->left, data);
else
root->right = insert(root->right, data);
return root;
}

void store(BSTNode *root, dataFreq count[], int *index)


{
if (root == NULL) return;

store(root->left, count, index);

count[(*index)].freq = root->freq;
count[(*index)].data = root->data;
(*index)++;

store(root->right, count, index);


}
void sort_by_frequency(int arr[], int n)
{
struct BSTNode *root = NULL;
for (int i = 0; i < n; ++i)
root = insert(root, arr[i]);

dataFreq count[n];
int index = 0;
store(root, count, &index);

qsort(count, index, sizeof(count[0]), compare);

int j = 0;
for (int i = 0; i < index; i++)
{
for (int freq = count[i].freq; freq > 0; freq–)
arr[j++] = count[i].data;
}
}

void display_elements(int arr[], int n)


{
for (int i = 0; i < n; i++)
cout << arr*i+ << ” “;
cout << endl;
}

int main()
{
int n;
cout << “\nEnter the number of elements : “;
cin >> n;
int arr[n];
cout << “\nInput the array elements : “;
for(int i = 0; i < n; i++)
{
cin >> arr[i];
}
sort_by_frequency(arr, n);
display_elements(arr, n);
return 0;
}

Q.12. Bob has to send a secret code S to his boss. He designs a method to
encrypt the code using two key values N and M. The formula that he uses to
develop the encrypted code is shown below:
(((S^N%10)^M)%1000000007)
Write a program to help Bob to encrypt the code.

Input:
The input to the function/method consists of three arguments secret code, an
integer representing the secret code (S) value N, an integer representing the
key value N and value M, an integer representing the key value M.

Output:
Return an integer representing the code encrypted by BOB.

Constraints:
1<=secret code<=10^9
0<=value N<=10^10
0<=value M<=10^10

Program:

#include<stdio.h>
int main()
{
long int s,n,m,ans;
scanf(“%ld %ld %ld”,&s,&n, &m);
ans=pow(s,n);
ans=ans%10;
ans=pow(ans,m);
ans=ans%1000000007;
printf(“%ld”,ans);
return 0;
}
Q.13. Let us consider the below problem to remove brackets from an
algebraic string.

In a mathematics class, Jason the mathematics teacher asked to solve a book


of expressions consisting of characters, operators, and brackets. But Jason
wants to give simplified expressions by removing brackets from the
expressions. Write an algorithm to help Jason simplify an expression by
removing brackets

Input:
Consists of a string expression, representing an expression. (x+y)-z

Output:
Return a string representing the simplified expressions by removing
brackets. x+y-z

Program:

// Program to remove brackets from an algebraic string

#include
int main()
{
int i=0,c=0,j=0;
char a[100],b[100];

printf(“\nEnter the string : “);


scanf(“%s”,a);
while(a*i+!=’\0′)
{
if((a*i+=='(‘) && (a*i-1+==’-‘))
{
(c==0)?j=i:j=c;
while(a*i+!=’)’)
{
if(a*i+1+==’+’)
b*j+++=’-‘;
else if(a*i+1+==’-‘)
b*j+++=’+’;
else if(a*i+1+!=’)’)
b[j++]=a[i+1];
i++;
}
c=j+1;
}
else if(a*i+=='(‘ && a*i-1+==’+’)
{
(c==0)?j=i:j=c;
while(a*i+!=’)’)
{
b[j++]=a[i+1];
i++;
}
j–;
c=j+1;
}
else if(a*i+==’)’)
{
i++;
continue;
}
else
{
b[j++]=a[i];
}
i++;
}
b*j+=’\0′;
printf(“%s”,b);
return 0;
}

Q.14. Emma wants to gift a bouquet to her father on his birthday and asked
for help from her mother Rosy. Rosy gives N flower sticks numbered 1 to N to
Emma and tells her to arrange it in the bouquet in a particular order. She
asks her to arrange the first K flower sticks in the order of their increasing
length and the remaining sticks in an order of their decreasing length. Write
an algorithm to find the final arrangement of the flower sticks in which
Emma gifted the bouquet to her father.
Input:
The input to the function/method consists of three arguments.

 num, an integer representing the number of flower sticks (N).


 random, an integer representing the number K given by Rosy to Emma sticks
 a list of integers representing the length of flower sticks.

Output:
Return a list of integers representing the final pattern of the flower sticks
in which Emma gifted the bouquet to her father

Constraints:
Random < num
0 < num < 106

Program:

// Arranging of flower sticks in a boquet – C code

#include
void arrange(int n, int k, int arr[])
{
int i,j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i]>arr[j])
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
for(i=0;i<k;i++)
printf(“%d “,arr*i+);
for(i=n-1;i>=k;i–)
printf(“%d “,arr*i+);
}
int main()
{
int n,k,i;
int arr[20];
printf(“\nEnter the values of n and k : “);
scanf(“%d%d”,&n,&k);
printf(“\nEnter all the elements:\n “);
for(i=0;i<n;i++)
scanf(“%d”,&arr*i+);
arrange(n,k,arr);
}

Q.15. In the city of Toyland, there are N houses. Noddy is looking for a piece
of land in the city to build his house. He wants to buy the land where he can
build the largest possible house. All the houses in the city lie in a straight line
and all of them are given a house number and position of the house from the
entry point in the city. Noddy wants to find the house numbers between
which he can build the largest house.Write an algorithm to help Noddy to
find the house numbers between which he can build his house.

Input: The input to the function/method consists of two arguments

 numOf House, an integer representing the number of houses.


 houseList, a list where each element of the list is a list of integers representing
the house number and its position respectively.

Constraints:
2 < numOfHouse < 106
1 <houseList[i][0] <numOfHouse
0 < houseList[i][1] < 106
0 < I < numOfHouse

Note: No two houses will have the same position. In case of multiple such
answers, return the one with the least distance from the reference point Zero.

Program:

// C++ code to build the largest house


#include <bits/stdc++.h>
using namespace std;
int main()
{
int num;
cout<<“Enter the number of houses: “;
cin>>num;
int house_number[num];
int position[num];
cout<<“Enter the house number and position of the house: “<< endl;
for(int i =0; i<num; i++)
{
cin>>house_number[i]; //Getting the house number as a single array
cin>>position[i]; //Getting the position as a single array
}
cout<<“Input: “<<endl;
for(int i=0; i<num; i++)
{
cout<<“*“<<house_number*i+<<“,”<<position*i+<<“+ “;
}
cout<<endl;
int copy_position[num];
for(int i=0; i<num; i++)
{
copy_position[i] = position[i]; //Copying the position to another array so that
the orginial array won’t be affected
}
sort(copy_position, copy_position+num); //Sorting the copied array
int temp;
int x1, x2;
int position1, position2;
int maxi =0;
for(int i=0; i<num-1; i++)
{
int temp = abs(copy_position[i+1]-copy_position[i]); //Difference between
two adjacent array elements is calculated
if(temp > maxi)
{
maxi = temp; //The highest difference is noted
x1 = copy_position[i]; //The two elements are noted
x2 = copy_position[i+1];
}
}
for(int i=0; i<num; i++) //The elements position are found in the main position
array
{
if(x1 == position[i])
{
position1 = i;
}
else if (x2 == position[i])
{
position2 = i;
}
}
if(house_number[position1]>house_number[position2]) //The house number
is displayed which is matched by the position obtained
{
cout<<“Result:
“<<“*“<<house_number*position2+<<“,”<<house_number*position1+<<“+ “;
}
else
{
cout<<“Result:
“<<“*“<<house_number*position1+<<“,”<<house_number*position2+<<“+ “;
}
return 0;
}

Output:

Enter the number of houses,


numOfHouse = 5

Enter the house number and position of house-


houseList = [[3, 7],[1, 9],[2, 0],[5, 15],[4, 30]]

Output: [4, 5]
Q.16. We are required to implement the following function:
Int SumNumberDivisible(int m, int n);

The function accepts 2 positive integer ‘m’ and ‘n’ as its arguments.
You are required to calculate the sum of numbers divisible both by 3 and 5,
between ‘m’ and ‘n’ both inclusive and return the same.
Note:
0 < m <= n
Example
Input:
m : 12
n : 50
Output: 90
Explanation:
The numbers divisible by both 3 and 5, between 12 and 50 both inclusive are
{15, 30, 45} and their sum is 90.
Program:
#include <stdio.h>
int Calculate(int, int);
int main()
{
int m, n, result;
// Getting Input
printf("Enter the value of m : ");
scanf("%d",&m);
printf("Enter the value of n : ");
scanf("%d",&n);
result = Calculate(n,m);
// Getting Output
printf("%d",result);
return 0;
}
int Calculate(int n, int m)
{
// Write your code here
int i, sum = 0;
for(i=m;i<=n;i++)
{
if((i%3==0)&&(i%5==0))
{
sum = sum + i;
}
}
return sum;
}
Q.17. Input: The first line of input consists of three space separated integers.
Num, start and end representing the size of list [N], the starting value of the
range and the ending value of the range respectively.
The second line of input consists N space separated integers representing the
distances of the employee from the company.
Output: Print space separated integers representing the ID’s of the employee
whose distance lieu within the given range else return -1.
Example
Input:
6 30 50
29 38 12 48 39 55
Output:
134
Explanation:
There are 3 employees with id 1, 3, 4 whose distance from the office lies within
the given range.
Program:
#include <stdio.h>
int main()
{
int start, end, a[50], num, i, flag;
scanf("%d %d %d",&num,&start,&end);
for(i=0; i<num; i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<num;i++)
{
if(a[i]>start && a[i]<end)
{
flag = 1;
}
else
{
flag = -1;
}
if(flag == 1)
{
printf("%d ",i);
}
}
return 0;
}

Q.18. Write a code for the following functions


Function 1: sortArray
It’s function is to sort the passed array with a particular length, there are 2
parameters passed into it first is the length of array and next is the elements
of list.
Function 2: findMaxElement
It’s function is to get the 2 array with their own particular elements and
length, and find the maximum element from both the array and print it.
Input:
12
2 5 1 3 9 8 4 6 5 2 3 11
11
11 13 2 4 15 17 67 44 2 100 23
Output:
100
Program:
#include <stdio.h>
int* sortArray(int len, int* arr)
{
int i=0, j=0, temp = 0;
for(i=0; i<len; i++)
{
for(j=i+1; j<len; j++)
{
if(arr[i]>arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
int findMaxElement(int len1, int* arr1, int len2, int* arr2)
{
sortArray(len1, arr1);
sortArray(len2, arr2);
if(arr1[len1-1]>arr2[len2-1])
return arr1[len1-1];
else
return arr2[len2-1];
}
int main()
{
int len1, len2, arr1[20], arr2[20], i;
int ans;
scanf("%d",&len1);
for(i=0; i<len1; i++)
{
scanf("%d",&arr1[i]);
}
scanf("%d",&len2);
for(i=0; i<len2; i++)
{
scanf("%d",&arr2[i]);
}
ans = findMaxElement(len1, arr1, len2, arr2);
printf("%d",ans);
return 0;
}

Q.19. Addition of Two Matrices in C:


Program:
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);
printf("Sum of entered matrices:-\n");
for (c = 0; c < m; c++)
{
for (d = 0 ; d < n; d++)
{
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
return 0;
}
Output:
Q.20. Program to find the average of n (n < 10) numbers using arrays.

Program:
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter n: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;
printf("Average = %d", average);
return 0;
}
Output:
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39

Q.21. C program To Implement Linked List.


Program:
#include <stdio.h>
#include <stdlib.h>.
struct node
{
int data;
struct node *next;
};
struct node *start = NULL;
void insert_at_begin(int);
void insert_at_end(int);
void traverse();
void delete_from_begin();
void delete_from_end();
int count = 0;
int main ()
{
int input, data;
for (;;)
{
printf("1. Insert an element at beginning of linked list.\n");
printf("2. Insert an element at end of linked list.\n");
printf("3. Traverse linked list.\n");
printf("4. Delete element from beginning.\n");
printf("5. Delete element from end.\n");
printf("6. Exit\n");
scanf("%d", &input);
if (input == 1)
{
printf("Enter value of element\n");
scanf("%d", &data);
insert_at_begin(data);
}
else if (input == 2)
{
printf("Enter value of element\n");
scanf("%d", &data);
insert_at_end(data);
}
else if (input == 3)
traverse();
else if (input == 4)
delete_from_begin();
else if (input == 5)
delete_from_end();
else if (input == 6)
break;
else
printf("Please enter valid input.\n");
}
return 0;
}
void insert_at_begin(int x)
{
struct node *t;
t = (struct node*)malloc(sizeof(struct node));
count++;
if (start == NULL)
{
start = t;
start->data = x;
start->next = NULL;
return;
}
t->data = x;
t->next = start;
start = t;
}
void insert_at_end(int x)
{
struct node *t, *temp;
t = (struct node*)malloc(sizeof(struct node));
count++;
if (start == NULL)
{
start = t;
start->data = x;
start->next = NULL;
return;
}
temp = start;
while (temp->next != NULL)
temp = temp->next;
temp->next = t;
t->data = x;
t->next = NULL;
}
void traverse()
{
struct node *t;
t = start;
if (t == NULL)
{
printf("Linked list is empty.\n");
return;
}
printf("There are %d elements in linked list.\n", count);
while (t->next != NULL)
{
printf("%d\n", t->data);
t = t->next;
}
printf("%d\n", t->data);
}
void delete_from_begin()
{
struct node *t;
int n;
if (start == NULL)
{
printf("Linked list is already empty.\n");
return;
}
n = start->data;
t = start->next;
free(start);
start = t;
count--;
printf("%d deleted from beginning successfully.\n", n);
}
void delete_from_end()
{
struct node *t, *u;
int n;
if (start == NULL)
{
printf("Linked list is already empty.\n");
return;
}
count--;
if (start->next == NULL)
{
n = start->data;
free(start);
start = NULL;
printf("%d deleted from end successfully.\n", n);
return;
}
t = start;
while (t->next != NULL)
{
u = t;
t = t->next;
}
n = t->data;
u->next = NULL;
free(t);
printf("%d deleted from end successfully.\n", n);
}

Q.22. Operations on linked list

Program:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
void display(struct node* head)
{
struct node *temp = head;
printf("\n\nList elements are - \n");
while(temp != NULL)
{
printf("%d --->",temp->data);
temp = temp->next;
}
}
void insertAtMiddle(struct node *head, int position, int value)
{
struct node *temp = head;
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = value;
int i;
for(i=2; inext != NULL)
{
temp = temp->next;
}
}
newNode->next = temp->next;
temp->next = newNode;
}
void insertAtFront(struct node** headRef, int value)
{
struct node* head = *headRef;
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = value;
newNode->next = head;
head = newNode;
*headRef = head;
}
void insertAtEnd(struct node* head, int value)
{
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = value;
newNode->next = NULL;
struct node *temp = head;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = newNode;
}
void deleteFromFront(struct node** headRef)
{
struct node* head = *headRef;
head = head->next;
*headRef = head;
}
void deleteFromEnd(struct node* head)
{
struct node* temp = head;
while(temp->next->next!=NULL){
temp = temp->next;
}
temp->next = NULL;
}
void deleteFromMiddle(struct node* head, int position){
struct node* temp = head;
int i;
for(i=2; inext != NULL)
{
temp = temp->next;
}
}
temp->next = temp->next->next;
}
int main()
{
/* Initialize nodes */
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
/* Allocate memory */
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
/* Assign data values */
one->data = 1;
two->data = 2;
three->data = 3;
/* Connect nodes */
one->next = two;
two->next = three;
three->next = NULL;
/* Save address of first node in head */
head = one;
display(head); // 1 --->2 --->3 --->
insertAtFront(&head, 4);
display(head); // 4 --->1 --->2 --->3 --->
deleteFromFront(&head);
display(head); // 1 --->2 --->3 --->
insertAtEnd(head, 5);
display(head); // 1 --->2 --->3 --->5 --->
deleteFromEnd(head);
display(head); // 1 --->2 --->3 --->
int position = 3;
insertAtMiddle(head, position, 10);
display(head); // 1 --->2 --->10 --->3 --->
deleteFromMiddle(head, position);
display(head); // 1 --->2 --->3 --->
}
Output:
List elements are -
1 --->2 --->3 --->
List elements are -
4 --->1 --->2 --->3 --->
List elements are -
1 --->2 --->3 --->
List elements are -
Wipro Elite NLTH Coding / Programming Questions
1 --->2 --->3 --->5 --->
List elements are -
1 --->2 --->3 --->
List elements are -
1 --->2 --->10 --->3 --->
List elements are -
1 --->2 --->3 --->

Q.23. Circular Linked List


Program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
struct node
{
int data;
int key;
struct node *next;
};
struct node *head = NULL;
struct node *current = NULL;
bool isEmpty()
{
return head == NULL;
}
int length()
{
int length = 0;
//if list is empty
if(head == NULL)
{
return 0;
}
current = head->next;
while(current != head)
{
length++;
current = current->next;
}
return length;
}
//insert link at the first location
void insertFirst(int key, int data)
{
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
if (isEmpty())
{
head = link;
head->next = head;
} else
{
//point it to old first node
link->next = head;
//point first to new first node
head = link;
}
}
//delete first item
struct node * deleteFirst()
{
//save reference to first link
struct node *tempLink = head;
if(head->next == head)
{
head = NULL;
return tempLink;
}
//mark next to first link as first
head = head->next;
//return the deleted link
return tempLink;
//display the list
void printList()
{
struct node *ptr = head;
printf("\n[ ");
//start from the beginning
if(head != NULL)
{
while(ptr->next != ptr)
{
printf("(%d,%d) ",ptr->key,ptr->data);
ptr = ptr->next;
}
}
printf(" ]");
}
void main()
{
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);
printf("Original List: ");
//print list
printList();
while(!isEmpty())
{
struct node *temp = deleteFirst();
printf("\nDeleted value:");
printf("(%d,%d) ",temp->key,temp->data);
}
printf("\nList after deleting all items: ");
printList();
}

Output:
Original List:[ (6,56) (5,40) (4,1) (3,30) (2,20) ]
Deleted value:(6,56)
Deleted value:(5,40)
Deleted value:(4,1)
Deleted value:(3,30)
Deleted value:(2,20)
Deleted value:(1,10)
List after deleting all items: [ ]

Q.24. Topological Sort Program In C Language


Program:
#include <stdio.h>
int main()
{
int i,j,k,n,a[10][10],indeg[10],flag[10],count=0;
printf("Enter the no of vertices:\n");
scanf("%d",&n);
printf("Enter the adjacency matrix:\n");
for(i=0;i<n;i++){
printf("Enter row %d\n",i+1);
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
for(i=0;i<n;i++)
{
indeg[i]=0;
flag[i]=0;
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
indeg[i]=indeg[i]+a[j][i];
printf("\nThe topological order is:");
while(count<n)
{
for(k=0;k<n;k++)
{
if((indeg[k]==0) && (flag[k]==0))
{
printf("%d ",(k+1));
flag [k]=1;
}
for(i=0;i<n;i++){
if(a[i][k]==1)
indeg[k]--;
}
}
count++;
}
return 0;
}
Output:
Enter the no of vertices: 4
Enter the adjacency matrix:
Enter row 1
0110
Enter row 2
0001
Enter row 3
0001
Enter row 4
0000
The topological order is:1 2 3 4

Q.25. String Processing & Manipulation In C Language


Program:
#include <stdio.h>
#include <string.h>
int main(void)
{
//variable
char str[100], tmp;
int i, len, mid;
//input
printf("Enter a string: ");
gets(str);
//find number of characters
len = strlen(str);
mid = len/2;
//reverse
for (i = 0; i < mid; i++)
{
tmp = str[len - 1 - i];
str[len - 1 - i] = str[i];
str[i] = tmp;
}
//output
printf("Reversed string: %s\n", str);
printf("End of code\n");
return 0;
}

Output:
Enter a string: Hello World
Reversed string: dlroW olleH
End of code

Q.26. .Stacks Queues Program in C Language


Program:
#include <stdio.h>
int MAXSIZE = 8;
int stack[8];
int top = -1;
int isempty()
{
if(top == -1)
return 1;
else
return 0;
}
int isfull()
{
if(top == MAXSIZE)
return 1;
else
return 0;
}
int peek()
{
return stack[top];
}
int pop()
{
int data;
if(!isempty())
{
data = stack[top];
top = top - 1;
return data;
} else
{
printf("Could not retrieve data, Stack is empty.\n");
}
}
int push(int data)
{
if(!isfull())
{
top = top + 1;
stack[top] = data;
} else {
printf("Could not insert data, Stack is full.\n");
}
}
int main()
{
// push items on to the stack
push(3);
push(5);
push(9);
push(1);
push(12);
push(15);
printf("Element at top of the stack: %d\n" ,peek());
printf("Elements: \n");
// print stack data
while(!isempty())
{
int data = pop();
printf("%d\n",data);
}
printf("Stack full: %s\n" , isfull()?"true":"false");
printf("Stack empty: %s\n" , isempty()?"true":"false");
return 0;
}

Output:
Element at top of the stack: 15
Elements:
15
12
1
9
5
3
Stack full: false
Stack empty: true

Q.27. Queues Program In C Language

Program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 6
int intArray[MAX];
int front = 0;
int rear = -1;
int itemCount = 0;
int peek()
{
return intArray[front];
}
bool isEmpty()
{
return itemCount == 0;
}
bool isFull()
{
return itemCount == MAX;
}
int size() {
return itemCount;
}
void insert(int data) {
if(!isFull())
{
if(rear == MAX-1)
{
rear = -1;
}
intArray[++rear] = data;
itemCount++;
}
}
int removeData()
{
int data = intArray[front++];
if(front == MAX) {
front = 0;
}
itemCount--;
return data;
}
int main()
{
/* insert 5 items */
insert(3);
insert(5);
insert(9);
insert(1);
insert(12);
// front : 0
// rear : 4
// ------------------
// index : 0 1 2 3 4
// ------------------
// queue : 3 5 9 1 12
insert(15);
// front : 0
// rear : 5
// ---------------------
// index : 0 1 2 3 4 5
// ---------------------
// queue : 3 5 9 1 12 15
if(isFull()) {
printf("Queue is full!\n");
}
// remove one item
int num = removeData();
printf("Element removed: %d\n",num);
// front : 1
// rear : 5
// -------------------
// index : 1 2 3 4 5
// -------------------
// queue : 5 9 1 12 15
// insert more items
insert(16);
// front : 1
// rear : -1
// ----------------------
// index : 0 1 2 3 4 5
// ----------------------
// queue : 16 5 9 1 12 15
// As queue is full, elements will not be inserted.
insert(17);
insert(18);
// ----------------------
// index : 0 1 2 3 4 5
// ----------------------
// queue : 16 5 9 1 12 15
printf("Element at front: %d\n",peek());
printf("----------------------\n");
printf("index : 5 4 3 2 1 0\n");
printf("----------------------\n");
printf("Queue: ");
while(!isEmpty()) {
int n = removeData();
printf("%d ",n);
}
}

Output:
Queue is full!
Element removed: 3
Element at front: 5
----------------------

index : 5 4 3 2 1 0
----------------------
Queue: 5 9 1 12 15 16

Q.28. Sorting: C program to accept N numbers and arrange them in an


ascending order.

Program:
#include <stdio.h>
void main()
{
int i, j, a, n, number[30];
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; ++i)
printf("%d\n", number[i]);
}

Output:
Enter the value of N: 6
Enter the numbers
3
78
90
456
780
200
The numbers arranged in ascending order are given below
3
78
90
200
456
780

Q.29. Searching Technique.

Program:
#include <stdio.h>
int main()
{
int array[100], search, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);
return 0;
}
Output:

Q.30. Dynamic Programming

Program:

#include<stdio.h>

int max(int a, int b) { return (a > b)? a : b; }

int knapSack(int W, int wt[], int val[], int n)

int i, w;

int K[n+1][W+1];
for (i = 0; i <= n; i++)

for (w = 0; w <= W; w++)

if (i==0 || w==0)

K[i][w] = 0;

else if (wt[i-1] <= w)

K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]);

else

K[i][w] = K[i-1][w];

return K[n][W];

int main()

int i, n, val[20], wt[20], W;

printf("Enter number of items:");

scanf("%d", &n);

printf("Enter value and weight of items:\n");

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

scanf("%d%d", &val[i], &wt[i]);


}

printf("Enter size of knapsack:");

scanf("%d", &W);

printf("%d", knapSack(W, wt, val, n));

return 0;

Output:

Enter number of items: 3

Enter value and weight of items:

100 20

50 10

150 30

Enter size of knapsack:50

250

Q.31. Greedy Algorithm In C Language

Program:

#include <stdio.h>

int main () {

int num_denominations, coin_list[100], use_these[100], i, owed;

printf("Enter number of denominations : ");

scanf("%d", &num_denominations);

printf("\nEnter the denominations in descending order: ");


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

scanf("%d", &coin_list[i]);

// use_these[i] = 0;

printf("\nEnter the amount owed : ");

scanf("%d", &owed);

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

use_these[i] = owed / coin_list[i];

owed %= coin_list[i];

printf("\nSolution: \n");

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

printf("%dx%d ", coin_list[i], use_these[i]);

}
Output:

Q.32. String Matching Program In C Language

Program:

#include<stdio.h>

#include<conio.h>

int length(char x[])

int i;

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

{}

return i;

void main()
{

char s[20],p[20];

int i,l,count=0;

clrscr();

printf("\n enter Your String = ");

scanf("%s",s);

printf("enter the string to be matched = ");

scanf("%s",p );

l=length(p);

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

if(s[i]==p[count] )

count++;

else

count=0;

if ( count == l )

printf("Substring %s found in the given string",p);

break;

}
}

if(count!=l)

printf("not found");

getch();

}
Output:

Q.33. Divide & Conquer Program In C language

Program:

#include <stdio.h>

#define max 10

int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };

int b[10];

void merging(int low, int mid, int high)

int l1, l2, i;

for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++)

{
if(a[l1] <= a[l2])

b[i] = a[l1++];

else

b[i] = a[l2++];

while(l1 <= mid)

b[i++] = a[l1++];

while(l2 <= high)

b[i++] = a[l2++];

for(i = low; i <= high; i++)

a[i] = b[i];

void sort(int low, int high)

int mid;

if(low < high)

mid = (low + high) / 2;

sort(low, mid);

sort(mid+1, high);

merging(low, mid, high);

} else {
return;

int main()

int i;

printf("List before sorting\n");

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

printf("%d ", a[i]);

sort(0, max);

printf("\nList after sorting\n");

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

printf("%d ", a[i]);

Output:

List before sorting

10 14 19 26 27 31 33 35 42 44 0

List after sorting

0 10 14 19 26 27 31 33 35 42 44

Q.34. Disjoint sets Program In C Language

Program:
// A union-find algorithm to detect cycle in a graph

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

// a structure to represent an edge in graph

struct Edge

int src, dest;

};

// a structure to represent a graph

struct Graph

// V-> Number of vertices, E-> Number of edges

int V, E;

// graph is represented as an array of edges

struct Edge* edge;

};

// Creates a graph with V vertices and E edges

struct Graph* createGraph(int V, int E)

struct Graph* graph =

(struct Graph*) malloc( sizeof(struct Graph) );


graph->V = V;

graph->E = E;

graph->edge =

(struct Edge*) malloc( graph->E * sizeof( struct Edge ) );

return graph;

// A utility function to find the subset of an element i

int find(int parent[], int i)

if (parent[i] == -1)

return i;

return find(parent, parent[i]);

// A utility function to do union of two subsets

void Union(int parent[], int x, int y)

int xset = find(parent, x);

int yset = find(parent, y);

if(xset!=yset){

parent[xset] = yset;

}
// The main function to check whether a given graph contains

// cycle or not

int isCycle( struct Graph* graph )

// Allocate memory for creating V subsets

int *parent = (int*) malloc( graph->V * sizeof(int) );

// Initialize all subsets as single element sets

memset(parent, -1, sizeof(int) * graph->V);

// Iterate through all edges of graph, find subset of both

// vertices of every edge, if both subsets are same, then

// there is cycle in graph.

for(int i = 0; i < graph->E; ++i)

int x = find(parent, graph->edge[i].src);

int y = find(parent, graph->edge[i].dest);

if (x == y)

return 1;

Union(parent, x, y);

return 0;

// Driver program to test above functions


int main()

/* Let us create following graph

|\

|\

1-----2 */

int V = 3, E = 3;

struct Graph* graph = createGraph(V, E);

// add edge 0-1

graph->edge[0].src = 0;

graph->edge[0].dest = 1;

// add edge 1-2

graph->edge[1].src = 1;

graph->edge[1].dest = 2;

// add edge 0-2

graph->edge[2].src = 0;

graph->edge[2].dest = 2;

if (isCycle(graph))

printf( "graph contains cycle" );

else

printf( "graph doesn't contain cycle" );


return 0;

Output:

graph contains cycle

Q.35. Computational Geometry

Program:

#include <bits/stdc++.h>

using namespace std;

struct Point

int x, y;

};

// To find orientation of ordered triplet (p, q, r).

// The function returns following values

// 0 --> p, q and r are colinear

// 1 --> Clockwise

// 2 --> Counterclockwise

int orientation(Point p, Point q, Point r)

int val = (q.y - p.y) * (r.x - q.x) -

(q.x - p.x) * (r.y - q.y);

if (val == 0) return 0; // colinear


return (val > 0)? 1: 2; // clock or counterclock wise

// Prints convex hull of a set of n points.

void convexHull(Point points[], int n)

// There must be at least 3 points

if (n < 3) return;

// Initialize Result

vector<Point> hull;

// Find the leftmost point

int l = 0;

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

if (points[i].x < points[l].x)

l = i;

// Start from leftmost point, keep moving counterclockwise

// until reach the start point again. This loop runs O(h)

// times where h is number of points in result or output.

int p = l, q;

do

// Add current point to result

hull.push_back(points[p]);
// Search for a point 'q' such that orientation(p, x,

// q) is counterclockwise for all points 'x'. The idea

// is to keep track of last visited most counterclock-

// wise point in q. If any point 'i' is more counterclock-

// wise than q, then update q.

q = (p+1)%n;

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

// If i is more counterclockwise than current q, then

// update q

if (orientation(points[p], points[i], points[q]) == 2)

q = i;

// Now q is the most counterclockwise with respect to p

// Set p as q for next iteration, so that q is added to

// result 'hull'

p = q;

} while (p != l); // While we don't come to first point

// Print Result

for (int i = 0; i < hull.size(); i++)

cout << "(" << hull[i].x << ", "

<< hull[i].y << ")\n";


}

// Driver program to test above functions

int main()

Point points[] = {{0, 3}, {2, 2}, {1, 1}, {2, 1},

{3, 0}, {0, 0}, {3, 3}};

int n = sizeof(points)/sizeof(points[0]);

convexHull(points, n);

return 0;

Output:

The output is points of the convex hull.

(0, 3)

(0, 0)

(3, 0)

(3, 3)

Q.35. Program to print BFS traversal from a given

Program:

#include<iostream>

#include <list>

using namespace std;

// This class represents a directed graph using


// adjacency list representation

class Graph

int V; // No. of vertices

// Pointer to an array containing adjacency

// lists

list<int> *adj;

public:

Graph(int V); // Constructor

// function to add an edge to graph

void addEdge(int v, int w);

// prints BFS traversal from a given source s

void BFS(int s);

};

Graph::Graph(int V)

this->V = V;

adj = new list<int>[V];

void Graph::addEdge(int v, int w)

adj*v+.push_back(w); // Add w to v’s list.


}

void Graph::BFS(int s)

// Mark all the vertices as not visited

bool *visited = new bool[V];

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

visited[i] = false;

// Create a queue for BFS

list<int> queue;

// Mark the current node as visited and enqueue it

visited[s] = true;

queue.push_back(s);

// 'i' will be used to get all adjacent

// vertices of a vertex

list<int>::iterator i;

while(!queue.empty())

// Dequeue a vertex from queue and print it

s = queue.front();

cout << s << " ";

queue.pop_front();

// Get all adjacent vertices of the dequeued


// vertex s. If a adjacent has not been visited,

// then mark it visited and enqueue it

for (i = adj[s].begin(); i != adj[s].end(); ++i)

if (!visited[*i])

visited[*i] = true;

queue.push_back(*i);

// Driver program to test methods of graph class

int main()

// Create a graph given in the above diagram

Graph g(4);

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 2);

g.addEdge(2, 0);

g.addEdge(2, 3);
g.addEdge(3, 3);

cout << "Following is Breadth First Traversal "

<< "(starting from vertex 2) \n";

g.BFS(2);

return 0;

Output:

Following is Breadth First Traversal (starting from vertex 2)

2031

Q.36. #include <stdio.h>

#include <stdlib.h>

struct node

int data;

struct node* left;

struct node* right;

};

struct node* createNode(value)

struct node* newNode = malloc(sizeof(struct node));

newNode->data = value;

newNode->left = NULL;
newNode->right = NULL;

return newNode;

struct node* insertLeft(struct node *root, int value)

root->left = createNode(value);

return root->left;

struct node* insertRight(struct node *root, int value)

root->right = createNode(value);

return root->right;

int main()

struct node *root = createNode(1);

insertLeft(root, 2);

insertRight(root, 3);

printf("The elements of tree are %d %d %d", root->data, root->left->data, root-


>right->data);

Output: 1 2 3
Q.37 . Dijkstra’s Algorithm

Program:

#include<stdio.h>

#include<conio.h>

#define INFINITY 9999

#define MAX 10

void dijkstra(int G[MAX][MAX],int n,int startnode);

int main()

int G[MAX][MAX],i,j,n,u;

printf("Enter no. of vertices:");

scanf("%d",&n);

printf("\nEnter the adjacency matrix:\n");

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

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

scanf("%d",&G[i][j]);

printf("\nEnter the starting node:");

scanf("%d",&u);

dijkstra(G,n,u);

return 0;

void dijkstra(int G[MAX][MAX],int n,int startnode)


{

int cost[MAX][MAX],distance[MAX],pred[MAX];

int visited[MAX],count,mindistance,nextnode,i,j;

//pred[] stores the predecessor of each node

//count gives the number of nodes seen so far

//create the cost matrix

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

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

if(G[i][j]==0)

cost[i][j]=INFINITY;

else

cost[i][j]=G[i][j];

//initialize pred[],distance[] and visited[]

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

distance[i]=cost[startnode][i];

pred[i]=startnode;

visited[i]=0;

distance[startnode]=0;

visited[startnode]=1;

count=1;
while(count<n-1)

mindistance=INFINITY;

//nextnode gives the node at minimum distance

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

if(distance[i]<mindistance&&!visited[i])

mindistance=distance[i];

nextnode=i;

//check if a better path exists through nextnode

visited[nextnode]=1;

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

if(!visited[i])

if(mindistance+cost[nextnode][i]<distance[i])

distance[i]=mindistance+cost[nextnode][i];

pred[i]=nextnode;

count++;

//print the path and distance of each node


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

if(i!=startnode)

printf("\nDistance of node%d=%d",i,distance[i]);

printf("\nPath=%d",i);

j=i;

do

j=pred[j];

printf("<-%d",j);

}while(j!=startnode);

Output:
Q.38. Prims Algorithm

// A C / C++ program for Prim's Minimum

// Spanning Tree (MST) algorithm. The program is

// for adjacency matrix representation of the graph

Program:

#include <stdio.h>

#include <limits.h>

#include<stdbool.h>

// Number of vertices in the graph

#define V 5

// A utility function to find the vertex with

// minimum key value, from the set of vertices

// not yet included in MST

int minKey(int key[], bool mstSet[])

// Initialize min value

int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)

if (mstSet[v] == false && key[v] < min)

min = key[v], min_index = v;

return min_index;
}

// A utility function to print the

// constructed MST stored in parent[]

int printMST(int parent[], int n, int graph[V][V])

printf("Edge \tWeight\n");

for (int i = 1; i < V; i++)

printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);

// Function to construct and print MST for

// a graph represented using adjacency

// matrix representation

void primMST(int graph[V][V])

// Array to store constructed MST

int parent[V];

// Key values used to pick minimum weight edge in cut

int key[V];

// To represent set of vertices not yet included in MST

bool mstSet[V];

// Initialize all keys as INFINITE

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


key[i] = INT_MAX, mstSet[i] = false;

// Always include first 1st vertex in MST.

// Make key 0 so that this vertex is picked as first vertex.

key[0] = 0;

parent[0] = -1; // First node is always root of MST

// The MST will have V vertices

for (int count = 0; count < V-1; count++)

// Pick the minimum key vertex from the

// set of vertices not yet included in MST

int u = minKey(key, mstSet);

// Add the picked vertex to the MST Set

mstSet[u] = true;

// Update key value and parent index of

// the adjacent vertices of the picked vertex.

// Consider only those vertices which are not

// yet included in MST

for (int v = 0; v < V; v++)

// graph[u][v] is non zero only for adjacent vertices of m

// mstSet[v] is false for vertices not yet included in MST

// Update the key only if graph[u][v] is smaller than key[v]

if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])


parent[v] = u, key[v] = graph[u][v];

// print the constructed MST

printMST(parent, V, graph);

// driver program to test above function

int main()

/* Let us create the following graph

23

(0)--(1)--(2)

|/\|

6| 8/ \5 |7

|/\|

(3)-------(4)

9 */

int graph[V][V] = {{0, 2, 0, 6, 0},

{2, 0, 3, 8, 5},

{0, 3, 0, 0, 7},

{6, 8, 0, 0, 9},

{0, 5, 7, 9, 0}};

// Print the solution


primMST(graph);

return 0;

Output: Edge Weight

0-12

1-23

0-36

1-45

Q.39. Program to print all the distinct elements in an array.

Input:

9 = size of an array

2 3 4 5 6 1 2 3 4 = array elements

Output:

234561

Program:

#include <stdio.h>
void distict_elements(int a[], int n);
int main()
{
int size_array, i, arr[20];
// Get the array size
scanf(“%d”, &size_array);
// Get the array elements
for(i=0; i<size_array; i++)
{
scanf(“%d”, &arr*i+);
}
// Function call to print the distinct elements in an array
distict_elements(arr, size_array);
return 0;
}
void distict_elements(int a[], int n)
{
int i, j;
// Pick all elements one by one
for (i=0; i<n; i++)
{
// Check if the picked element is already printed
for (j=0; j<i; j++)
{
if (a[i] == a[j])
break;
}
// If not printed earlier, then print it
if (i == j)
printf(“%d “, a*i+);
}
}

Output:
Enter the size of the array: 5
Enter the array elements :- 1 2 3 4 4
Input Array : 1 2 3 4 4
Distinct Elements: 1 2 3 4

Q.40. Program to replace a substring in a string.

Program:

// C code to replace a substring in a string

#include
#include
void replaceSubstring(char [],char[],char[]);
main()
{
char string[100],sub[100],new_str[100];
printf(“\nEnter a string: “);
gets(string);
printf(“\nEnter the substring: “);
gets(sub);
printf(“\nEnter the new substring: “);
gets(new_str);
replaceSubstring(string,sub,new_str);
printf(“\nThe string after replacing : %s\n”,string);
}

void replaceSubstring(char string[],char sub[],char new_str[])


{
int stringLen,subLen,newLen;
int i=0,j,k;
int flag=0,start,end;
stringLen=strlen(string);
subLen=strlen(sub);
newLen=strlen(new_str);

for(i=0;i<stringLen;i++)
{
flag=0;
start=i;
for(j=0;string[i]==sub[j];j++,i++)
if(j==subLen-1)
flag=1;
end=i;
if(flag==0)
i-=j;
else
{
for(j=start;j<end;j++)
{
for(k=start;k<stringLen;k++)
string[k]=string[k+1];
stringLen–;
i–;
}
for(j=start;j<start+newLen;j++)
{
for(k=stringLen;k>=j;k–)
string[k+1]=string[k];
string[j]=new_str[j-start];
stringLen++;
i++;
}
}
}
}

Output:

Enter the main String: Notwithstanding


Enter the string to be replaced: with
Enter the replacing string: under
Notunderstanding

Q.41. Program to check for balanced parenthesis with and without using
stack.

Program:
// C code to check balanced parenthesis

#include
#include
char st[20];
int top=-1;
void psh(char);
char pop();
int main()
{
char a[20],t;
int i,f=1;
scanf(“%s”,a);
for(i=0;i<strlen(a);i++)
{
if(a*i+=='(‘||a*i+==',‘||a*i+=='*‘)
psh(a[i]);
if(a*i+==’)’||a*i+==’-’||a*i+==’+’)
{
if(top==-1)
f=0;
else
{t=pop();
if(a*i+==’)’&&(t=='*‘||t==',‘))
f=0;
if(a*i+==’-’&&(t=='(‘||t=='*‘))
f=0;
if(a*i+==’+’&&(t==',‘||t=='(‘))
f=0;
}
}
}
if(top>=0)
f=0;
if(f==0)
printf(“Unbalanced\n”);
else
printf(“Balanced\n”);
return 0;
}
void psh(char a)
{
st[++top]=a;
}
char pop()
{
return st[top–];
}

Input : ((()))
Output: 1

Input : ()((
Output : -1
Q.42. Program to find the transpose of a matrix.
Program:
#include <stdio.h>
int main()
{
int m, n, c, d, matrix[10][10], transpose[10][10];
scanf(“%d%d”, &m, &n);
for (c = 0; c < m; c++)
for(d = 0; d < n; d++)
scanf(“%d”, &matrix*c+*d+);
for (c = 0; c < m; c++)
for( d = 0 ; d < n ; d++ )
transpose[d][c] = matrix[c][d];
for (c = 0; c < n; c++)
{
for (d = 0; d < m; d++)
printf(“%d\t”, transpose*c+*d+);
printf(“\n”);
}
return 0;
}
Output:
Enter number of rows: 3
Enter number of columns: 3
Enter matrix:
1
1
1
2
2
2
3
3
3

The Input Matrix is


1 1 1
2 2 2
3 3 3
The above matrix after Transpose is
1 2 3
1 2 3
1 2 3

Q.43. Program to half pyramid pattern using stars or Half Pyramid star
patterns.
Program:
// C program to print half pyramid pattern using stars
#include <stdio.h>
int main()
{
int i, j,n;
scanf(“%d”,&n);
for(i = 0; i < n; i++)
{
for(j = 0; j <= i; j++)
{
printf(“*”);
}
printf(“\n”);
}
return 0;
}
Output:
*
**
***
****
*****
******

Q.44. Program to print inverted half pyramid pattern using stars.

Program:
// C program to print inverted half pyramid pattern using stars
#include <stdio.h>
int main()
{
int i, j, n, k = 0;
scanf(“%d”,&n);
for(i = n; i >= 1; –i)
{
for(j = 1; j <= i; ++j)
{
printf(“* “);
}
printf(“\n”);
}
return 0;
}

Output:

******
*****
****
***
**
*
Q.45. Program to print full pyramid pattern using stars.

Program:

// C program to print full pyramid pattern using stars


#include <stdio.h>
int main()
{
int i, j, n, k = 0;
scanf(“%d”,&n);
for(i = 1; i <= n; ++i, k = 0)
{
for(j = 1; j <= n – i; ++j)
{
printf(” “);
}
while(k != 2 * i-1)
{
printf(“* “);
++k;
}
printf(“\n”);
}
return 0;
}

Output:

**

***

****

*****

******
Q.46. Program to print half pyramid pattern printing using numbers or Half
Pyramid number patterns.

Program:

/* C program – Half Pyramid Pattern Printing using numbers */


#include
int main()
{
int i, j,n;
scanf(“%d”,&n);
for(i = 1; i <= n; i++)
{
for(j = 1; j <= i; j++)
{
printf(“%d “,j);
}
printf(“\n”);
}
return 0;
}

Output:

12

123

1234

12345

Q.47. Program to print inverted half pyramid pattern printing using numbers.

Program:
/* C program – Pyramid Pattern Printing using numbers */
#include
int main()
{
int i, j,n;
scanf(“%d”,&n);
for(i = 1; i <= n; i++)
{
for(j = i; j <= n; j++)
{
printf(“%d “,j);
}
printf(“\n”);
}
return 0;
}

Output:

12345

1234

123

12

Q.48. Program to print full pyramid using numbers.

Program:
/* C program – Full Pyramid Pattern Printing using numbers */
#include
int main()
{
int i, j, n, count = 0, count1 = 0, k = 0;
scanf(“%d”,&n);
for(i = 1; i <= n; ++i)
{
for(j = 1; j <= n-i; ++j)
{
printf(” “);
++count;
}

while(k != 2*i-1)
{
if (count <= n-1)
{
printf(“%d “, i+k);
++count;
}
else
{
++count1;
printf(“%d “, (i+k-2*count1));
}
++k;
}
count1 = count = k = 0;
printf(“\n”);
}
return 0;
}

Output:

2 3 2

34543

4567654

567898765
Q.49. Program to print hollow half pyramid pattern using numbers.

Program:

/* C program print hollow half pyramid pattern using numbers */


#include <stdio.h>
int main()
{
int i, j, n, k = 0;
scanf(“%d”,&n);
for(i = 1; i <= n; i++)
{
for(j = 1; j <= i; j++)
{
if (j == 1 || j == i || i == n)
printf(“%d”, j);
else
printf(” “);
}
printf(“\n”);
}
return 0;
}

Output:

1 2

1 3

1 4

1 2 3 4 5

Q.50. Program for solid diamond pattern using stars.

Program:
/* C program – solid diamond pattern printing using stars */
#include <stdio.h>
int main()
{
int n, c, k, space = 1;
printf(“Enter the number of rows\n”);
scanf(“%d”, &n);
space = n – 1;
for (k = 1; k <= n; k++)
{
for (c = 1; c <= space; c++)
printf(” “);
space–;
for (c = 1; c <= 2*k-1; c++)
printf(“*”);
printf(“\n”);
}
space = 1;

for (k = 1; k <= n – 1; k++)


{
for (c = 1; c <= space; c++)
printf(” “);

space++;

for (c = 1 ; c <= 2*(n-k)-1; c++)


printf(“*”);

printf(“\n”);
}
return 0;
}

Output:
*

**

***

****

*****

*****

****

***

**