C++ Program to Find the Sum and Average of Three Numbers

In this post, we will write a C++ program to find the Sum and Average of three numbers. First, we develop a simple program, then we will C++ program to find the Sum and Average of three numbers using the function concept.

Let us first develop a Simple C++ program to find the sum and average of three numbers.

#include<iostream>
using namespace std;
int main()
{
  // declare variables
  double num1, num2, num3;
  double sum, average;

  // take input from end-user
  cout << "Enter three Numbers :: ";
  cin >> num1 >> num2 >> num3;

  // calculate sum value
  sum = num1 + num2 + num3;
  
  // calculate average value
  average = sum / 3;

  // display result
  cout << "Sum = " << sum << endl;
  cout << "Average = " << average << endl;

  return 0;
}

Output:-

Enter three Numbers: 10 15 20
Sum = 45 Average = 15

In this C++ program, we define three variables num1, num2, and num3 of float data types. These variables store data given by the user. Two other variables sum and average are defined to store sum and average value after calculation.

Sum is calculated by adding variables. sum = num1 + num2 + num3. The average value is calculated by the sum of variables divided by the number of variables. Here, the number of variables is three. So, average = sum / 3 calculates the average value.

C++ Program to Find Sum and Average of Three Numbers Using the Function

A function is a block of code that performs a specific task. For example, the main is function and every program execution starts from main function in C++ programming.

#include<iostream>
using namespace std;

// declare functions
double add(double num1, double num2, double num3);
double avg(double sum, int n);

// main function
int main()
{
  // declare variables
  double num1, num2, num3;
  double sum, average;

  // take input from end-user
  cout << "Enter three Numbers :: ";
  cin >> num1 >> num2 >> num3;

  // calculate sum value
  sum = add(num1 , num2, num3);
  
  // calculate average value
  average = avg(sum, 3);

  // display result
  cout << "Sum = " << sum << endl;
  cout << "Average = " << average << endl;

  return 0;
}

// function to add three numbers
double add(double num1, double num2, double num3)
{
    return num1+num2+num3;
}

// function to calculate average of n number
double avg(double sum, int n) 
{
    return sum / n;
}

Output:-

Enter three Numbers :: 20 30 45
Sum = 95
Average = 31.6667

Also Read:- Database Management System Tutorial

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Learn More C++ Programming Examples,

Leave a Reply