Can someone explain the math behind this program?

1. Write a program that asks the user for a number n and prints the sum of the numbers 1 to n
2. Modify the previous program such that only multiples of three or five are considered in the sum, e.g. 3, 5, 6, 9, 10, 12, 15 for n=17


I don't understand what the second problem is asking. When asking a classmate for help he gave me the code but didn't explain why it worked. When I input a number 9. I get the output 23. Can someone explain the math? I'm just very confused. The code is useless if I don't understand the problem. The n=17 is throwing me off . I'm very new to programming so any help is appreciated.

#include <iostream>
using namespace std;

int main()
{
int n = 0;
int sum = 0;


cout << "Write a number" << endl;
cin >> n;

for(int i=0;i<=n;i++)
{


if ((i % 3 == 0) || (i % 5 == 0))
{
sum+=i;
}
}
cout << sum << endl;

}
Your assignment is asking for the summation between 1 to n.

#2 is saying, it only takes in numbers which are divisible by 3 and 5 so:
3+5+6+9 = 23
oh!!! ok I understand it now. Code makes perfect sense. Thanks a ton!
Topic archived. No new replies allowed.