Showing posts with label for. Show all posts
Showing posts with label for. Show all posts

Monday, 23 May 2011

Nested for Loop

It is possible to nest one for loop inside another. To demonstrate this structure, we'll concoct a program that will print the multiplication table:


included files
void main()
{
 int cols,rows;
 for(row=1;rows<13;rows++)   /*outer loop*/
  {
   for(cols=1;cols<13;cols++) /*inner loop*/
   printf("%3d",cols*rows);
   printf("\n");
  }
 getch();
}


The output will be:
1   2   3   4   5    6   7    8   9    10   11    12
2   4   6   8.....................................24
.   .   .  .....................................  36
.   .   .  .....................................  48
.   .   .  .....................................  60
.   .   .  .......................................72
.   .   .  .......................................84
.   .   .  ........................................
12  24  36  48 60   72  84   96  108  120   132  144




If you have any question, you can ask me freely!

Saturday, 21 May 2011

The for Loop

It is often the case in programming that you want to do something a fixed number of times. Perhaps you want to calculate the paychecks for 120 employees  or print out the squares of all the numbers from 1 to 50. The for loop is ideally suited for such cases.


Let's look at a simple example of a for loop which will print numbers from 0 to 9:


included files
void main()
{
 int count;
 clrscr();
 for(count=0;count<10;count++)
 printf("Count=%d\n",count);
 getch();
}


The output will be:
   Count=0
   Count=1
   Count=2
   Count=3
   Count=4
   Count=5
   Count=6
   Count=7
   Count=8
   Count=9


This program's role in life is to execute a printf() statement 10 times.


Structure of the for Loop:
The loop expression is divided by semicolons into three separate expressions: the "initialize expression", the "test expression", and the "increment expression".
==================================================
Expression                                    Name                                     Purpose
==================================================
count=0                          Initialize expression         Initializes loop variable
count<10                            Test expression              Tests loop variable
count++                          Icrement expression         Increments loop variable
---------------------------------------------------------------------------------------------


The Body of the Loop:
Following the keywords for and the loop expression is the body of the loop: that is, the statement (or statements) that will executed each time round the loop. In our above example, there is only one statement:


printf("Count=%d\n",count);


Note that this statement is terminated with a semicolon, wheras the for with the loop expression is not.




If you have any questions, you can ask me freely!