Replacing for with while loop.
Hey there,
I am currently attending my first year of computer programming languages and I have my first tests in a few weeks. My teacher gave me an example of exercises we can expect on our test.
One of the test exercises is this:
Code:
public void testWhileLoop(int limit)
{
int i = 1;
while ( i <= limit ) {
// Print a number of '*' characters
for (int j=0; j<i; j++) {
System.out.print("*");
}
// Print a 'newline' character
System.out.print("\n");
i++;
}
}
I got this piece of code. And now I have to replace the while loop with the for loop, and the for loop with the while loop. So basically turn those 2 arround.
Basically what this code does is: It asks the user for an input int. And say for example the user inputs 4. This code outputs:
*
**
***
****
Can you guys help me?
Thanks in advance!
Re: Replacing for with while loop.
Here's a suggestion to get you started
Why not replace the while loop with a for loop first, and see if you can get the code to run properly. Think about what the i++ does.
After that try and change the while loop
Re: Replacing for with while loop.
I tried to replace the loop but I just couldn't get a working solution. I kept getting endless loops or unwanted results. Could anyone help me a bit more on this one? Shouldn't be too much of a problem for
experienced java programmers I guess.
Re: Replacing for with while loop.
Its simple u can try.jst check the limit condition in for and no of time you need "*" in inside while.
Re: Replacing for with while loop.
If you look at your code from a great distance, you see something like this:
Code:
int i= 1;
while (i <= limit) {
// here is code that uses, but doesn't change, variable i
i++;
}
I doesn't take rocket science to change the code to:
Code:
for (int i= 1; i <= limit; i++) {
// here is code that uses, but doesn't change, variable i
}
You can apply the same logic (but all reversed) to change your inner loop.
kind regards,
Jos