Posts

Showing posts from October, 2015

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

Find the Factorial of a number

Summary: Factorial is represented using '!', so five factorial will be written as (5!),n factorial as (n!). n! = n*(n-1)*(n-2)*(n-3)...3.2.1 and zero factorial is defined as one i.e. 0! = 1. Using While Loop #include<stdio.h> void main() { int a,f,i; printf("Enter a number: "); scanf("%d",&a); f=1; i=1; while(i<=a) { f = f * i; i++; } printf("\nFactorial of %d is: %d",a,f); } Using For Loop #include<stdio.h> void main() { int a,f,i; printf("Enter a number: "); scanf("%d",&a); f=1; for(i=1;i<=a;i++) f = f * i; printf("\nFactorial of %d is: %d",a,f); } Using Recursion #include<stdio.h> int fact(int); int main(){ int num,f; printf("\nEnter a number: "); scanf("%d",&num); f=fact(num); printf("\nFactorial of %d is: %d",num,f); return 0; } int fact(int n){ if(n==1)

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