Simple For Loop Problem


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: Simple For Loop Problem

  1. #1
    Join Date
    Oct 2004
    Location
    Chicago
    Posts
    108

    Question Simple For Loop Problem

    I am trying to generate a simple multiplication table, at this point (I am not worried about all the spaces between the numbers), I required to do this using three nested for loops. I have done this using two loops, but I need to use a third one. All i got my code to do using three is print out the first row of numbers, and the first column, but i could not figure out the third loop with the actual values of the numbers being multiplied. Does anybody know if im doing something wrong with the nesting of the loops or is it something else..?



    -----------------------------------------------------------
    class multiplication{
    public static void main(String[]args){
    int j;//horizontal numbers
    int i;//vertical numbers
    System.out.println("\n\tMultiplication Table\n");
    System.out.print(" ");
    for(j=1;j<=12;j++){
    System.out.print(" "+j);//Prints First line of horizontal numbers
    }
    System.out.println();
    for(i=1;i<=12;i++){
    System.out.println(" "+i);
    }
    for(i=i;i<12;i++){
    System.out.print(" "+j*i);
    }
    }

  2. #2
    Join Date
    Oct 2004
    Location
    UK
    Posts
    12
    Try:

    Code:
    class multiplication
    {
        public static void main(String[]args)
        {
            System.out.println("\n\tMultiplication Table\n");
            System.out.print(" ");
            
            for(int j = 1; j <= 12; j++)
            {
                System.out.print("  " + j);
            }
            System.out.println();
            
            for(int i = 1; i <= 12; i++)
            {
                System.out.print(" " + i);
            
                for(int k = 1; k <= 12; k++)
                {
                    System.out.print(" " + k * i);
                }
                
                System.out.println();      
            }
        }
    }
    If you want to get the formatting right you'll need to play around with determining the number of characters occupied by each int and thus how many spaces to print after each.

  3. #3
    Join Date
    Oct 2004
    Location
    Chicago
    Posts
    108

    Thumbs up

    Thanks alot

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center