For this lab, you need to create three simple methods that will count from 1 to
ID: 3601009 • Letter: F
Question
For this lab, you need to create three simple methods that will count from 1 to 630 by 37s. One method will use a for loop; one using a while loop, and one using a do loop. In each of these methods, label the output for the type of loop and print the values on a single line. In the application method, instantiate the class and call the three methods.
Here is a sample output:
Using a for loop:
1 38 75 112 149 186 223 260 297 334 371 408 445 482 519 556 593 630
Using a while loop:
1 38 75 112 149 186 223 260 297 334 371 408 445 482 519 556 593 630
Using a do loop:
1 38 75 112 149 186 223 260 297 334 371 408 445 482 519 556 593 630
That's all there's to it. Just use the loops to print out these values.
Note: There are actually two forms for the for loop in Java. For this lab, you must use the form that has two semicolons within the parentheses. This is the one presented in the notes this week. Later, we'll learn about the other for loop.
Check Level
For the check level, add punctuation. That is put commas between the values and a period at the end of the line.
Note: There should be no comma before the first value, nor after the last.
Using a for loop:
1, 38, 75, 112, 149, 186, 223, 260, 297, 334, 371, 408, 445, 482, 519, 556, 593, 630.
Using a while loop:
1, 38, 75, 112, 149, 186, 223, 260, 297, 334, 371, 408, 445, 482, 519, 556, 593, 630.
Using a do-while loop:
1, 38, 75, 112, 149, 186, 223, 260, 297, 334, 371, 408, 445, 482, 519, 556, 593, 630.
For check credit, do not use the if statement within your methods.
Explanation / Answer
class Main{
// for loop
public void forloop()
{
System.out.print(1);
for(int i=38;i<=630;i=i+37)
{
System.out.printf(", %d",i);
}
System.out.println(".");
}
// while loop
public void whileloop()
{
int i = 38;
System.out.print(1);
while(i<=630)
{
System.out.printf(", %d",i);
i = i + 37;
}
System.out.println(".");
}
// do while loop
public void dowhileloop()
{
int i = 38;
System.out.print(1);
do
{
System.out.printf(", %d",i);
i = i + 37;
}while(i<=630);
System.out.println(".");
}
// main method which is driver
public static void main(String[] args)
{
Main a = new Main();
a.forloop();
a.whileloop();
a.dowhileloop();
}
}
/*
SAMPLE OUTPUT
1, 38, 75, 112, 149, 186, 223, 260, 297, 334, 371, 408, 445, 482, 519, 556, 593, 630.
1, 38, 75, 112, 149, 186, 223, 260, 297, 334, 371, 408, 445, 482, 519, 556, 593, 630.
1, 38, 75, 112, 149, 186, 223, 260, 297, 334, 371, 408, 445, 482, 519, 556, 593, 630.
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.