Suppose I have N float variables x0, x1, x2, …, xn.
I basically want to loop through each of them and sum them all in a final variable sum.
I’m in a context where I cannot make use of data structures like arrays, vectors, etc. If it helps, in my context N is always less than 10.
Is it possible to make a for loop to do this?
My first thought was using macros like the concatenate (##) or something like that but I guess it won’t fit my case.
>Solution :
not sure whether it fits your needs, but you can try something like:
#define SUM_X0 (x0)
#define SUM_X1 (SUM_X0 + x1)
#define SUM_X2 (SUM_X1 + x2)
#define SUM_X3 (SUM_X2 + x3)
#define SUM_X4 (SUM_X3 + x4)
#define SUM_X5 (SUM_X4 + x5)
#define SUM_X6 (SUM_X5 + x6)
#define SUM_X7 (SUM_X6 + x7)
#define SUM_X8 (SUM_X7 + x8)
#define SUM_X9 (SUM_X8 + x9)
int main(int argc, char* argv[]) {
int x0, x1, x2, x3, x4, x5;
if (scanf("%d %d %d %d %d %d", &x0, &x1, &x2, &x3, &x4, &x5) != 6) {
printf("error");
return 1;
}
printf("%d\n", SUM_X0);
printf("%d\n", SUM_X1);
printf("%d\n", SUM_X2);
printf("%d\n", SUM_X3);
printf("%d\n", SUM_X4);
printf("%d\n", SUM_X5);
return 0;
}