Author Topic: C# - Multi byte addition source code using stack  (Read 1515 times)

kathir

  • Administrator
  • Sr. Member
  • *****
  • Posts: 283
C# - Multi byte addition source code using stack
« on: December 08, 2011, 06:09:25 pm »
Here is the C# source code for multibyte addition which can take any number of digits as input and prints out the result nicely using stack.

Code: (C#)
//Source Code Listing

using System;
using System.Collections.Generic;
using System.Text;

namespace CSTest
{  
   class Program
   {
      static void Main(string[] args)
      {
         Console.Write("Enter 1st number:");
         string buffer1 = Console.ReadLine();

         Console.Write("Enter 2nd number:");
         string buffer2 = Console.ReadLine();

         Stack<int> numberStack1 = new Stack<int>();
         Stack<int> numberStack2 = new Stack<int>();
         Stack<int> resultStack  = new Stack<int>();

         foreach(char ch in buffer1.ToCharArray())
         {
            if(ch >= '0' && ch <= '9')
               numberStack1.Push(ch - '0');
            else
            {
               System.Console.WriteLine("Invalid Input - Use digits 0 - 9");
               return;
            }
         }

         foreach (char ch in buffer2.ToCharArray())
         {
            if (ch >= '0' && ch <= '9')
               numberStack2.Push(ch - '0');
            else
            {
               System.Console.WriteLine("Invalid Input - Use digits 0 - 9");
               return;
            }
         }

         int remainder = 0;
         int a = 0;
         int b = 0;
         int length = (numberStack1.Count > numberStack2.Count) ? numberStack1.Count : numberStack2.Count;
         for (int i = 0; i < length; i++ )
         {
            a = b = 0;
            if (numberStack1.Count >= 1)
               a = numberStack1.Pop();
            if (numberStack2.Count >= 1)
               b = numberStack2.Pop();
            int result = a + b + remainder;
            remainder = result / 10;
            result = result % 10;
            resultStack.Push(result);
         }
         System.Console.Write("The result is: ");
         while (resultStack.Count >= 1)
         {
            System.Console.Write(resultStack.Pop());
         }
         System.Console.WriteLine();
      }
   }
}

Sample output:

Enter 1st number: 123456789123456789123456789
Enter 2nd number:123456789

The result is: 123456789123456789246913578

Press any key to continue . . .
« Last Edit: December 08, 2011, 06:11:52 pm by kathir »

 


Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.
Content copyright 2010-2014. Kathiresan. All rights reserved.
This page is using SMF version 2.0.1