I got this question in the exam and i couldn't figure out the correct way to solve it

//input two integers a and b. find out small and big values between a and b.
//Example if a is 12 and b is 5 then small will be b and big will be a.
//Use a loop to output multiples of 3 from small to big.
//Display their count and sum.

I'm studying biotechnology and im taking programming 1 as an elective so i'm not really smart in it but i tried my best to write the basics.



#include<iostream>
using namespace std;
int main()
{
int a, b, i, sum=0, count=0;
cout<<"Enter two numbers:";
cin>>a>>b;
cout<<" Multiples of 3 from " << a << " to " << b <<":"<<endl;

if (a<=b)
{
for (i=a; i<=b; i++)
{
cout<<i<<endl;

}
}
else {for (i=b; i<=a; i++)

{
cout<<i<<endl;
}

}
sum= sum + i;

cout<<"Count="<<endl;
cout<<"Sum= "<<sum<<endl;


return 0;
}
Please format your code correctly. Edit your post and add [code] and [/code] around your code.

You should be checking for divisibility by 3. If something is divisible by 3, then its remainder when divided by 3 is 0. This is done through the modulo operator, %.

Do this instead:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    if (a<=b)
    {
        for (i=a; i<=b; i++)
        {
            if (i % 3 == 0) // "if i is divisible by 3"
                cout << i << endl;
        }
    }
    else
    { 
        for (i=b; i<=a; i++)
        {
            if (i % 3 == 0) // "if i is divisible by 3"
                cout << i << endl;
        }
    }
Last edited on
if you wanted to be slick you can find the first multiple of 3 and loop by 3s. This is just to make you think a little, the above is perfect.

int lt[3] = {0,2,1}; //lookup table of modulo corrections
if (a<b)
{
m = lt[a%3]; //so, if a is 4, m is 2, sum is 6. if a is 3, 3+0 is 3. If a is 5, 5+1 is 6 again... etc...
for(I= a+m ; I <= b; I+=3)
cout << I << endl;


Last edited on
Thankyou both so much, i looked up more examples on loops and i kind of get it now.
jonnin, yeah that's true.

Another way of doing it would be:

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
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    const int n = 3;
    int a = 2;
    int b = 16;
    
    std::cin >> a;
    std::cin >> b;
    
    int temp = std::max(a, b);
    a = std::min(a, b);
    b = temp;

    cout << "Multiples of " << n << " from " << a << " to " << b << ":" << endl;
    
    int start = a + ((a * (n - 1)) % n + n) % n;
    int sum = 0;
    for (int i = start; i <= b; i += n)
    {
        cout << i << endl;
        sum = sum + i;
    }
    
    cout << "Sum = " << sum << endl;
}


This also accounts for negative values, and generalizes 3 to be n, for n > 0.
Last edited on
1
2
    if (a > b) { int t = a; a = b; b = t; }    
    int start = (n - a % n) % n + a;

Ah, a more eloquent version of my start equation. Nice.
Topic archived. No new replies allowed.