The for and Nested-for statements can be gathered in multiply way, it is usually building the for statement into another for statement in the case of ( Nested-for statements ), but in Syntax for the for statement it is easier to use and initialize or add increment as follows.
.
for( initialization; boolean expression; increment, decrement or update)
{
Statement here .......
}
Now this is another example to multiply numbers in the shape of multiplication table to Nested-for statements, because we have to add columns and rows, so two or three the for statement in one not matter, it depends on the programmer.
public class columnsAndRows
{
public static void main(String[]args)
{
System.out.println("Multiply numbers");
System.out.println("----------------");
for (int rows =1; rows <= 10; rows++) // Ten rows
{
for (int columns = 1; columns <= 6; columns++) // Nine columns
{
System.out.print(rows*columns + ", "); // Multiply row by columns and print them as one
// line has 5 column
}
System.out.println(" "); // To print 10 rows in print line
}
}
}
You have to know that we printed first columns after Multiplying them and add them in ( System.out.print ), That meant do not jump or print them in a new line, then we added (System.out.println(" ")) as lines with space. You may want to know that we added each one of these ( prntln And print ) with their correct for statements.
This is the output of the program
Multiply numbers
----------------
1, 2, 3, 4, 5, 6,
2, 4, 6, 8, 10, 12,
3, 6, 9, 12, 15, 18,
4, 8, 12, 16, 20, 24,
5, 10, 15, 20, 25, 30,
6, 12, 18, 24, 30, 36,
7, 14, 21, 28, 35, 42,
8, 16, 24, 32, 40, 48,
9, 18, 27, 36, 45, 54,
10, 20, 30, 40, 50, 60,
0 comments:
Post a Comment