where can I use try catch in dynamic memory allocation program? - c++

i'm new to the world of c ++ so i need a little help. I wrote a program with dynamic memory allocation that does the following:
Print a message to the user to enter the array size
User input the array size
Filling an array of n elements with zeros
Printing an array
Print a message to the user to enter n elements
User input n elements and their placement in the array
Print the total number of even numbers entered
Print the total number of odd numbers entered
Delete a dynamic array
#include <iostream>
using namespace std;
int main()
{
int even_counter = 0;
int odd_counter = 0;
int* a = NULL;
cout << "Enter size of an array:"<< endl;
int n;
cin >> n;
a = new int[n];
for (int i=0; i<n; i++) {
a[i] = 0;
cout << a[i]<<endl;
}
cout<< "Enter the elements of an array:"<<endl;
for (int i=0; i<n; i++) {
cin>>a[i];
}
for (int i=0; i<n; i++) {
if (i % 2 == 1) {
even_counter = even_counter + 1;
}
if (i % 2 == 0) {
odd_counter = odd_counter + 1;
}
}
cout << You've entered " << even_counter << " even and " << odd_counter <<
" odd numbers." << endl;
delete [] a;
a = NULL;
return 0;
}
I wanted to ask if my program is completely correct and how could I use the try catch command in this program. Thanks a lot

Related

How to check whether array elements entered by user are sorted or not in c++

So it's a simple c++ program which takes 2 sorted arrays from user dynamically using new operator and sum ups their size to create a third array which is equal to the length of the both array sum..
Like final_arr = arr1_size +arr2_size;
Everything is working fine but the problem is that is that I am taking array values from user so I need to check up that array entered by user is sorted or not, if array is not sorted then program must take that array values from user until he entered in correct order. I am using label with goto statement for checking the array, if some element smaller than previous element is found, then we will go at the top of the for loop through goto statement..as shown in code below.
//receiving array 1 input from user dynamically...
cout << "How many numbers you want to enter for array 1" << endl;
cin >> arr1_size;
arr1 = new int [arr1_size]; //creating array dynamically
arr1_label: //goto label
cout << "Enter numbers " << endl; //just to display
for (int i = 0; i < arr1_size; i++) { //loop for taking value from the user for arr1
cin >> arr1[0];
}
for (int i = 1; i < arr1_size; ) {//loop for checking for unordered array, if detects restart the input for loop
if (arr1[i--] > arr1[i]) {
cout << "Array 1 is not sorted" << endl;
goto arr1_label;
break;
}
i++;
}
It's a task in which I can't use vector ... I only have to use arrays dynamically.....Complete code of project is given below..
int main()
{
int arr1_size, arr2_size, final_arr_size;
int* arr1; int* arr2; int* final_array;
//receiving array 1 input from user dynamically...
cout << "How many numbers you want to enter for array 1" << endl;
cin >> arr1_size;
arr1 = new int [arr1_size]; //creating array dynamically
arr1_label: //goto label
cout << "Enter numbers " << endl; //just to display
for (int i = 0; i < arr1_size; i++) { //loop for taking value from the user for arr1
cin >> arr1[0];
}
for (int i = 1; i < arr1_size; ) {//loop for checking for unordered array, if detects restart the input for loop
if (arr1[i--] > arr1[i]) {
cout << "Array 1 is not sorted" << endl;
goto arr1_label;
break;
}
i++;
}
//receiving array 2 input from user dynamically...
cout << "How many numbers you want to enter for array 2" << endl;
cin >> arr2_size;
arr2 = new int[arr2_size];
cout << "Enter numbers " << endl;
for (int i = 0; i < arr2_size; i++) {
cin >> arr2[i];
}
//Merged array code here...
final_arr_size = arr1_size + arr2_size;
final_array = new int[final_arr_size];
int i = 0, j = 0, k = 0;
while (i < arr1_size && j < arr2_size) {
if (arr1[i] < arr2[j]) {
final_array[k++] = arr1[i++];
}
else {
final_array[k++] = arr2[j++];
}
}
while (i < arr1_size) {
final_array[k++] = arr1[i++];
}
while (j < arr2_size) {
final_array[k++] = arr2[j++];
}
//displaying final array
for (int i = 0; i < final_arr_size; i++) {
cout << final_array[i] << " ";
}
//deleting dynamically allocated memory.
delete[] arr1;
delete[] arr2;
delete[] final_array;
return 0;
}
#include <algorithm>
// ...
// check if arr1 is sorted
bool input_is_sorted = std::is_sorted(arr1, arr1 + arr1_size);
See https://en.cppreference.com/w/cpp/algorithm/is_sorted
Of course you would better replace bare pointers with std::vector etc.

Checking for duplicates in an array using for loop

I am trying to check whether there is any duplicate integer in the user input array. The problem is that the validation of the duplicate does not work properly and I have no idea why it is not showing the desired output. Following is the code:
#include <iostream>
using namespace std;
int main()
{
int length;
int arrValue;
cout << "Enter the length : ";
cin >> length;
int *arr = new int[length];
cout << "Enter " << length << " integers for array : ";
for(int i = 0; i < length; i++)
{
cin >> arr[i];
}
cout << "Array : ";
for(int i = 0; i < length; i++)
{
arrValue = arr[i];
for(int k = i + 1; k < length; k++)
{
if(arr[i] == arr[k])
{
cout << "Duplicate found" << endl;
break;
}
else
{
cout << arrValue << " ";
}
}
}
delete[] arr;
}
Current result (assuming no duplicate in user input):
Enter the length: 5
Enter 5 integers for array : 5 4 3 2 1
Array : 5 5 5 5 4 4 4 3 3 2
Expected result (assuming no duplicate in user input):
Enter the length: 5
Enter 5 integers for array : 5 4 3 2 1
Array : 5 4 3 2 1
Current result (assuming duplicate in user input):
Enter the length: 5
Enter 5 integers for array : 5 4 4 2 1
Array : 5 5 5 5 Duplicate found 4 4 3
Expected result (assuming duplicate in user input):
Enter the length: 5
Enter 5 integers for array : 5 4 4 2 1
Array : Duplicate found
I believe my loops is the source to the problem. The current result output 10 times and I do not understand why there will be so many same numbers appearing.
Do note that I am trying to apply the validation using loop only and not from C++ standard library.
The issue in your code is that you are printing out each array element every time a particular element is not matching another element. It seems that you only want to print out whether any duplicate values are found. For this, you can use a bool flag to indicate whether any element is duplicated:
bool found_dup = false;
for(int i = 0; i < length; i++)
for(int k = i + 1; k < length; k++)
if(arr[i] == arr[k])
{
found_dup = true;
break;
}
// else: don't print anything yet
and then at the end print out the array:
if (found_dup)
std::cout << "Duplicate found";
else
for(int i = 0; i < length; i++)
std::cout << arr[i] << " ";
You may achieve the program in a more enhanced way (where you don't need to define the length manually - notice the explanation given as comments in code):
#include <iostream> // for input/output operation
#include <vector> // for dynamic array management
#include <sstream> // to split the user inputs and assign them to the vector
#include <algorithm> // to sort the vector
#include <string> // to work with getline()
// using this statement isn't recommended, but for sake of simplicity
// and avoiding the use of std:: everywhere temporarily (for small programs)
using namespace std;
int main(void) {
vector<int> numbers;
vector<int> duplicates;
string input;
int temp;
// getting the user input as string
cout << "Enter the numbers: ";
getline(cin, input);
stringstream ss(input);
// splitting the user input string into integers and assigning
// them into the vector
while (ss >> temp)
numbers.push_back(temp);
// sorting the vector in increasing order
sort(numbers.begin(), numbers.end());
// getting the unique numbers (which are not repeated)
cout << "Unique numbers: ";
for (size_t i = 0, len = numbers.size(); i < len; i++) {
if (temp == numbers[i])
// if found a duplicate, then push into the 'duplicates' vector
duplicates.push_back(temp);
else
cout << numbers[i] << ' ';
temp = numbers[i];
}
// getting the duplicates
cout << "Total duplicates: ";
for (size_t i = 0, len = duplicates.size(); i < len; i++)
cout << duplicates[i] << ' ';
cout << endl;
return 0;
}
It'll output something like:
Enter the numbers: 1 4 8 9 3 2 3 3 2 1 4 8
Unique numbers: 1 2 3 4 8 9
Total duplicates: 1 2 3 3 4 8
Please change the if condition to something like this.
cout << "Enter the length : ";
cin >> length;
int *arr = new int[length];
cout << "Enter " << length << " integers for array : ";
for(int i = 0; i < length; i++)
{
cin >> arr[i];
}
cout << "Array : ";
for(int i = 0; i < length; i++)
{
arrValue = arr[i];
for(int k = i + 1; k < length; k++)
{
if(arrValue == arr[k]) //change here.
{
cout << "Duplicate found" << endl;
break;
}
else
{
cout << arrValue << " ";
}
}
}
delete[] arr;
}
I would also suggest to use a map data structure. Map allows you to count the frequency of numbers, and thus detect duplicates in linear time.
map<int, int> m; // specify the key-value data-type.
for(int i = 0;i<length;i++)
{
m[arr[i]]++;
}
map<int, int>::iterator it; // an iterator to iterate over the datastructure.
for(it = m.begin();it!=m.end();it++)
{
if(it->second>1) //it->second refers to the value(here, count).
{
cout<<it->first<<" "; //it->first refers to the key.
}
}
Your loops are actually iterating n-1 times for first element, n-2 times for second element etc., where n is the length of your array. This is why for 5 element array you have printed 5 4 times.
But generally, if the purpose is to detect duplicates in the array, this strategy is not the best one. Please note that having exemplary array 4 3 4, with current approach you will correctly detect for the first 4 that the third element is also 4 but once you will move to the third element, it will be marked as ok since it is not checked with the first one element.
You may consider another strategy: create another array of the n size. Then iterate through your original array and for each element check if that element is already in the new array. If you detect the presence, you may raise duplicate event. Otherwise you can add this element to the array.
It doesn't work because you're trying to print the same value everytime you find a different one. I got here a solution with one more array that will store the array. It would work too with just one array.
#include <iostream>
using namespace std;
int main()
{
int length;
int arrValue;
cout << "Enter the length : ";
cin >> length;
int *arr = new int[length];
int *noDuplicateArr = new int[length];
cout << "Enter " << length << " integers for array : ";
for(int i = 0; i < length; i++)
cin >> arr[i];
cout << "Array : ";
bool duplicateFound = false;
int noDuplicateArrLen = 0;
for(int i = 0; i < length && !duplicateFound; i++)
{
arrValue = arr[i];
int k;
for(k = i + 1; k < length; k++)
{
if(arrValue == arr[k])
{
duplicateFound = true;
break;
}
}
if (k == length)
noDuplicateArr[noDuplicateArrLen++] = arrValue;
}
if (duplicateFound)
{
cout << "Duplicate found";
}
else
{
for (int i = 0; i < noDuplicateArrLen; i++)
{
cout << noDuplicateArr[i] << " ";
}
}
delete[] arr;
delete[] noDuplicateArr;
}
Here is the version with just one array:
#include <iostream>
using namespace std;
int main()
{
int length;
int arrValue;
cout << "Enter the length : ";
cin >> length;
int *arr = new int[length];
cout << "Enter " << length << " integers for array : ";
for(int i = 0; i < length; i++)
cin >> arr[i];
cout << "Array : ";
bool duplicateFound = false;
int noDuplicateArrLen = 0;
for(int i = 0; i < length && !duplicateFound; i++)
{
arrValue = arr[i];
int k;
for(k = i + 1; k < length; k++)
{
if(arrValue == arr[k])
{
duplicateFound = true;
break;
}
}
if (k == length)
arr[noDuplicateArrLen++] = arrValue;
}
if (duplicateFound)
{
cout << "Duplicate found";
}
else
{
for (int i = 0; i < noDuplicateArrLen; i++)
{
cout << arr[i] << " ";
}
}
delete[] arr;
}

Random Integers Appearing In Program Bug

So I'm trying to make a program that will separate one array of ints into two, one for even ints, and one for uneven ints. Now, the strange thing is, if I only enter even or uneven numbers into the base array, the program works fine, but if I enter a mix of the two, one of the values held by the two new array will be a random, usually negative, big number, any idea why that is?
#include <iostream>
using namespace std;
void main()
{
int *a, n, *even_nums = 0, *uneven_nums = 0, counter_even = 0,counter_uneven = 0;
cout << "How many values does your array have?\n" << endl;
cin >> n;
a = new int[n];
cout << "\nEnter the values in your array:" << endl;
for (int i = 0; i < n; i++)
{
cout << "a[" << i << "] = ";
cin >> a[i];
if (a[i] % 2 == 0)
counter_even++;
else
counter_uneven++;
}
if (counter_even == 0)
cout << "There are no even numbers in your array." << endl;
else
even_nums = new int[counter_even];
if (counter_uneven == 0)
cout << "There are no uneven numbers in your array." << endl;
else
uneven_nums = new int[counter_uneven];
for (int i = 0; i < n; i++)
{
if (a[i] % 2 == 0)
even_nums[i] = a[i];
else
uneven_nums[i] = a[i];
}
if (counter_even != 0)
{
cout << "\nThe even numbers in your array are:" << endl;
for (int i = 0; i < counter_even; i++)
cout << even_nums[i] << " ";
}
if (counter_uneven != 0)
{
cout << "\nThe uneven numbers in your array are:" << endl;
for (int i = 0; i < counter_uneven; i++)
cout << uneven_nums[i] << " ";
}
system("PAUSE");
}
In
for (int i = 0; i < n; i++)
{
if (a[i] % 2 == 0)
even_nums[i] = a[i];
else
uneven_nums[i] = a[i];
}
You are using the same index for all of the arrays. This will not work as even_nums and uneven_nums will be smaller than a if you have both. You will eventually be writing past the end of the array which is undefined behavior.
What you need to do is add one index for each array and every time you insert an element into the array then you advance that index.
for (int i = 0, u = 0, e = 0; i < n; i++)
{
if (a[i] % 2 == 0)
even_nums[e++] = a[i];
else
uneven_nums[u++] = a[i];
}
Also you are using void main() which is not standard and should not be used. int main() and int main(int argc, char** argv) are the standard acceptable signatures of main()
In the block
for (int i = 0; i < n; i++)
{
if (a[i] % 2 == 0)
even_nums[i] = a[i];
else
uneven_nums[i] = a[i];
}
you are using i as the same index for arrays a, even_nums and uneven_nums. You need to use separate indexes for these arrays.
For example, if you have n=10 elements, 5 even and 5 odd, your even_nums and uneven_nums contains only 5 elements each.

Lesser number of columns of the second row "cuts off" a bigger number of columns of the first row

*Edit: Still, when input 3 columns for the 1st row and 2 columns for the 2th, in the output 1st row becomes 2-elemented as the first.
Problem with outputting dynamically allocated number of equipes with separately dynamically allocated number of columns (for number of catches for the each equip)... Namely, if I try to allocate 2 equipes and then for the first equip two "catches" of fish (two columns) and for second equip three catches of fish, everything is o.k.... but if I try input of smaller number of columns ("catches") for the second row (equip) then in the output the "excess" of the first row is "cutted off", so for example if there where a 3 columns input for the 1st row and 2 columns input for the second row, in the output there will be just two columns (indices of numbers) for the every of the two rows.
#include<iostream>
int main()
{
using namespace std;
int *sum;
int *a = new int;
int *b = new int;
cout << "Total number of equips: ";
cin >> *a;
// Allocate a two-dimensional 3x2 array of ints
int** ippArray = new int*[*a];
for (int i = 0; i < *a+1; ++i) {
ippArray[i] = new int[*b];
}
// fill the array
for (int i = 1; i < *a+1; ++i) {
cout << "Total number of catches for " << i << "th equip : ";
cin >> *b;
cout << "Equip number: " << i << endl;
for (int j = 1; j < *b+1; ++j) {
cout << "Catch number: " << j << endl;
cin >> ippArray[i][j];
ippArray[i][j];
}
}
// Output the array
for (int i = 1; i < *a+1; ++i) {
for (int j = 1; j < *b+1; ++j) {
cout << ippArray[i][j] << " ";
*sum = *sum + ippArray[i][j];
}
cout << endl;
}
cout << endl;
cout << "All catches of the all equipes: " << *sum-3;
// Deallocate
for (int i = 1; i < *a+1; ++i) {
delete [] ippArray[i];
}
delete [] ippArray;
// Keep the window open
cin.get();
return 0;
}
First, don't make your integers into pointers (int *a = new int;) unless they really need to be. It makes the code much harder to read, and if anyone has to maintain your code they'll call you an a-hole.
Second, int** ippArray = new int*[*a]; combined with multiple spots where you do this... for (int i = 1; i < *a+1; ++i) are bad. ippArray has valid references from 0 to *a, therefore it should be for (int i = 0; i < *a; ++i)
Edit: Try something like this http://ideone.com/4egQl3
Edit2: Also the standard advice...
{
std::vector<string> advice;
advice.push_back( "These will make your life easier" );
}
// No de-allocation needed!
Parts of your program that have undefined behaviour
Use of *b before you assign to it
Access out-of-bounds elements of all your arrays
Never initialise sum
Use of *sum before you assign to it
cleaned up, your code becomes
int main()
{
using namespace std;
int sum, a, b;
cout << "Total number of equips: ";
cin >> a;
typedef vector<vector<int> > vvint;
typedef vector<int> vint;
// Allocate a two-dimensional structure of ints
vvint ippArray(a);
// fill the array
for (vvint::size_t i = 0; i < a; ++i) {
cout << "Total number of catches for " << i+1 << "th equip : ";
cin >> b;
cout << "Equip number: " << i+1 << endl;
ippArray[i] = vint(b);
for (int j = 0; j < b; ++j) {
cout << "Catch number: " << j+1 << endl;
cin >> ippArray[i][j];
}
}
// Output the array
for (const vint & inner : ippArray) {
for (int num : inner) {
cout << num << " ";
sum += num;
}
cout << endl;
}
cout << endl;
cout << "All catches of the all equipes: " << sum;
cin.get();
return 0;
}

C++ Populate new elements in a resized dynamic array

While ripping through my homework, I've run across a bug I can't figure out. I've read and played around it but I can't figure out what I'm doing wrong.
The user enters an int pointer array, then the code is supposed double the size of the array and populate the new elements with 0. The problem is that the new elements aren't 0. What am I doing wrong and what are these numbers being printed, addresses?
Output:
Enter array size: 3
Enter Element 0: 10
Enter Element 1: 11
Enter Element 2: 12
Entered Array:
Element 0/3 is 10
Element 1/3 is 11
Element 2/3 is 12
Resized Array:
Element 0/6 is 10
Element 1/6 is 11
Element 2/6 is 12
Element 3/6 is -33686019
Element 4/6 is 1196933248
Element 5/6 is 201354124
Press any key to continue . . .
Code:
#include <iostream>
#include <string>
using namespace std;
int *createArray(int size)
{
int *newArray;
newArray = new int[size];
for( int i = 0; i < size; i++){
cout << "Enter Element " << i << ": ";
cin >> newArray[i];
}
return newArray;
}
int *dblArraySize ( int *myArray, int& size)
{
int *newArray;
newArray = new int[size*2];
for (int i = 0; i < size; i++)
newArray[i] = myArray[i];
for (int i = size; i < size*2; i++){
newArray[i] = 0;
}
size = size*2;
return newArray;
}
void displayArray(int *anArray, int size, string msg)
{
cout <<endl << endl << msg;
for (int i = 0; i<size;i++){
cout << endl << "Element " << i << "/" << size << " is " << anArray[i];
}
}
int main ()
{
int size,
*mainArray;
cout << "Enter array size: ";
cin >> size;
mainArray = createArray(size);
displayArray(mainArray,size, "Entered Array:");
dblArraySize(mainArray,size);
displayArray(mainArray,size, "Resized Array:");
}
The problem is that you are returning the newArray from dblArraySize, but never using it. You never modify mainArray
dblArraySize(mainArray,size);
Should be:
mainArray = dblArraySize(mainArray,size);
Also note: You are forgetting to release the memory for the original array.