3. Program to search an element using linear search technique
#include <stdio.h>
#include<conio.h>
void main()
{
int a[100],i,n, key,c=0;
clrscr();
printf("Enter the size of array : ");
scanf("%d",&n);
printf("\nEnter the array elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nEnter the elements to be searched : ");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(key==a[i]
) {
c=1;
break;
}
}
if(c==1)
printf("\nSearch is successful");
else
printf("\nSearch is unsuccessful");
getch();
}
5. Program to implement Stack
#include<stdio.h>
#include<conio.h>
#define N 5
int top=-1;
int s[N];
push();
pop();
display();
void main()
{
int ch;
clrscr();
do
{
printf("\nEnter your choice :1-push() 2-pop() 3-display() : ");
scanf("%d",&ch);
switch(ch)
{
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
case 4:exit(0);
}}while(ch!=0);
getch();
}
push()
{
int a;
printf("Enter the element : ");
scanf("%d",&a);
if(top==N-1)
printf("Stack is overflow/full");
else
{
top++;
s[top]=a;
}
}
pop()
{ if(top==-1)
printf("Stack is
underflow/empty"); else
top--;
}
display() {
int i;
if(top==-1)
printf("Stack is empty");
else
{
for(i=top;i>=0;i--){
printf("%d",s[i]); }
}
}
1. Program to find GCD using recursive function
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,result;
int GCD(int x, int y);
clrscr();
printf("Enter any two numbers : ");
scanf("%d%d",&a,&b);
result=GCD(a,b);
printf("\n\nGCD number = %d",result);
getch();
}
int GCD(int x, int y)
{
if(y==0)
return x;
else
return(GCD(y,x%y));
}
2. Program to generate bionomial coefficient using recursive function.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,r,ncr;
int fact(int n, int r);
clrscr();
printf("Enter values of n and r : ");
scanf("%d%d",&n,&r);
ncr=fact(n,r);
printf("\n\nBionomial coefficient nCr = %d",ncr);
getch();
}
int fact(int n, int r)
{
if(r==0 || n==r)
return 1;
else
return(fact(n-1,r-1)+fact(n-1,r));
}
3. Program to generate n Fibonacci numbers using recursive function.
#include<stdio.h>
#include<conio.h>
void main() {
inti,f,n;
clrscr();
printf("Enter a number : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
f=fib(i);
printf("\n %d",f);
}
getch();
}
int fib(int num)
{
if(num==0)
return 0; else
if(num==1)
return 1; else
return(fib(num-1)+fib(num-2));
}
4. Program to implement Tower of Hanoi using
recursion
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
int toh(int n, char a, char b,char c);
clrscr();
printf("Enter the number of discs : ");
scanf("%d",&n);
toh(n,'S','T','D');
getch();
}
int toh(int n, char a, char b,char c)
{
if(n==1)
printf("\nMove the disc from %c to %c",a,c);
else
{
toh(n-1,a,c,b);
printf("\nMove the disc from %c to %c",a,c);
toh(n-1,b,a,c);
}
}
Comments
Post a Comment