Average of Array Elements in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Average of Array Elements in C: Program to Calculate Average of N Numbers

📑 On this page:
  • Introduction
  • C Program to Calculate Average
  • Sample Output
  • Program Explanation
  • Practice Exercise
  • Frequently Asked Questions
📚 In this tutorial, you will learn:
  • How to calculate the average of array elements
  • How to use type casting for accurate results
  • How to handle integer and float calculations
  • Step-by-step explanation of the program
  • Practice exercises to test your understanding

Introduction

In this tutorial, we will learn how to write a C program to calculate the average of array elements.

Finding the average of elements in an array is a common programming task. It is used in many real-world applications, such as:

  • Calculating the average score of students in a class
  • Finding the average temperature in weather data
  • Calculating the average sales figures
  • Finding the average of sensor readings

💡 Key Point: The average is calculated by first finding the sum of all elements and then dividing by the total number of elements. Using type casting ensures you get a decimal result instead of integer division.

C Program to Calculate Average of Array Elements

#include <stdio.h>

int main() {
    int n, i;
    int sum = 0;
    float average;
    
    // Ask user for number of elements
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    // Declare array of size n
    int arr[n];
    
    // Read elements into the array
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    // Calculate sum of array elements
    for(i = 0; i < n; i++) {
        sum = sum + arr[i];
    }
    
    // Calculate average using type casting
    average = (float)sum / n;
    
    // Display the average
    printf("\nSum of all elements: %d\n", sum);
    printf("Average of all elements: %.2f\n", average);
    
    return 0;
}

Sample Output

Enter the number of elements: 5
Enter 5 elements:
10 20 30 40 50

Sum of all elements: 150
Average of all elements: 30.00

Another Example (With Decimal Result):

Enter the number of elements: 4
Enter 4 elements:
10 15 25 30

Sum of all elements: 80
Average of all elements: 20.00

Example with Non-Integer Average:

Enter the number of elements: 6
Enter 6 elements:
10 20 30 40 50 60

Sum of all elements: 210
Average of all elements: 35.00

Program Explanation

Let's break down the code step by step:

  1. Include Header File: #include <stdio.h> includes the standard input/output library.
  2. Declare Variables:
    • int n; — stores the number of elements
    • int i; — loop counter
    • int sum = 0; — stores the sum of elements
    • float average; — stores the calculated average
  3. Get User Input: Prompts the user to enter the number of elements and then reads them into the array.
  4. Calculate Sum: The for loop for(i = 0; i < n; i++) iterates through each element and adds it to sum using sum = sum + arr[i];.
  5. Calculate Average: average = (float)sum / n; divides the sum by the number of elements. The (float) type casting is important because:
    • If both operands are integers, C performs integer division and truncates the decimal part
    • Type casting converts the sum to float, resulting in a decimal value
  6. Display Results: printf("\nSum of all elements: %d\n", sum); and printf("Average of all elements: %.2f\n", average); display the results with two decimal places.
  7. Return: return 0; indicates successful program execution.

📝 Important: Without type casting (float)sum / n, if sum is an integer and n is an integer, the result will be truncated. For example, 7 / 2 = 3 instead of 3.5. Always use type casting for accurate average calculations.

Algorithm to Calculate Average

  1. Start
  2. Read the number of elements (n)
  3. Read n elements into the array
  4. Set sum = 0
  5. For i = 0 to n-1:
    • sum = sum + arr[i]
  6. Set average = (float)sum / n
  7. Print sum and average
  8. End

Optimized Version: Single Loop

You can combine the sum calculation into the same loop where you read the input, making the program more efficient:

#include <stdio.h>

int main() {
    int n, i;
    int sum = 0;
    float average;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int arr[n];
    
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
        sum = sum + arr[i];  // Calculate sum on the fly
    }
    
    average = (float)sum / n;
    
    printf("\nSum of all elements: %d\n", sum);
    printf("Average of all elements: %.2f\n", average);
    
    return 0;
}

💻 Practice Exercise

Challenge 1: Modify the program to calculate the average of only the even numbers in the array.

Challenge 2: Calculate the average of positive and negative numbers separately.

🔍 Click to Show Solution for Challenge 1
#include <stdio.h>

int main() {
    int n, i;
    int sum = 0;
    int count = 0;
    float average;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int arr[n];
    
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
        if(arr[i] % 2 == 0) {  // Check if even
            sum = sum + arr[i];
            count++;
        }
    }
    
    if(count > 0) {
        average = (float)sum / count;
        printf("\nSum of even elements: %d\n", sum);
        printf("Average of even elements: %.2f\n", average);
    } else {
        printf("\nNo even numbers found.\n");
    }
    
    return 0;
}

Frequently Asked Questions

1. How do you calculate the average of array elements in C?

First, calculate the sum of all elements using a loop. Then, divide the sum by the total number of elements. Use type casting (float) to get a decimal result.

2. Why do I need type casting when calculating average?

Without type casting, C performs integer division when both operands are integers. For example, 7 / 2 = 3 instead of 3.5. Type casting ensures you get the correct decimal result.

3. What happens if the array is empty?

If the array has no elements (n = 0), division by zero occurs, which causes an error. Always check that n > 0 before calculating the average.

4. Can I calculate the average using a float array?

Yes, you can use a float array. The average calculation remains the same. If the array is of type float, you don't need type casting.

5. How can I display the average with more decimal places?

Use %f instead of %.2f in the printf statement. You can also specify the number of decimal places, like %.3f for three decimal places.

💡 Tip: Always use type casting (float) when dividing integers to get accurate decimal results. This is a common mistake beginners make.

📖 Related Tutorials

  • Sum of Array Elements
  • Find Maximum Element in Array
  • Find Minimum Element in Array
  • Reverse an Array in C

Previous Topic: -->> Find Minimum Element in Array   ||   Next topic: -->> Print Negative Elements in Array


📚 Explore More Topics

🗄️ SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

🐍 Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

☕ Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.