如何使用C#打印一个二进制三角形?

王林
王林 转载
2023-08-24 15:05:04 575浏览

如何使用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("");
}

上面的代码中,当a的值为1时显示“0”,而当a的值为0时显示“1”。这样,如果在for循环中将行数设置为7,即n的值为7,则会显示以下二进制三角形。

1
01
010
1010
10101
010101
0101010

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

以上就是如何使用C#打印一个二进制三角形?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除