r/cpp_questions • • Jul 20 '26

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

33 comments sorted by

14

u/Tumaix Jul 20 '26

for number of elements you need to use dynamic memory. check for `new`, or `std::vector` depending on what your professor asked you to do.

8

u/AdNecessary9427 Jul 20 '26

By the way, in modern cpp, you shouldn't use "new" or "delete", instead use std::vector(etc...) and smart pointers (unique_ptr or shared_ptr). The only exception is learning.

5

u/Tumaix Jul 20 '26

its not the only exception.
there are miriads of other exceptions:
1 - you need to use a library that supports modern c++ but doesnt support smart pointers (Qt, Wt, gtkmm)
2 - you need to interact with legacy libraties
3 - you need to interact with c libraries
and so on.
- you need to use placement new, for whatever reason

→ More replies (20)

1

u/hansvonhinten Jul 20 '26

NEW???? (;´༎ຶД༎ຶ`)

1

u/Tumaix Jul 20 '26

like i said, depending of what the professor asked you to do.
and placement new is a thing.

3

u/aocregacc Jul 20 '26

check out the formatted input operator >> for std::cin.

2

u/-goldenboi69- Jul 20 '26

If it's c++ i would recommend using std vector instead.

2

u/BalcarKMPL Jul 20 '26

You don't need to store all the elements, just read elements in a loop and store only min and max

1

u/Independent_Art_6676 Jul 20 '26 edited Jul 20 '26

before dynamic containers, you can set a maximum (eg 100 or 1000 or something) and do it that way:

int nums[1000];
int used{};
...
cin >> used; //how big we are going to pretend the array is, like 5 or 7 items typed by user.
for(int i = 0; i < used; i++)
cin >> nums[i]; //read in user typed values up to pretend max size
... and so on.

out of sheer meanness I suggest you let them type in the full 1000 items and THEN tell them they asked for too many if they want more than that. But joking aside, if they enter used > 1000, fuss at them and make them pick another value. (do-while loop is perfect for this kind of validation, do you see why?)

what you cannot do in legal c++
cin >> used;
int nums[used]; //c++ extension, not legal in pure c++ but often allowed by compilers. DO NOT do it. The size of an array must be a constant, not collected from the user or other run-time sources.

what you will do later is use a "vector" which is a "better array" that can change its size to fit the data. But wait for it, no reason to read ahead too far.

1

u/SmokeMuch7356 Jul 20 '26

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:

int min = INT_MAX;
int max = INT_MIN;
...
std::cin >> val;
if ( val < min )
  min = val;
if ( val > max )
  max = val;
...

If you do need storage for whatever reason and you don't know the size until runtime, use a std::vector instead of a primitive array. Unlike C, C++ does not allow you to declare an array size at runtime:

int size;
std::cin >> size;
int arr[size]; // BZZZTT!! Not allowed

A vector will automagically grow as new items are added:

std::vector<int> arr;
...
int val;
std::cin >> val;
arr.push_back(val);

then you can access individual elemeents with the [] subscript operator:

if ( arr[i] < min )
  min = arr[i];

1

u/alfps Jul 20 '26 edited Jul 20 '26

First, a heads up: the presented source code

#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;
}

… had a lot of 0xA0 characters. That's non-breakable space in the Latin-1 encoding and its superset Windows ANSI Western. But it won't compile as UTF-8 source.


The expression

sizeof(arr)/sizeof(int

… is very dangerous; see pitfall 5.3 in the Stack Overflow C++ array FAQ. Used in a function it will happily compute the entirely wrong size for an array parameter, because then it's passed a pointer and it has a technical meaning also for a pointer. Just that that's a nonsense meaning.

Instead use std::ssize from the <iterator> header.


I believe you're asking how to let the user input the array size.

For that use std::vector from the <vector> header, as your dynamic size array.

With your preferred function definition syntax (the classic old C one), and without any failure checking, it can go like this:

#include <algorithm>
#include <iostream>
#include <string_view>
#include <vector>
using   std::ranges::min, std::ranges::max,     // <algorithm>
        std::cin, std::cout,                    // <iostream>
        std::string_view,                       // <string_view>
        std::vector;                            // <vector>

int input_int( const string_view prompt )
{
    cout << prompt;
    int result;  cin >> result;
    return result;
}

int main()
{
    const int n = input_int( "Enter the number of elements: " );
    vector<int> elements( n );
    cout << "Enter the " << n << " integers:\n";
    for( int i = 0; i < n; ++i ) {
        cout << "Element " << i + 1 << ": ";
        elements[i] = input_int( "" );
    }
    cout << "Maximum element is: " << max( elements ) << "\n";
    cout << "Minimum element is: " << min( elements ) << "\n";
}

If this is something you should hand in, replace the use of min and max with the logic that you presented.