C# Program to Print a Binary Triangle

This is a C# Program to Print a binary triangle.

Problem Description

This C# Program Prints a Binary Triangle.

Problem Solution

Binary Triangle is a Triangle formed with 1’s and 0’s.Number of rows in the binary triangle is obtained from the user.

Program/Source Code

Here is source code of the C# Program to Print a Binary Triangle. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

```/*
* C# Program to Print a BinaryTriangle
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Program
{
class Program
{
public static void Main(String[] args)
{
int p, lastInt = 0, input;
Console.WriteLine("Enter the Number of Rows : ");
for (int i = 1; i <= input; i++)
{
for (p = 1; p <= i; p++)
{
if (lastInt == 1)
{
Console.Write("0");
lastInt = 0;
}
else if (lastInt == 0)
{
Console.Write("1");
lastInt = 1;
}
} Console.Write("\n");
}
}
}
}```
Program Explanation

In this C# program, we are reading the number of rows using ‘input’ variable. Binary Triangle is a triangle formed with 1’s and 0’s. Number of rows in the binary triangle is obtained from the user. Nested-if else condition statement is used to check that the value of ‘lastInt’ variable is equal to 1. If the condition is true, then execute the statement print the value as 0.

Otherwise, if the condition is false, then execute the else if condition statement and check the value of ‘lastInt’ variable is equal to 0. If the condition is true, then execute the statement and print the statement value as 1 and again initialize the value of ‘lastInt’ variable as 1. Print the Binary Triangle from the given number.

Runtime Test Cases
```
Enter the Number of Rows : 5
1
01
010
1010
10101```

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

Note: Join free Sanfoundry classes at Telegram or Youtube
If you wish to look at all C# Programming examples, go to 1000 C# Programs.

If you find any mistake above, kindly email to [email protected]