-3

enter image description here

Side note: I've been trying to trace this code, but every time I end up with output, it seems to be far more or less than the right answer which is 30. If anybody can explain in to me, I'd be more than appreciated. Thanks

Jason
  • 36,170
  • 5
  • 26
  • 60
  • 3
    code should be included as text in the question. And why do you think the output should be different? – 463035818_is_not_an_ai Oct 08 '22 at 12:56
  • Do you expect the result to be 30 or not. You contradict yourself in this regard. Furthermore your indendation doesn't meet my standards. The intendation of second `++t` suggests it's executed as part of one of the inner loops, when it's executed once per iteration of the outer loop only. Recommendation: NEVER use single statement loop bodies that aren't surrounded by `{}`; this just makes issues like this one more likely in addition to resulting in harder to read code... – fabian Oct 08 '22 at 13:00
  • adding `{}` for the loops blocks can help to either get desired result, or understand why the code produces the result it does – 463035818_is_not_an_ai Oct 08 '22 at 13:01
  • `t` is incremented `((2*4)+2)*3 == 30` times, thats what the code does. We cannot read your mind to tell why or what else you expect as output – 463035818_is_not_an_ai Oct 08 '22 at 13:03
  • The code start with `int t = 0;` and does `++t;` 30 times. – Eljay Oct 08 '22 at 13:04
  • 1
    [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Jason Oct 08 '22 at 13:09
  • 1
    The indentation is deceptive; one of the `++t;`s is not in the loop where you think it is. – molbdnilo Oct 08 '22 at 13:15

1 Answers1

2

Always make sure to add { and } to loops so that you avoid thinking that some instruction is within a loop when it's actually not.

The code you added in the screenshot is equivalent to the following

#include <iostream>
using namespace std;

int main() {
    int t = 0;

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

        // +8
        for (int v = 0; v < 4; ++v) {
            for (int h = 0; h < 2; ++h) {
                ++t;
            }
        }

        // +2
        ++t;
        ++t;
    }
    cout << t << endl;
    return 0;
}       

So, each iteration of the first loop (variable c) adds 10 to t. There are three iterations of the first loop, the total value added to t is 30.