Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to print a BinaryTriangle 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("
");
}
Above, “0” displays when the value of a is 1, whereas if a is 0, then 1 gets printed. In this way, if the rows are set as 7 i.e. the value of n in the for loop, then the following binary triangle would be visible.
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();
}
}
}Advertisements