OOP-JAVA Practical 9
- Aim: Write a method with following method header. public static int gcd(int num1, int num 2)Write a program that prompts the user to enter two integers and compute the gcd of two integers.
- Code:
import java.util.*; public class practical9{ public static int gcd(int n1,int n2){ int gcd=1; for(int i=1;i<=n1 && i<=n2;i++){ if(n1%i==0 && n2%i==0){ gcd=i; } } return gcd; } public static void main(String[] args){ int x,y; Scanner s=new Scanner(System.in); System.out.println("Enter two numbers"); x=s.nextInt(); y=s.nextInt(); System.out.println("GCD of given 2 numbers:"+gcd(x,y)); } }
- Output:
Comments
Post a Comment