This is the code that I made to find the highest and lowest number between 10 elements:
#include <iostream>
using namespace std;
#define SIZE 10
void acceptNumbers (int Numbers[SIZE]);
int High(int Numbers[SIZE]);
int Low(int Numbers[SIZE]);
void acceptNumbers(int Numbers[SIZE])
{int i, *max, *min;
for (i=0; i<SIZE; i )
cin>>Numbers[i];
max = Numbers;
min = Numbers;
}
int High(int Numbers[SIZE])
{int i, *max;
for (i = 0; i < SIZE; i )
{
if (*(Numbers i) > *max)
max = (Numbers i);
}
cout<<*max;
}
int Low(int Numbers[SIZE])
{int i, *min;
for (i = 0; i < SIZE; i )
{
if (*(Numbers i) < *min)
min = (Numbers i);
}
cout<<*min;
}
int main()
{
int arr[SIZE];
cout<<"Enter Elements: \n";
acceptNumbers(arr);
cout<<"Highest Number: ";
High(arr);
cout<<endl;
cout<<"Lowest Number: ";
Low(arr);
cout<<endl;
}
On my PC, it doesn't run the whole program. It just stops right when it reaches the code for finding the highest and lowest number
This is homework I'm working on and I can't use any shortcuts and whatnots since there is a required line of code to be used that is given. And so I tried running this code on another PC and it worked just fine:
I also tried running it on online c compiler and it still doesn't work. I can't find solution online so this is my last resort please help me
CodePudding user response:
Your code exhibits undefined behavior.
In each of your functions, you are declaring min
and max
as local variables. Thus, when you initialize min
/max
in acceptNumbers()
, they are only initialized in that function. You are not initializing the min
/max
variables in High()
/Low()
at all. Your code is crashing when those functions try to dereference those uninitialized variables.
Also, your High()
/Low()
functions have non-void
return types, but are not actually return
'ing any values.
Try this instead:
#include <iostream>
using namespace std;
#define SIZE 10
void acceptNumbers (int Numbers[SIZE]);
int High(int Numbers[SIZE]);
int Low(int Numbers[SIZE]);
void acceptNumbers(int Numbers[SIZE])
{
for (int i=0; i<SIZE; i )
cin>>Numbers[i];
}
int High(int Numbers[SIZE])
{
int *max = Numbers;
for (int i = 1; i < SIZE; i )
{
if (*(Numbers i) > *max)
max = (Numbers i);
}
return *max;
}
int Low(int Numbers[SIZE])
{
int *min = Numbers;
for (int i = 1; i < SIZE; i )
{
if (*(Numbers i) < *min)
min = (Numbers i);
}
return *min;
}
int main()
{
int arr[SIZE];
cout<<"Enter Elements: \n";
acceptNumbers(arr);
cout<<"Highest Number: ";
cout<<High(arr);
cout<<endl;
cout<<"Lowest Number: ";
cout<<Low(arr);
cout<<endl;
}
CodePudding user response:
The functions Low() and High() only declare the int* max, min but never initialize. Though they hold invalid addresses.
if (*(Numbers i) > *max)
This function causes a segmentation fault because your program tries to dereference an invalid memory address.
If you want to store int *min, *max
make them either global or declare them in main().