Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that takes two non-negative integers from standard input and cal

ID: 3797220 • Letter: W

Question

Write a program that takes two non-negative integers from standard input and calculates their greatest common divisor (gcd). Recall that the greatest common divisor of two integers is the largest positive integer that is a divisor of both numbers. For example, the gcd of 6 and 9 is 3; the gcd of 16 and 32 is 16; and. by number theory, the gcd of 0 and a, for a = 0, 1, 2, ... is a. At the start of the program, prompt the user to input two integers by printing "Calculate GCD (A, B). Input A B: ". If either input is negative, then print "Both inputs must be non-negative. ". If both inputs are non-negative, then print their gcd as "The gcd is . ", where is replaced by your calculated gcd. As part of your program, you must make a function that takes two integer arguments and returns their gcd as an integer. You can use the following function prototype: int gcd(int a, int b); Example input/output pairs (excluding the prompt) are provided below: Input: 6 9; Output: The gcd is 3. Input: 32 16; Output: The gcd is 16. Input: 4 0; Output: The gcd is 4. Input: -1 3; Output: Both inputs must be non-negative.

Explanation / Answer

PROGRAM CODE:

#include <stdio.h>

int gcd(int a, int b)
{
   int gcd;
   if(a==0)
       return b;
   else if(b==0)
       return a;
   else
   {
       for(int i=1; i <= a && i <= b; ++i)
   {
   // Checks if i is factor of both integers
   if(a%i==0 && b%i==0)
   gcd = i;
   }
   }
   return gcd;
}

int main(void) {
   int a,b;
   printf("Calculate GCD(A,B). Input A B: ");
   scanf("%d %d", &a, &b);
   if(a<0 || b< 0)
   {
       printf("Both inputs must be non-negative. ");
       exit(0);
   }
   else
   {
       printf("The gcd is %d",   gcd(a,b));
   }
   return 0;
}

OUTPUT:

RUN #1:

RUN #2:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote