Hi all, i have this following program to solve and it took me long time to figure it out.
Write a program which promts the user to enter 2 positive integers, each with up to 50 digits, then subtracts the second number from the first number, and prints the answer. You should use an array to store eaxh of the integers, with one digit in each array element. Each input should be in the normal format, e.g.
enter first integer
15615615484321315161231
enter second integer
78945643554895112
Similarly the output of the answer should be in the normal format, i.e. the format that you expect to get from a calculatormwith a large enough display.
the difference is: 48494556421684
or
the difference is: -4564864545646
The code i tried first is the following but after finishing, i could not make the subtraction..
(i could not initialise the 2 arrays to do the subtraction)
HEADER FILE:
#ifndef READARRAY_H
#define READARRAY_H
#include<iostream>
using namespace std;
void read_int_as_array ( int input[] , int size, int& numdigits, bool& success);
#endif
READARRAY.CPP:
#include "readarray.h"
// function read_int_as_array
//
// parameter input: array to hold the digits of the integer
// parameter size: the size of the array
// parameter numdigits: the number of digits of the integer read in
// parameter success: indicates that integer was read successfully,
// or otherwise.
//
//
// This function reads an integer of up to "size" digits
// and stores the digits in the array "input".
//
void read_int_as_array(int input[], int size, int& numdigits, bool& success)
{
char temp;
int i;
success = true;
if (size < 1) return;
int count = 0;
// initialise array entries to 0
for (i = 0; i < size; i++)
input[i] = 0;
do
// loop through input characters
{
// get character
cin.get(temp);
// if we have not reached end of line or got too many digits
// place digit into array, converted to int
if ((temp != '\n') && (count < size))
input[count] = int(temp) - int('0');
// if the character was not a digit, make success false
if ((!isdigit(temp)) && (temp != '\n'))
success = false;
// increase counter
count ++;
}
while (temp != '\n');
// set numdigits to avoid counting the end of line character
numdigits = count-1;
MAIN ():
#include <iostream>
#include "readarray.h"
using namespace std;
int main()
{
const int MAXSIZE = 50;
int num1[MAXSIZE];
bool success;
int numdigits;
cout << "Enter a positive integer:" << endl;
read_int_as_array(num1,MAXSIZE,numdigits,success);
if (success)
cout << "Valid input" << endl;
else
cout << "Invalid input" << endl;
cout << endl << numdigits << " digits entered" << endl << endl;
for (int i = 0; i < MAXSIZE; i++)
cout << "Array entry " << i << ": " << num1[i] << endl;
char junk; cin.get(junk);
return 0;
}
Can you help me please?