Computer Science, asked by khadargaas143, 8 months ago

1. Write a while loop that verifies that the users enters a positive integer value

Answers

Answered by Mahikmr
0

Answer:

The do-while loop works by executing the "do" part first and then checking the "while" condition. So, you first ask the user for a number, and if you don't like it, you just keep asking them for another one.

Let me know if anything is unclear!

Edit:

If you want to give the user an error message when the number is negative, then you need to consider a modified algorithm. You want to

Ask the user for a number (without displaying an error message)

As long as the number is not positive, tell the user it's not acceptable and ask for another one.

I assume you know about the various loops in Java like for, while, do-while. See you if you can code the logic for this one on your own and comment if you're having trouble.

Answered by avinashkumar288
0

import java.util.Scanner;

public class GCD {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter a positive integer: ");

int firstN = input.nextInt();

System.out.print("Enter another positive integer: ");

int secondN = input.nextInt();

System.out.println("The GCD of " + firstN + " and " + secondN + " is: " + gCd(firstN, secondN));

}

public static int gCd(int firstN, int secondN) {

if(secondN == 0) {

return firstN;

} else

return gCd(secondN, firstN%secondN);

}

}

Similar questions