Home »
.Net »
C# Programs
C# program to print pattern of 0's and 1's
This C# program is used to print 0's and 1's in a pattern, here I am using two loops (nested loop) and one counter variable to print the pattern, explanation and output is in the article.
Submitted by Ridhima Agarwal, on October 01, 2017 [Last updated : March 21, 2023]
Printing pattern of 0's and 1's
In this C# program, we are printing the following pattern of 0's and 1's.
1
01
010
1010
In this following solution, we will learn how to print the following of 0's and 1's?
Looking at the pattern shows that the 0 comes at odd position while 1 comes at even, when we start indexing from 0.
So for this we can use the modular logic. We have taken a count variable c which is the position; if the c is at odd index then "0" will be printed otherwise "1" will be printed.
In this we are using 2 for loops one for the row and other for the columns.
C# code for printing pattern of 0's and 1's
//include the namespace
using System;
namespace program {
class ab {
static void Main(String[] args) {
int i, j, c = 0;
for (i = 0; i < 4; i++) //loop for row
{
for (j = 0; j <= i; j++) //loop for column
{
c++; //increment in count variable
if (c % 2 == 0)
Console.Write(0);
else
Console.Write(1);
}
Console.WriteLine(); //for new line
}
}
}
}
Output
1
01
010
1010
C# Basic Programs »