Friday, January 25, 2013

Nesting for Loops


for loop within another for loop is useful when you need to work with product of more than one set. That maybe a little vague, I would say -- when you need to work with Cartesian products, but I don’t think that will help the vagueness at all. Let me try again.
Imagine the multiplication table, if we were to generate the multiplication table, the size of which is 3 rows by 5 columns, it would look like this
We all know how to do this arithmetically, but if we were to write a code for this using Java, it may stomp us for a little while. Look closely though and you will start to see a plan of attack. That is, if I write a for loop to walk through the values of the first column (1..6), it would look like.
for(int i=1; i<=6 ; i++) {
    print(i);
    }
Let’s make a minor change on the statement inside the for loop
for(int i=1; i<=6 ; i++) {
    print(i * 1);
}   
This does not really change our output arithmetically, anything multiplied by 1 is equal to itself. This small modification though gives us further insight into our Cartesian problem and one step closer to the solution.
We can programatically increase the value of the multiplier by one, which then allows us to generate the values for the rows (2..4). We can use another loop inside the first for loop.
    for(int i=col; col<=6 ; col++) {
        for(int row=1;row<=4;row++) {
            print(col*row);
        }
    }



Call me and you will get the knowledge and skills you need instantly.
For inquiries contact me on my mobile number or email me at inquiry@eglobiotraining.com. View my multiply site http://erwinglobio.multiply.com
 
 
Prof. Erwin M. Globio, MSIT
Senior IT Lecturer
Far Eastern University
Email Address: inquiry@eglobiotraining.com
Skype: erwinglobio
 
 
Call Now:
 
SMART: 09393741359
SUN: 09323956678

No comments:

Post a Comment