C++ Program to Find GCD (Using ‘for’ loop for both negative and positive integers)

by | Jan 29, 2023 | C++, C++ Programs

Home » C++ » C++ Programs » C++ Program to Find GCD (Using ‘for’ loop for both negative and positive integers)

Introduction

This program will help you to find the GCD of two numbers.

The task is that the user will be asked to enter two integers, and then through this program GCD of both numbers will be computed.

GCD: Greatest common divisor, which is also called as Highest common factor (HCF)

The largest common number that can exactly divide both numbers is GCD. It means there should be no remainder left. Thus, we will use this logic in our code.

There are several methods to compute the GCD, and in those numerous methods, there are many syntaxes to perform a single program. In this program, we will first convert the negative values to the positive values and then compute GCD using for loop.

To understand this example, you should know about some concepts of C++ programming.

1. Operators

2. for loop

3. if, if-else, nested if-else statement

4. while and do-while loop

Note: The program written below will work for both positive numbers or both negative numbers or one positive and one negative number.

Program

#include<iostream>
using namespace std;
int main()
{
int num1, num2;
cout<<"Enter two positive integers: ";
cin>>num1>>num2;
// if either num1 or num2 or both are negative integers
if(num1<0)
{
num1=-num1;
}
if(num2<0)
{
num2=-num2;
}


// we will find a value that divides num1 and num2 completely
int GCD;
for(int i=1; i<=num1 && i<=num2; i++) // 'i' must be less than both of the numbers
{
if (num1%i==0 && num2%i==0) // if 'i' is completely dividing both the numbers
{
GCD=i;
}
}
cout<<"GCD: "<<GCD;
return 0;
}

 

Output

Explanation

The values of num1 and num2 can be positive or negative.

First of all, we will convert the negative values to positive values.

if(num1<0)

if num1 is negative, then its sign will get changed using the statement

num1=-num1;

Similarly, for num2.

After that, the for loop is used to compute the GCD.

num1 and num2 contain two values -8 and 64, respectively.

int GCD; declaration of the ‘GCD’ variable

for(int i=1; i<=num1 && i<=num2; i++)

the above loop will iterate until ‘i’ remains less than equal to both num1 and num2

if (num1%i==0 && num2%i==0)

This condition will get checked in each iteration; if both num1 and num2 are exactly divisible by ‘i’ the value of ‘i’ will be assigned to GCD.

Since at i=8 the above condition becomes true thus, the value of GCD printed is 8.

 

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author