简体   繁体   中英

convert nested for loop into a nested while loop JAVA

I'm a beginner and I need to convert this "for" loop into a "while" loop.

int s = 0;
int t = 1;

for (int i = 0; i < 5; i++) {
    s = s + i;
    for (int j = i; j > 0; j--) {
        t = t + (j - 1);
    }
    s = s + t;
    System.out.println("T is " + t);
}
System.out.println("S is " + s);

I tried this and it didn't work

int s = 0;
int t = 1;
int i = 0;

while (i < 5)
    i++;
{
    s = s + i;
    int j = i;

    while (j > 0)
        j--;
    {
        t = t + (j - 1);
    }
    s = s + t;
    System.out.println("T is " + t);
}
System.out.println("S is " + s);

the output was T=0 and S = 5 when it should read

T is 1
T is 1
T is 2
T is 5
T is 11
S is 30

thanks

int s = 0;
int t = 1;
int i = 0;

while (i < 5) 
{
    s = s + i;
    int j = i;

    while (j > 0) 
    {
        t = t + (j-1);
        j--;
    }
    i++;
    s = s + t;
    System.out.println("T is " + t);
}
System.out.println("S is " + s);

You should look into the syntax more carefully. Otherwise you were executing the blocks single time.

Earlier you were running this

while (i < 5) 
    i++;

Which is basically executing the loop 5 times and after the end of the loop i gets the value of 5.

After that we are running the block and we encounter the while loop again.

while (j > 0) 
        j--;

It executes 5 times again. So it would be j=0 after this loop ends.

So you end up with t=0 and s=5 . That's it.

The i++; should be inside the loop's brackets, not placed before. Same with j .

while (i < 5) 
{
    s = s + i;
    int j = i;

    while (j > 0) 
    {
        t = t + (j-1);
        j--; // j needs to be incremented here
    }
    s = s + t;
    i++; // i needs to be incremented here
}

As it currently is, you have a loop where the only statement is i++; , and then the rest of the code, which is in its own code block (or local scope), is executed only once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM