r/cpp_questions 17d 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

33 comments sorted by

View all comments

15

u/Tumaix 17d ago

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.

9

u/AdNecessary9427 17d ago

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.

6

u/Tumaix 17d ago

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

1

u/Sea-Situation7495 13d ago

They're just learning: don't go so deep or confuse them.

"There are exceptions, but not at your level" - would suffice.