Homework 3
Part A
Answer the following in a Word or .txt document. Attach this to the same submission as for part B
- Describe a specific situation where a while loop would make more sense than a for loop, and a specific situation
where a for loop would make more sense than a while loop.
"Specific situation" means: make up a program scenario; you may not use any scenario already used in
a classwork, homework, or lecture example.
- Explain why we would want to use a sentinel value. When can we not use a sentinel value?
Part B
We will use Java to do a few programming tasks. Here is an online Java IDE -- an editor that also lets you
run code right in the browser. Make a new .java file
More about using the IDE for this course.
The following example code shows using loops in java.
// This code sets things up for a general java program with input
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// done with setup, main code starts here
String secretWord = "swordfish";
// print and then read in a String from the user
System.out.println("Guess the word?");
String user = scan.next();
// while the user's word is not the same as the secret
// note .equals() for checking string equality in java
while (! user.equals(secretWord)) {
System.out.println("Wrong! Try Again");
user = scan.next();
}
System.out.println("You got it right!");
// a for loop to print numbers from 0 to 9
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
// nested for loops to print a grid of X's
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
System.out.print("X"); // print continues on the same line
}
System.out.println(); // println moves to a new line
}
// main code ends (still need the below two lines!!)
}
}
Do each in its own program:
- Test the users on their squares knowledge from 1*1 to 9*9 --
for each number from 1 to 9, ask the user for its square, and make them keep trying to guess it until they get it right, then congratulate them for getting it right.
-
Print a table of sums from 1+1 to 5+5 using one nested loop structure.
[EC +10] Also print headers on the rows and columns. The top header can be done in a separate loop. It might look like
---1---2---3---4---5
1| 2 3 4 5 6
2| 3 4 5 6 7
3| 4 5 6 7 8
4| 5 6 7 8 9
5| 6 7 8 9 10