1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

c# code for a pattern

Discussion in 'C#' started by naziasarguru, Jan 3, 2012.

  1. naziasarguru

    naziasarguru New Member

    Joined:
    Jan 3, 2012
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    somebody help me out with the c# program code which prints the following output:
    1
    0 1
    1 0 1
    0 1 0 1

    where the height of the triangle is taken as command line argument.
     
  2. Ranzan

    Ranzan New Member

    Joined:
    Jan 4, 2012
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    This will help you:

    Code:
                StringBuilder sb = new StringBuilder();
                //height of triangle  
                int height = 5;
                bool latestZeroWritten = false;
                for (int i = 1; i <= height; i++)
                {
                    //decides whether next line starts with 1 
                    latestZeroWritten = !(i % 2 == 0);
    
                    for (int j = 1; j <= i; j++)
                    {
                        if (latestZeroWritten)
                        {
                            sb.Append("1 ");
                            latestZeroWritten = false;
                        }
                        else
                        {
                            sb.Append("0 ");
                            latestZeroWritten = true;
                        }
    
                    }
                    sb.Append(Environment.NewLine);
                }
                MessageBox.Show(sb.ToString());
     
    Last edited by a moderator: Jan 4, 2012

Share This Page