954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Patterns(For Loop)

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)

CY0T3R
Newbie Poster
5 posts since Feb 2012
Reputation Points: 10
Solved Threads: 0
 

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.

DJSAN10
Posting Whiz in Training
249 posts since Dec 2010
Reputation Points: 38
Solved Threads: 26
 
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;
}
Ali_2101
Newbie Poster
16 posts since Feb 2012
Reputation Points: 4
Solved Threads: 3
 

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. :)

StuXYZ
Practically a Master Poster
680 posts since Nov 2008
Reputation Points: 760
Solved Threads: 138
 

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";
}
CY0T3R
Newbie Poster
5 posts since Feb 2012
Reputation Points: 10
Solved Threads: 0
 

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";
}
ravenous
Posting Pro
516 posts since Jul 2005
Reputation Points: 269
Solved Threads: 92
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: