dandan
dandan

Reputation: 115

Nested for loop only runs inner loop (c++)

I am quite new to c++, and I believe the answer to my problem is very, very simple.

I've been using the Eclipse IDE, but have recently changed to a simple text editor and using the command line for compiling. (As i currently don't have my own computer, and I am not allowed to install anything on the one I am using).

However, while writing a program, I noticed that whenever I had nested loops, it would only run the inner loop.

I've tried compiling my code using different online compilers, which results in the same problem.

Because of this, I believe that the problem is related to something simple, that Eclipse was taking care of automatically.

#include <iostream>

int main() {
  for (int i; i<3; i++) {
    for (int j; j<3; j++) {
      std::cout << j << std::endl;
    }
  }
  return 0;
}

Above is the simplest example, I could think of, that produces the problem. The expected output is 0, 1, 2, 0, 1, 2, 0, 1, 2, however it only outputs 0, 1, 2 when I compile and run it.

Upvotes: 0

Views: 360

Answers (2)

Jack
Jack

Reputation: 133577

The problem is that you are using uninitialized variables, which leave them with undefined values

for (int i; i < 3; i++) {
         ^

Try with

for (int i = 0; i < 3; i++) {

Upvotes: 0

lost_in_the_source
lost_in_the_source

Reputation: 11237

You're not initializing the i and j variables to 0, so the variables start off by having undefined values. Fix to:

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        std::cout << j << std::endl;
    }
}

Upvotes: 5

Related Questions