c - How to get the GCD of command line argument integers entered by the user after './a.out' in any order? -


this program returns gcd of command line args inputed user least greastest. example:

user input: './a.out 5 10 15 20 25 '

this program returns: "the gcd of command line args 5"

however, problem running if user types example:

user input: './a.out 15 10 5 25 20'

this program returns: 15

can tell me how fix issue?

this aiming for:

if user input: './a.out 15 10 5 25 20'

this program should return: 5

//header files #include<stdio.h> #include<string.h>  //main method int main(int argc, char *argv[]){  //declared variables here , print statements  int i,x,y,min;  printf("number of command line args %d\n", argc);  printf("the gcd is:\t");   //this main while loop  while( x !=0 && y !=0 && y != x){   if(x<y){   y=y-x;  }//end first if statement  if(y<x){   x-x-y;  }//end second if statement  }//end while loop   //this function returns converted integral number int value   x=atoi(argv[i]);   for(i=2;i<argc;i++){   y=atoi(argv[i]);    }     //the following code gets gcd , prints command line    min = (x>y)?x:y;   for(i=min;i>=1;--i){   if(x%i==0 && y%i==0){   for(i=1;i<argc;i++){    printf("%s\n", argv[i]);     break;}//end loop     }//end if statement    }//end loop   }//end of main 

i've cleaned up, should work you:

initialize every variable before consider calculation in code.

#include<stdio.h> #include<string.h>  //main method int main(int argc, char *argv[]){  //declared variables here , print statements  int i,x,y,gcd;  printf("number of command line args %d\n", argc);  printf("the gcd is:\t");  x=atoi(argv[1]);  for(i=2;i<argc;i++){     y=atoi(argv[i]);     while( x !=0 && y !=0 && y != x){         if(x<y){             y=y-x;         }else if(y<x){             x=x-y;         }     }     gcd=x;  }  printf("%d",gcd); }//end of main 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -