首頁  >  文章  >  後端開發  >  如何使用C#列印一個二進位三角形?

如何使用C#列印一個二進位三角形?

王林
王林轉載
2023-08-24 15:05:04937瀏覽

如何使用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.com。如有侵權,請聯絡admin@php.cn刪除