adding two seperate arrays into one is displaying garbage

I'm trying to obtain a large integer (20 characters long) get it from a string then put it into an int array and do the math from there, I'm trying to add the two seperate arrays into one array and display it, but i am getting garbage
http://i.imgur.com/sIoiCEL.jpg

// ConsoleApplication11.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>

using namespace std;


int main()
{
string input1;
string operation;
string input2;
int array1[20];
int array2[20];

cout << "Enter an expression: ";
cin >> input1 >> operation >> input2;

if (input1.length() > 20)
cout << "Invalid Operand (too large). " << endl;
if (input2.length() > 20)
cout << "Invalid Operand (too large). " << endl;

if (input1 == "0" && operation == "%" && input2 == "0")
cout << "thanks for using my program. Good bye!" << endl;

// use subcript and size to keep track of quantity
for (int i = 0; i < input1.size(); i++)
{
array1[i] = input1[i] - '0';

}


//testing array
for (int i = 0; i < input1.size(); i++)
{
cout << array1[i];
}

int temp;
//make array stored backwards
for (int i = 0, j = input1.size() - 1; i< input1.size() / 2; i++, j--)
{
temp = array1[i];
array1[i] = array1[j];
array1[j] = temp;
}

cout << "\nbackwards:";

for (int i = 0; i < input1.size(); i++)
{
cout << array1[i];
}


// string 2
int temp2;
for (int i = 0; i < input2.size(); i++)
{
array2[i] = input2[i] - '0';

}

//make array stored backwards
for (int i = 0, j = input2.size() - 1; i < input2.size() / 2; i++, j--)
{
temp2 = array2[i];
array2[i] = array2[j];
array2[j] = temp2;
}


// if operator is +
int sum[20];
if (operation == "+")
{
for (int i = 0; i < 20; i++)
{
sum[i] = (array1[i] - '0') + (array2[i] - '0');

//carrying over
if (sum[i] >= 10)
{
sum[i + 1] = sum[i + 1] + (sum[i] - 10);
sum[i] = sum[i] - 10;

}

}
}
cout << "\nsum" << endl;


//make sum array stored in normal order
for (int i = 0, j = 20; i < 20; i++, j--)
{
temp2 = sum[i];
sum[i] = sum[j];
sum[j] = temp2;
}



// cout the sum
for (int i = 0; i < input1.size(); i++)
{
cout << sum[i];
}



// if operator is -
//if (operation == "-")






system("pause");
return 0;
}








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// if operator is +
	int sum[20]; //uninitialized
	if(operation == "+") {
		for(int i = 0; i < 20; i++) { //your number does not have 20 digits.
			//array have elements from 0 to 9, not from '0' to '9'
			//you already made the subtraction when copied from input
			sum[i] = (array1[i] - '0') + (array2[i] - '0'); //overwriting the carry

			// carrying over
			if(sum[i] >= 10) {
				//sum[i+1] is out of bounds in the last step
				//sum[i+1] is uninitialized 
				sum[i + 1] = sum[i + 1] + (sum[i] - 10); 
				sum[i] = sum[i] - 10;
			}
		}
	}

Last edited on
Topic archived. No new replies allowed.