Lucas Ranieri
Lucas Ranieri

Reputation: 41

How to define the number of elements in an array with user input of type int?

I am a beginner. I'm trying to solve a pair-sum program. The program calls for the number of pairs being added and the actual pairs, then it returns the sum of each pair. I'm using an array to store the sum of each pair, but when I print out every element the last one is always wrong. This is what I have so far:

int c, val1, val2, x, i;

printf("Enter the number of pairs to sum: \n");
scanf("%d", &c);
int sum [c];
printf("Enter the pairs: \n");
for ( x = 0; x < (c - 1); ++x)
{
    scanf("%d", &val1); 
    scanf("%d", &val2);
    sum [x] = val1 + val2;
    val1 = 0;
    val2 = 0;
}

printf("The sum of each pair is: \n");
for (i = 0; i < c; ++i)
{
     printf("%d\t", sum[i]);
}

Upvotes: 0

Views: 88

Answers (1)

gsamaras
gsamaras

Reputation: 73384

Change this

for ( x = 0; x < (c - 1); ++x)

to this:

for ( x = 0; x < c; ++x)

You are going until (c-1), where you print c times.

So, after the fix, your loop will be like this:

printf("Enter the pairs: \n");
for ( x = 0; x < (c - 1); ++x)
{
    scanf("%d %d\n", &val1, &val2 );
    sum [x] = val1 + val2;
    val1 = 0;        // Do you really need me?
    val2 = 0;        // and me?
}

You do not need to nullify val1 and val2 at the end of every loop.

Think the first time you enter the loop. These variables are uninitialized, but they get initialized by scanf().

Let's say the user typed 0 and 1, so your variables got these values respectively.

Then, you set them to zero.

Then, you go again inside the loop and the variables get assigned the input of the user.

And so on...

Think how this would work, if you would discard this step:

Then, you set them to zero.

It would be the same!

The only difference is that when you exit the loop, these variables will have what the user typed for the last run of the loop and not the zero values, but I think that's not a problem. :)

Upvotes: 1

Related Questions