I’m new to C++ and trying to make two simple functions, but something goes wrong.
I am trying to do the following:
1.Function for input some data.
2.Function to show what data is input.
I just want to make it simple. The code I wrote so far is:
#include <iostream>
void masiv()
{
int x[10];
int n, i;
int min;
int max=0, imax=0, imin;
cout << "Enter the number of elements: ";
cin >> n;
for(i=0; i < n; i++)
{
cout << "Input value for x["<<i<<"]=";
cin >> x[i];
if (min > x[i])
{
min = x [i];
imin = i;
}
if (max < x[i])
{
max = x[i];
imax = i;
}
}
void rezult()
{
cout << "the smallest value on is xthe biggest value on is x["<<imin<<"]=" << min <<endl;
cout << "nai golqmata stoinost e na x["<<imax<<"]=" << max <<endl;
}
void main()
{
masiv();
rezult();
}
I got bunch of errors. I know this is poor code but as I mentioned I’m just starting.
Thanks
P.s. Sorry for my English
Edit: Working with this code.
#include <iostream>
using namespace std;
void masiv(int& min, int&max)
{
int x[10];
int n;
int i;
int imin, imax;
cout << "Enter the number of elements: ";
cin >> n;
for(i=0; i < n; i++)
{
cout << "Input value for x["<<i<<"]=";
cin >> x[i];
if(min > x[i])
{
min = x [i];
imin = i;
}
if(max < x[i])
{
max = x[i];
imax = i;
}
}
}
void rezult(int min, int max)
{
cout << "the smallest value on is x= " << min << endl;
cout << "the biggest value on is x= " << max << endl;
system ("pause");
}
int main(int argc, char** argv)
{
int min = 999999;
int max = -999999;
masiv(min,max);
rezult(min,max);
return 0;
}
The min variable is never initialized, it should be initialized to a large value.
You declare an array
int x[10];but later you let user enter the number of valuescin>>nwithout checking if it is larger than 10 or negative. This could cause an issue.The max and min are declared only in the function masiv() they cannot be reached outside the function. If you want to make them accessible you could for instance pass them to the function instead of declaring them inside the function:
edit : and add using namespace std; at start of file