#include <stdio.h>
int main(void){
int k, m, n, i, sum = 0;
printf("Enter two integers m an n.\n");
scanf("%d %d", &m, &n);
printf("Enter an integer k greater than 1.\n");
scanf("%d", &k);
for(i=m; i<=n; i++){
if (i % k == 0){
sum += i;
}
}
printf("Sum of numbers between %d and %d that are divisible by %d: %d \n", m, n, k, sum);
return 0;
}
![]() | This is a solution to exercise 18 on page 118 of C by Dissection. For some given integer input n, m, and k we are asked to add all those integers, i, between n and m for which i % k == 0. |
![]() | int k, m, n, i, sum = 0; |
The variables k, m, n, i and sum are declared. |
![]() | printf("Enter two integers m an n.\n");
scanf("%d %d", &m, &n);
printf("Enter an integer k greater than 1.\n");
scanf("%d", &k); |
The user is first asked to enter values for the variables m and n. Next, the user is asked to enter a k value greater than 1. There is no control nor consequence, however, if k is one or below. |
![]() | for(i=m; i<=n; i++){
if (i % k == 0){
sum += i;
}
} |
The variable i runs from m to n. If m happens to be larger than n, nothing happens at all. In a normal cases, however, m is supposed to be smaller than n. If i is divisible by k (if i % k equals 0), we accumulate the i value in the variable sum. Notice the % operator, which is called modulus. x % y returns the remainder of the integer division x / y. |
![]() | printf("Sum of numbers between %d and %d that are divisible by %d: %d \n", m, n, k, sum); |
The result is printed in a nice way, using the control string of the printf commmand. |