How can I generate a number with 7 digits adding up to 21?

14 Views Asked by At

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.

1

There are 1 best solutions below

0
Aaryaman1409 On

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 to num[6] = sum and it should work fine. Also, your code as is can generate negative numbers for the final value of the array.