+ 1

How can solution this question display the first 20 numbers that are evenly divisible (%)by 3?loop

26th Mar 2017, 9:45 PM
Bts...
Bts... - avatar
4 Respuestas
+ 19
int num = 0; int count = 0; while (count < 20) { if (num % 3 == 0) { cout << num << " "; count++; } num++; }
26th Mar 2017, 11:30 PM
Hatsy Rei
Hatsy Rei - avatar
+ 5
int i; for ( i =1; i <= 20; i++) cout << i*3;
27th Mar 2017, 1:07 AM
Player
+ 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 << ' ';
26th Mar 2017, 11:41 PM
Squidy
Squidy - avatar
+ 2
thank you
27th Mar 2017, 4:15 AM
Bts...
Bts... - avatar