Welcome to the World of Online Learning:
Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Write a Java Program to Find GCD of two Numbers
PROGRAM: Java Program to Find GCD of two Numbers
/* Java Program to Find GCD of two Numbers*/
1: Find GCD of two numbers using for loop and if statement
class Main {
public static void main(String[] args) {
// find GCD between n1 and n2
int n1 = 81, n2 = 153;
// initially set to gcd
int gcd = 1;
for (int i = 1; i <= n1 && i <= n2; ++i) {
// check if i perfectly divides both n1 and n2
if (n1 % i == 0 && n2 % i == 0)
gcd = i;
}
System.out.println(“GCD of ” + n1 +” and ” + n2 + ” is ” + gcd);
}
}
2: Find GCD of two numbers using while loop and if else statement
class Main {
public static void main(String[] args) {
// find GCD between n1 and n2
int n1 = 81, n2 = 153;
while(n1 != n2) {
if(n1 > n2) {
n1 -= n2;
}
else {
n2 -= n1;
}
}
System.out.println(“GCD: ” + n1);
}
}
3: GCD for both positive and negative numbers
class Main {
public static void main(String[] args) {
// find GCD between n1 and n2
int n1 = 81, n2 = 153;
while(n1 != n2) {
if(n1 > n2) {
n1 -= n2;
}
else {
n2 -= n1;
}
}
System.out.println(“GCD: ” + n1);
}
}