Reputation:
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.
Upvotes: 1
Views: 1727
Reputation: 1085
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]]++;
Upvotes: 2
Reputation: 881373
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)) ...
Upvotes: 1
Reputation: 180500
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;
Upvotes: 1
Reputation: 3302
how about
howMany[a[i]] += 1;
since you are always accessing the element of howMany
based on the value of a[i]
Upvotes: 1