GCD program written But some error

Ques : 4. WAP to find the GCD (Greatest Common Divisor) of two positive numbers using Euclid's Algorithm. The Euclidean Algorithm transforms a pair of positive integers (m, n) into a pair (d, 0) by repeatedly dividing the larger integer by the smaller integer and replacing the larger with the remainder. When the remainder is 0, the other integer in the pair will be the greatest common divisor of the original pair (and of all the intermediate pairs).

Doubt : Program not executing. Program.cpp has stopped working. How should I rectify it? Where is the error? Code s given below
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
#include <iostream>
using namespace std;

int main()
{
 int n1,n2;
 cin>>n1>>n2;
 
 while(n1 !=0 || n2!=0)
 {
 if(n1>n2)
 n1 = n1%n2;
 else 
 n2 = n2%n1;
}
cout<<n1<<endl;
cout<<n2;

return 0;
}
Last edited on
Check for line 10,
I think it's
while (n1 != 0 && n2 != 0)
Got it. It should be while(n1 && n2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
 
int main() 
{
    int a, b, num1, num2, temp, gcd;
    printf("Enter First Integer:\t");
    scanf("%d", &num1);
    printf("\nEnter Second Integer:\t");
    scanf("%d", &num2);
    a = num1;
    b = num2;
    while (b != 0) 
    {
            temp = b;
            b = a%b;
            a = temp;
    }
    gcd = a;
    printf("\nGreatest Common Divisor of %d and %d = %d\n", num1, num2, gcd);
    printf("\n");
    return 0;
}
Topic archived. No new replies allowed.