GoogleTag

Google Search

[Programming] Question 26: Write a C program to find the GCD of two numbers

 

#include <stdio.h>

int main() {
	int num1, num2, i, gcd;

	printf("Enter two positive integers: ");
	scanf("%d %d", &num1, &num2);

	for(i=1; i <= num1 && i <= num2; ++i) {
		// Check if i is a factor of both num1 and num2
		if(num1 % i == 0 && num2 % i == 0)
			gcd = i;
	}

	printf("GCD of %d and %d is %d\n", num1, num2, gcd);

	return 0;
} 

Inside the main() function:

- Integer variables `num1`, `num2`, `i`, and `gcd` are declared to store the input numbers, loop iterator, and the greatest common divisor respectively.

- The user is prompted to enter two positive integers.

- A for loop iterates from 1 up to the smaller of the two numbers.

- Within the loop, it checks if the current value of `i` is a factor of both `num1` and `num2`.

- If it is, `i` is assigned to `gcd`.

- Finally, the program prints the greatest common divisor.




Featured Posts

SQL Interview Questions Topics

 SQL Topics to prepare for interviews,   SQL Basics: Introduction to SQL SQL Data Types DDL (Data Definition Language): C...

Popular Posts