Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Do while loop c++ assistance

I’m trying to make a cpp program that asks the user for two number inputs. Then print from 1 to the first number the user entered or until the first multiple of the second number. Print "Multiple of X(second number)" if the number is a multiple of the second input. using Do while loop.
This is what I managed to do so far.


int main()
{
    std::cout << "enter two numbers: ";
    int first = 0;
    int second = 0;
    std::cin >> first >> second;

    if(second != 0 && first%second == 0)
        std::cout << first << " is a multiple of " << second << '\n' ;
    else 
    {
        int n = 0;
        int maxval = second*2 > first ? first : second*2;
        do 
            std::cout << ++n << '\n';
        while(n < maxval);
    }
}

I’m hoping someone can help me fix the code or point out what’s wrong/missing in it.
Input should be any two numbers
then output should print numbers from 1 until the first number OR until the first multiple of the second number if it comes before the first number.
Example:
Enter two numbers: 10
7
1
2
3
4
5
6
Multiple of 7

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should use break when you get to the target number.

#include <iostream>

int main() {
    std::cout << "enter two numbers: ";
    int first = 0;
    int second = 0;
    std::cin >> first >> second;

    if (second != 0 && first % second == 0)
        std::cout << first << " is a multiple of " << second << '\n';
    else {
        int n = 0;
        int maxval = second * 2 > first ? first : second * 2;
        do {
            if (++n % second == 0) {
                std::cout << "Multiple of " << second << '\n';
                break;
            } else {
                std::cout << n << '\n';
            }
        } while (n < maxval);
    }
}

https://cplayground.com/?p=marmoset-tiger-vicuna

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading