C++ Programming Code Examples C++ > For Loops and While Loops Code Examples Find HCF/GCD using for loop Find HCF/GCD using for loop Examples on different ways to calculate GCD of two integers (for both positive and negative integers) using loops and decision making statements. The largest integer which can perfectly divide two integers is known as GCD or HCF of those two numbers. The logic of this program is simple. In this program, small integer between number1 and number2 is stored in number2. Then the loop is iterated from i = 1 to i <= number2 and in each iteration, value of i is increased by 1. If both numbers are divisible by i then, that number is stored in variable hcf. When the iteration is finished, HCF will be stored in variable hcf. #include <iostream> using namespace std; int main() { int number1, number2, hcf; cout << "Enter two numbers: "; cin >> number1 >> number2; // Swapping variables number1 and number2 if number2 is greater than number1. if ( number2 > number1) { int temp = number2; number2 = number1; number1 = temp; } for (int i = 1; i <= number2; ++i) { if (number1 % i == 0 && number2 % i ==0) { hcf = i; } } cout << "HCF = " << hcf; return 0; }