//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;
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;
}
}
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;
#include <iostream>
#include <algorithm>
usingnamespace std;
int main()
{
constint 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.