c++ Given two sequences with n integers between 0 and 9, interpreted as two n-digit integers, calculate a sequence of numbers that represents the sum of the two integers. Example: n = 8, 1st sequence 8 2 4 3 4 2 5 1 2nd sequence + 3 3 7 5 2 3 3 7 1 1 6 1 8 6 5 8 8
c++
Given two sequences with n integers between 0 and 9, interpreted as two n-digit integers, calculate a sequence of numbers that represents the sum of the two integers. Example: n = 8,
1st sequence 8 2 4 3 4 2 5 1
2nd sequence + 3 3 7 5 2 3 3 7
1 1 6 1 8 6 5 8 8
I have generated random numbers for n-sequence numbers. The numbers can be entered from the user as well.
Value of n is taken from the user.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
void addSequence(int arr1[], int arr2[], int n)
{
int arrSum[n]; // Array to store sum
int i = n - 1, j = n - 1, k = n - 1; // Variables for indexing array arr1, arr2, arrSum.
int carry = 0, sum = 0; // Variables to find carry and sum of two numbers. For example, 9 + 3; sum = 12, carry = 1;
while (j >= 0)
{
sum = arr1[i] + arr2[j] + carry;
arrSum[k] = (sum % 10);
carry = sum / 10;
k--;
i--;
j--;
}
//If last number has carry value
if (carry)
arrSum[0] = arrSum[0] + 10;
//Printing sum array
cout<<endl<<"Sum array:\t";
for(int i=0;i<n;i++)
{
cout<<arrSum[i]<<"\t";
}
}
int main()
{
int arr1[8], arr2[8]; // Two array containing n sequence number
int n;
cout<<"\nEnter value of n: ";
cin>>n;
srand(time(0));
//Generating values of both arrays through random() function
int upper = 9, lower = 0;
for (int i = 0; i < n; i++)
{
arr1[i] = (rand() % (upper - lower + 1)) + lower;
arr2[i] = (rand() % (upper - lower + 1)) + lower;
}
cout<<"\nArray 1:\t";
for(int i = 0; i < n; i++)
{
cout<<arr1[i]<<"\t";
}
cout<<"\nArray 2:\t";
for(int i = 0; i < n; i++)
{
cout<<arr2[i]<<"\t";
}
addSequence(arr1,arr2,n);
return 0;
}
Step by step
Solved in 2 steps with 1 images