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)
Related
This is the program for printing out sum of array elements. It is showing run time error. The output is coming out to be 0 instead of printing out the sum of the elements.
#include<iostream.h>
using namespace std;
void simpleArraySum()
{
int ar[100],n,i,sum=0;
for(i=0;i<n;i++)
{
sum=sum + ar[i];
}
cout<<sum;
}
int main()
{
int ar[100],n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>ar[i];
}
simpleArraySum();
return 0;
}
On this line in your main:
int ar[100], n;
You create an array of 100 elements. You later fill that array using cin
for(int i = 0 ; i < n ; i++)
{
cin >> ar[i];
}
Then you do nothing with that array. You are not calculating any sum. You let that array go, forgotten.
Then, you call a simpleArraySum function. That function is creating an entirely new, distinct array.
// v-----v------There
int ar[100],n,i,sum=0;
That array has no value assigned to it. In fact, reading from it is undefined behavior.
What you want is to receive that array in the arguments of your function:
void simpleArraySum(int* ar, int n) {
// ...
}
And call it like that in your main:
simpleArraySum(ar, 100);
You can avoid the issues of arrays and functions by not using them:
int main()
{
int quantity = 0;
std::cin >> quantity;
int sum = 0;
int value;
while (std::cin >> value)
{
sum += value;
}
std::cout << sum << "\n";
return EXIT_SUCCESS;
}
In simpleArraySum, the variable n is uninitialized. So this loop:
for(i=0;i<n;i++)
invokes undefined behavior when reading from n.
Also, you are summing a different array in the function, than the one you read in mian. It seems that you need to pass in the array from main to this function:
void simpleArraySum(int *ar, int n) {
and call it like this:
simpleArraySum(ar, n);
Finally, you don't even need a function for this, since there is an existing algorithm std::accumulate that you can use:
cout << std::accumulate(ar, ar + n, 0);
In the function, you're adding the elements of ar which is local to the function simpleArraySum() and is not of the array ar that is local to main().
So, pass the array and its length to the function and return its sum. Here is your corrected code:
#include<iostream>
using namespace std;
void simpleArraySum(int ar[], int n)
{
int i, sum = 0;
for(i=0;i<n;i++)
{
sum=sum + ar[i];
}
cout<<sum;
}
int main()
{
int ar[100],n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>ar[i];
}
simpleArraySum(ar, n);
return 0;
}
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.
I need some help here please.
I just started learning C++ (coming from Python background).
I'm trying to familiarize myself with arrays and functions. Wrote a bunch of functions to do as stated, above each one.
However, the function which is supposed to sum elements in an array and return their sum, seem to be adding 10 to the result, no matter the argument supplied as input. What am I doing wrong please, as I can't seem to find this out. Any help on general layout of my code also would be appreciated.
// WORKING WITH ARRAYS AND FUNCTIONS
#include<iostream>
using namespace std;
// FUNCTION TO INSTANTIATE ARRAY INT OF LENGTH N.
int* array_creator(int n)
{
static int ary_of_ten[10]; //declare array
for (int i=0; i<n; i++) //use loop to fill it up
{
ary_of_ten[i] = i+1;
}
return ary_of_ten;
}
//FUNCTION TO PRINT ARRAY ELEMENTS
void* array_printer(int arr[], int array_lenght)
{
for (int i=0; i<array_lenght-1; i++)
{
cout << arr[i] << " ";
}
cout << arr[array_lenght-1] << endl;
}
//FUNCTION ACCEPTS INT ARRAYS AND RETURNS ARRAY OF SQUARE OF EACH ELEMENT
int* square_array(int *p, int array_length)
{
const int ary_sz(array_length);
static int sqd_values[10];
for (int i=0; i<ary_sz; i++)
{
*(sqd_values + i) = *(p+i) * *(p+i);
}
return sqd_values;
}
//FUNCTION ACCEPTS INT ARRAYS AND RETURNS SUM OF ITS ELEMENTS
int sum_array(int *arry, int array_length)
{
int summation;
for(int i=0; i<array_length; i++)
{
summation += *(arry + i);
}
return summation;
}
int main()
{
cout << sum_array(array_creator(10), 3) << endl;
array_printer(array_creator(10), 10); //print array of 1-10 elements
array_printer(square_array(array_creator(10), 10), 10); //prt arry of sqrd values
return 0;
}
summation shuld be initialized to 0.
int summation=0;
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.
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!