Incrementing within nested loop - java

I have a pretty straight forward question. In the program below, why does i not increment to 1 in the first iteration of the for loop? My compiler shows that for the first run, j is not less than i because they are both 0. Thanks!
int i;
for (i = 0; i < 5; i++) {
int j = 0;
while (j < i) {
System.out.print(j + " ");
j++;

The value of i will be 0 for the first iteration and 1 for the second. Take the following:
for (int i = 0; i < 5; i++) {
// loop code
}
The above for loop is just syntactic sugar for:
{
int i = 0;
while (i < 5) {
// loop code
i++;
}
}
Note that the outer braces are there to show that after the for loop exits the variable i is no longer in scope.

while (j <= i)
Output: 0 0 1 0 1 2 0 1 2 3 0 1 2 3 4

Related

The iteration variable is +1 outside the for-loop?

I have an array of size 4 and I want to check if the array contains the number 8 (which it obviously does not, the code is just for testing).
In the for-loop j goes from 0 to 3, so the final value of j in the loop is 3. However I don't follow why the value of j after the loop has been changed to 4, why is it still not 3?
public class Test {
public static void main (String[] args) {
int[] a = new int[4];
a[0] = 2;
a[1] = 3;
a[2] = 4;
a[3] = 5;
int n = a.length; // n = 4
int number = 8;
int j;
for (j = 0; j < n; j++) {
if (a[j] == number) {
System.out.println("The number is at place " + j);
break;
}
// Last value of j is 3:
System.out.println("Value of j after each iteration " + j);
}
// But here j is 4?
System.out.println("Value of j after the for-loop: " + j);
}
}
The output:
Value of j after each iteration 0
Value of j after each iteration 1
Value of j after each iteration 2
Value of j after each iteration 3
Value of j after the for-loop: 4
Yes because at the end of a for loop there is an increment to the variable. A for loop can be rewritten as:
int j = 0;
while(j < n) {
//code
j++;
}
So on the last iteration j will be incremented, it will go to the condition, and it will be false so the body of the for loop will not be entered. In order for the loop to end, j has to be more than or equal to the condition.
Think about it...
This is your for loop:
for (j = 0; j < n; j++){
//your code here
}
You start your for loop with j = 0 and every time you iterate through it, you have to check if the value is less than n ( j < n ).
To achieve that you have to increment it on every iteration.
So this is what happens for n = 4:
1st iteration:
j = 0;
0 < 4 == true;
// you execute your code
j++; //As you can see you increment before you continue to the next iteration
2nd iteration:
j = 1; // j now equals 1 because you incremented it on the previous iteration
1 < 4 == true;
// you execute your code
j++;
3rd iteration:
j = 2;
2 < 4 == true;
// you execute your code
j++;
4th iteration:
j = 3;
3 < 4 == true;
// you execute your code
j++;
5th iteration:
j = 4;
4 < 4 == false;
// loop ends
As you can see, when your code is about to start the fifth iteration, the j variable now equals 4 so it doesn't pass the j < n criteria.
However, it still incremented in the 4th iteration so you get j = 4.
This was how my teacher explained it to me when I was just starting my coding education, I hope it helps you as it helped me!
New to programming?
for(initialization; booleanExpression; updateStatement) {
; // Body
}
The steps is,
Initialization statement executes
If booleanExpression is true continue, else exit loop
Body executes
Execute updateStatements
Return to Step 2
So the end value should be 4

I just tried this code in java and here is my output 011. Can anyone please explain me how this happend

for(int i =0; i <= 1; i++)
{
for(int j =0; j <= i; j++)
{
System.out.print(i);
}
}
Output: 011
I just want to know how this happened.
You have two loops:
for(int i =0; i <= 1; i++) //external loop
for(int j =0; j <= i; j++) //internal loop
System.out.print(i);
The external loop has 2 iteration since it starts in i = 0 and ends in i = 1 when i is incremented to i = 2 you exit the for loop.
The internal loop has i + 1 iterations.
When i = 0 the internal loop iterates once. That`s when you get the 0.
When i = 1 the internal loop iterates twice (j = 0 and j = 1). That`s when you get 11

nested loops and increment user input

I'm trying to print user input numbers and indent them by that number of spaces. I can't seem to get the numbers to indent, however, I am able to print them all vertically. Any help? Here is my code.
for (i = 0; i <= userNum; i++) {
for (j = 0; j < i; j++) {
System.out.println(i);
break;
If a user entered the number 3, my output would currently look like this:
1
2
3
When it should look like this:
1
2
3
This should do it
for (int i = 0; i <= userNum; i++) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
System.out.println(i);
}
You can try to add another for loop within that for loop. The print statement would be after this nested for loop. The inner loop would start from zero to i+1. In this for loop, you can print the spaces or tabs. Then after the for loop you can print the number. Make sure you do not include a new line inside the print statement in the inner for loop.
You haven't added the code yet to add the indenting. Try this:
public static void printNum(int userNum) {
for (int i = 0; i < userNum; i++) {
System.out.print(" ");
}
System.out.print(userNum+ "\n");
}
Calling it with:
printNum(10);
printNum(1);
printNum(2);
printNum(3);
Gives the following:
run:
10
1
2
3
BUILD SUCCESSFUL (total time: 0 seconds)
I hope this solves your problem :
for (i = 1; i <= userNum; i++)
System.out.format("%+(i-1)+s]%n", i);
public class Program {
public static void main(String[] args) {
int i = 3; // or your userNum
// this loop will iterates through 1 to i (or 1 to userNum for you)
for (int j = 1; j <= i; j++) {
// this loop iterates until j2 equals j (e.g. if j = 5, this loop will iterates 4 times)
for (int j2 = 1; j2 < j; j2++) {
// prints the space(s)
System.out.print(" ");
}
// prints the current number (in the first loop) and line break
System.out.println(j);
}
}
}

Upside-down triangle of numbers

I'm a beginner to Java and can't figure out how to print an upside down triangle of numbers. The numbers should decrease in value by 1 for each row. Ex. Number of rows: 6;
Print:
666666
55555
4444
333
22
1
So far this is what I came up with; (int nr is scanned input from user)
for (int i = 1; i <= nr; i++) {
for (int j = 1; j <= nr; j++) {
System.out.print(nr);
}
nr--;
System.out.println();
}
By having nr--; the loop gets shorter and I cant figure out how to keep the loop going for nr-times, yet still decreasing the amount of numbers printed out.
You are right in that you need to write a loop to print a line for each number, starting at nr and decreasing by 1 until you get to 0. But you also have to print a variable number of numbers at each line. To do that, a nested loop could be used to print the number the amount of times necessary.
Since you start printing at nr and decrease until you reach 1, you could try writing an outer loop that decrements rather than increments. Then use a nested loop to print the number the required number of times. For example:
for (int i = nr; i > 0; i--) {
for (int j = 0; j < i; j++) {
System.out.print(i);
}
System.out.println();
}
In this case, you can use a single while loop and two decreasing variables:
i - number of the row - from 6 to 1
j - number of repetitions in the row - from i to 1:
int i = 6, j = i;
while (i > 0) {
if (j > 0) {
// print 'i' element 'j' times
System.out.print(i);
--j;
} else {
// start new line
System.out.println();
j = --i;
}
}
Output:
666666
55555
4444
333
22
1
See also: Printing a squares triangle. How to mirror numbers?
You can't decrease nr and still use it as upper limit in the loops. You should in fact consider nr to be immutable.
Instead, change outer loop to count from nr down to 1, and inner loop to count from 1 to i, and print value of i.
for (int i = nr; i > 0; i--) {
for (int j = 0; j < i; j++) {
System.out.print(i);
}
System.out.println();
}
Your problem is that you are changing nr, try:
int original_nr = nr;
for (int i = 1; i <= original_nr; i++) {
for (int j = 1; j <= nr; j++) {
System.out.print(nr);
}
nr--;
System.out.println();
}

Struggling with nested for loops

Alright so, I'm new to nested for loops adn I'm having a bit of an issue on understanding them. I've read many guides, but I still don't fully understand.
Alright the prompt:
Write nested for loops that produce the following output:
000111222333444555666777888999
000111222333444555666777888999
000111222333444555666777888999
What I have so far
for(int num2 = 0; num2 <= 9; num2++) {
for(int num1 = 0; num1 <= 2; num1++) {
System.out.println(num2 + " " + num2 + " " + num2);
}
}
And the output is
0 0 0
0 0 0
0 0 0
1 1 1
1 1 1
1 1 1
2 2 2
2 2 2
2 2 2
3 3 3
3 3 3
3 3 3
4 4 4
4 4 4
4 4 4
5 5 5
5 5 5
5 5 5
6 6 6
6 6 6
6 6 6
7 7 7
7 7 7
7 7 7
8 8 8
8 8 8
8 8 8
9 9 9
9 9 9
9 9 9
What am I doing wrong?
You got 3 copies of each number.
the outer loop:
for (int i = 0; i < 10; i++) {
chooses which number you want to print so that is fine.
The inner loop however is comparing j against the chosen number. You want 3 copies, not a variable number of copies. This change will make 3 copies:
for (int j = 0; j < 3; j++) {
You also don't need this:
System.out.println(i);
EDIT: I just noticed you need 3 of these outputs.
add an outer loop:
for (int x = 0; x < 3; x++) {
and a blank space
System.out.println(" ");
So the final result should be:
for (int x = 0; x < 3; j++) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(i);
}
}
System.out.println(" ");
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 10; j++) {
System.out.print(j + "" + j + "" + j);
}
System.out.println();
}
In the program provided by you the following events take place:-
In first loop variable i is initiated, condition for loop is checked and then it moves to the second loop if condition is true.
Now second loop iterates over the value of j until the condition is false and then control returns to the first loop.
Try to follow the working of loop and you can see yourself where were you wrong.
Try this:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 10; j++) {
for (int k = 0; k < 3; k++) {
System.out.print(j);
}
}
System.out.println("");
}
loop 1: You want the sequence 3 times, each occurrence on its own line.
loop 2: You want the sequence to have digits 0 through 9 ascendingly.
loop 3: You want the sequence to have each digit in succession 3 times.
for (int k = 0; k<3, k++){
for (int i = 0; i< 10; i++) {
for (int j = 0; j < 3;j++) {
System.out.println(i);
}
}
System.out.println("")};
}
}
for(int k=0;k<3;k++) {
for (int i = 0; i< 10; i++) {
for (int j = 0; j < 3;j++) {
System.out.println(i);
}
}
}
Although I am by far most inexperienced guy here, I think this should give exact output you're looking for.

Categories