Help with homework For Loop

Hey guys my H.W. asks me to write some code that, given a number n stored in an integer variable n, computes the product of all numbers less than or equal to n that are divisible by 2 or 3.

I think I have the right idea but i'm unsure of what I am suppose to do next. I don't know how to have the numbers multiply each other once I find out that they are divisible by 2 or 3.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

int main()
{

    int n;
    int sum;

    cin >> n;


    sum = 0;
    for (int i=0; i<=n; i++)
    {
        if ((i % 2 == 0) || (i % 3 == 0 ));
        {
            sum *= i;
        }

        
    }


return 0;


1) sum = 0 1; 0 multiplied by anything is still 0. You should start with multiplication neutral value i.e. 1.

2) for (int i= 0 1; i<=n; i++) 0 is divisible by any number and when multiplied with your sum, you get 0 again. Start with 1.

3)
1
2
if ((i % 2 == 0) || (i % 3 == 0 ));
//                   Bad semicolon↑ 
Your multiplication is executed unconditionally because of that.

4) Do not forget to output result.
Last edited on
Thanks MiiNiPaa I totally over looked those. After fixing it the only problem I have now is that sum is giving me the wrong answer. For example, if I enter n to be 4 I get the answer 10 for my sum when it really should be 24.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
using namespace std;

int main()
{

    int n;
    int sum;
    cout << "Enter number " << endl;
    cin >> n;


    sum = 1;
    for (int i=1; i<=n; i++)
    {
        if ((i % 2 == 0) || (i % 3 == 0 ))
        {
            sum *= i;
        }

    }

    cout << sum;




return 0;

}

Last edited on
Why did you changed multiplication to addition on line 18?
Yeah that was just a typo. It should still be multiplication.
Ok I closed Codeblocks and re-opened it and the program works fine now. I appreciate your help MiiNiPaa you are the best!
Topic archived. No new replies allowed.