Wednesday, February 15, 2017

C++ Tips: Two Approaches to Find an Average of Numbers

by Dax Bradley

On occasion, I will drop notes on programming some basic code here and there.  In this entry, we examine how to use C++ to prompt the user to enter a set of positive integers and average them up.  The code is pretty straightforward, when you have a fixed number of integers pre-determined.  For example, you might know you have 20 numbers to add up and average out. 

However, it would be more useful to be able to specify how many numbers you need to add up and discover the average for.  Here are two methods.  The first is not using Dynamic Memory Allocation, and the 2nd one does use it.  I'll explain the difference.

Dynamic memory allocation is crucial if there is a chance you could enter a null value, such as a negative number by mistake, or possibly that you use so much memory with your data that you crash the program.  The second example below will address that, with a few comments thrown in for good measure (Denoted by the /*...*/ symbols).

Find the Average of n Integers 
(without Dynamic Memory Allocation)

#include <iostream>
using namespace std;
int main()
{
   int n, count;
   float sum, avg;
   sum = 0;
   cout << "How many numbers?  ";
   cin >> n;
   int a;
   for (count=1; count<=n; count++) {
        cout << "Enter Number:  ";
        cin >> a;
        sum = sum + a;
   }
   cout << "The sum is " << sum << endl;
   avg = sum / n;
   cout << "The average is  " << avg << endl;
   return 0;
 }



Online compiler: C Shell

And finally, here is another version with a little more code in it, and some comments that highlight the need for pointers and other tidbits...

Find the Average of n Integers 
(with Dynamic Memory Allocation)
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
int main ()
{

int sum=0, avg, i;
int how_many;
int *p;
printf ("Enter number of values you want to input: ");

scanf ("%d",&how_many);
/* This next block uses malloc dynamic memory pointer to make sure the pointer value is not null*/
p = (int *)malloc(how_many * 4);
if (p == NULL)   
      
{
printf(" Out of memory!\n");
printf ("Press any key to close.");
exit(0);
}

for (i=0;i<how_many;i++)

     /*printf returns the number of characters written or a negative value if an error occurs*/

printf ("Enter value of %dth integer: ",i+1);

     /*scanf returns data items successfully assigned a value, like the opposite of printf*/

scanf ("%d",&p[i]);

     /* %d is a format specifier that stands for Signed Decimal integers */

sum = (sum + p[i]);
}

     avg = (sum / how_many);
     printf ("Sum = %d\n\n",sum);
     printf ("Average = %d\n\n",avg);
     free (p);

/* where malloc allocates memory, free needs to be at the end to free up the memory */

     printf ("press any key to close.");

}

Did I get anything wrong? See something you'd do differently? Drop me a note, leave a comment in the comment section, and let me know. Let's do some coding!

No comments:

Post a Comment