1
1 0
1 0 1
1 0 1 0
1 0 1 0 1
How To Print The Above Pattern ?? (Using For-Loops Only)
1.Take number of rows as input from user
2.Loop until all rows are done
3.According to the pattern, number of elements in a row = row number itself. Loop for printing elements in 1 row. If the element number you are printing is odd ,print 1, if it is even print 0.
Start coding and post back if you have any further problems in your code.
int main()
{
for(int i=0;i<5;i++)
{
int prev=0,curr=0;
for(int j=1;j<=i+1;j++)
{
curr=prev+pow(double(-1),j+1);
cout<<curr<<" ";
prev=curr;
}
cout<<endl;
}
return 0;
}
The most scary thing about the above code is the pow(double(-1),j+1)
...
please think, an alternating pattern is required.
I initial thought that it was homework help, but it is actually nicely formatted obstifacted C++. So am not sure that the code deserves the -1 reputation. :)
Thanks for the help guys i've made the source code for this pattern -
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
if(j%2!=0)
cout<<" "<<"1";
else cout<<" "<<"0";
}
cout<<"\n";
}
if you were so inclined, you don't actually need the if... else
structure in the inner-loop:
int rows = 5;
for( int i = 0; i < rows; ++i )
{
for( int j = 1; j <= i; ++j )
std::cout << " " << j % 2;
std::cout << "\n";
}
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.