﻿ C# - Convert a decimal number to binary without an array

# C#: Convert a decimal number to binary without using an array

## C# Sharp For Loop: Exercise-41 with Solution

Write a program in C# Sharp to convert a decimal number into binary without using an array.

Visual Presentation:

Sample Solution:

C# Sharp Code:

``````using System;  // Importing necessary namespace

public class Exercise41  // Declaration of the Exercise41 class
{
public static void Main()  // Main method, entry point of the program
{
int n, i, j, binno = 0, dn;  // Declaration of variables

Console.Write("\n\n");  // Displaying new lines
Console.Write("Convert a decimal number to binary without using array:\n");  // Displaying the purpose of the program
Console.Write("---------------------------------------------------------\n\n");  // Displaying a separator and new lines

Console.Write("Enter a number to convert : ");  // Prompting user to enter a number

dn = n;  // Storing the original decimal number

i = 1;  // Initializing variable for binary conversion

for (j = n; j > 0; j = j / 2)  // Loop to convert decimal to binary
{
binno = binno + (n % 2) * i;  // Calculating binary digits
i = i * 10;  // Shifting position for next binary digit
n = n / 2;  // Updating the decimal number for next iteration
}

Console.Write("\nThe Binary of {0} is {1}.\n\n", dn, binno);  // Displaying the converted binary number
}
}
```
```

Sample Output:

```Convert a decimal number to binary without using array:
---------------------------------------------------------
Enter a number to convert : 65
The Binary of 65 is 1000001.
```

Flowchart:

C# Sharp Code Editor: