Tams Tams - 3 months ago 6
Java Question

Printing Small Numbers Between 1 and 100 in Java

I'm new to Java and this is a simple question but i'm having trouble printing small numbers between 1 and 100. Small numbers are those less than 20 and I want my program to print out "small x" for each small number.

When I run this I'm not getting what I'm suppose to I just get "small x" printed 100 times.

Here's my code:

class ExerciseA {
public static void main(String[] args) {
int x = 1;
while ( x < 100 ) {
x = x + 1;
if( x > 20) {
System.out.println("small x");
}
}
}
}

Answer

> means greater, but you want lesser. So use <. Another thing in your code 1 would not be printed as it's being incremented before printing. This should be:

int x = 0;
while ( x  <  100 ) {
    x = x + 1;
    if( x < 20) {
     System.out.println("small x");
     // System.out.println("small "+x); // if you want to print like small 1, small 2 etc.
  }
}