QuestionC++ Help

Posts 1–5 of 5 · Page 1 of 1
C++ Help
https://gyazo.com/df8ad46ec1f59b0e390d2d20f8e58ac4

For this program i created a few variables and gave them random numbers. I would like to find the minimum, highest and the sum of the set.

I know I need to declare a variable for sum and highest value.

But I'm having trouble of finding the minimum of the set. I'm not sure if I should be using for, while, if/else or whatever :/
Similarly I don't know how to find the highest value.

I know how to find the total (obviously just add all of the variables).

I'd appreciate the help
Is this homework? If it isn't, why not use a std::list<int>, add the 5 numbers in there and then use std::min and std::max functions to retrieve the min and max? Using 5 separate variables for the numbers only complicates things.

If it is homework and you must do it with 5 variables, consider this;
Code:
int maxNr = -9999; // set it to something really low initially.

if( m >= maxNr )  maxNr = m;
if( n >= maxNr ) maxNr = n;
if( o >= maxNr ) maxNr = o;
if( p >= maxNr ) maxNr = p;
if( q >= maxNr ) maxNr = q;

std::cout<<maxNr;
maxNr will hold the highest number at the end.

reverse the logic to find the minimum number.
Code:
int nums[5];

int min = INT_MAX;
int max = INT_MIN;
int sum = 0;
for (int i = 0; i < std::size(nums); i++) 
{
	nums[i] = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
	sum += nums[i];
	if (min > nums[i]) 
		min = nums[i];
	if (max < nums[i])
		max = nums[i];
}

printf("Min: %d Max: %d Sum: %d\n", min, max, sum);
First of all don't use rand or using namespace std. Theres <random> for that. Then there are standard library functions to find the stuff you want. std::accumulate, std::min_element, std::max_element. Simply look them up on cppreference.

This is how the implementation could look like this.
Code:
#include <algorithm>
#include <array>
#include <iostream>
#include <limits>
#include <numeric>
#include <random>

int main()
{
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_int_distribution<int> dist(1, 20);

    std::array<int, 5> values { dist(mt), dist(mt), dist(mt), dist(mt), dist(mt) };

    std::cout << "Min: " << *std::min_element(values.begin(), values.end()) << '\n';
    std::cout << "Max: " << *std::max_element(values.begin(), values.end()) << '\n';
    std::cout << "Sum: " << std::accumulate(values.begin(), values.end(), 0) << '\n';

    return 0;
}
Online version
use loop to loop thru the values and compare them all
Posts 1–5 of 5 · Page 1 of 1

Post a Reply

Similar Threads

Tags for this Thread

None

Need help?