+ 1

15.2 practice problem

While loops only You are given a program that outputs all the numbers from 0 to 20. Change the code to make it output only numbers that are multiples of 3. My code: cin << number; While( number <= 20) { Number = ( number +1)*3; Cout >> number; }

4th May 2021, 6:26 PM
salem
9 Respuestas
+ 2
1.You have the << and >> operators mixed up. You need to use cin>> and cout<<. 2.You need to increment number in the while loop. Just add number++; in the loop. 3.You don't need to add one two number in the loop(that's probably the increment attempt, i think) P.S. you can do cout<<number*3; directly. Hope this helps :)
4th May 2021, 6:31 PM
Mihail
Mihail - avatar
+ 1
Spotted some more problems, besides incomplete code and wrong casing: You are stopping too late, because output is after increment without checking. Also use correct indention and post code as a link please like this: https://code.sololearn.com/cmNM4W6vig7C/?ref=app
4th May 2021, 6:44 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
+ 1
salem num goes up to 20 and only for output you are multiplying by 3. That's why it stops at 60
4th May 2021, 9:19 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
+ 1
salem You are doing wrong. You have get those numbers which are multiple of 3 so to check multiple of 3 use modulus operator (%). You code should be look like this #include <iostream> using namespace std; int main() { //change the code int num = 1; while(num < 20) { if (num % 3 == 0) cout << num << endl; num++; } return 0; } // This is what I got but I still need it to stop at 20, it just keeps going
4th May 2021, 9:40 PM
A͢J
A͢J - avatar
0
You are multiplying the number(+1) by 3 each iteration, giving you the sequence 0, 3, 12, 39, 120, 363, ... You want 0, 3, 6, 9, ... So from each step to the next you have to ADD 3. Do you really need input? The description doesn't say so
4th May 2021, 6:35 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
0
int main() { //change the code int num = 0; while(num < 20) { num ++; cout<<num*3<< endl; } return 0; } // This is what I got but I still need it to stop at 20, it just keeps going
4th May 2021, 7:12 PM
salem
0
include <iostream> using namespace std; int main() { //change the code int num = 1; while(num<=20){ num ++; cout<<num*3<<endl; } return 0; } how can I make it stop at 20, also why does it print from 3 to 63 why doesnt it stop at my condition
10th May 2021, 8:24 AM
salem
0
i got it, instead of num<20, it should be 6. since we are multiplying num
10th May 2021, 8:43 AM
salem
- 2
hi
6th May 2021, 7:16 AM
‎امیرحسین نوری‎
‎امیرحسین نوری‎ - avatar