Hi i am trying to write a function using my own addition algorithm and printing it out using arrays.. I am having trouble printing it out. I keep getting a memory location as my output instead of an integer number.
using namespace std;
int add(int a[], int b[], int result[]);
int main() {
int aop1[5] = {0,0,3,2,1}; // 321
int aop2[5] = {0,0,0,5,6}; // 56
int result[5] = {0};
add(aop1, aop2, result);
//print my array
for(int i = 0; i > 6; i++)
cout << result[i]<<endl;
}
// addition algorithm
int add(int a[], int b[], int result[]){
int carry = 0;
int sum = 0;
for (int i = 6; i > 0; i--){
sum = a[i] + b[i] + carry;
if (sum >=10){
sum -= 10;
carry = 1;
}
else carry = 0;
result[i] = sum;
return result[i];
}
}
#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <iomanip>
usingnamespace std;
int add(int a[], int b[], int result[]);
int main() {
int aop1[5] = {0,0,3,2,1}; // 321
int aop2[5] = {0,0,0,5,6}; // 56
int result[5] = {0};
add(aop1, aop2, result);
//print my array
for(int i = 0; i > 6; i++){
cout << result[i]<<endl;
}
}
// addition algorithm
int add(int a[], int b[], int result[]){
int carry = 0;
int sum = 0;
for (int i = 6; i > 0; i--){
sum = a[i] + b[i] + carry;
if (sum >=10){
sum -= 10;
carry = 1;
}
else {
carry = 0;
}
result[i] = sum;
return result[i];
}
}
Right off the bat I can see there's a problem with the for loop. In your test values you have 5 places, but you start with a value of 6 for the for loop. Furthermore, the first indice of a loop is 0, not 1. So you are starting outside of the range of those arrays. An elegant way to handle this would be to have a function that tokens out entered values into the individual array elements, but for the sake of this exercise, you at least need to start at the array size minus 1 and work down from there. I say minus 1 because if an array is 5 elements, the highest indice will be 5-1 or 4.