Click here to Skip to main content
15,885,537 members
Please Sign up or sign in to vote.
4.50/5 (3 votes)
See more:
Hello folks,

I am completely new to programming as well as to this amazing open source community. Recently I have started learning C/C++ at local institute here in Mumbai, India. I am quite good in basic high school mathematics but I am facing a lot of trouble to understand logic used in nested looping in programming. Last week I learned pattern making, using nested for loop in C, I got confused between the inner and out loops. Our trainer said outer loop deals with rows while the inner one deals with columns of the output (which happened to be numerical pyramid and various other shapes like simple steps and diamond shape). I know that we use loops when we need to repeat certain condition for specific known or unknown number of times (with respect to different scenarios) but in this specific code I could not figure out how does the control gets transfer between inner and outer loops. Here is the example of the code :

C++
int main () 
{
    int row,col;
    for (row=1; row<=3; row++)
    {
        for (col=1; col<=row; col++)
        {
		printf ("%d", row);
	}
        printf ("\n");
    }
    getch();
}


Output :

1
22
333


I know this is very basic problem but I have been trying hard from last couple of days to understand the logic behind this nested for loops so that I solve variety of problems, so can anybody please explain me what's the logic behind such coding and is there any decent book to understand methodology involved in this logic ?? thanks in advance.
Posted
Updated 12-Apr-17 14:09pm
v5
Comments
enhzflep 26-Aug-12 10:23am    
I've re-formatted your ode to make reading (& I hope) understanding it easier.
I've also changed the variable names to something a little more clear.
Volynsky Alex 26-Aug-12 11:23am    
Try read the "Programming In C++" book by Nell B. Dale,Chip Weems.
Chapter 6.5 ("Nested logic"), you can find a detailed explanation about the topic that interests you. Please see here: http://books.google.com
Volynsky Alex 26-Aug-12 11:24am    
and here:
http://mathbits.com/MathBits/CompSci/looping/nested.htm

Well, this is a basic example code for a nested loop. Not the smartest though as the inner loop counter j is not even used.

Most common use of this construction would be to browse through some objects (e.g. Car) and to search for a special argument (e.g. like highest top speed, certain color value "red", ...).
Also often used for making an average value if something, like e.g. the average gas consumption.
 
Share this answer
 
v2
int main () 
{
    int row,col;
    for (row=1; row<=3; row++)
    {
        for (col=1; col<=row; col++)
        {
		printf ("%d", row);
	}
        printf ("\n");
    }
    getch();
}


Firstly,
row=1, then condition will be checked, if condition is true it will enter the block
2ndly,
if condition is true control moves to the inner for loop where col=1 and again condition will be checked, if condition true it will entered inside

and value of row will be printed then col value will be incremented col++ and again condition will be checked if it false the control again move to upper for loop and incremented value of row, row++ and step moves till the upper condition get false.
 
Share this answer
 
v2
The inner loop executes completely for every iteration of the outer loop. For example, lets say we want to count the percentage of girls in each class in a school.

The outer loop would iterate over each class. For Each iteration(in this case each class), the inner loop would count the number of girls in that class and divide it by the number of students and store the result. The outer loop would then move on to the next class.

Hope this helps.

-Debdatta Basu
 
Share this answer
 
v2
Logic of loop 1)
C
for (row=1; row<=3; row++)

Until value of variable row is lowest or equal to 3, loop.

Logic of loop 2)
C
for (col=1; col<=row; col++)

Until value of variable col is lowest or equal to value of current row, loop.


Why your result is: 1,22,333? Becuase inside column-loop, you print a row no.

Iteration no.Value of rowValue of colComment
111Print row no. 1; col is equal row, the condition is true, so jump to the next row
221Print row no. 2
322Print row no. 2; col is equal to row, jump to the next row
431Print row no. 3
532Print row no. 3
633Print row no. 3; col is equal to row, exit form inside and outside loop


To "print" two-dimensional array, for example 3 x 3 cells, use:
C#
int row,col;
for (row=1; row<=3; row++)
  {
      for (col=1; col<=3; col++)
      {
          printf ("%d", col);
      }
      printf ("\n");
  }
  getch();
 
Share this answer
 
v2
C#
int main ()
{
    int row,col;
    for (row=1; row<=3; row++)
    {
        for (col=1; col<=row; col++)
        {
        printf ("%d", row);
    }
        printf ("\n");
    }
    getch();
}


Given this code, and having in mind that execution is sequential (unless you establish interruptions, timers, threads or events) then the code will go into the first loop and execute the second loop 3 times.

The idea is that you will go inside the second loop for the first row (row = 1) and you will execute the second loop an amount of rows (as row is changing the first time you will do it only one time). Once the execution of the second loop will be finished you will start again with the first one, calling again the second one... you will leave this looping once the first loop is completed for the last time.

then you will call getch() which will stop the program.

Good luck!
 
Share this answer
 
Any book on C++, will have a chapter on looping.

But generally to give you a basic understanding of for loops and nested for loops:-

The for loop has 3 parts:
1) Declare and initialize a variable : Ex: int i = 0;
2) Test the variable : For any condition you want. Ex: i< 4
3) Perform some operation: Usually the variable is incremented or decremented. Ex: i++;

1)The for loop (not nested) can be used to for displaying values, testing an array of values etc.

Ex :
C++
int main()
 {
   int a[4] = {1, 2, 3,4 };  
   for (int i=0; i < 4; i++)
   {
 cout << a[i] << endl;
   }
 }

output:
1
2
3
4

2) But when you are dealing with 2 - d array, That is, which consists of both row and column, the nested for loop can be used.

The example you have illustrated itself is a very good example. But still, To print 5 rows and 6 columns of "*", the for loop would be:
C++
main()
 {
  int row,col;
  for (row=1; row<=5; row++)
    {
        for (col=1; col<=6; col++)
        {
		printf ("*", col);
	       }
        printf ("\n");
    }
    getch(); 


output:
******
******
******
******
******


Here, the variable "row" in the outer loop is initialized to 0
row = 1 This is Row 1
Then the loop goes into inner loop, where the loop is run until the condition col<=6 is reached -
col = 1;
print *
col is incremented and checked if it is less than /equal to 6,
if yes print *

This is done until col = 6, thus displaying 6 columns. Then the loop moves to the outer loop again, increments row, checks if the value is less than 5 and the process continues until row = 5. Then stops.

Try this same example with different values for row and column and run your program in debug. You will understand what is going on exactly.
 
Share this answer
 
Comments
Maciej Los 27-Aug-12 12:14pm    
+5!
Sumal.V 27-Aug-12 13:46pm    
Thank You :)
at first, please forget about outer loop.
step1-then, please trace the inner loop.
then pay attention that for every, row=1 & row=2 &row=3 runs step1
 
Share this answer
 
Comments
Stefan_Lang 6-Jan-14 6:04am    
No point in necroing a 4 months old thread, especially since it's been sufficiently answered.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900