Converting a while loop to a for loop and a for loop to a while loop.
Hi guys,
I want to convert the while loop of this code to a for loop, and the for loop to a while loop but i tried and couldnt figure out, what i need to do?
The results have to be the same.
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++;
}
}
Re: Converting a while loop to a for loop and a for loop to a while loop.
Re: Converting a while loop to a for loop and a for loop to a while loop.
How does a for loop work? You basically are running your while loop as a for loop so why does it matter?
Re: Converting a while loop to a for loop and a for loop to a while loop.
basically both loops function the same. If it is code you want to change for personal reasons, or an assignment, I will give you standard loop protocol.
for loops are used when you can more or less predict the number of iterations. traveling through an array, counting to 10, and so forth. Typically the incrementation is predictible and linear +1 every time being the most common, though it can be
words to explain:
do something 10 times, starting at 1 and going to 10 "for(int idx = 1; idx <=10; idx++) { //stuff }"
a while loop is best for situations you are asking for something to happen first. while the user has not exited, while the pie is uneaten, while any Boolean expression you can think of. it can still be mathematical.
do something until i say you are done. never ever stop until then. "while(!done) { //stuff(better change done Boolean somewhere!)"
you could use a math expression while(numberOfCars != 7) { //stuff} this loop will run until cars = 7. hopefully its possible!
Hope this helps,
Jonathan