Casey Vanecek Casey Vanecek - 2 months ago 258
Java Question

Homework assignment using loops to count (Java)

The assignment is...


Write a while loop that prints 1 to
userNum
, using the variable
i
.
Follow each number (even the last one) by a space. Assume
userNum
is
positive. Ex:
userNum = 4
prints:
1 2 3 4



This is what I have:

int userNum = 0;
int i = 0;

userNum = 4; // Assume positive

while (i < 4) {
i = userNum - 1;
System.out.print(userNum + " ");
}

System.out.println("");


I keep getting an infinite loop error. Any help is greatly appreciated. I am new to Java and still trying to figure it out.

Answer

You should use i++

while (i < userNum) {
     i++;
     System.out.print(i + " ");
  }
Comments