this is a java programming question with loops and algerthims If you could help
ID: 3558049 • Letter: T
Question
this is a java programming question with loops and algerthims
If you could help me code it and explain why you did that code it would help a lot!! Thanks
Explanation / Answer
/******************************************************************
* This program demonstrates the procedure to calculate *
* greatest common divisor between two numbers using *
* Euclid algorithm *
* ****************************************************************/
//imported packages
import java.util.Scanner;
//main class section
public class find_gcd
{
public static void main(String args[])
{
//declaring and initializing object of scanner class
Scanner sc=new Scanner(System.in);
//declaring variables x,y
int x;
int y;
//prompt user to enter x value
System.out.println("enter the x value");
//read x value
x=sc.nextInt();
//prompt user to enter y value
System.out.println("enter the y value");
//read y value
y=sc.nextInt();
//while loop
this loop works on infinity condition, which is always
true,to compare and substract the x,y values till the
condition (x==y) is attained. And if the former
condition is obtained, break the loop.
while(true)
{
compare if x is greater than y then substract y value from x
if(x>y)
{
//substract y value from x
x=x-y;
}
compare if y is greater than x then substract x value from y
else if(y>x)
{
//substract x value from y
y=y-x;
}
compare if x is equal to y then break the loop
else if (x==y)
{
//break the loop
break;
}
}
//display the message to standard output
System.out.println("gcd(x,y) is:"+x);
}
}
Sample output:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.