c++ - Addition and subtraction of arrays -
i have been working on day cant output right. want input 2 numbers, pushed 2 arrays can subtract or add together them , display result. seems simple, there few catches
input must pushed array, user, 1 one. in case don't come in value, code should assume'0'
or 'null'
. '0'
if in origin , 'null'
if in end. illustration if 1st number 234
, sec number 23
code should create '023'
, if come in first number 2
, 2nd number 3
don't come in in end code should assume null
. problems
i cant take 'carry' next set, in case sum greater10
. means value m getting add-on of 2 numbers doesn't matter if greater 10 or not. illustration add-on of 234
, 890
giving me [10, 12, 4]
here code.....
#include<iostream> using namespace std; main() { int first[10], second[10], result[10], c, n; cout << "enter number of elements in array "; cin >> n; if (n > 10 || n < 0) { std::cout << "invalid number, bad reader" << endl; system("pause"); homecoming 0; } cout << "enter elements of first array " << endl; (c = 0; c < n; c++) { cin >> first[c]; if (first[c] > 9 || first[c] < 0) { std::cout << "invalid number, bad reader" << endl; system("pause"); homecoming 0; } } cout << "enter elements of sec array " << endl; (c = 0; c < n; c++) cin >> second[c]; cout << "sum of elements of 2 arrays " << endl; (c = 0; c < n; c++) cout << first[c] + second[c] << endl; if ((first[c] + second[c]) > 9) { cout << "overflow" << endl; } //result[c] = first[c] + sec [c]; //cout << result[c] <<endl; system("pause"); homecoming 0; }
i appreciate suggestions.
in case intention have result of e.g.
234 + 890 = 1124
then addition loop should in reverse order. (since reading number of elements of array prompt, may utilize info input first/second numbers each array in order preferred next addition loop.)
for carry problem, need setup variable , utilize in loop this, example.
int sum[10] = {0}; int c; int carry = 0; (c = 0; c < n; c++) { sum[c] = first[c] + second[c] + carry; carry = sum[c] / 10; } if (c < n) sum[c] = carry; else cout << "overflow";
c++ arrays addition
No comments:
Post a Comment