Displaying all the Odd number between 1 - 99 in java using Nested For Loop

32,908

Solution 1

first you need to calculate your number, try

for (int i=0; i<=9; i++)
    {
        for (int j=1; j<=10; j++)
        {
            int number = j+i*10
            if (number%2 !=0)
            System.out.print(number + " " );
        }
        System.out.println();
    }

but this problem you can solve with single loop

 for (int i=1; i<=99; i++)
 {
      if (number%2 !=0)
          System.out.print(number + " " );

      if (number%10 ==0)
          System.out.println();
 }

Solution 2

for ( i = 1; i < 100; i+=2 ) {
    System.out.print(i);
}
System.out.println();
Share:
32,908
Luke
Author by

Luke

Updated on July 07, 2022

Comments

  • Luke
    Luke almost 2 years

    Currently I'm only able to display odd numbers of 1 3 5 7 9. However, I would like to display all the odd numbers from 1 - 99 with 9 rows and 5 col. May I know how am I able to display from 11 onwards rather than just 9 rows of 1 3 5 7 9.

    Below is the code I'm stuck with.

    public static void main(String args[])
    {
        for (int i=1; i<=9; i++)
        {
            for (int j=1; j<=10; j++)
            {
                if (j%2 !=0)
                System.out.print(j + " " );
            }
            System.out.println();
        }
    }
    
    • Maroun
      Maroun over 9 years
      What's your problem?
    • Olavi Mustanoja
      Olavi Mustanoja over 9 years
      You should re-read how for loops work. In your current solution you are looping 10 times 9 times (sounds retarded, I know). My hint for you: you need only one loop.
    • Luke
      Luke over 9 years
      I'm only able to display 1 3 5 7 9 for all the 9 rows but I wanted all the odd numbers from 1 - 99 for 9 rows.
    • RealSkeptic
      RealSkeptic over 9 years
      Did they ask you to use nested loops? Because this can be achieved with one simple loop.
  • Zéychin
    Zéychin over 9 years
    If you put i += 2 instead of i++ you can get rid of the modulus check. Functionally the same though.
  • Kent
    Kent over 9 years
    in your output, I don't understand why there are two spaces in 1st row? (I meant between numbers)
  • Maroun
    Maroun over 9 years
    @Kent There shouldn't be, fixed :) Instinctively I aligned the table when I posted the output.