Click here to Skip to main content
15,908,842 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to write a C sharp program to display something like this

1
01
101
0101 but i'm having trouble doing that.So far i can display only like this

1
10
101
1010. i know its simple for you guys..i need help...anyone??? thanks in advance...
Here is my coding so far..........
C#
static void Main(string[] args)
{
    String input;
    int i, j, ran;
    Console.WriteLine("Enter the Range:");
    input = Console.ReadLine();
    ran = Convert.ToInt16(input);

    for (i = 1; i <= ran; i++)
    {
        for (j = 1; j <= i; j++)
        {
            if (j % 2 == 0)
            {
                Console.Write("0 ");
            }
            else
            {
                Console.Write("1 ");
            }
        }
        Console.WriteLine();
    }
    Console.Read();
}

[Added code formatting]
Posted
Updated 14-Apr-10 8:11am
v3

You don't actually need the inner for loop. All that is happening is that a 0 or a 1 is being prepended to the previous string. So you can do this.


C#
StringBuilder sb= new StringBuilder();
           int count = 5;

           for (int t = 1; t <= count; t++)
           {
               sb.Insert(0, t & 1);
               Console.WriteLine(sb);
           }
 
Share this answer
 
C#
static void Main(string[] args)
        {
           
            for (int i = 0; i <= 5; i++)
            {
                for (int j = 0; j <= i; j++)
                {
                    if (j % 2 == 0 && i % 2 == 0)
                    {
                        Console.Write("1");
                    }
                    else if (j % 2 != 0 && i % 2 != 0)
                    {
                        Console.Write("1");
                    }
                    else
                    {
                        Console.Write("0");
                    }
                }
                Console.Write("\n");
            }
            Console.Read();
        }
 
Share this answer
 
v2
Alison beat me to it! just a small improvement to her solution - you don't need the if condition:
for (int j = i; j > 0; j--)
    {
    Console.Write("{0} ", j & 1);
    }
Console.WriteLine();
 
Share this answer
 
Since you code works nicely except that the 1's and 0's come out backwards, howabout starting the inner loop with j = i and reduce it by 1 each time, stopping at 1?
ie

for (j = i; j >= 1 ; j--)
{
      if (j % 2 == 0)
      {
            Console.Write("0 ");
      }
      else
      {
            Console.Write("1 ");
      }
}


I haven't tried it, just an idea for you. :)

[edit]Converted to code block to preserve formatting[/edit]
[edit]Cheers! :) Ali[/edit]
 
Share this answer
 
v5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900