- What is gcd ?
Using if conditional statement and for loop.
Read 2 numbers from user and print the gcd of these number.
Code
//Program to find gcd of 2 numbers import java.util.Scanner; public class gcd { public static void main(String args[]) { int i,gcdV=0; Scanner sc =new Scanner(System.in); System.out.print("Enter first number :"); int num1 = sc.nextInt(); System.out.print("Enter Second number :"); int num2 = sc.nextInt(); for(i=1; i<num1 && i<num2;i++) { if(num1%i==0 && num2%i ==0) { gcdV = i; } } System.out.println("GCD of "+num1 +" and "+ num2 +" is "+ gcdV); } }
OutputEnter first number :8 Enter Second number :12 GCD of 8 and 12 is 4
0 Comments