So I have this program that is getting me crazy. Here is what it's asking me to do. The program outputs how many numbers are multiples of 3 and how many numbers are multiples of 5 between the two integers (inclusive). Now before you see what I did, I was trying to make the input 7 23 to output 5 3 and so on. Please, coders, help me out with this hot mess.
1. Take out the switch statements.
2. Make a loop that iterates from number1 to number2.
3. Count divisible numbers in the loop. Test division with modulus operator (%)
There is a (efficient) way to calculate without a loop, but the loop version is good practice.
/*
The program outputs how many numbers are multiples of 3 and how many
numbers are multiples of 5 between the two integers (inclusive).
*/
#include <iostream>
usingnamespace std;
int main()
{
int number1{0};
int number2{0};
cout << " Please enter an integer: ";
cin >> number1;
cout << "Please enter another integer: ";
cin >> number2;
int count_multiple_of_3{0};
int count_multiple_of_5{0};
for(int i = number1; i <= number2; i++)
{
if(i % 3 == 0)
count_multiple_of_3++;
if(i % 5 == 0)
count_multiple_of_5++;
}
cout << "Multiples of 3: " << count_multiple_of_3 << '\n';
cout << "Multiples of 5: " << count_multiple_of_5 << '\n';
return 0;
}
Please enter an integer: 7
Please enter another integer: 23
Multiples of 3: 5
Multiples of 5: 3
Program ended with exit code: 0
#include <iostream>
int main()
{
int st {}, ed {};
std::cout << "Please enter start and end numbers: ";
std::cin >> st >> ed;
int mul_3 {};
int mul_5 {};
for (int n = st; n <= ed; mul_3 += n % 3 == 0, mul_5 += n++ % 5 == 0);
std::cout << "Multiples of 3: " << mul_3 << '\n';
std::cout << "Multiples of 5: " << mul_5 << '\n';
}
@OP don't throw away your code. Some of it as you can see is good and you've probably spent some considerable time on it.
As a tip, and this is emphasized by Bjarne Stroustrup, gimmicky code is invariably a disaster. Properly set out and clear code like yours can be debugged and maintained easily every time.
Code is just a recipe to make a machine do what you want - not a quiz gimmickry show that hides the intent :)