Pattern printing in cpp | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
0

Pattern printing in cpp

I have to print a pattern like this * ## *** #### ***** But the hash symbol wasn't displayed in the way I expected what's the problem with my code anyone help me!? #include <iostream> using namespace std; int main() { int rows; cin >> rows; for(int i = 1; i <= rows; ++i) { if(i%2==0) { cout<<"#"; } else{ for(int j = 1; j <= i; ++j) { cout << "* "; } } cout << "\n"; } return 0; }

23rd Feb 2023, 5:42 PM
maha Lakshmi
maha Lakshmi - avatar
4 Réponses
+ 4
maha Lakshmi Using ternary operator #include <iostream> using namespace std; int main() { int rows; cin >> rows; for(int i = 1; i <= rows; ++i) { for(int j = 1; j <= i; ++j) cout << ((i % 2 == 1) ? "*" : "#"); cout << "\n"; } return 0; }
24th Feb 2023, 5:13 AM
A͢J
A͢J - avatar
+ 3
// you need similar to * loop for # #include <iostream> using namespace std; int main() { int rows; cin >> rows; for(int i = 1; i <= rows; ++i) { if(i%2==0) { for(int j = 1; j <= i; ++j) { cout << "# "; } } else{ for(int j = 1; j <= i; ++j) { cout << "* "; } } cout << "\n"; } return 0; }
23rd Feb 2023, 5:49 PM
JaScript
JaScript - avatar
+ 2
You forgot the for loop for the #.
23rd Feb 2023, 5:47 PM
Stefanoo
Stefanoo - avatar
+ 2
U can reduce your code remove both inside loops and write only once like this // you need similar to * loop for # #include <iostream> using namespace std; int main() { int rows; cin >> rows; for(int i = 1; i <= rows; ++i) { for(int j = 1; j <= i; ++j) { if(i%2==0) { cout << "# "; } else{ cout<< "* "; } } cout << "\n"; } return 0; }
23rd Feb 2023, 8:28 PM
A S Raghuvanshi
A S Raghuvanshi - avatar