What is wrong with my C program?

From: Hoffmann (oasf2004_at_yahoo.com)
Date: 03/26/05


Date: 25 Mar 2005 17:12:20 -0800

Dear All,

I am trying to write a C program that asks the user to supply three
integers k, m, and n. Then, the program computes the sum of all the
integers between m and n that are divisible by k. I just wrote the
following program, so. [Please, see below]. However, I am getting a
wrong output. I mean, I am getting a number higher than the expected
one. For instance, if I enter k = 2, m = 4, and n = 10, the sum of the
numbers between m (= 4) and n (= 10), that are divisible by k (= 2)
would be 14 (= 6 + 8). However, I am getting 18, instead.
Could you, please, help me to fix this program?
Thanks!
Hoffmann

#include <stdio.h>

int main()
{
    int k, m, n, //The three integers
          n2, //Numbers between m and n
          sum = 0; //Sum of the numbers

    printf("Input three integers: ");
    scanf("%d%d%d", &k, &m, &n);
    if (k > 1) {
        for (n2 = m; n2 < n; ++n2) { //Numbers between m and n
            if (n2 % k == 0)
                sum += n2;
        }
        printf("You entered the integers k = %d, m = %d, and n =
%d.\n", k, m, n);
        printf("The sum of all integers between m and n that are
divisible"\
            " by k is %d.\n", sum);
    }
    getch();
    return 0;
}



Relevant Pages

  • Re: fractions summing to a string instead of a number
    ... easy fix is to compare on the Int or the Fix of the total. ... that if they don't sum to 100%, the user is warned by the total turning ... *I've tried it without formatting, and it doesn't change the problem at ...
    (microsoft.public.access.formscoding)
  • Re: What is wrong with my C program?
    ... Hoffmann wrote: ... so my first guess would be that your sum ... > int main ... > getch(); ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Performance of hand-optimised assembly
    ... Why not use unsigned for sum in the test harness? ... int is better yet because the output will then be same across machines. ... gcc -O3 seems ... but taking an average by eye my best asm version was *slower* than ...
    (comp.lang.c)
  • Re: [PATCH] input: Introduce light-weight contact tracking
    ... seems the patch was damaged somehow. ... static int illegal(int nslot, int npos, unsigned x) ... int i, j, sum; ...
    (Linux-Kernel)
  • Re: Algorithm
    ... Wont sum of all positive numbers will be the largest sub-array? ... int getint ... struct sofar *next; ... struct sofar *discard(struct sofar *trail) ...
    (comp.lang.c)