Array math, average, even numbers and the minimal value.

Hello,

i was wanting to know how to find the average of a set of randomly generated numbers in an array. I also need to display the
even numbers of the array and then show the smallest number in the set. However, the program should loop back and generate a new set of numbers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{

    float avg;
    float evn;
    float mini;
    char opt;
    int randval[10];
    srand(time(NULL));
    int n;

    do
    {
        for(n=0; n<10; n++)
        {
            randval[n]=50 + rand( ) % (150 + 1-50);
            cout << randval[n] << "    " ;
        }
     cout << endl;
     cout << "[A]verage    [E]ven    [M]inimum     [Q]uit";
     cout << "Select an option";
     cin >> opt;

    if(opt=='a'||opt=='A')
        {
        // function for calculating the average of the numbers inside the array.
            cout << "The average value of the array is:" << avg;
            cout << setiosflags(ios::showpoint) << setprecision(2);
        }
        else if (opt=='e'||opt=='E')
        {

            // function for displaying only the even numbers in the array.
            cout << "The even number of the array are:" << evn;
            cout << setiosflags(ios::showpoint) << setprecision(2);

        }
        else if (opt=='m'||opt=='M')
        {
            // function for displaying the smallest value in the array.
            cout << "The minimum number of the array is:" << mini;
            cout << setiosflags(ios::showpoint) << setprecision(2);
        }

    }
    while(opt=='q'||opt=='Q');
    {
     false;
    }

 return 0;
}


Math in C++ is not my strongest suit and doing these calculations for numbers that have yet to be generated is really confusing me.
It's always a good habit to initialise your variables so that they don't become the source of bugs when your program grows.

Line 32 to 51
I'd recommend you use a switch statement rather than if, else-if as it makes your code more readable. tolower() converts the character argument to its lowercase variant.
http://www.cplusplus.com/reference/cctype/tolower/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
opt = tolower( opt );
switch( opt )
{
case 'a':
	// calculate average
	break;

case 'e':
	// show even numbers
	break;

case 'm':
	// show smallest number
	break;

default:
	// invalid option
}


while(opt=='q'||opt=='Q');
This means to keep looping as long as the user enters 'q' or 'Q', which isn't what you intended.
Last edited on
I was advised against using a switch structure, as it would "complicate the overall program." But I know what you mean, it does look like a mess.

I changed the while part so that it now says;

1
2
3
4
5
6
7
8
9
 else if (opt!='Q'||opt!='q')
        {
            return 0;
        }
}
    while (opt!='a'||opt!='A');
        {
            return 0;
        }


For some reason it wont with just while (opt!='q'||opt!='Q')
Last edited on
For some reason it wont with just while (opt!='q'||opt!='Q')

If opt is 'q', this statement returns true, as it satisfies the second segment (opt != 'Q').
If opt is 'Q', this statement returns true, as it satisfies the first segment (opt != 'q').

You could either:
Convert opt to lower/uppercase and check for that.
or
while( !(opt == 'q' || opt == 'Q') )
Just to break the above statement down:
- opt is 'q' or 'Q' -> inner brackets becomes true -> statement becomes false -> loop stops
- opt is 'z', for example, -> inner brackets becomes false -> statement becomes true -> loop continues
Well that fixed the looping. But the worst has yet to discussed, getting the math down.
Average: Sum of numbers / amount of numbers.

Even numbers: If (number % 2 == 0). % is modulo (remainder of division).

Smallest number in set: You can either sort the elements so it is least to greatest or pick one number at a time and see if the rest of the elements are greater than it.
Last edited on
I'm not sure how I would go about adding the numbers generated in the array then dividing them. Like int n [arraySize] = { 19, 3, 15, 7, 11, 9, 13, 5, 6, 1 }; would be easy since the values are given.

I tried if (randval % 2 == true); Won't work.


1
2
3
4
5
6
7
8
9
10
11
const int ARRAY_SIZE{ 10 };
int randval[ARRAY_SIZE]{ 19, 3, 15, 7, 11, 9, 13, 5, 6, 1 };

double average( int arr[ARRAY_SIZE] )
{
    int sum{};
    for( int i{}; i < ARRAY_SIZE; i++ )
        sum += arr[i];
    
    return sum / ARRAY_SIZE;
}

Note that there is a logic error which you will have to fix. Hint: when sum doesn't divide evenly into ARRAY_SIZE, what is the value returned?
My bad it's number % 2 == 0 to check for even numbers.

And to add the elements in an array then, dividing it by 2 would be like this:

1
2
3
4
5
6
7
8
9
10
11
12
int array[SIZE] = { 1, 2, 3, 4, 5, 6 }; // assume SIZE is 6

int sum = 0;

for (int number : array)
{
        sum += number;
}

// if sum / SIZE is not a whole number it will round down
// so use type double
double average = ( (double) (sum) ) / ( (double) (SIZE) );
Last edited on
Hmm, avg = ( (double) (sum) / (double) (10)); "works" but I'm getting weird values like 057 or 0108. I set the variable avg to a double, should it remain as a float then set it to a double?
Also, number % 2 == 0 is still not working. unless its supposed to be like if (n % 2 ==0)?
Some code demonstrating your problems would be nice.
Also prefer to use C++ casts, in this case static_cast<double>, rather than C-style or function-style casts. Alternatively, you can just do double average = 1.0 * sum/SIZE;, which will automatically promote sum to a double.
If you mean examples of the initial questions I had, then no I have no real examples to work with. But if you meant issues with my code then yeah:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    int sum=0;                                                                      
    double avg;                                                                    
    char opt;                                                                       
    int randval[10];                                                               
    srand(time(NULL));                                                              
    int n;                                                                         
                                                                             
        for(n=0; n<10; n++)                                                         
        {                                                                          
            randval[n]=50 + rand( ) % (150 + 1-50);                                 
            cout << randval[n] << "  ";                                             
        }                                                                                          
     cout << "Select an option: ";                                                  
     cin >> opt;                                                                   

    if(opt=='a'||opt=='A')                                                          
        {
            avg = ( (double) (sum)/ (double) (n) );                                
            cout << "The average value of the array is:" << avg;                    
            cout << setiosflags(ios::showpoint) << setprecision(2) <<endl;   
I'd recommend you make a function for each calculation you want to do. For example,
1
2
3
4
5
6
7
8
9
const int ARRAY_SIZE{ 10 };
double average( int arr[ARRAY_SIZE] )
{
    int sum{};
    for( int i{}; i < ARRAY_SIZE; i++ )
        sum += arr[i];
    
    return sum / ARRAY_SIZE;
}


 
cout << setiosflags(ios::showpoint) << setprecision(2);

You only need to call this once and you're supposed to use the manipulator like so:
cout << showpoint << setprecision(2);
simply for average u write a while loop

#include <iostream>
using namespace std;
int main()
{
float sum=0;
float average=0;
int i=0;
while (i < lenght of array)
{
sum=sum+ list_name[i];
i=i+1;
}
average=sum/lenght of array;
cout<<average;
}




For even numbers you can use again while loop

int i=0;
while (i<lenght of array)
{
if ( array_name[i]%2==0 )
cout<<array_name[i];
i=i+;
}


for cout of minimum element

again use while loop

int i=0;
int min1=array_name[ any element index ];
while (i<lenght of array )
{
if ( array_name[i] < min1 )
{ min1=array_name[i]; }
i=i+1;
}
cout<<min1





In this way you can find average, print even number and find minimum number
Topic archived. No new replies allowed.