+ 1
How can solution this question display the first 20 numbers that are evenly divisible (%)by 3?loop
4 Respuestas
+ 19
int num = 0;
int count = 0;
while (count < 20)
{
if (num % 3 == 0)
{
cout << num << " ";
count++;
}
num++;
}
+ 5
int i;
for ( i =1; i <= 20; i++)
cout << i*3;
+ 4
I wanted to see if I could write this in one line. So without further ado:
int divisor = 3; // our divisor
int start = 0; // our starting value
int max = 20; // the maximum number of multiples to find
for (int inc = 1, found = 0; start % divisor == 0 && (++found, inc = divisor, std::cout << start << ' '), found < max; start += inc);
It's smart, because once it finds the first match, it'll just keep incrementing by our divisor, skipping values that will never satisfy the condition. You can simplify it quite a bit if we can assume you'll always start at 0.
If your inputs are constant, it's easy enough to just do this:
for (int i = 0; i < 20; ++i)
std::cout << i * 3 << ' ';
+ 2
thank you