Reputation: 13
Hi I am currently in a AP java class in 11th grade. I need specific help on nested for loops counting to 100. I need 2 for loops and said I can't use the numbers 100.
for (int i = 1; i <= ???; i++){
for (int j = 1; j <= ???; j++){
System.out.print(j + " ");
}
}
I want it to count to 100 from 1 with 2 for loops. And no number 100s. I am going through it step by step the ones I tested, but couldn't figure out completely
more complete answer below:
for (int i = 0; i <= 9; i++){
for (int j = 1; j <= 10; j++){
System.out.print(i * 10 + j + " ");
}
}
Step 1 (from outer loop): variable i is declared with a value of 0. Step 2: Test case if i is less than or equal to 9, if true, run body of code in loop. if false, exit loop Step 3: if outer loop's test case is true, run body of code; declares j to 1, tests if j is less than or equal to 10 step 4: if inner loops' test case is true, run the print command
Upvotes: 1
Views: 4682
Reputation: 3085
I assume you want to count from 0 to 99, since you don't want to use 100, So this should do the job.
for (int i = 0; i <= 9; i++){
for (int j = 0; j <= 9; j++){
System.out.print(i + "" + j + "\n");
}
}
Edit 1: If you're interested in printing the range from 1 to 100 instead, You can Parse the string to integer before you print it, and add one to it.
for (int i = 0; i <= 9; i++){
for (int j = 0; j <= 9; j++){
System.out.print((Integer.parseInt(i + "" + j)+1) + "\n");
}
}
Upvotes: 1