Need help with simple programming assignment

Greetings!!! Normally I would consider myself an ok programmer, but my professor has clearly stomped me. He wants me to write a program that uses no If, If-Else or switch-case statements, that takes an array of numbers, up to 1000, and keeps count of how many are in each range. eg 0-99, 100 through 199, etc. Problem is I don't know how to approach this since I can't do if/switch statements. Nor use ternary operator. Any ideas?

This is as much a math question as anything else.

You only need a loop and a ten-element array for the sums. Each time through the loop you simply add one to the element in the correct range.

(Hint, there is a convenient mathematical operation which will convert from the input number to the index in the array of the element to update.)

When in doubt, take a look at the various operators available:
https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Arithmetic_operators

Good luck!

[edit] Post 12,000. Woot!
Last edited on
you can do screwy things to avoid if statements. This is occasionally a performance tweak, depending on the code.
for example, say you wanted to set x to 12.34 if something is false, else set it to 56.78
double tf[] = {12.34, 56.78};
result = tf[(int)(boolean condition here)];
result = tf[(int)(x<y)]; //concrete example
this works because the condition returns 0 or 1, for false / true.

that is not how to solve THIS problem. Its just some ammo for the future.

this problem is trying to get you to re-invent a classic algorithm. If you still do not see it, ask again.. the above is the hint..

in action, this is an integer power function that avoids if/else to multiply by 1 (do nothing) or by p depending on if that bit was set.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
inline long long ipow(long long p, unsigned long long e) //fast for big powers (> 8)
{ 
  const long long one = 1;
  const long long *lut[2] = {&p,&one};
  register long long result = 1;
    result *= lut[!(e&1)][0]; p *= p;
	result *= lut[!(e&2)][0]; p *= p;
	result *= lut[!(e&4)][0]; p *= p;
	result *= lut[!(e&8)][0]; p *= p;
	result *= lut[!(e&16)][0]; p *= p;
	result *= lut[!(e&32)][0]; p *= p;
	result *= lut[!(e&64)][0]; 	
	return result;
}
Last edited on
Just use integer division to find the appropriate range (assuming equal intervals).
@Duthomhas thanks for pointing me in the right direction, I am still stomped. Could you extend a little more info one which operator you were hinting about?
@Viprous,
You just need two operators:
/
++
Topic archived. No new replies allowed.