Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
i need help with this program

subtracting 2 large numbers using string





using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SUBTRACTION PROGRAM
{
class Arithmetic
{
static void Main(string[] args)
{
const int LENGTH = 1000;
String In1;
String In2;
String Out;
int[] Top = new int[LENGTH];
int[] Bottom = new int[LENGTH];
int[] Dif = new int[LENGTH - 1];
StringBuilder temp;
int borrow = 0;
int TopLen = 0;
int BottomLen = 0;
int LenDif = 0;
int SumLen = 0;
int TopIn = 0;
int BottomIn = 0;



Console.WriteLine("Doing Subtraction\n");
Console.Write("Enter the First Number: ");
In1 = Console.ReadLine();
Console.Write("Enter the Second Number: ");
In2 = Console.ReadLine();


//GETTING LARGER NUMBER ON TOP

// if(In1 < In2) //first shorter than second
{

for (int i = 0; i < TopLen; i++)
{
if (In1[i] < In2[i]) ;
Top[i] = In2[i] - '0';
}
LenDif = TopLen - BottomLen;

for (int i = 0; i < LenDif; i++)
{
Bottom[i] = 0; // pad bottom with zeros on left
}
for (int i = 0; i < BottomLen; i++)
{
Bottom[i + LenDif] = In1[i] - '0';
}
}
else

// if (In2 < In1 )
{
TopLen = In1.Length;
BottomLen = In2.Length;
for (int i = 0; i < TopLen; i++)
{
Top[i] = In1[i] - '0';
}
LenDif = TopLen - BottomLen;
for (int i = 0; i < LenDif; i++)
{
Bottom[i] = 0;
}
for (int i = 0; i < BottomLen; i++)
{
Bottom[i + LenDif] = In2[i] - '0';
}
}

// start subtraction from the left and work back to right

//---------------DOING ARITHMETIC---------------------------
for (int i = TopLen -1; i >= 0; i--)
{
//two inputs are same
if (In1[i] == In2[i])
{
Out = 0; // figure out.....
}


//one of the numbers is zero
else
{
if (BottomIn == 0)
{
Out = Top[i];
}
}
else
{
if (TopIn == 0)
{
Bottom[i] = Out;
}
}

}

for (int i = TopLen -1 -BottomLen)
{
//two digits plus borrow
if(i > TopLen -1 -BottomLen)
{
Dif[i] = Top[i] - Bottom[i];
if (Top[i] == 0)
{
borrow = 1;
Top[i] = 10;
Top[i] -= 9;
}
else
{
borrow = 0;
}
}

What I have tried:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SUBTRACTION PROGRAM 
{
    class Arithmetic
    {
        static void Main(string[] args)
        {
        const int LENGTH = 1000;
        String In1;
        String In2;
        String Out;
        int[] Top = new int[LENGTH];
        int[] Bottom = new int[LENGTH];
        int[] Dif = new int[LENGTH - 1];
        StringBuilder temp;
        int borrow = 0;
        int TopLen = 0;
        int BottomLen = 0;
        int LenDif = 0;
        int SumLen = 0;
        int TopIn = 0;
        int BottomIn = 0;



        Console.WriteLine("Doing Subtraction\n");
        Console.Write("Enter the First Number: ");
        In1 = Console.ReadLine();
        Console.Write("Enter the Second Number: ");
        In2 = Console.ReadLine();


        //GETTING LARGER NUMBER ON TOP 

        // if(In1 < In2)    //first shorter than second
        {
            
            for (int i = 0; i < TopLen; i++)
            {
                if (In1[i] < In2[i]) ;
                Top[i] = In2[i] - '0';
            }
            LenDif = TopLen - BottomLen;

            for (int i = 0; i < LenDif; i++)
            {
                Bottom[i] = 0;               // pad bottom with zeros on left 
            }
            for (int i = 0; i < BottomLen; i++)
            {
                Bottom[i + LenDif] = In1[i] - '0';
            }
        }
        else

         //   if (In2 < In1 )
        {
            TopLen = In1.Length;
            BottomLen = In2.Length;
            for (int i = 0; i < TopLen; i++)
            {
                Top[i] = In1[i] - '0';
            }
            LenDif = TopLen - BottomLen;
            for (int i = 0; i < LenDif; i++)
            {
                Bottom[i] = 0;
            }
            for (int i = 0; i < BottomLen; i++)
            {
                Bottom[i + LenDif] = In2[i] - '0';
            }
        }

        // start subtraction from the left and work back to right

        //---------------DOING ARITHMETIC---------------------------
        for (int i = TopLen -1; i >= 0; i--)
        {
            //two inputs are same 
            if (In1[i] == In2[i])
            {
               Out = 0;       // figure out.....
            }


            //one of the numbers is zero
            else
            {
                if (BottomIn == 0)
                {
                    Out = Top[i];
                }
            }
            else
            {
                if (TopIn == 0)
                {
                    Bottom[i] =  Out;
                }
            }

        }

        for (int i = TopLen -1 -BottomLen)
        {
            //two digits plus borrow
            if(i > TopLen -1 -BottomLen)
            {
                Dif[i] = Top[i] - Bottom[i];
                if (Top[i] == 0)
                {
                    borrow = 1;
                    Top[i] = 10;
                    Top[i] -= 9;
                }
                else
                {
                    borrow = 0;                
                }            
            }
Posted
Updated 7-May-19 19:14pm
Comments
Patrice T 7-May-19 17:40pm    
describe the problem you have.
Show sample input and output actual and expected.
[no name] 7-May-19 18:20pm    
Looks almost like assembler. I think you'll do well. (but you didn't initialize "TopLen")

The best thing to do is work with numbers as numbers. There are a few methods available such as int.Parse() or int.TryParse() which can assist.

I prefer to use the latter as it will return a boolean indicating if the operation was successful.

The way I rewrote a chunk of your code is using 2 instances TryParse() method to not only retrieve the values but to also return an error message if either value cannot be parsed.
C#
Console.WriteLine("Doing Subtraction\n");
Console.Write("Enter the First Number: ");
In1 = Console.ReadLine();
Console.Write("Enter the Second Number: ");
In2 = Console.ReadLine();

// new variables to store the actual values entered as numbers
int Input1 = 0;
int Input2 = 0;
int SubtractionValue = 0;
int AdditionValue = 0;

if ((!int.TryParse(In1, out Input1)) || (!int.TryParse(In2, out Input2))) {
	Console.WriteLine("You didn't enter 2 numbers");
} else {
	// do normal math for the rest of program
}
The other numeric types (float, double, Int64...) have similar functionality also.

Reference: Int32.TryParse Method (System) | Microsoft Docs[^]
 
Share this answer
 
Comments
Christian Graus 7-May-19 20:26pm    
I think a full example would do better to ask again with a while loop if they don't enter numbers....
MadMyche 7-May-19 20:28pm    
I had thought of that and started to code that way, but I figure baby steps would be a better approach
Christian Graus 7-May-19 20:29pm    
He's just going to copy and paste now you gave him full code anyhow :)
MadMyche 7-May-19 20:40pm    
That may be true. Maybe they will explore on their own and learn the old fashioned way. Or maybe ask another question
andres_fprado 7-May-19 22:55pm    
This does not comply with the original question. The submitted program is expected to work with numbers up to 1000 digits long. Numbers that long can not be represented by any of the built-in numeric types (not even by decimal).
You can compare strings. As a string, 1 is less than 22, because the leftmost character is most significant. What you're looking for is int.TryParse. It returns a bool. You can keep asking for a number until the user enters one.

 In1 = Console.ReadLine();
int n = 0;

if (int.TryParse(In1, out n)
{
// n is now the number version of In1
}
 
Share this answer
 
The following program does what you asked for, if I understood it correctly. The code could be simplified and optimized, but I went for readability. Hope it helps!

C#
using System;
using System.Linq;
using System.Text;

namespace substraction_program
   {
   class Arithmetic
      {
      static void Main(string[] args)
         {
         String In1;
         String In2;
         String Out;

         // Get and validate numbers
         Console.WriteLine("Doing Subtraction\n");
         do
            {
            Console.Write("\nEnter the First Number: ");
            In1 = Console.ReadLine();
            } while(!NumberValid(In1));

         do
            {
            Console.Write("\nEnter the Second Number: ");
            In2 = Console.ReadLine();
            } while(!NumberValid(In2));

         int maxLength = Math.Max(In1.Length, In2.Length);
         int[] Num1 = new int[maxLength];
         int[] Num2 = new int[maxLength];
         int[] Diff = new int[maxLength];

         // Load numbers from last to first char, completing with leading zeroes
         int i = maxLength - 1;

         foreach(var c in In1.Reverse())
            {
            Num1[i--] = c - '0';
            }
         while(i >= 0)
            {
            Num1[i--] = 0;
            }

         i = maxLength - 1;
         foreach(var c in In2.Reverse())
            {
            Num2[i--] = c - '0';
            }
         while(i >= 0)
            {
            Num2[i--] = 0;
            }

         // Determine largest number
         int largest = 0;     // -1 if Num1, 0 if equal, 1 if Num2
         for(i = 0; i < maxLength; ++i)
            {
            if(Num1[i] == Num2[i])
               continue;
            else
               {
               if(Num1[i] < Num2[i])
                  largest = 1;
               else
                  largest = -1;
               break;
               }
            }

         // If numbers are equal, fill result with zeroes
         if(largest == 0)
            {
            for(i = 0; i < maxLength; ++i)
               Diff[i] = 0;
            }
         else
            {
            // Start subtraction from RIGHT to left. 
            int borrow = 0;
            for(i = maxLength - 1; i >= 0; --i)
               {
               int n1 = largest > 0 ? Num2[i] : Num1[i]; // Digit from largest
               int n2 = largest > 0 ? Num1[i] : Num2[i]; // Digit from smallest
               n1 -= borrow;
               borrow = 0;

               while(n1 < n2)
                  {
                  borrow += 1;
                  n1 += 10;
                  }
               Diff[i] = n1 - n2;
               }
            if(borrow != 0)
               throw new InvalidOperationException("This should not happen!");
            // Note: this exception means the numbers were not correctly ordered.
            }

         // Store result in string
         StringBuilder sb = new StringBuilder();
         bool leading = true;
         for(i = 0; i < maxLength; ++i)
            {
            if(leading && Diff[i] == 0)
               continue;   // Skip leading zeroes.
            leading = false;
            sb.Append((char)(Diff[i] + '0'));
            }
         if(sb.Length == 0)   // If difference is zero!
            sb.Append('0');
         Out = sb.ToString();

         // Show result
         Console.WriteLine("\nThe result is:");
         Console.WriteLine(Out);
         }

      private static bool NumberValid(string str)
         {
         foreach(var c in str)
            if(c < '0' || c > '9')
               return false;     // Not a valid number!
         return true;            // All numbers -> valid!
         }
      }
   }
 
Share this answer
 
Quote:
i need help with this program

I suspect the first problem is that your program do not compile because of this line:
C#
// if(In1 < In2)    //first shorter than second

because the if is needed.

When you ask for help, it is a good idea to tell what is the problem and give error messages with position.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900