- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the Sum of two Binary Numbers without using a method in C#?
First, declare and initialize two variables with the binary numbers.
val1 = 11010; val2 = 10100; Console.WriteLine("Binary one: " + val1); Console.WriteLine("Binary two: " + val2);
To get the sum, loop until both the value are 0.
while (val1 != 0 || val2 != 0) { sum[i++] = (val1 % 10 + val2 % 10 + rem) % 2; rem = (val1 % 10 + val2 % 10 + rem) / 2; val1 = val1 / 10; val2 = val2 / 10; }
Now, let us see the complete code to find the sum of two binary numbers.
Example
using System; class Demo { public static void Main(string[] args) { long val1, val2; long i = 0, rem = 0; long[] sum = new long[30]; val1 = 11010; val2 = 10100; Console.WriteLine("Binary one: " + val1); Console.WriteLine("Binary two: " + val2); while (val1 != 0 || val2 != 0) { sum[i++] = (val1 % 10 + val2 % 10 + rem) % 2; rem = (val1 % 10 + val2 % 10 + rem) / 2; val1 = val1 / 10; val2 = val2 / 10; } if (rem != 0) sum[i++] = rem; i = i - 1; Console.Write("Sum = "); while (i >= 0) Console.Write(sum[i--]); } }
Output
Binary one: 11010 Binary two: 10100 Sum = 101110
Advertisements