Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - Nested loops

Node:Nested loops, Next:, Previous:Terminating and speeding loops, Up:Loops



Nested loops

Just as decisions can be nested, so can loops; that is, you can place loops inside other loops. This can be useful, for example, when you are coding multidimensional arrays. (See Arrays.)

The example below prints a square of asterisks by nesting a printf command inside an inner loop, which is itself nested inside an outer loop.

Any kind of loop can be nested. For example, the code below could have been written with while loops instead of for loops:

#include <stdio.h>

#define SIZE 5

int main()
{
  int square_y, square_x;

  printf ("\n");

  for (square_y = 1; square_y <= SIZE; square_y++)
  {
    for (square_x = 1; square_x <= SIZE; square_x++)
    {
      printf("*");
    }
    printf ("\n");
  }

  printf ("\n");
  return 0;
}

The output of the above code looks like this:

*****
*****
*****
*****
*****

 
 
  Published under free license. Design by Interspire