Skip to main content

Posts

Showing posts with the label DS

Find the GCD of two numbers

Using For Loop #include<stdio.h> int main(){ int x,y,m,i; do { printf("Enter two number: "); scanf("%d%d",&x,&y); if(x==0 || y==0) printf("Please check the input and try again...\n"); }while(x==0 || y==0); if(x>y) m=y; else m=x; for(i=m;i>=1;i--){ if(x%i==0&&y%i==0){ printf("\nGCD of %d and %d is %d",x,y,i) ; break; } } return 0; } Using Recursion #include <stdio.h> int gcd(int a, int b) { if (a == b) return a; if (a > b) return gcd(a-b, b); return gcd(a, b-a); } int main() { int x,y,m,i; do { printf("Enter two number: "); scanf("%d%d",&x,&y); if(x==0 || y==0) printf("Please check the input and try again...\n"); }while(x==0 || y==0); printf("GCD of %d and %d

Solve All-Pairs Shortest Path Problem using Floyd - Warshall Algorithm

#include<stdio.h> #include<conio.h> #define inf 999 void main() { int i,j,k,n,w[20][20]; printf("\n Enter the no. of vertices : "); scanf("%d",&n); printf("\n Enter the weights : "); for(i=1;i<=n;i++) for(j=1;j<=n;j++) { printf("w[%d][%d]= ",i,j); scanf("%d",&w[i][j]); if(i!=j && (w[i][j]==0)) w[i][j]=inf; } for(i=1;i<=n;i++) { printf("\n"); for(j=1;j<=n;j++) printf("%d\t",w[i][j]); } for(k=1;k<=n;k++) { for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { if(w[i][k]+w[k][j]<w[i][j]) w[i][j]=w[i][k]+w[k][j]; } } } printf("\n The resultant Matrix : \n"); for(i=1;i<=n;i++) { printf("\n"); for(j=1;j<=n;j++) printf("%d\t",w[i][j]); } getch(); } Output   Print   Output Enter the no. of vertices : 5 E

Binary Search using Recursion

#include<stdio.h> void bins(int lb,int ub,int item,int a[]); void main() { int i,n,item,a[20]; printf("Enter the size of an array: "); scanf("%d",&n); printf("Enter the elements of the array: " ); for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("Enter the number to be search: "); scanf("%d",&item); bins(0,n-1,item,a); } void bins(int lb,int ub,int item,int a[]) { int mid,flag=0; if(lb<=ub) { mid=(lb+ub)/2; if(item==a[mid]) { flag=flag+1; } else if(item<a[mid]) { return bins(lb,mid-1,item,a); } else return bins(mid+1,ub,item,a); } if(flag==0) printf("Number is not found."); else printf("Number is found at %d", mid+1); } Output   Print   Out