Add two large number using array - c++

sorry for my english.
I wrote a programm that add two large numbers.
Number 1 is read from file data1.in, the same with the second, data2.in.
The problem was when I tryed to add 68925579999999999990+79925579999999999990 I am getting the wrong result:48951159999999999980.
using python to add these numbers I have got 148851159999999999980.
Where I got wrong ??
#include <iostream.h>
#include <fstream.h>
#include<math.h>
int n = 0;
int m = 0;
const int zerou = 9000;
//using namespace std;
void zero(int*a)
{
for(int i = 0;i<zerou;i++)
a[i]=0;
}
void zero(int*a,int*b)
{
for(int i = 0;i<zerou;i++)
a[i]=b[i]=0;
}
void rebuild(int* a)
{
int temp[9000];
zero(temp);
int i;
int delta = abs(m-n)+1;//k1 -dim a
for(i = delta;i<n+delta;i++)
{
temp[i] = a[i-delta];
a[i-delta] = 0;
}
n += delta;
for(i =0;i<n;i++)
a[i] = temp[i];
}
void rebuildS(int* a)
{
int temp[9000];
zero(temp);
int i;
int delta = abs(m-n)+1;//k1 -dim a
for(i = delta;i<m+delta;i++)
{
temp[i] = a[i-delta];
}
m += delta;
for(i =0;i<m;i++)
a[i] = temp[i];
}
void citirea(int* ar){
ifstream f;
f.open("data1.in");
int data;
while (f>>data){
ar[n++] = data;
}
f.close();
}
void citirea_(int* ar){
ifstream f("data2.in");
int data;
while (f>>data){
ar[m++] = data;
}
f.close();
}
/*
void perDig(int*a, int*b,int *t,int i)
{
*t += (a[i]+b[i])/10;
a[i] = (a[i]+b[i]+*t)%10;
}*/
void adunarea(int*a, int* b)
{
int transport = 0;
int sum;
for(int i = n;i>=0;i--)
{
sum = a[i]+b[i]+transport;
//sum = perDig(a,b,transport,i);
if(sum >9)
{
transport = (sum)/10;
sum %=10;
}
a[i] = sum;
}
}
int main()
{
int a[9000],b[9000];
zero(a,b);
citirea(a);
citirea_(b);
if(n > m)
rebuildS(b);
else if(m > n)
rebuild(a);
adunarea(a,b);
ofstream rez;
rez.open("data.out");
for(int i = 0;i<m;i++)
{
rez<<a[i]<<" ";
}
rez.close();
cin.get();
return 0;
}

There are two errors in your answer.
if (!sum > 9) you don't zero the transport, so numbers carry forever.
You are going to be one digit short because you add N digits and don't account for an Nth+1 digit in the answer if transport != 0.
You have a bigger problem, though. You don't know how to debug the code yourself. If in doubt, make the program tell you each step it performs, and read what it says, and see where it goes wrong. Knowing how to do this is worth more than 10 correct versions of your code.
void adunarea(int*a, int* b)
{
int transport = 0;
int sum;
for(int i = n;i>=0;i--)
{
cout << a[i] << " + " << b[i] << " + " << transport << endl;
sum = a[i]+b[i]+transport;
if(sum >9)
{
transport = (sum)/10;
sum %=10;
}
a[i] = sum;
cout << " = " << sum << " ( " << transport << " )" << endl;
}
}
All I've done is add two print statements, and with that and the correct answer you can look for the first incorrect digit and see absolutely everything about how the wrong digit was made, and then fix it.

Related

Program is meant to count how many duplicates are in an array. However, it returns the wrong frequency values

Normally I would use other methods to fix this program but I am not allowed to use advanced techniques for this project, and so what I have is more or less as far as I'm allowed to go.
So my program is meant to take in an array with 10 numbers and then output how many of each value is in the array. For example, {1, 1, 1, 1, 1, 2, 2, 2, 2, 2} is meant to return
5 1
5 2
However, it returns
6 1
4 2
I've made sure that the finalData and Data arrays are holding the proper values.
cout << count(data, data + MAX_VALUE, finalData[i+1]) << " " << data[i] << "\n";
seems to be outputting the wrong value.
for some reason. I believe the error is in my last function, getResults, more specifically the last for loop. Here is that function.
void getResults(int finalData[], int data[])
{
int temp[MAX_VALUE];
int j = 0;
for (int i = 0; i < MAX_VALUE - 1; i++)
if (finalData[i] != finalData[i + 1])
temp[j++] = finalData[i];
temp[j++] = finalData[MAX_VALUE - 1];
for (int i = 0; i < j; i++)
{
finalData[i] = temp[i];
}
for (int i = 0; i < j; i++)
{
cout << count(data, data + MAX_VALUE, finalData[i+1]) << " " << data[i] << "\n";
}
}
This is my complete code.
#include<iostream>
#include<iomanip>
#include<string>
#include<cmath>
#include <algorithm>
using namespace std;
void printHeader();
int getData(string);
void getResults(int finalData[], int data[]);
const int MAX_VALUE = 10;
int main(void)
{
int countValue = 0;
int freq = 0;
printHeader();
int data[MAX_VALUE] = {};
int frequency[MAX_VALUE] = {};
for (int i = 0; i < MAX_VALUE; i++)
{
cout << "Please enter data position " << i + 1 << "\n";
data[i] = getData("\nPlease enter a valid integer.\n");
}
sort(data, data + MAX_VALUE);
int values[MAX_VALUE] = {};
int secondData[MAX_VALUE] = {};
for (int i = 0; i < MAX_VALUE; i++)
{
secondData[i] = data[i];
}
getResults(data, secondData);
return 0;
}
void printHeader()
{
}
int getData(string error)
{
int userInput = 0;
do
{
cin >> userInput;
if (cin.fail())
{
cout << error;
}
} while (cin.fail());
return userInput;
}
void getResults(int finalData[], int data[])
{
int temp[MAX_VALUE];
int j = 0;
for (int i = 0; i < MAX_VALUE - 1; i++)
if (finalData[i] != finalData[i + 1])
temp[j++] = finalData[i];
temp[j++] = finalData[MAX_VALUE - 1];
for (int i = 0; i < j; i++)
{
finalData[i] = temp[i];
}
for (int i = 0; i < j; i++)
{
cout << count(data, data + MAX_VALUE, finalData[i+1]) << " " << data[i] << "\n";
}
}
Got the right answer. Made the changes I listed at the top as well as the following change to the count function.
cout << count(data, data + MAX_VALUE, finalData[i]) << " " << finalData[i] << "\n";
You have done a simple error. When you call getResults you pass the same array(pointer) to 2 different parameters. Now when you update finalData the unwanted side effect update also data(they are the same pointer(with different name). So when you call count will not return the expected result.
To solve this problem you can do a copy of the input array and give it as second parameter of getResults(...) function.

Square Root Code C++ without sqrt()

I have to create a code where the user inputs a number which is a perfect square, and I have to show its root. I've made this code, but I'm getting Segmentation Fault 11 , in this piece: int j = squareRootVector[i];
squareRoot.push_back(j);.
I can't change the code too much, so is there a way that I can do that?
#include <iostream>
#include <vector>
using namespace std;
int main() {
cout <<
"Enter the number:\n";
int input;
int number = input;
int divider = 2;
vector<int> squareRootVector;
vector<int> squareRoot;
cin >> number;
for(int divider = 2; number > 1; divider++) {
while((number % divider) == 0) {
number /= divider;
cout << number << endl;
squareRootVector.push_back(divider);
}
}
for(int i = 0; i < squareRootVector.size(); i++) {
cout << squareRootVector[i] << " ";
/*******PROBLEM*******/
if(squareRootVector[i] == squareRootVector[i+1]) {
int j = squareRootVector[i];
squareRoot.push_back(j);
}
/*********************/
}
int root;
for (int i = 0; squareRoot.size(); i++) {
root = root * squareRoot[i];
}
cout << "Square Root of " << input << " is: " << root << endl;
return 0;
}
The behaviour on accessing squareRootVector[i+1] with i just one below size (which your loop constaint allows) is undefined.
Consider writing
for (std::size_t i = 1; i < squareRootVector.size(); i++) {
instead, and rebasing the for loop body accordingly. I've also slipped in a change of type for i.
Shortly, the problem is that the last cycle in the last "for":
for(int i = 0; i < squareRootVector.size(); i++)
has the following line in it:
squareRootVector[i] == squareRootVector[i+1];
This is an "out of limits" error: squareRootVector only has squareRootVector.size() elements (let's say n), and the elements are indexed from 0 to n-1.
squareRootVector[i+1] in the last cycle points one element after the last one of squareRootVector, which is undefined behavior.
Using vector::iterator is proper way.
for(vector<int>::iterator it = squareRootVector.begin(); it != squareRootVector.end(); ++it)
{
if( (it+1) == squareRootVector.end() )
{
//what to do if there's no next member???
break;
}
if( *it == *(it+1) )
{
squareRoot.push_back(*it);
}
}
Thanks for the answers, guys. I've ended up with this code:
#include <iostream>
#include <vector>
using namespace std;
int main() {
cout << "Enter the number:\n";
int input = 0;
int number = 0;
cin >> input;
number = input;
int divider = 2;
vector<int> squareRootVector;
vector<int> squareRoot;
for(int divider = 2; number > 1; divider++) {
while((number % divider) == 0) {
number /= divider;
squareRootVector.push_back(divider);
}
}
int vectorSize = squareRootVector.size() - 1;
for(int i = 0; i < vectorSize; i++) {
if(squareRootVector[i] == squareRootVector[i+1]) {
int j = squareRootVector[i];
squareRoot.push_back(j);
}
}
int root = 1;
for (int i = 0; i < squareRoot.size(); i++) {
root = root * squareRoot[i];
}
cout << "Square Root of " << input << " is " << root << endl;
return 0;
}

Finding the mode of a sorted array using bin search

Hi there i've been tasked with Writing a simple program that is given an array of integers and determines the mode, which is the number that appears most frequently in the array.
The approach i'm trying to adopt is using a bubble sort with a bin search algorithm my level of knowledge is at a beginner stage can someone help point me?
Where i'm going wrong i believe it to be passing the correct search value to find it in the array! But i maybe wrong but some help would be very much appreciated, thanks in advance for those to take time to try help me.
#include <iostream>
using namespace std;
const int arrayLength = 10;
int searchVal;
int numGroup[arrayLength];
bool isSorted(int [], int arrayLength);
int binSearch(int [],int arrayLegth,int searchVal);
int main()
{
// Take in num
for (int index = 0; index < arrayLength; index++)
{
cout << "Enter Number: ";
cin >> numGroup[index];
}
// Sort numbers
//var to hold the val being swaped
int swapHolder = 0;
//bubble sort
for (int iSort = 0; iSort < arrayLength; iSort++)
{
for (int jSort = (iSort + 1); jSort <= arrayLength - 1; jSort++)
{
if (numGroup[iSort] > numGroup[jSort])
{
swapHolder = numGroup[iSort];
numGroup[iSort] = numGroup[jSort];
numGroup[jSort] = swapHolder;
}
}
}
//passes the sorted array and the length to the isSorted
isSorted(numGroup, arrayLength);
return 0;
}
bool isSorted(int numGroup[], int arrayLength){
cout << "Final result" << endl;
for (int index = 0; index < arrayLength - 1 ; index++)
{
if (numGroup[index] > numGroup[index + 1])
{
cout << "it's false";
system("pause");
return false;
}
cout << numGroup[index] << endl;
//cout << arrayLength << endl;
}
cout << numGroup[arrayLength - 1] << endl;
//trying to make searchVal
for (int i = 0; i < numGroup[arrayLength - 1]; i++)
{
if (numGroup[i] == numGroup[i])
{
int searchVal = numGroup[i];
}
}
binSearch(numGroup, arrayLength, searchVal);
cout << "It's true ";
system("pause");
return true;
}
int binSearch(int numGroup[], int arrayLength,int searchVal){
int low = 0;
int high = arrayLength - 1;
int mid;
while (low <= high)
{
mid = (low + high) / 2;
//search through the array
if (searchVal == numGroup[mid])
{
return mid;
}
else if (searchVal > numGroup[mid])
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
cout << "In bin search " << mid;
return mid;
}
You don't need to sort the array. You can have another array (freq) which will count the numbers appearances. So, a mini code for that:
int myArray[10];
int freq[1000]; //we assume that the numbers are smaller than 1000
void count()
{
for(int i = 0; i < 10; ++i)
{
++freq[v[i]];
}
}
int ReturnModeElement()
{
int maxFreq = -1;
int element = -1;
for(int i = 0 ; i < 10; ++i)
{
if(freq[v[i]] > maxFreq)
{
maxFreq = freq[v[i]];
element = v[i];
}
}
return element;
}
I hope you got the idea :)

c++ dynamic array Floating Point exception

For my homework I had to design an arraylist in c++ using only 1d arrays and pointers to make the array dynamic. I have done ample testing and my functions work correctly, but when I use the main that the teacher has provided me I get this floating point error. The point of this homework is to create a class that will work for the teachers main without changing any code in the main
here is the main:
#include "ArrayList.h"
#include <iostream>
using namespace std;
int main(int argc,char *argv[])
{
ArrayList arr;
for (int i=1;i<=50;i++)
{
arr.push_back(i);
}
cout << "Should contain numbers 1..50, is ";
cout << arr.toString() << endl;
for (int i=arr.size()-1;i>=1;i--)
{
arr.erase(arr[i]);
}
cout << "Should contain only 1, is ";
cout << arr.toString() << endl;
arr.erase(arr[0]);
for (int i=1;i<=50;i++)
{
if (i<=2)
arr.push_back(i);
else
{
int j=1;
while ((j<arr.size()) && (i%arr[j]!=0))
j++;
if (j==arr.size())
{
arr.push_back(i);
}
}
}
cout << "Prime numbers between 1 and 50 are: " << arr.toString() << endl;
}
here is my cpp:
#include<iostream>
#include<string>
#include<sstream>
#include "ArrayList.h"
using namespace std;
void ArrayList:: intialArr(int arr[])
{
for(int i = 0; i < length; i++)
{
arr[i] = 0;
}
}
string ArrayList:: toString()
{
std::ostringstream ss;
for(int i = 0; i < capacity; i++)
{
if(arr[i]>0 || arr[i] <0)
{
ss << arr[i] << " ";
}
}
return ss.str();
}
ArrayList::ArrayList()
{
length = 1;
capacity=0;
arr = new int[length];
intialArr(arr);
}
int& ArrayList:: operator[] (unsigned int i)
{
return arr[i];
}
void ArrayList:: push_back(int m)
{
if(capacity>=length)
{
int oldlength = length;
length = length*2;
int* curArr = new int[length];
intialArr(curArr);
for (int i = 0; i < oldlength; i++)
{
curArr[i] = arr[i];
}
delete [] arr;
arr = curArr;
}
arr[capacity] = m;
capacity++;
}
void ArrayList:: erase(int m)
{
if(capacity == length/2)
{
length = length/2;
int* curArr = new int[length];
intialArr(curArr);
for (int i = 0; i<capacity; i++)
{
curArr[i] = arr[i];
}
delete [] arr;
arr = curArr;
}
for(int i = 0; i < capacity; i++)
{
if(arr[i]==m)
{
for(int j = i; j<length; j++)
{
arr[j] = arr[j+1];
}
capacity--;
break;
}
}
cout << "length = " << length << " capacity = " << capacity << " capacity/length = " << capacity*2 << endl;
}
from what I have read online floating point exceptions are normally thrown when you try to divide by zero or an infinate value arises but I dont understand how I am getting either of these issues to arise.
My code get through the main where number 1-50 are added and deleted but I get the error once I go into setting up the array to hold prime numbers (after the arr.erase(arr[0]) in the main)
I just set a couple of tags in the main to find what my number look like going into the while ((j<arr.size()) && (i%arr[j]!=0))and i find that my numbers before the crash are
j = 1 and arr[j] = 2
i = 5 and arr.size() = 4

Run Time Check failure # 2 - Stack around variable 'ary' was corrupted. Why?

I'm new, don't know what I'm doing.
The compile warnings are on and do not show any warnings. Executable pops up and alerts of Run Time Check Failure #2.
Help would be appreciated as to why this is happening.
#include <iostream>
#include <string>
using namespace std;
class romanType {
public:
string strg;
void inputRoman(int ary[]);
//void CalculateRoman(int ary[]);
//void outputRoman(int total);
};
int main()
{
int M = 1000;
int D = 500;
int C = 100;
int L = 50;
int X = 10;
int V = 5;
int I = 1;
romanType numerals;
int ary[50];
cout << "This is to convert your input of Roman numerals to a positiver integer" << endl;
cout << "When prompted, do as you're told" << endl;
numerals.inputRoman(&ary[50]);
// numerals.CalculateRoman(&input[50]);
return 0;
}
void romanType::inputRoman(int ary[])
{
string strg;
int array_size;
int i;
cout << "Input the an appropriate Roman Numeral value" << endl;
cin >> strg;
array_size = strg.length();
for (i = 0; i < array_size; i++)
{
ary[i] = strg[i];
}
}
/*
void romanType::CalculateRoman(int ary[])
{
int total = 0;
int i;
for (i=0; i < 50 ; i++){
if (ary[i] < (ary[i + 1])){
total = total + (ary[i + 1] - ary[i]);
}
else {
total = total + ary[i];
}
}
cout << "Your conversion should equal " << total << endl;
}
*/`
&ary[50] is the address of 51st element of ary, which means it points just after the last element of ary. Change it to ary:
numerals.inputRoman(ary);