Arfater Rahman
Arfater Rahman

Reputation: 133

How to print nth number series in java

Could anyone please help me to print below series in java . I am trying to use below code but it seems not working correctly.

Desired output:


 9  18  27  36  45   
 9  18  27  36   
 9  18  27   
 9  18   
 9 

My code :

public class NumberSet {
    public static void main (String args[])
    {
        int i = 0, j=0;        
        for (j=1;j<=5;j++)
        {
            for (i=1;i<=50;i++)
            {
                if (i%9 ==0)
                {
                    System.out.print(" " + i + " ");
                }
            }
            System.out.println();
        }      
    }
}

Output of my code:


 9  18  27  36  45 

 9  18  27  36  45 

 9  18  27  36  45 

 9  18  27  36  45 

 9  18  27  36  45 

Thanks for your help in Advance.

Arfater

Upvotes: 0

Views: 202

Answers (3)

kelvincer
kelvincer

Reputation: 6138

Try this:

enter code here

public class Myclass {

     public static void main(String args[])

     {
        int num = 5;

        for (int i = 0; i < 5; i++, num--)
        {
          for (int j = 1; j <= num; j++ )
          {
            System.out.print(9*j + " ");
          }
          System.out.println();
        }

      }
}

Upvotes: 0

Sarjit Delivala
Sarjit Delivala

Reputation: 567

Try this:

public class NumberSet {
    public static void main (String args[])
    {
        int i = 0, j=0, mul= 1;        
        for (j=5;j>=1;j--)
        {
           mul = 1;
           for (i=1;i<=j;i++)
           {
              System.out.print(" " + mul++ * 9 + " ");
           }
           System.out.println();
        }      
    }
}

Hope this helps u...

Upvotes: 0

merlin2011
merlin2011

Reputation: 75565

First, you can generate multiplies of 9 more efficiently by multiplying by 9 than by looping over all numbers and checking if they are divisible by 9.

Second, you can simply change the order of the outer loop, and make the inner loop variable depend on the outer loop variety to get different behavior for every iteration of the outer loop.

public class NumberSet {
public static void main (String args[])
{
    int i,j;
    for (j=5;j>=1;j--)
    {
        for (i=1;i<=j;i++)
        {
            System.out.print(" " + i*9 + " ");
        }
        System.out.println();
    }

}
}

Output:

 9  18  27  36  45 
 9  18  27  36 
 9  18  27 
 9  18 
 9 

Upvotes: 4

Related Questions