1

I have:

    if (a[i] == 1) {
        howMany[1] += 1;
    }
    else if (a[i] == 2) {
        howMany[2] += 1;
    }
    else if (a[i] == 3) {
        howMany[3] += 1;
    }
    else if (a[i] == 4) {
        howMany[4] += 1;
    }
    else if (a[i] == 5) {
        howMany[5] += 1;
    }
    else if (a[i] == 6) {
        howMany[6] += 1;
    }
    else if (a[i] == 7) {
        howMany[7] += 1;
    }
    else if (a[i] == 8) {
        howMany[8] += 1;
    }
    else if (a[i] == 9) {
        howMany[9] += 1;
    }

I want to replace it with something like:

    if (a[i] == 1 || a[i] == 2 <-- etc) {
        howMany[i] += 1;
    }

But that doesn't work. Anybody has a clue? This is C++, but I've experienced the same issue in Python, so I don't think it's a language issue but rather just a general problem.

2
  • Are you sure you want to accomplish this with a for loop rather than the one-line answers provided? Commented Dec 12, 2015 at 0:15
  • Actually I decided to use the one liner. Thanks guys! I really wanted to see a for statement out of curiosity. It was a relatively simple problem that I could not wrap my head around. Commented Dec 12, 2015 at 0:43

4 Answers 4

2

If you are sure that the range of a is from one to nine you can simply write

howMany[a[i]]++;

otherwise you will need one if statement

if(a[i] >= 1 && a[i] <= 9)
    howMany[a[i]]++;
Sign up to request clarification or add additional context in comments.

Comments

1

how about

howMany[a[i]] += 1;

since you are always accessing the element of howMany based on the value of a[i]

Comments

1

Lets look at what you are doing

if (a[i] == 1) {
    howMany[1] += 1;
}

So if a[i] is 1 then you want to increment the value of howMany[1]. Since a[i] == 1 and index of howMany == 1 then all you need is howMany[a[i]] += 1;

Comments

1

You need to use:

howMany[a[i]] += 1;

(or ++ rather than += 1) inside the if statement (not a loop, by the way) since a[i] is the variable holding 1, 2, etc.

Your new if statement could also be simplified to something like:

if ((a[i] >= 1) && (a[i] <= 9)) ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.