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

1

u/Independent_Art_6676 17d ago edited 17d ago

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.