Search code examples
carraysunixgreatest-common-divisor

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


This program returns the GCD of the command line args inputed by the user ONLY from least to greastest. For example:

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

This program returns: "The GCD of the command line args is 5"

However, the problem I am running into is if the user types for example:

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

This program returns: 15

Can someone tell me how to fix this issue?

This is what I am 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 and print statements
 int i,x,y,min;
 printf("Number of command line args is %d\n", argc);
 printf("The GCD is:\t");

 //This is the 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 the converted integral number as an int value
  x=atoi(argv[i]);
  for(i=2;i<argc;i++){
  y=atoi(argv[i]);
   }

   //The following code gets the GCD and prints from the 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 for loop
    }//End IF statement
   }//End For loop
  }//End of MAIN

Solution

  • I've cleaned it up, this should work for you:

    Initialize every variable before you consider it up for calculation in your code.

    #include<stdio.h>
    #include<string.h>
    
    //Main Method
    int main(int argc, char *argv[]){
    
    //Declared variables here and print statements
     int i,x,y,gcd;
     printf("Number of command line args is %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