I have tried this code:
int number = 0;
int sum = 21;
int num[7];
for (int i = 0; i < 6; i++) {
num[i] = (rand() % 9) + 1;
sum -= num[i];
}
num[7] = sum;
for (int i = 0; i < 7; i++) {
number += num[i];
}
However, the code generates a number that has digits not adding up to 21.
It's a minor mistake in your 8th line because you do
num[7] = sum, which is out of bounds for your 7-element array. Since arrays are 0-indexed you need to change it tonum[6] = sumand it should work fine. Also, your code as is can generate negative numbers for the final value of the array.