Home > Backend Development > C#.Net Tutorial > How to print a binary triangle using C#?

How to print a binary triangle using C#?

王林
Release: 2023-08-24 15:05:04
forward
1009 people have browsed it

How to print a binary triangle using C#?

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("");
}
Copy after login

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
Copy after login

Example

is:

Example

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();
      }
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template