Search code examples
c++arraysnested-loopsincrement

C++ Looping through an Array to display contents


I'm writing a loop to go through a 3d array and display the contents of [0][0][0] through [0][2][4]. It displays and acts normal from [0][0][0] through [0][0][4], but after that it jumps to [0][2][0] instead of to [0][1][0]. I can't figure out why that is myself if anyone could correct my mistake.

a, b, c, d, and e are all integer variables. at the beginning of this loop i initialized b as 0, c as 1, d as 0, and e as 1.

for (int a = 0; a < students;)
 {
   cout << "Let's help Student #" << e << "!" << endl;
   do 
    {
     cout << "Question #" << c << ":" << endl;
     cout << math_rooms[0][a][b] << endl;
     cin >> math_rooms[0][a][b];
     cout << " " << endl;
     
     if (math_rooms[0][a][b] != math_answers[0][a][b])
      {       
       d++;
       //Set up the error variable so we keep track of pass/fail
       cout << "Sorry, that was incorrect." << endl;
       cin >> math_rooms[0][a][b];
       cout << " " << endl;
      }
     else
      {
       cout << "That's correct!" << endl;
       cout << " " << endl;
      }
         
     //Increment b and c to go through all questions/keep track of question #.
     b++, c++;

     //Set up loop that checks pass_fail on final question.
     if (d >= 3)
      {
       cout << "Sorry, you failed the test." << endl;
       pass_fail = false;
       return pass_fail;
      }

    } while (b < questions);

  //restart counter
  c = 1;
  //Increment a so that it changes to the next student & f so that it keeps track of the student #.
  a++, e++;
 }

So essentially, the loop works fine until it increments the a variable. It starts at 0 and then when it's supposed to increment to 1 it goes to 2 instead. IDK why?


Solution

  • You need to reset the value of b each time the for loop is executed