In: Computer Science
JAVA
Lab Assignment #13: Looping Lab with both types of loops.
Lab 13 Part a:
Using a While Loop, write the code that does the following:
Lab 13 Part b:
Using a Do While Loop, write the code that does the following:
Include the following in your programs:
NOTE 1:
NOTE 2:
1. Declare all variables within the data declaration section of
each class and method. (-.1)
2 Do not get input on the same line as a variable
declaration. (-.1)
3. Do not place an equation for computation on the same line as
declaring a variable. (-.1)
3. Do not place an equation for computation on the
same line as an input
statement. (-.1)
Solution :
Initiallize n to -1. For both the while and do-while loops, write the condition for n to not be in the range [0-100] and continue till the condition is not satisfied.
Following is the Java code for the same :
import java.util.*;
class Main {
public static void main(String args[])
{
// initialisation expression
int n;
n=-1;
Scanner sc= new Scanner(System.in); //System.in is a standard input stream.
System.out.println("\nWhile loop demonstration : \n");
while(n<0 || n>100) {
// Prompt the user
System.out.println("\nEnter a score between 0 and 100(inclusive)\n");
n=sc.nextInt();
}
System.out.println("\nDo While loop demonstration : \n");
do
{ // Prompt the user
System.out.println("\nEnter a score between 0 and 100(inclusive)\n");
n=sc.nextInt();
}
while(n<0 || n>100);
}
}
Code demo for reference :