Adding/Removing Elements in an Array Inside a Function Using Pointers - c++

I am trying to figure this problem out. This is for a project and our instructor requires this header. I got the check function working properly but adding when adding to the array we must use a pointer. My understanding is that we should copy this array to another array and replace the pointer. For example Array1 {1,2,3} then copy it to Array2 {1,2,3,4} then add 4 to expand the array. Unfortunately everything I have found researching.. vectors and other functions would be better suited for this task but we are required to only use the pointer and the size to resize and add the element.
// returns the index of the element in "arrayPtr" of "size"
// that corresponds to the element holding "number"
// if number is not in the array, returns -1
int check(int *arrayPtr, int number, int size);
// adds "number" to the array pointed to by "arrayPtr" of "size".
// if the number is not already there, if "number" is there - no action
// Note, the size of the array is thus increased.
void addNumber(int *& arrayPtr, int number, int &size);
// removes a "number" from the "arrayPtr" of "size".
// if "number" is not there -- no action
// note, "size" changes
void removeNumber(int *& arrayPtr, int number, int &size);
I have this so far:
// returns the index of the element in "arrayPtr" of "size"
// that corresponds to the element holding "number"
// if number is not in the array, returns -1
int check(int *arrayPtr, int number, int size) {
for (int i = 0; i < size; i++) {
if (arrayPtr[i] == number) {
return i;
}
}
return -1;
}
// adds "number" to the array pointed to by "arrayPtr" of "size".
// if the number is not already there, if "number" is there - no action
// Note, the size of the array is thus increased.
void addNumber(int *& arrayPtr, int number, int &size) {
if (check(arrayPtr, number, size)==-1) {
//add the element to the end of the array
}
//did not run if -1
}
// removes a "number" from the "arrayPtr" of "size".
// if "number" is not there -- no action
// note, "size" changes
void removeNumber(int *& arrayPtr, int number, int &size) {
}
Any hints or tips or suggestions on how to proceed would be appreciated!

To be more clear what you are trying to build is an Set like data structure (because you are avoiding duplicates).
Another thing from you code is you have big chunck of memory allocated for this purpose and you are just access it with the arrayPtr and size.
If this is the case You might be maintaining a MAX_MEMORY_SIZE.
something like
#define MAX_MEMORY_SIZE 1000000
Have this assumption,
Algorithm for addNumber:
If size+1 >= MAX_MEMORY_SIZE return an 'overflow or max memory' exception
Check for existence of new element
If found, do nothing and simply return
If not found, copy the new element # arrayPtr[size] (arrayPtr[size] = number). (You may choose to keep them in some order so that your search can be effective as well. For that your check function and implementation has to be different)
Increase the size
Algorithm for removeNumber:
Check for existence of given element
If not found, do nothing and simply return
If found, loop the all the elements array and shift 1 position left. A code like below.
Decrease the size
Hope this will take you to next level.
position = check(arrayPtr, number, size);
for (i = position; i < size-1; i++) {
arrayPtr[i] = arrayPtr[i+1];
}

Related

Is there a way to find the INDEX of the minimum value in an array using a recursive function? C++

I need to find the Index of the minimum number in an array using a recursive function in c++ the function can only get 2 parameters: the pointer to the array and the size of it.
int smallest(int arr[], int num);
I managed to do this but with a helper variable that is static and declared outside the function here is what I got:
static int flag = 0;
int smallest(int* arr, int num) {
if (flag == num - 1)
return flag;
if (arr[num - 1] > arr[flag]) {
return smallest(arr, num - 1);
} else {
flag++;
return smallest(arr, num);
}
}
Now my question is can I do this without the static variable or any other variable other than the num? here is what I got so far:
int smallest(int arr[], int num) {
if (arr != &arr[num - 1])
if (*arr < arr[num - 1])
smallest(arr, num - 1);
else
smallest(arr + 1, num);
return num - 1;
}
It doesn't return the index of the minimum value but it does get to its adress, the function ends when the array pointer address is the same as the address of the minimum value. how can I get it to return the index?
I'm a student and I'm pretty new to C++ I appreciate the help! thanks!
===
edit:
this is originally from a homework assignment but the constraint to not use external help variables or functions is mine! and I'm curious to know if its even possible.
Because this is obviously homework, I'm not going to reveal the ACTUAL answer in entirety, but I'll give some (hopefully) good advice.
With recursion, think first of what your end condition is. That should be an array of 1 element. You return the index 0 in that case because of the array you have, it's the only element, so return the index of it.
if(num == 1)
{
return 0;
}
So then how is that useful to you? Compare it to exactly one other element. That's how you break this down. Your array turns into "one element and MANY" or "It's just one element." If it's just one, return the only value. If it's many, call yourself recursively from the second element (index 1) onward:
int restOfArraySmallest = smallest(arr+1, num-1) + 1;
You need the +1 because you've offset where it starts from. But you know the value in restOfArraySmallest is the index into YOUR arr of the smallest value of everything except the first element. Because your recursive calls don't include the first element, just the rest.
Hopefully that's enough to get you the rest of the way.
Edit: Because the OP has responded and said it wasn't essential to their homework assignment, here's the entire function:
// Recursively finds the index of the smallest element of the passed-in array
int smallest(int* arr, int num)
{
if(num <= 1)
{
return 0; // If we're in the last element, the smallest is the only element
}
// More than one element, so find the least element in all the elements
// past the first element of the array
// Note: the index returned is offset from our current view of the array,
// so add +1 to any returned result so we can index directly from it
int restOfArraySmallest = smallest(arr+1, num-1) + 1;
// Compare the first element in the array to the smallest of the entire rest
// of the array:
if(arr[0] < arr[restOfArraySmallest])
{
// The first element is smaller, it's the smallest, so return that index
return 0;
}
else
{
// The element already found is smaller, so return that index. It's already
// correctly offset
return restOfArraySmallest;
}
}
And that's it. If there's duplicate entries for smallest, it will favor the LAST one.
The trick with recursion is to NOT keep external variables. What you pass as the arguments and RETURN BACK are all the information you have. For some algorithms, it's enough.
Note, if you use recursive functions with datasets big enough, you will eventually get a Stack Overflow. Not the website, the crash type. This algorithm is pretty light in that only one extra variable and the two arguments themselves get allocated each pass, but it adds up eventually.

while every value in array is different than specific int value

I have an array of values e.g. 1, 4, 7, 2.
I also have another array of values and I want to add its values to this first array, but only when they all are different from all values that are already in this array. How can I check it? I've tried many types of loops, but I always ended with an iteration problem.
Could you please tell me how to solve this problem? I code in c++.
int array1[7] = {2,3,7,1,0};
int val1 = rand() % 10;
int val2 = rand() % 10;
int array2[2] = {val1, val2};
and I am trying to put every value from array2 into array1. I tried loop
for (int x:array2)
{
while((val1 && val2) == x)
{
val1 = rand() % 10;
val2 = rand() % 10;
}
}
and many more, but still cannot figure it out. I have this problem because I may have various number of elements for array2. So it makes this "&&" solution infinite.
It is just a sample to show it more clearly, my code has much more lines.
Okay, you have a few problems here. If I understand the problem, here's what you want:
A. You have array1 already populated with several values but with space at the end.
1. How do you identify the number of entries in the array already versus the extras?
B. You have a second array you made from two random values. No problem.
You want to append the values from B to A.
2. If initial length of A plus initial length of B is greater than total space allocated for A, you have a new problem.
Now, other people will tell you to use the standard template library, but if you're having problems at this level, you should know how to do this yourself without the extra help from a confusing library. So this is one solution.
class MyArray {
public:
int * data;
int count;
int allocated;
MyArray() : data(nullptr), count(0), allocated(0) {}
~MyArray() { if (data != nullptr) free(data); }
// Appends value to the list, making more space if necessary
void add(int value) {
if (count >= allocated) {
// Not enough space, so make some.
allocated += 10;
data = (data == nullptr) malloc(allocated * sizeof(int))
: realloc)data, allocated * sizeof(int));
}
data[count++] = value;
}
// Adds value only if not already present.
void addUnique(int value) {
if (indexOf(value) < 0) {
add(value);
}
}
// Returns the index of the value, if found, else -1
int indexOf(int value) {
for (int index = 0; index < count; ++index) {
if (data[index] == value) {
return index;
}
}
return -1;
}
}
This class provides you a dynamic array of integers. It's REALLY basic, but it teaches you the basics. It helps you understand about allocation / reallocating space using old-style C-style malloc/realloc/free. It's the sort of code I was writing back in the 80s.
Now, your main code:
MyArray array;
array.add(2);
array.add(3);
array.add(7);
// etc. Yes, you could write a better initializer, but this is easy to understand
MyArray newValues;
newValues.add(rand() % 10);
newValues.add(rand() % 10);
for (int index = 0; index < newValues.count; ++index) {
array.addUnique(newValues.data[index]);
}
Done.
The key part of this is the addUnique function, which simply checks first whether the value you're adding already is in the array. If not, it appends the value to the array and keeps track of the new count.
Ultimately, when using integer arrays like this instead of the fancier classes available in C++, you HAVE TO keep track of the size of the array yourself. There is no magic .length method on int[]. You can use some magic value that indicates the end of the list, if you want. Or you can do what I did and keep two values, one that holds the current length and one that holds the amount of space you've allocated.
With programming, there are always multiple ways to do this.
Now, this is a lot of code. Using standard libraries, you can reduce all of this to about 4 or 5 lines of code. But you're not ready for that, and you need to understand what's going on under the hood. Don't use the fancy libraries until you can do it manually. That's my belief.

How to write a void function that will search for values in an array and pass the position of that value back to main function by reference?

User will enter a value (size) which represents the number of values to process. The values entered will be stored in an array of type short that has 1000 elements. User will enter size numbers. The user will enter a search value. The program will search the data for a specific value. Program will display a message in which element the value was found or display a message the value was not found
// Function to search the array using a sequential search
// Assign the subscript/element # to offset where found or assign offset -1 if not found.
void sequential_search(short data[], short size, short search_value, short &offset)
for (int n = 0; n < size; n++)
{
if (search_value == data[n])
offset = n;
else
offset = -1;
}
I'm only finding a value for the last element of the array, and I'm confused about where to go from here. If I take the else statement out, I get the positions of the values in the array, but it also gives any number value the last position in the array.
Do offset = -1 before the for statement. Any negative finds you do after a good find will corrupt your good find.
This is very not idiomatic c++.
The idiomatic way would be to use find.
auto data_result = std::find(data, data + size, element);
auto offset = data_result - data;

Optimize code-Maximum Element in an Array using functions

i'm new to posting questions here but have been looking for answers for a long time. I've created this code to return the maximum element in the array x[]. I did get results but not all the test cases are passed. I have checked it multiple times, but got no clue ion what is to be done to correct it.
I'm doing this on part of my online training so the test case values aren't openly visible. This code generated 85.71% positive outcome. Please help me do 100%. Thank you.
The question is to create a function findMax(int n,int *a) to return the maximum element. WHERE
The first argument corresponds to the number of elements in the array.
The second argument corresponds to the pointer to an array.
#include<stdio.h>
int findMax(int n,int *a)
{
int i,max=a[0]=0;
for(i=1;i<=n;i++)
{
if(a[i]>max)
max=a[i];
}
return(max);
}
int main()
{
int i,x[16],k,max;
printf("Enter the number of elements in the array\n");
scanf("%d",&k);
printf("Enter the elements in the array\n");
for(i=1;i<=k;i++)
{
scanf("%d",&x[i]);
}
max=findMax(k,x);
printf("The maximum element in the array is %d",max);
return 0;
}
I'm a beginner in coding, so a simpler explanation might help. Thanks again
max=a[0]=0;
This sets both a[0] and max to 0.
The loop in main() populates the array starting with index 1. Setting a[0] to 0 here accomplishes absolutely nothing. That, in itself, is not a problem, but setting max to 0 is. This is because if all elements in the array that main() initializes are negative, then because max is initially set to 0, the returned maximum value will be 0 instead of the highest negative value in the array.
You should make the following changes.
1) Instead of populating x[1] through x[k], the loop in main() should populate x[0] through x[k-1]. Arrays in C and C++ are, traditionally, 0-based.
2) The loop in your function should be adjusted accordingly as well, and it should not set a[0] to 0, of course. It should simply set max=a[0].
#include<stdio.h>
int findMax(int i,int *a)
{
max=a[0]; // you were setting a[0] to zero
for(i=1;i<n;i++) // there are n numbers beginning from position 0
{
if(a[i]>max)
max=a[i];
}
return(max);
}
int main()
{
int i,x[16],k,max;
printf("Enter the number of elements in the array\n");
scanf("%d",&k);
printf("Enter the elements in the array\n");
for(i=0;i<k;i++)
{
scanf("%d",&x[i]);
}
max=findMax(k,x);
printf("The maximum element in the array is %d",max);
return 0;
}
In your code, you have set max=0. Consider the test case when all the numbers are negative, then your code will return 0 which is not correct.
Correct Approach:
Assign max to first element of array and check the condition for remaining elements.
If first element is maximum then it will be returned otherwise the updated maximum is returned (after being checked through loop).

Counting the elements in a local array

I have a double x[12] which has no elements in it. When the user is prompted, he/she enters a number, which is stored in x.
I want the program to first check if x is empty and if it is, put the user's input in x[0] or if it isn't, put the user's input in the next free index.
I had done this:
...
double x[12];
void AddPayment(double Amount)
{
int i = sizeof(x);
x[i] = Amount;
}
Is it that sizeof() doesn't work with arrays, is there a better way of doing this?
When sizeof is applied to an array, it does not tell you how much data the array holds; it tells you how much data the array could hold. The fact that you did not specify any data to put into your double x[12] has no influence on the size of the array. Therefore, sizeof would return the number of bytes required on your system to hold an array of twelve doubles.
If you would like to keep a count of how many items among 12 have been assigned, add a separate variable for it. Initialize it to zero, and use it to keep track of how many items have been inserted:
size_t x_count = 0;
double x[12];
void AddPayment(double Amount) {
if (x_count == 12) {
// Error; we cannot add more than 12 items.
// Tell the user what's going on and quit,
// or handle the error in some other way.
cerr << "Cannot add more than 12 elements to x[]" << endl;
return;
}
x[x_count++] = Amount;
}
Whether x[12] has values or not, it will always have a size of 12 * sizeof(double).
So using the sizeof() operator is not a good way to accomplish your aim.
A best thing to do would be initialize x[12] with a value that the user cannot enter, say 0, and test for the first available location in the array that has a zero to enter that value.
double x[12] = { 0 };
void AddPayment(double Amount)
{
for (int i = 0; i < 12; i++) {
if (x[i] == 0) {
x[i] = Amount;
break;
}
}
}
I have a double x[12] which has no elements in it.
That's a misconception. double x[12]; creates 12 double elements, leaving their values in an undefined status. So you have 12 uninitialised elements. That's quite different from having no elements.
(The misconception would become even clearer if you had, for example, an array of type std::string. Unlike double, std::string is always initialised to a defined value, an empty string. So std::string x[12] would definitely be 12 strings, not an empty array.)
When the user is prompted, he/she enters a number, which is stored in
x.
I want the program to first check if x is empty and if it is, put the
user's input in x[0] or if it isn't, put the user's input in the next
free index.
I'm really surprised that nobody has suggested this, but an array is the wrong tool for what you are trying to accomplish. You need a container which can grow. You need std::vector:
std::vector<double> x; // starts off empty
void AddPayment(double Amount)
{
x.push_back(Amount); // grows by 1 element
}
std::vector also has a size() member function to tell you the current number of elements. No more sizeof needed.