Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++ C C# Java
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 :
 
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 26-Aug-12 3:58am
geek747324
Edited 26-Aug-12 4:28am
enhzflep37.3K
v5
Comments
enhzflep at 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 at 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 at 26-Aug-12 11:24am
   
and here:
http://mathbits.com/MathBits/CompSci/looping/nested.htm
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 5

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.
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 6

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
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

Logic of loop 1)
for (row=1; row<=3; row++)
Until value of variable row is lowest or equal to 3, loop.
 
Logic of loop 2)
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:
int row,col;
for (row=1; row<=3; row++)
  {
      for (col=1; col<=3; col++)
      {
          printf ("%d", col);
      }
      printf ("\n");
  }
  getch();
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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!
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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 :
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:
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.
  Permalink  
Comments
losmac at 27-Aug-12 12:14pm
   
+5!
Sumal.V at 27-Aug-12 13:46pm
   
Thank You :)
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 9

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
  Permalink  
Comments
Stefan_Lang at 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)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 853
1 OriginalGriff 410
2 CPallini 275
3 George Jonsson 226
4 Richard Deeming 145
0 OriginalGriff 5,450
1 CPallini 4,500
2 Sergey Alexandrovich Kryukov 4,482
3 George Jonsson 3,057
4 Gihan Liyanage 2,445


Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 5 Jan 2014
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100