Arrays

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.


#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <iomanip>

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];
}
}
I think you have a problem with your loop, it's hard to tell because of the formatting (and lack of code tags).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <iomanip>

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];
     } 
}


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.
Topic archived. No new replies allowed.