Binary triangle is formed with 0s and 1s. To create one, you need to work around a nestes for loop and display 0s and 1s till the row entered.
for (int i = 1; i <= n; i++) { for (j = 1; j <= i; j++) { if (a == 1) { Console.Write("0"); a = 0; } else if (a == 0) { Console.Write("1"); a = 1; } } Console.Write(""); }
In the above code, "0" is displayed when the value of a is 1, and "1" is displayed when the value of a is 0. In this way, if the number of rows is set to 7 in the for loop, that is, the value of n is 7, the following binary triangle will be displayed. The Chinese translation of
1 01 010 1010 10101 010101 0101010
using System; namespace Program { public class Demo { public static void Main(String[] args) { int j; int a = 0, n = 7; // looping from 1 to 7 for (int i = 1; i <= n; i++) { for (j = 1; j <= i; j++) { if (a == 1) { Console.Write("0"); a = 0; } else if (a == 0) { Console.Write("1"); a = 1; } } Console.Write(""); } Console.ReadLine(); } } }
The above is the detailed content of How to print a binary triangle using C#?. For more information, please follow other related articles on the PHP Chinese website!