xeperia1
xeperia1

Reputation: 13

C programming: Does scanf not read values 0 and 1 as intended as integers?

I am trying to get the sum of all the multiples of any two values.

I used scanf to request an integer value twice from the user.

In the code and the algorithm I created works as intended except for when the user would input value of 0 and/or 1.

I want the computer to be able to accept the value of zero and result in a total of zero and when accepting 1 a total sum of 1 but 0 gives me odd crash and 1 gives me a big value.

/*multiples of 3 or 5: 3,5,6,9; sum is 23*/

#include <stdio.h>

int main()
{
    int value,value2,limit = 1000;
    int i,divi,sum = 0; 

    /*read user input for the first value*/ 
    scanf("%d",&value);

    /*get sum of all multiples of value*/
    for(i = value;i < limit;){
        sum = sum + i;
        i = i + value;
    }
    printf("%d\n",sum);
    printf("done for %d\n",value);

    /*read user input for the second value*/
    scanf("%d",&value2);
    /*get sum of all multiples of value2*/
    for(i = value2;i < limit;){
        divi = i%value;
        if((divi)==0){
            i = i + value2;
        }
        else
        {
            sum = sum + i;
            i = i + value2;
        }

    }
    printf("%d\n",sum);
    printf("done for %d\n",value2);
    return 0;
}

Upvotes: 1

Views: 476

Answers (1)

John C
John C

Reputation: 1981

The for loop is mostly intended to count things off. You don't need to, but it's more readable. I'll get to that later.

For your first loop, you have:

for(i = value;i < limit;){
    sum = sum + i;
    i = i + value;
}

This...

  • Sets an initial value of i, to value. This is...a little unorthodox and might be causing you some confusion.
  • Each iteration, it will test i against limit.
  • Increments sum by the ever-increasing value of i.
  • Increases the value of i by value.

The problem you see is that, when value is zero, i never changes.

There's also an oddity that sum doesn't appear to get multiples. If value is 1, sum will be 0, 1, 3, 6, 10, 15...triangular numbers. That doesn't sound like what you want.

Instead, I think you want to use the for loop for its intent, counting, and just increase the sum repeatedly. Something like:

for(i = 0;i < limit;i++){
    sum = sum + value;
}

That says to add value to sum, limit times.

If you did need the triangular numbers, you may want to introduce a supplemental variable. If counting isn't what you want, you might want a while loop, instead, for readability, something like:

while (sum < limit){
    sum = sum + value;  /* or whatever you need, here */
}

But definitely test the input value to make sure it's not 0. No matter how many zeroes you add, they're not going to be bigger than limit...well, unless limit is negative.

Upvotes: 1

Related Questions