0

I want to know why the value of i is not updating to i=0 when i == n-1, as I have written in the code. The bool flag is just there to check if the if statement was rendering at all or not (It is).

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int t;
    scanf("%d", &t);
    while (t--)
    {
        int n, ans = 0;
        scanf("%d", &n);
        int s[n];
        bool flag = false;
        for (int i = 0; i < n; i++)
        {
            scanf("%d", &s[i]);
        }
        for (int i = 0; i < n; i++)
        {
            s[i] -= 1;
            if (s[i] < 0)
                break;
            ans++;
            if (i == (n - 1))
            {
                i=0;
                flag = true;
            }
        }
        printf("\n%d\n", ans);
        printf("%d", flag);
    }

    return 0;
}
James Z
  • 12,209
  • 10
  • 24
  • 44
Apurv Dev
  • 1
  • 1

1 Answers1

0

How do you know it's not doing what you want. I ran it and got this:

$ ./foo 1 2 3 4

5 1 $

The final value (1) is true. So it looks like it's doing it to me.

However, this is pretty terrible code. It's a really bad practice to muck with your iterator variable inside your loop like that. That's GOING to bite you. Furthermore, you're not going to go back to 0 -- you're going to go back to 1, because the next thing it does is increment the variable with your i++. So your if-statement sets i to 0 and your for-loop turns it into 1.

But this is just weird. If you need to run the loop multiple times, then wrap it in a larger loop.


Others have commented on printf. Personally, I disagree with them. There are times printf is completely valid. HOWEVER -- the way you're using it for such simple, unformatted stuff, isn't really one of them.

I changed the last printf to this:

cout << "Flag (raw): " << flag << ". Which means: " << (flag ? "True" : "False") << endl;

Output is this:

Flag (raw): 1. Which means: True

As you can see -- it's 1, which is not 0, so it's true.

Joseph Larson
  • 8,530
  • 1
  • 19
  • 36