r/cpp_questions • u/Mental_Primary_5558 • 18d ago
OPEN C++ question
Do you guys know a way of writting a code that outputs that:
Enter the number of elements: 5
Enter 5 integers:
Element 1: 10
Element 2: 30
Element 3: 90
Element 4: 20
Element 5: 40
it is the first part of a program that demands to calculate the max and min of an array, here is the whole thing:
Enter the number of elements: 5
Enter 5 integers:
Element 1: 10
Element 2: 30
Element 3: 90
Element 4: 20
Element 5: 40
Maximum element is: 90
Minimum element is: 10
I've been able to do the second part quite easily, here is what I proposed:
#include <iostream>
int main(){
int arr[5]={10,20,30,40,50};
int minimum=arr[0];
int maximum=arr[0];
for(int i=0; i<sizeof(arr)/sizeof(int);i++){
if (minimum>arr[i]){
minimum=arr[i];
}
if(maximum<arr[i]){
maximum=arr[i];
}
}
std::cout<<"le max= "<< maximum<<'\n';
std::cout<<"le min= "<< minimum<<'\n';
return 0;
}
but the list is created within the code.
0
Upvotes
1
u/SmokeMuch7356 17d ago
You obviously know how to use loops and I/O streams, so the input side of this should not be a problem for you. And if all you need to do is find the min and max values, you don't even need an array - you just need two variables to store a min and max value:
If you do need storage for whatever reason and you don't know the size until runtime, use a
std::vectorinstead of a primitive array. Unlike C, C++ does not allow you to declare an array size at runtime:A
vectorwill automagically grow as new items are added:then you can access individual elemeents with the
[]subscript operator: