Please correct my code to print 2*4**6*** (within separate lines) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Please correct my code to print 2*4**6*** (within separate lines)

#include <iostream> using namespace std; int main() { int x=2; int y=1; while (x<7) { cout<<x; while (y<4) { cout<<"*"; if (y==x/2) break; y++; } x+=2; cout<<endl; } return 0; }

25th Aug 2017, 8:52 AM
Nasma Najeeb
Nasma Najeeb - avatar
10 Answers
+ 10
@Nasma Najeeb The problem was that you forgotten to re-initialize y to zero for the outer loop. This causes y to keep incrementing and reach the designated limit earlier than expected.
25th Aug 2017, 9:09 AM
Hatsy Rei
Hatsy Rei - avatar
+ 8
// A few tweaks from your code. Remember to indent code for readability next time. #include <iostream> using namespace std; int main() { int x=2, y; while (x<7) { y=0; cout<<x; while (y< x/2) { cout<<"*"; y++; } x+=2; cout<<endl; } return 0; }
25th Aug 2017, 9:04 AM
Hatsy Rei
Hatsy Rei - avatar
+ 7
You can really just do: for (int i = 2; i <= 6; i += 2) { cout << i; for (int j = 0; j < i/2; j++) cout << "*"; cout << endl; }
25th Aug 2017, 8:59 AM
Hatsy Rei
Hatsy Rei - avatar
+ 7
K just give me a few minutes.
25th Aug 2017, 9:01 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Thank you very much, BTW can you mention my mistake??
25th Aug 2017, 9:06 AM
Nasma Najeeb
Nasma Najeeb - avatar
+ 2
The mistake is that you did not reinitialise y value each loop
25th Aug 2017, 9:07 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
Yeah, thank you:)
25th Aug 2017, 9:09 AM
Nasma Najeeb
Nasma Najeeb - avatar
0
Need an answer using while loops
25th Aug 2017, 8:57 AM
Nasma Najeeb
Nasma Najeeb - avatar
0
No question is to use while loops
25th Aug 2017, 9:00 AM
Nasma Najeeb
Nasma Najeeb - avatar
0
yeah sure!!
25th Aug 2017, 9:02 AM
Nasma Najeeb
Nasma Najeeb - avatar