Hello everyone I am a college student learning c++ and I am not understanding why you put a "For loop" inside of another one. What advantage does it have and what can you use it for.

For example:

for (int i = 0; i < 5; i++){
    for (int g = 0; i < 5; g++) 
    {
    }
}

thank you

Recommended Answers

All 2 Replies

It lets you iterate through multiple items multiple times.

One very common use is multi-dimensional arrays:

//#include the necessary headers
#include <iostream>
#include <cstdlib>
#include <ctime>

//declare needed constants
const int ROWS = 10, COLS = 20;

int main() {
  srand((unsigned)time(0)); //seed the RNG

  char Array[ROWS][COLS] = {'\0'};      //declare the data array

  for (int i = 0; i < ROWS; ++i) {      //randomly populate the data array
    for (int j = 0; j < COLS; ++j) {
      if (rand()%2) {
        Array[i][j] = '*';
      }
    }
  }

  std::cout << "Displaying Array: \n\n";  //display the data array

  for (int i = 0; i < ROWS; ++i) {
    for (int j = 0; j < COLS; ++j) {
      std::cout << '[' << Array[i][j] << ']' << " ";
    }
    std::cout << std::endl;
  }

  return 0;
}

Another common use is sorting data.

//Bubble sort
void BubbleSort() {
  for (int i = 0; i < ARRAY_SIZE; ++i) {        //establish "surface" index
    bool swap = false;                          //declare flag variable
    for (int j = (ARRAY_SIZE-1); j > i; --j) {  //establish "bubble" index
      if (array[j] > array[j-1]) {              //compare "bubble" with adjacent value
        std::swap(array[j], array[j-1]);        //perform the swap, if necessary
        swap = true;                            //set the flag, if necessary
      }
    } //end for (index j)
    if (!swap)                                  //check the flag
      break;                                    //end the sort if flag not set
  } //end for (index i)
} //end BubbleSort()

This is a Bubble Sort, which is extremely simple and rather inefficient, but there is a certain amount of this concept in almost all sorting algorithms.

Thank you very much. I was having problems understanding for loops but now I understand.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.