Reputation: 19
I'm trying to subtract all the values in the array loop, the values are generated randomly, but when I put that y = y - Array[I], it starts as 0-i and then it becomes negative. But when I put y = Array[I] - y; it also doesn't work, can anybody find me somebody to love, jk, can anybody help me subtract the array values, pls. Thanks :)
srand(time(NULL));
int Array[10],i,y=0;
for( i = 0;i<10;i++){
Array[i]=rand()%(20+1-5) + 5;
printf("%d,",Array[i]);
y = y - Array[i];
printf("(%d)",y);
}
return 0;
}
Upvotes: 1
Views: 1211
Reputation: 84559
If I understand your question, then you have the right pieces to accomplish creating a random array (with your modulo, range 5
to 28
), and then subtracting each number sequentially to arrive at the negative sum -- you just have them slightly out of order from a scope standpoint.
For example, your computation of y
should not be printed until you leave the loop. That way your negative sum is printed after the sequence, e.g.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main (void) {
srand(time(NULL));
int Array[10] = {0}, y = 0;
for (int i = 0; i < 10; i++) {
Array[i] = rand() % (20+1-5) + 5;
printf (i ? ",%d" : "%d", Array[i]);
y = y - Array[i];
}
printf (" = (%d)\n", y);
return 0;
}
Example Use/Output
Two runs of the code:
$ ./bin/array_seq
14,5,12,11,20,13,18,17,5,12 = (-127)
$ ./bin/array_seq
18,20,19,16,20,15,19,17,6,17 = (-167)
If this isn't what you intended, let me know and I'm happy to help further.
Upvotes: 1