How to call this function in main() in cpp - c++

I am trying to use the following remove() function in the main() function. Please let me know what is wrong with my current code.
void remove(float a[], int& n, int i);
int main() {
float a[]={56.8, 14.2, 0.2, 22.3, 3.3, 54.02, 543.33, 456,333, 1.1};
int size, del;
size =sizeof(a)/sizeof(a[0]);
cout<<"Enter the element to be deleted!";
cin >>del;
cout << "Removed= "<< remove(a, size, del) << "\n";
}
void remove(float a[], int& n, int i){
for (int j=i+1; j<n; j++)
a[j-1] = a[j];
--n;
}

So your question is
a) let me know what is wrong with my code
and
b) isn't there another way to do the same without altering the function code
to a)
I learned recently not to use namespace if possible because of the high chance to get avoidable errors due to variable naming that actually happened very often - so std:: is recommended instead of using namespace std;
sizeof() may use internally double not float so beside it works my warning: implicit conversion loses floating-point precision: 'double' to 'float'
A for - slope with more than one line in the body should be written in brackets else my warning: this ‘for’ clause does not guard... [-Wmisleading-indentation]
20 | for (int j=i+1; j
If you use std::cin always should be checking for wrong input e.g. like I did with the input() function.
Since int main(){return 0;} is a function and the "int" indicates a return value, always close the function with a "return 0" for a stop signal to your OS.
Declaring the variables at the beginning instead between the lines makes the code more readable
Also please don't forget check your Question as solved if you got a proper answer to avoid it showing up in the "unsolved" section of stackoverflow.com ;)
to b)
yes, it is - just besides using the { } - brackets like so:
#include <iostream> //std, std::cin
#include <limits> //std::numeric_limits<std::streamsize>::max()
int input(int size); //int signals return
void remove(double a[], int& n, int i); //void signals no return
int main() {
int size, del;
double rem;
double a[]={56.8, 14.2, 0.2, 22.3, 3.3, 54.02, 543.33, 456,333, 1.1};
size =sizeof(a)/sizeof(a[0]);
std::cout<<"Which element do you want to remove: ";
del = input(size); //check the input
rem = a[del]; //filling rem to print out the value to be removed to not change the function like you asked for
std::cout << "Removed= " << rem << std::endl;
remove(a, size, del);
return 0;
}
void remove(double a[], int& n, int i)
{
for (int j=i+1; j<n; j++)
{
a[j-1] = a[j];
--n;
}
}
int input(int size)
{
int input;
while (!(std::cin >> input) || input < 0 || input >= size) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "invalid input ignored; try again and enter a valid move between -1 and " << size << "\n";
}
return input;
}
My intention is for everyone including myself to learn even from seemingly easy questions. I hope I reached my goal for you :)

float remove(float a[], int& n, int i);
int main() {
float a[]={56.8, 14.2, 0.2, 22.3, 3.3, 54.02, 543.33, 456,333, 1.1};
int size, del;
size =sizeof(a)/sizeof(a[0]);
cout<<"Which element do you want to remove: ";
cin >>del;
remove (a, size, del);
}
float remove(float a[], int& n, int i){
cout << "Removed= "<< a[i] << "\n";
for (int j=i+1; j<n; j++)
a[j-1] = a[j];
--n;
return i;
}

float remove(float a[], int& n, int i){
float deleted = a[i];
for (int j=i+1; j<n; j++)
a[j-1] = a[j];
--n;
return deleted;
}

Add return statement in remove function and change return type accordingly.

Related

How do I use pointers with arrays in c++ and return a pointer value?

I am trying to use pointers whenever possible in the following code and am having difficulty figuring out how, exactly, to institute the pointers and how to return a pointer value at the end of my first function. I have done some research on the subject but none of the methods I found have been helpful so far, so I was hoping you may have some specialized tips.
Note: I am a beginner.
#include <iostream>
using namespace std;
int mode(int *pies[], int size) {
int count = 1;
int max = 0;
int *mode=pies[0];
for (int i=0; i<size-1; i++)
{
if (pies[i] == pies[i+1])
{
count++;
if (count>max)
{
max = count;
mode = pies[i];
}
}
else
count = 1;
}
return *mode;
}
int main() {
int n;
cout<<"Input the number of people: "<<endl;
cin>>n;
int survey[n];
cout << "Enter the amount of pie eaten by each person:" << endl;
for(int i = 0; i < n; i++) {
cout <<"Person "<<(i + 1)<< ": "<<endl;
cin>>survey[i];
}
cout<<"Mode: "<<mode(survey, n)<< endl;
return 0;
}
Here is an attempt to answer.
In your main(), you call the mode() function with mode(survey, n) while int survey[n]; is an array of int, so you may use int mode(int *pies, int size) instead of int mode(int *pies[], int size) (as the array int survey[n] can be implicitly converted into pointer).
However, you need to modify two more things in your function:
int *mode=pies[0]; is wrong as pies[0] is the first element of an array of int, thus is an int, while int* mode is a pointer on an int which is incompatible. mode should be an int to receive pies[0]. The correct code is then int mode = pies[0].
Your function signature is int mode(int *pies, int size), thus, again, you should return an int. You should then just return mode;
These are only hints on how to make the code compile.
Your next step is to formalize what you would like it to do and then modify the code accordingly
NB: The correct practice is to think about what you would like to achieve first and then code afterwards (but let us say that this is for the sake of helping each other)
To get started using pointers, you may look at some simple tutorials at first:
http://www.cplusplus.com/doc/tutorial/arrays/
https://www.programiz.com/c-programming/c-pointers
https://www.programiz.com/c-programming/c-pointers-arrays
https://www.geeksforgeeks.org/pointer-array-array-pointer/
https://www.geeksforgeeks.org/how-to-return-a-pointer-from-a-function-in-c/
https://www.tutorialspoint.com/cprogramming/c_return_pointer_from_functions.htm
Here is the modified code with the stated modifications above (it compiles):
#include <iostream>
using namespace std;
int mode(int *pies, int size) {
int count = 1;
int max = 0;
int mode=pies[0];
for (int i=0; i<size-1; i++)
{
if (pies[i] == pies[i+1])
{
count++;
if (count>max)
{
max = count;
mode = pies[i];
}
}
else
count = 1;
}
return mode;
}
int main() {
int n;
cout<<"Input the number of people: "<<endl;
cin>>n;
int survey[n];
cout << "Enter the amount of pie eaten by each person:" << endl;
for(int i = 0; i < n; i++) {
cout <<"Person "<<(i + 1)<< ": "<<endl;
cin>>survey[i];
}
cout<<"Mode: "<<mode(survey, n)<< endl;
return 0;
}

Error during implementation of quickSort algorithm in c++:- "error: cannot convert 'int*' to 'int**'....."

The full error is as follows:- "|error: cannot convert 'int*' to 'int**' for argument '1' to 'void quickSort(int**, int, int)'|"
MY whole code is below:
#include <iostream>
using namespace std;
int Partition (int *A[], int p, int r) {
int x = *A[r];
int i = p-1;
for (int j=0; j<=r; j++){
if(*A[j]<=x){
i++;
int save=*A[j];
*A[j] = *A[i];
*A[i] = save;
}
}
int save2=*A[i+1];
*A[i+1]=*A[r];
*A[r]=save2;
return (i+1);
}
void quickSort(int *A[], int p, int r) {
if (p<r){
int q = Partition(A, p, r);
quickSort(A, p, (q-1));
quickSort(A, (q+1), r);
}
}
int main() {
int RR[] = {2,8,7,1,3,5,6,4};
int y=sizeof(RR)/sizeof(int)-1;
cout << y << endl;
int *QQ = RR;
cout << *QQ << endl;
quickSort(QQ, 0, y);
return 0;
}
This is an implementation that I tried myself from a pseudo code. I'm new to programming so it would be a great help if you could illustrate a little of why this error occurred.
Thanks in advance
The first thing I notice about the code is a whole lot of unneccessary pointer dereferencing. The contents of A will be changed without the need for additional pointers because Arrays decay to pointers (What is array decaying?) so A is treated as a pointer to the first array element and you are effectively passing the array by reference already.
Worse, int * A[] isn't a pointer to an array of int, it is an array of pointers to int. A very different thing. *A[0] does not return 2, it tries to use 2 as an address and return whatever happens to be in memory at address 2. This will almost certainly not be anything you want, or are allowed, to see so the program will do something unfortunate. Crash if you are lucky.
Instead, try
int Partition (int A[], int p, int r) {
int x = A[r];
int i = p-1;
for (int j=0; j<=r; j++){
if(A[j]<=x){
i++;
int save=A[j];
A[j] = A[i];
A[i] = save;
}
}
int save2=A[i+1];
A[i+1]=A[r];
A[r]=save2;
return (i+1);
}
void quickSort(int A[], int p, int r) {
cout << p << ',' << r << endl; // Bonus: This will make the next bug really easy to see
if (p<r){
int q = Partition(A, p, r);
quickSort(A, p, (q-1));
quickSort(A, (q+1), r);
}
}
Note the extra cout statement at the top of quickSort This will help you see the logic error in Partition. The program will crash due to a... wait for it! A Stack Overflow, but the cout will show you why.

Deleting element from an array in c++

I have read others posts, but they don't answer my problem fully.
I'm learning to delete elements from an array from the book and try to apply that code.
As far as I can grasp I'm passing array wrong or it is sending integer by address(didn't know the meaning behind that).
#include <iostream>
#include <cstdlib>
using namespace std;
void delete_element(double x[], int& n, int k);
int main()
{
// example of a function
int mass[10]={1,2,3,45,12,87,100,101,999,999};
int len = 10;
for(int i=0;i<10;i++)
{
cout<<mass[i]<<" ";
};
delete_element(mass[10],10&,4);
for(int i=0;i<10;i++)
cout<<mass[i]<<" ";
return 0;
}
void delete_element(double x[], int& n, int k)
{
if(k<1 || k>n)
{
cout<<"Wrong index of k "<<k<<endl;
exit(1); // end program
}
for(int i = k-1;i<n-1;i++)
x[i]=x[i+1];
n--;
}
There are a couple of errors in your code. I highlight some of the major issues in question 1-3:
You call exit, which does not provide proper cleanup of any objects since it's inherited from C. This isn't such a big deal in this program but it will become one.
One proper way too handle such an error is by throwing an exception cout<<"Wrong index of k "<< k <<endl;
exit(1);
Should be something like this:
throw std::runtime_error("invalid index");
and should be handled somewhere else.
You declare function parameters as taking a int& but you call the function like this: delete_element(mass[10],10&,4); 10& is passing the address of 10. Simply pass the value 10 instead.
You are "deleting" a function from a raw C array. This inherently doesn't make sense. You can't actually delete part of such an array. It is of constant compile time size created on the stack. The function itself doesn't do any deleting, try to name the functions something more task-oriented.
You are using C-Arrays. Don't do this unless you have a very good reason. Use std::array or std::vector. These containers know their own size, and vector manages it's own memory and can be re sized with minimal effort. With containers you also have access to the full scope of the STL because of their iterator support.
I suggest you rewrite the code, implementing some type of STL container
Line 15: syntax error
you can't pass a number&
If you want to pass by reference, you need to create a variable first, like:
your delete_element function signature conflicts with your declared arrays. Either use a double array or int array and make sure the signatures match.
delete_element(mass, len , 4);
when you write the name of an array without the brackets, then it's the same as &mass[0]
ie. pointer to the first element.
complete changes should be:
#include <iostream>
#include <cstdlib>
using namespace std;
void delete_element(int x[], int& n, int k);
int main(){
// example of a function
int mass[10] = { 1, 2, 3, 45, 12, 87, 100, 101, 999, 999 };
int len = 10;
for (int i = 0; i<10; i++){ cout << mass[i] << " "; };
cout << endl;
delete_element(mass, len , 4);
for (int i = 0; i<10; i++)cout << mass[i] << " ";
cout << endl;
cin.ignore();
return 0;
}
void delete_element(int x[], int& n, int k){
if (k<1 || k>n){
cout << "Wrong index of k " << k << endl;
exit(1); // end program
}
for (int i = k - 1; i<n - 1; i++)
x[i] = x[i + 1];
n--;
}
There are a couple of mistakes in your program.
Apart from some syntax issues you are trying to pass an int array to a function which wants a double array.
You cannot pass a lvalue reference of a int literal. What you want is to pass a reference to the length of the int array. see also http://en.cppreference.com/w/cpp/language/reference.
Here is an updated version of your program.
#include <iostream>
#include <cstdlib>
using namespace std;
void delete_element(int x[], int& n, int k);
int main() {
// example of a function
int mass[10] = { 1,2,3,45,12,87,100,101,999,999 };
int len = 10;
for (int i = 0;i < len;i++)
cout << mass[i] << " "; ;
cout << endl;
delete_element(mass, len, 4);
for (int i = 0;i < len;i++) // len is 9 now
cout << mass[i] << " ";
cout << endl;
return 0;
}
void delete_element(int x[], int& n, int k) {
if (k<1 || k>n) {
cout << "Wrong index of k " << k << endl;
exit(1); // end program
}
for (int i = k - 1;i<n - 1;i++)
x[i] = x[i + 1];
n--;
}
Although it does not answer your question directly, I would like to show you how you can use C++ to solve your problem in a simpler way.
#include <vector>
#include <iostream>
void delete_element(std::vector<int>& v, const unsigned i)
{
if (i < v.size())
v.erase(v.begin() + i);
else
std::cout << "Index " << i << " out of bounds" << std::endl;
}
int main()
{
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7};
delete_element(v, 4);
for (int i : v)
std::cout << i << std::endl;
return 0;
}
You cannot delete elements from an array, since an array's size is fixed. Given this, the implementation of delete_element can be done with just a single call to the appropriate algorithm function std::copy.
In addition, I highly suggest you make the element to delete a 0-based value, and not 1-based.
Another note: don't call exit() in the middle of a function call.
#include <algorithm>
//...
void delete_element(int x[], int& n, int k)
{
if (k < 0 || k > n-1 )
{
cout << "Wrong index of k " << k << endl;
return;
}
std::copy(x + k + 1, x + n, x + k);
n--;
}
Live Example removing first element
The std::copy call moves the elements from the source range (defined by the element after k and the last item (denoted by n)) to the destination range (the element at k). Since the destination is not within the source range, the std::copy call works correctly.

C++ Splitting an array into 2 separate arrays

I need to write a program that takes a given array and then splits it into two separate arrays with one array's elements being the positive elements of the main array and the other's elements being the negative elements of the main array.
After doing my best with the code, I got about a million lines of errors when trying to compile it. Is there a problem with how I am deleting the three dynamically allocated arrays? What huge error is preventing compiling?
Here is my code:
#include <iostream>
using namespace std;
void count(int ARRAY[], int SIZE, int& NEG, int& POS);
void split(int ARRAY[], int SIZE, int& NEG_ARRAY, int NEG, int& POS_ARRAY, int POS);
void print_array(int ARRAY[], int SIZE);
int main()
{
int SIZE(0);
int* ARRAY;
cout << "Enter number of elements: ";
cin >> SIZE ;
ARRAY = new int[SIZE];
int x(0);
int numEle(0);
cout << "Enter list: " << endl;
while (numEle < SIZE)
{
ARRAY[numEle] = x;
numEle++;
cin >> x;
}
int POS(0), NEG(0);
count(ARRAY, SIZE, NEG, POS);
int* NEG_ARRAY;
NEG_ARRAY = new int[NEG];
int* POS_ARRAY;
POS_ARRAY = new int[POS];
split(ARRAY, SIZE, NEG_ARRAY, NEG, POS_ARRAY, POS);
cout << "Negative elements: " << endl;
cout << print_array(NEG_ARRAY, NEG) << endl;
cout << "Non-negative elements: " << endl;
cout << print_array(POS_ARRAY, POS) << endl;
delete [] ARRAY;
delete [] NEG_ARRAY;
delete [] POS_ARRAY;
return 0;
}
void count(int ARRAY[], int SIZE, int& NEG, int& POS)
{
for (int x=0; x < SIZE; x++)
{
if (ARRAY[x] >= 0)
{
POS = POS + 1;
}
if (ARRAY[x] < 0)
{
NEG = NEG + 1;
}
}
}
void split(int ARRAY[], int SIZE, int& NEG_ARRAY, int NEG, int& POS_ARRAY, int POS)
{
NEG = POS = 0;
for (int x = 0; x < SIZE; x++)
{
if (ARRAY[x] < 0)
{
NEG_ARRAY[NEG++] = ARRAY[x];
}
else
{
POS_ARRAY[POS++] = ARRAY[x];
}
}
}
void print_array(int ARRAY[], int SIZE)
{
for (int i = 0; i < SIZE; i++)
{
cout << ARRAY[i] << " ";
}
cout << endl;
}
The code is supposed to read in the array and display a new negative and a new positive array. Thanks in advance!
There is a bunch of errors in your code. The worst one is passing the arrays by references in the declaration and definition of the split function. Change both to void split(int ARRAY[], int SIZE, int *NEG_ARRAY, int NEG, int *POS_ARRAY, int POS);, and most of the errors will be gone.
The rest is from the two lines in which you print the array in your main:
cout<<print_array(NEG_ARRAY, NEG) <<endl;
You don't want to print the function, you want to use the function to print inside it (which you do correctly). You need to change the calls to simply:
print_array(NEG_ARRAY, NEG);
And that'll make your code compile.
Hovewer there's one more error, which will make the whole app work in an improper way. In the place you input the values, you need to get the input from cin before inputting it in the array. Like this:
while(numEle<SIZE) {
cin>>x;
ARRAY[numEle] = x ;
numEle++;
}
You have the following bugs:
void split(int ARRAY[], int SIZE, int&NEG_ARRAY, int NEG, int&POS_ARRAY, int POS);
change to :
void split(int ARRAY[], int SIZE, int*NEG_ARRAY, int NEG, int*POS_ARRAY, int POS);
also the :
void split(int ARRAY[], int SIZE, int&NEG_ARRAY, int NEG, int&POS_ARRAY, int POS){..}
change to :
void split(int ARRAY[], int SIZE, int*NEG_ARRAY, int NEG, int*POS_ARRAY, int POS){..}
and
cout<<print_array(NEG_ARRAY, NEG) <<endl
cout<<print_array(NEG_ARRAY, POS) <<endl;
to :
print_array(NEG_ARRAY, NEG);
print_array(NEG_ARRAY, POS);
After fixed these bugs, it can compile and run well.
First of all, using a std::vector is almost always nicer than using dynamically allocated C arrays. You don't get the horrible mixture of pointers and square bracket array access, and you don't need to pass round extra size variables.
Secondly, the standard library has some nice algorithms to help do what you want to do. Let's assume that you write the given numbers into a vector called vec. You can then use std::partition to move all the elements less than zero to the first half of the vector, and all the elements greater than or equal to zero to the second half, like so:
inline bool less_than_zero(int a)
{
return a < 0;
}
std::vector<int>::iterator midpoint = std::partition(vec.begin(),
vec.end(),
less_than_zero);
(There are other ways of specifying the predicate, but a simple function definition like this is easiest for demonstration purposes.)
The returned iterator points to the first item in the vector which is non-negative. So now you can easily copy the values into two new vectors:
std::vector<int> negative(vec.begin(), midpoint);
std::vector<int> positive(midpoint, vec.end());
And that's it!

Array Manipulation C++

I am trying to create a code that reads in an array, finds the smallest element in that array, and then subtracts that smallest element from all the other elements in the array and prints a new array with these elements.
The code I have written so far will not even compile.
Here is what I have:
#include <iostream>
#include <iomanip>
using namespace std;
const int SIZE(25);
void read_list(int a[], int&num_ele);
void print_array(const int a[], const int num_ele);
int find_min(const int a[], const int num_ele);
void array_subtract(int x, int&a[], int num_ele) ;
int main()
{
int num_ele(0);
int array[SIZE] ;
read_list(array, num_ele);
cout<<"Before list: ("<<num_ele<< " numbers): " <<endl;
print_array(array, num_ele) ;
min = find_min(array, num_ele) ;
cout<<"The minimum value = "<<min<<endl;
array_subtract(min ,array ,num_ele) ;
cout<<"After list: ("<<num_ele<< " numbers): " <<endl;
print_array(array, num_ele) ;
return 0;
}
void read_list(int a[], int&num_ele)
{
int x(0);
cout<<"Enter positive numbers (ints) terminated 0: "<<endl;
cin>>x;
while(x!=0 && num_ele <= SIZE)
{
a[num_ele] = x ;
num_ele++;
cin >> x;
}
}
void print_array(const int a[], const int num_ele)
{
for(int i=0; i<num_ele; i++)
{
if(i<num_ele-1)
{cout<<a[i]<<", "; }
else
{cout<<a[i]<<"."}
}
}
int find_min(const int a[], const int num_ele)
{
int x= a[0];
for(int k=0; k<num_ele; k++)
{
if(a[k] < x)
{ x=a[k] ;}
}
return x ;
}
void array_subtract(int x, int&a[], int num_ele)
{
for(int j=0; j<num_ele; j++)
{
a[j] = a[j]-x ;
}
}
When I go to compile, at the line
cout<<"The minimum value = "<<min<<endl;
I get about 100 lines of errors.
Is there some huge error in my code I am missing? Why would this happen? I would like to keep the code in the same format it is in (calling functions to get the final output).
Thanks
You have 3 problems, after correcting these problems, at least you have not compile errors.
i.
You're passing arrays wrong:
void array_subtract(int x, int&a[], int num_ele);
^^^^^^^
Pass it like below (remove &)
void array_subtract(int x, int a[], int num_ele);
ii.
You're using variable min without declaring it. Declare it like below:
int min;
iii.
You've missed a semicolon ; in function print_array:
cout<<a[i]<<".";
^
You did not define variable min so the compiler reports errors when encounters statement
min = find_min(array, num_ele) ;
Aside from the compilation errors addressed by others...
Instead of using an array, use a vector (since logically you array is variably sized from 0-SIZE, and a vector is a variable sized array)...
vector<int> v;
Accept integer input until 0 is typed...
for(int n; cin >> n && n != 0;)
v.push_back(n);
Find the min element...
auto min = min_element(begin(v), end(v));
Printing can be done a variety of ways...
cout << "Vector: [";
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
cout << "]\n";
Subtract the min from the elements...
transform(v.begin(), v.end(), v.begin(), [min](int n){ return n-min; });
Try to use the C++ standard library when possible instead of hand rolling loops. It reduces the potential for bugs, and is often clearer (but not always... for example that print I posted above doesn't exactly read intuitively IMO)