How to output the maximum value inside an array - c++

#include <iostream>
using namespace std;
void value(int array[],int size){
int minimum;
int maximum;
minimum = array[0];
for(int x = 0; x < size; x++){
if(minimum > array[x+1]){
minimum = array[x+1];
}
}
maximum = array[0];
for(int x = 0; x < size; x++){
if(maximum < array[x+1]){
maximum = array[x+1];
}
}
cout << "Minimum Value is: " << minimum << endl;
cout << "Maximum Value is: " << maximum;
}
int main(){
int size;
cout << "Number of values you want to input: ";
cin >> size;
cout << "Input " << size << " values" << endl;
int array[size];
for(int x = 0; x < size; x++){
cout << "Input #" << x+1 <<": ";
cin >> array[x];
}
value(array,size);
return 0;
How can I output the maximum value inside the array? whenever I print the value the maximum value always return a number that is not present inside the array but the minimum seems fine, its only the maximum value that I am encountering a problem, I tried every possible answer that I know but it doesn't work, I hope ya'll can help Thank you in advance

for(int x = 0; x < size; x++){
If you have an array with ten values, size will be 10. If you work out, with paper and pencil, what this for loop does, you will see that it iterates for values of x 0 through 9, that's what this says. x starts with 0. When it reaches 10, x < size will be false and the loop ends, so the loop runs with x ranging from 0 to 9.
if(minimum > array[x+1]){
Since x will range from 0-9, it logically follows that x+1 will range from 1 to 10, and so this if statement will check the values in array[1] through array[10].
In C++ array indexes start with 0, not 1. The values in your array are array[0] through array[9]. array[10] does not exist, so the above code is undefined behavior.
Furthermore:
int array[size];
This is not valid C++ either. Your C++ compiler may allow this as a non-standard C++ extension, but array sizes must be fixed, constant sizes in C++, determined at compile time. You can't use a non-constant variable to set the size of an array, C++ does not work this way. If you need to have an array of size that's determined at runtime then you need to use std::vector instead of a plain array, and change the rest of your code accordingly.

Mistake 1
Your example has undefined behavior because of the expression array[x+1]. That is, for the last iteration of the for loop, you're going out of bounds of the array and so have undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
Mistake 2
In standard C++, the size of an array must be a compile time constant. So in your code:
int size;
cin >> size;
int array[size]; //NOT STANDARD C++
The statement int array[size]; is not standard C++ because size is not a constant expression.
Additionally you don't need 2 separate for loops when you can achieve the goal in 1 for loop as shown below.
Solution 1
You can use std::vector as shown below:
#include <iostream>
#include <vector>
#include <climits>
//this function take a vector as input
void value(const std::vector<int>& arr)
{
int max_num = INT_MIN;
int min_num = INT_MAX;
//iterate through the vector to find the max and min value
for(const int& element: arr)
{
if(element > max_num)
{
max_num = element;
}
if(element < min_num)
{
min_num = element;
}
}
std::cout<<"maximum is: "<<max_num<<std::endl;
std::cout<<"minimum is: "<<min_num; //return the difference of mx and min value
}
int main()
{
int n;
std::cout<<"elements: ";
std::cin >> n;
//create vector of int of size n
std::vector<int> arr(n);
//take elements from user
for(int i=0; i<n; i++)
{
std::cin >> arr[i];
}
value(arr);
return 0;
}
Demo
Solution 2
You can make the function a function template so that you don't need to pass a separate argument to the function as shown below:
#include <iostream>
#include <climits>
//N is a nontype template parameter
template<std::size_t N>
void value(const int (&array)[N]){
int max_num = INT_MIN;
int min_num = INT_MAX;
//iterate through the array to find the max and min value
for(const int& element: array)
{
if(element > max_num)
{
max_num = element;
}
if(element < min_num)
{
min_num = element;
}
}
std::cout<<"maximum is: "<<max_num<<std::endl;
std::cout<<"minimum is: "<<min_num;
}
int main(){
int array[3] = {};
for(int x = 0; x < sizeof (array) / (sizeof (array[0])); x++){
std::cout << "Input #" << x+1 <<": ";
std::cin >> array[x];
}
value(array); //no need to pass the second argument
return 0;
}
Demo
Also note that with C++17, you can use std::size instead of sizeof (array) / (sizeof (array[0])) to find the length of the array.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.

Related

C++ code don't have errors but not giving output [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
I am writing code for selection sort in c++. It gives no error when i compile it with the command g++ main.cpp -o main in powershell but when i run the code with ./main, it don't show anything. I tried with hello world program and it worked. I don't know why the selection sort code not working.
Here Is the code of Selection sort
#include<iostream>
using namespace std;
int main()
{
int n, a[n];
cout << "Enter the size of the array = ";
cin >> n;
cout << "Enter the numbers :" << endl;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
for (int i = 0; i < n-1; i++)
{
for (int j = i+1; j < n; j++)
{
if (a[i] > a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (int b=0; b<n; b++)
{
cout<<a[b];
}
return 0;
}
There are 2 problems in your program.
Mistake 1
In Standard C++ the size of an array must be a compile time constant. So take for example,
int n = 10;
int arr[n] ; //INCORRECT because n is not a constant expression
The correct way to write the above would be:
const int n = 10;
int arr[n]; //CORRECT
Mistake 2
You're using an uninitialized variable which leads to undefined behavior. In particular when you wrote:
int n, a[n]; //here variable n is uninitialized and holds **indeterminate value**.
In the above statement, you are creating an int named n but since you have not explicitly initialized it, it holds an indeterminate value.
Next, you're using that garbage value as the size of the array a. But note that using uninitialized variable results in undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.
This is why it is advised that
always initialize built in types in local/block scope.
Solution
A better way would be to use std::vector as shown below.
#include <iostream>
#include <vector>
int main()
{
int n = 0; //always initialize built in types in local/block scope
std::cout<<"Enter size: "<<std::endl;
std::cin >> n;
//create a vector of size n
std::vector<int> a(n);
//iterate and ask for input
for(int i = 0; i < a.size(); ++i)
{
std::cout<<"Enter element: "<<std::endl;
std::cin >> a[i];
}
for (int i = 0; i < a.size() - 1; ++i)
{
int index = i;
for (int j = i + 1; j < a.size(); j++) {
if (a[j] < a[index])
index = j;
}
int temp = a[index];
a[index] = a[i];
a[i] = temp;
}
std::cout<<"The elements of the vector are:"<<std::endl;
//print the element of the vector
for(const int& elem: a)
{
std::cout<<elem<<std::endl;
}
return 0;
}
The output of the program can be seen here.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
Always initialize variables. A declaration without initialization is a code smell, eg this one:
int n;
The issue immediately follows, because
int n, a[n];
uses n uninitialized. Compilers do a pretty good job at warning about this: https://godbolt.org/z/ErPY3x936. Before you initialize n, it has an indeterminate value. Using its value leads to undefined behavior. Further, a[n] is a variable length array (unless n is a constant expression), which is not part of standard C++. When you need an array whose size is only known at runtime, you can use a std::vector:
int n = 0;
cout << "Enter the size of the array = ";
cin >> n;
std::vector<int> arr(n);
You are trying to use a variable length array
int n, a[n];
Variable length arrays is nit a standard C++ feature. So you should avoid to use them. Instead use the standard container std::vector<int>.
Moreover the variable n is not initialized. So the declaration of the variable length array invokes undefined behavior.
Within the for loops where you are sorting the array there are too many swaps of elements of the array.
The selection sort algorithm assumes that a selected element in an array is swapped at most one time.
And there is the standard function std::swap that can be used instead of manually swapping elements.
Your program can look the following way
#include <iostream>
#include <utility>
#include <vector>
int main()
{
size_t n = 0;
std::cout << "Enter the size of the array (0 - exit): ";
std::cin >> n;
if ( n )
{
std::vector<int> v( n );
std::cout << "Enter the numbers :" << std::endl;
for ( auto &item : v )
{
std::cin >> item;
}
for ( std::vector<int>::size_type i = 0; i < v.size(); i++ )
{
auto min = i;
for ( auto j = i + 1; j < v.size(); j++ )
{
if ( v[j] < v[min] ) min = j;
}
if ( min != i ) std::swap( v[min], v[i] );
}
for ( const auto &item : v )
{
std::cout << item << ' ';
}
std::cout << std::endl;
}
return 0;
}.

The check with the module in the loop doesn`t work

There is a task. It is necessary in a one-dimensional array of N real numbers to calculate the number of the maximum modulo element among unpaired numbers.
I wrote the code, but it does not work. I can’t understand what’s wrong with him.
#include <iostream>
#include <math.h>
using namespace std;
int main() {
setlocale(0, "");
const int KolEl = 5;
int mas[KolEl];
int max = abs(mas[0]);
int result;
for (int i = 0; i < KolEl; i++)
{
cout << " Введите елемент[" << i << "] = ";
cin >> mas[i];
if (mas[i] % 2 == 1) {
if (abs(mas[i]) > max) {
result = i;
cout << result << endl;
}
}
}
system("pause");
}
You initialize max as:
int mas[KolEl];
int max = abs(mas[0]);
However, the values in mas[] are garbage values (read: undefined behavior). So now the value in max is also UB.
You then go on to use that value to compare to the input you take:
if (abs(mas[i]) > max) {
So the result of that comparison is undefined.
You probably meant to declare max as something like:
int max = INT_MIN;
So that the first comparison will always be true (every int except INT_MIN will be greater than it).

Outputting weirdly large number in C++

Hey new to C++ and working on a simple problem that takes a sequence of Int's and outputs the sum of the numbers without the smallest and largest number.
If the vector has one or no elements then it is to return 0.
Here is my code:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int test(vector<int> numbers) {
typedef vector<int>::size_type vec_sz;
vec_sz size = numbers.size();
if (size <= 1) {
cout << "Vector less than 2" << endl;
return 0;
} else {
sort(numbers.begin(), numbers.end());
int answer;
for (int i=1; i < size-1; i++) {
answer += numbers[i];
}
return answer;
}
}
int main() {
vector<int> vec = {2,1,3,4,6,5,7,9,8,10};
cout << test(vec) << endl;
vector<int> vec_2 = {1};
cout << test(vec_2) << endl;
}
When I run this I get something along the lines of:
3829804
Vector less than 2
0
Why am I getting an absurdly large number when the vector is > 1, when it is just supposed to be returning the sum of 2-8?
When I make the program without the checking for the vector with 1 or less items I have no problem. Thanks for any help!
answer is not initialized in your function and will have indeterminate value.
Any usage will lead to undefined behavior.
int answer; // uninitialized
// answer will have indeterminate value
for (int i=1; i < size-1; i++) {
answer += numbers[i]; // undefined behavior
}
return answer;
As per dcl.init/12:
If no initializer is specified for an object, the object is default-initialized.
When storage for an object with automatic or dynamic storage duration
is obtained, the object has an indeterminate value,
So just initialize answer:
int answer = 0;
Try making answer set to 0 before the for for loop. This should fix the problem since the APU is trying to add a number to an undefined number.

The three biggest numbers in array

#include<iostream>
using namespace std;
int main()
{
int s;
cin>>s;
int t=3;
int maxValue,imax[t],maxIndex,arr[s];
for(int i=0; i<s; i++){
cin>>arr[i];
}
maxValue=arr[0];
for(int i=0;i<s;i++){
if(arr[i]>maxValue){
maxValue=arr[i];
imax[0] = i;
}
}
maxValue=arr[0];
for(int i=0;i<s;i++){
if (i == imax[0]) { continue; }
if(arr[i]>maxValue){
maxValue=arr[i];
imax[1] = i;
}
}
maxValue=arr[0];
for(int i=0;i<s;i++){
if (i == imax[0]) { continue; }
if (i == imax[1]) { continue; }
if(arr[i]>maxValue){
maxValue=arr[i];
imax[2] = i;
}
}
cout<<"First biggest number:"<<arr[imax[0]]<<"\n";
cout<<"Second biggest number:"<<arr[imax[1]]<<"\n";
cout<<"Third biggest number:"<<arr[imax[2]];
return 0;
}
This program must return tree numbers which is biggest in this arraybut , i do not know why when I introduce as example five numbers (121,34,56,67,545) and the compiler was return 545 and then crash.
Thank you in advance for the answer.
The problem is that before iterating the loop, you first set the maxValue to be the first element in the array. The imax only gets updated whenever there is at least one element greater than the current maxValue. However, if the first element is somehow the maxValue you are looking for, then the imax never gets set, which would be uninitialized causing segmentation fault at the end.
In your code, after finding the largest element 545, the second largest element was never found, since 121 is the first element in the array. Hence after printing out 545, imax[1] is uninitialized and the program crashes.
You use uninitialized array values in lines
cout<<"First biggest number:"<<arr[imax[0]]<<"\n";
cout<<"Second biggest number:"<<arr[imax[1]]<<"\n";
cout<<"Third biggest number:"<<arr[imax[2]];
If there are less than 3 different numbers in input, some imax array elements will not be initialized. Also if input array is empty, imax will not be initialized at all.
Therefore in expression arr[imax[1]] you read element of arr with index, which was not initialized and can be some very big number. It can be fixed if you declare iarr as
int imax[t] = {};
This will zero-initialize all elements of array and will prevent crashing.
Your program also doesn't check number of elements in input array, so if there are less than three input numbers arr[2] will also print uninitialized value.
Here's proper solution using STL algorithms and std::vector. It works with any number of t - you can easily change it to print largest 10 numbers. It is also memory efficient - it does not need to store whole input array so you can process large inputs with it.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
int s;
std::cin >> s;
unsigned t = 3;
std::vector<int> max_numbers;
max_numbers.reserve(t + 1);
for (int i = 0; i < s; ++i) {
int number;
if (std::cin >> number) { //Check basic input errors
max_numbers.push_back(number); // Add number to top-3 list
// Sort elements in descending order
std::sort(max_numbers.begin(), max_numbers.end(), std::greater<int>());
// Remove duplicates
max_numbers.erase(std::unique(max_numbers.begin(), max_numbers.end()),
max_numbers.end());
// Remove excess elements
if (max_numbers.size() > t) {
max_numbers.resize(t);
}
}
}
std::cout << "Biggest " << t << " numbers are" << std::endl;
for (int i : max_numbers) {
std::cout << i << std::endl;
}
}

C++ Variable not properly receiving new value from vector?

I'm trying to write a program that creates and fills a vector with int values, then searches through it and returns the minimum value, recursively. I have the code written out and building, but it returns a weirdly large value for minimum every time- I have a feeling it's not properly assigning the smallest value to int minimum, but I'm not sure. Any thoughts?
#include <iostream>
#include <conio.h>
#include <vector>
using namespace std;
int vectorSize;
int minimum;
int result = -1;
int start;
int ending;
int answer;
int test;
int recursiveMinimum(vector<int>, int, int);
void main() {
cout << "How many values do you want your vector to be? ";
cin >> vectorSize;
cout << endl;
vector<int> searchVector(vectorSize);
start = 0;
ending = searchVector.size() - 1;
for (int i = 0; i < vectorSize; i++) {
cout << "Enter value for position " << i << " " << endl;
cin >> searchVector[i];
}
for (int x = 0; x < vectorSize; x++) {
cout << searchVector[x] << " ";
}
int answer = recursiveMinimum(searchVector, start, ending);
cout << "The smallest value in the vector is: " << answer;
_getch();
}
int recursiveMinimum(vector<int> searchVector, int start, int end) {
if (start < end) {
if (searchVector[start] < minimum) {
minimum = searchVector[start]; //this part seems to not work
}
start++;
recursiveMinimum(searchVector, start, end);
}
else {
return minimum;
}
}
`
Your minimum variable is not initialised, which leads to undefined behaviour. It should be set to the first value in the vector:
minimum = searchVector[0];
int answer = recursiveMinimum(searchVector, start, ending);
Additionally, ending is off by one, which makes it pick 6 as the smallest value out of [6, 9, 8, 4].
So, ultimately, your code should look like this:
minimum = searchVector[0];
int answer = recursiveMinimum(searchVector, start, ending + 1); // note the + 1
While irrelevant to the question, I advise you to use a tail call in recursiveMinimum, as explained here:
start++;
return recursiveMinimum(searchVector, start, end);
The main issue is that you do not initialise minimum. Hence, comparison searchVector[start] < minimum might never become true, and minimum remains uninitialized.
As a quick fix, write int minimum = MAX_INT; instead of int minimum;. MAX_INT is the maximum positive integer value (defined in limits.h). So the values in your array will never be greater that this value, and your minimum search loop will work (unless there are other issues; but for that, please consult the debugger :-) )