Displaying numbers that are multiples of...

Hi,

I'm taking a C++ programming course and I'm having a problem completing one of the assignments.

The requirements are
1) Ask the user to enter a number (m)
2) Check to see if the number is positive, if not give an error
3) Display all numbers that are multiples of 3 between 1 and m and display the values to the user

At first I was trying to use the while function but got frustrated so I switched it to for statement.

Could someone give me a hint so I can try to solve this problem?

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
#include <iostream>

using namespace std;

int main()
{
    int n=0,i=0;
    double mul;
    cout << "Please enter an integer." << endl;
    cin >> n;
    for (n>=0)
    {
       cout << "The number you entered is positive." << endl;
        mul=n%3;
        for (mul==0)
            {
              cout << n << " ";
              n-=3;
            }
    }
    cout << "The multiples of 3 of the number you enterd are:" << endl;
    else
    {
    cout << "Error: Please enter a positive number." << endl;
    }
    return 0;
}
A for statement looks like this: for ( start action ; while condition ; next action) You need 3 arguments seperated by ;

While was correct for how you are using it, but you should have also used an IF statement:
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>

using namespace std;

int main()
{
    int n=0;
    int mul;
    cout << "Please enter an integer." << endl;
    cin >> n;
    if (n>=0)
    {
        cout << "The number you entered is positive." << endl;
        while (n > 0)
        {
            mul=n%3;
            if (mul==0)
            {
                cout << n << " ";
            }
            n -= 3;
        }
    }
    else
    {
        cout << "Error: Please enter a positive number." << endl;
    }
    return 0;
}
All integer positive numbers that are in the range [1, n] and multiples of m are easily obtained by means of the following loop


1
2
for ( int i = m; i <= n; i += m ) std::cout << i << ' ';
std::cout << std::endl;
Last edited on
Thank you both so much for the help!

As vlad stated I had to show all multiples of whatever integer user inputs till zero, so I had to decrease it by n--; to continue the loop instead of decreasing it by 3.

Thank you both again for the help!
if (mul==0)

Will almost always fail, mul is a double.
Topic archived. No new replies allowed.