furybowser
furybowser

Reputation: 13

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

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.

Upvotes: -1

Views: 16

Answers (1)

Aaryaman1409
Aaryaman1409

Reputation: 36

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.

Upvotes: 0

Related Questions