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; }
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;
}
+ 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;
}
+ 2
You forgot the for loop for the #.
+ 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;
}