Introduction Assignment 13 — Average Marks of Three Subjects
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Calculate the Average Marks of Three Subjects

📑 On this page:
  • Reading multiple inputs from the user
  • Designing the average-marks program
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to read multiple inputs from the user with successive scanf calls
  • Why the average must be a floating-point calculation — even when marks are integers
  • How to store a student's name in a character array with %s
  • How to compute a sum and an average from three values
  • How to display student details and formatted results with printf
  • How to avoid the classic integer-division trap in the average formula

Reading multiple inputs from the user

Most real programs don't read a single number — they read several pieces of data and combine them. This program reads a student's name and the marks obtained in three subjects, computes the average, and displays a report. It's a small step up from the single-input programs, but it introduces a pattern you'll use constantly: prompt, read, compute, display.

The key function is scanf, the input counterpart to printf. Each call to scanf consumes one input value, with a format specifier that matches the variable's type. For an integer, use %d; for a double, use %lf; for a string (character array), use %s. If you call scanf three times in a row, the user must supply three values, either separated by whitespace on one line or entered on three separate lines.

The average formula is deceptively simple: average = (marks1 + marks2 + marks3) / 3.0. The tricky part is the divisor. If you write / 3, the compiler performs integer division — 250 / 3 becomes 83, not 83.33 — and you silently lose the fractional part. Using 3.0 forces floating-point division. This is the single most common bug in average-calculating programs, and we'll cover it in detail.

💡 In one line: read each input with its own scanf call, store the marks in variables, compute the average with a floating-point divisor (3.0), and print the result with %.2lf for two decimal places.

Diagram of a student report card showing three subject marks, total, and average, with a C code snippet for reading marks and computing the average.

The program accepts the student's name and three subject marks, adds the marks, divides by three, and prints a short report. For example, if the student scores 78, 85, and 92, the total is 255 and the average is 85.00. The program displays both the individual marks and the average, so the user can verify the calculation.

Designing the average-marks program

The design has a handful of decisions that matter:

Decision Choice Reason
Type for marksdouble (or float)Marks can be fractional (e.g., 78.5). Using int would truncate.
Type for averagedoubleThe average is almost always fractional.
Storage for namechar name[50]A character array holds a short string. 50 is enough for most names.
Input methodscanf("%lf", &marks1)%lf is the format specifier for a double.
Average divisor3.0A floating-point divisor forces floating-point division, avoiding truncation.
Output format%.2lfTwo decimal places — enough precision for a typical marks report.

Why choose double for marks instead of int? Most marks are whole numbers, so int would technically work. But real marks can be fractional (78.5 out of 80), and the average is almost certainly fractional. Using double throughout avoids the risk of accidentally truncating somewhere. If you do use int for marks, the average must still be double — and you must remember to divide by 3.0, not 3.

The character array char name[50] is the simplest way to store a name in C. It's a fixed-size buffer that holds up to 49 characters plus a terminating null byte. scanf("%s", name) reads a whitespace-delimited word — so it works for "Alice" but stops at the space in "Alice Smith." Handling full names with spaces requires a more advanced approach (like fgets), which is beyond this program's scope. For a first assignment, a single-word name is fine.

🎯 Key idea: the divisor in the average formula determines the type of the division. / 3 on integers truncates; / 3.0 on doubles gives the full fractional result. Make this a habit early, and you'll never be surprised by a truncated average.

Complete C Program

Program: read three subject marks and compute the average

#include <stdio.h>                       // Include standard I/O library for printf and scanf

int main(void) {                           // Program entry point
    char name[50];                         // Array to hold the student's name (up to 49 chars + '\0')
    double marks1, marks2, marks3;         // Marks for the three subjects (double for fractional values)
    double total, average;                 // Total and average of the three marks

    printf("Enter the student's name: ");   // Prompt for the name
    scanf("%s", name);                     // Read a word into name; no & needed for a character array

    printf("Enter marks for subject 1: ");  // Prompt for the first subject
    scanf("%lf", &marks1);                 // Read a double into marks1

    printf("Enter marks for subject 2: ");  // Prompt for the second subject
    scanf("%lf", &marks2);                 // Read a double into marks2

    printf("Enter marks for subject 3: ");  // Prompt for the third subject
    scanf("%lf", &marks3);                 // Read a double into marks3

    total = marks1 + marks2 + marks3;      // Sum the three subject marks
    average = total / 3.0;                 // Divide by 3.0 (floating-point) to get a fractional average

    printf("\nStudent Details\n");          // Print a report header
    printf("Name    : %s\n", name);         // Print the student's name
    printf("Subject 1: %.2lf\n", marks1);   // Print the first mark with two decimals
    printf("Subject 2: %.2lf\n", marks2);   // Print the second mark
    printf("Subject 3: %.2lf\n", marks3);   // Print the third mark
    printf("Total    : %.2lf\n", total);    // Print the total
    printf("Average  : %.2lf\n", average);  // Print the average with two decimals

    return 0;                              // Return success to the operating system
}
                                    

The program has four scanf calls (one for the name, three for the marks) and six printf calls (one per line of output). The flow is straightforward: read the inputs, compute the total and average, then print a report. Notice the \n at the start of the "Student Details" header — that produces a blank line before the report, separating it from the last prompt.

The scanf("%s", name) call has no &. That's correct: name is an array, and in most contexts (including as an argument to scanf) an array name decays to a pointer to its first element. Passing name is equivalent to passing &name[0]. For scalar variables like marks1, you must pass &marks1 because scanf needs the address to write into.

And here is the same program without the comments, for comparison:

Same program, no comments

#include <stdio.h>

int main(void) {
    char name[50];
    double marks1, marks2, marks3;
    double total, average;

    printf("Enter the student's name: ");
    scanf("%s", name);

    printf("Enter marks for subject 1: ");
    scanf("%lf", &marks1);

    printf("Enter marks for subject 2: ");
    scanf("%lf", &marks2);

    printf("Enter marks for subject 3: ");
    scanf("%lf", &marks3);

    total = marks1 + marks2 + marks3;
    average = total / 3.0;

    printf("\nStudent Details\n");
    printf("Name    : %s\n", name);
    printf("Subject 1: %.2lf\n", marks1);
    printf("Subject 2: %.2lf\n", marks2);
    printf("Subject 3: %.2lf\n", marks3);
    printf("Total    : %.2lf\n", total);
    printf("Average  : %.2lf\n", average);

    return 0;
}
                                    

Both versions compile and run identically. The commented version is easier to read for a beginner; the uncommented version is what production code usually looks like for a program this simple. As your programs grow, the right amount of commenting shifts — more for tricky logic, less for self-evident statements.

Program Output

Here is typical output for a student named Alice who scored 78, 85, and 92:

Enter the student's name: Alice
Enter marks for subject 1: 78
Enter marks for subject 2: 85
Enter marks for subject 3: 92

Student Details
Name    : Alice
Subject 1: 78.00
Subject 2: 85.00
Subject 3: 92.00
Total    : 255.00
Average  : 85.00
                                

Check: 78 + 85 + 92 = 255; 255 / 3 = 85.00. Correct. The output shows two decimal places for all numeric values because the format string is %.2lf.

For a case with fractional marks and a non-terminating average:

Enter the student's name: Bob
Enter marks for subject 1: 77.5
Enter marks for subject 2: 82
Enter marks for subject 3: 90.5

Student Details
Name    : Bob
Subject 1: 77.50
Subject 2: 82.00
Subject 3: 90.50
Total    : 250.00
Average  : 83.33
                                

Check: 77.5 + 82 + 90.5 = 250; 250 / 3 = 83.3333..., rounded to 83.33. Correct. Notice that the fractional inputs are printed with two decimals even though the user typed them with one. That's the format specifier doing its job.

For a case with all marks equal:

Enter the student's name: Carol
Enter marks for subject 1: 100
Enter marks for subject 2: 100
Enter marks for subject 3: 100

Student Details
Name    : Carol
Subject 1: 100.00
Subject 2: 100.00
Subject 3: 100.00
Total    : 300.00
Average  : 100.00
                                

A perfect score. The average equals each mark, which makes sense: when all values are equal, the average equals that value.

For a case that exposes the integer-division trap, suppose a buggy version used int for the average and / 3 instead of / 3.0:

Enter marks: 78, 85, 92
Buggy average (int / 3): 85
Correct average (double / 3.0): 85.00
                                

In this particular case the average happened to be a whole number, so both versions agree. But try marks 70, 75, and 80 (total 225, average 75) — also fine. Try 70, 71, and 72 (total 213, average 71) — still fine. The bug surfaces with marks like 70, 71, and 73 (total 214): correct average is 71.33, but int division gives 71. That's a quarter-mark error per student, which adds up. Always use floating-point division for averages.

🔍 Try this: change double to int for marks1, marks2, marks3, and average, and change scanf("%lf", ...) to scanf("%d", ...). Enter marks 70, 71, 73. The average printed will be 71, not 71.33. That's the integer-division truncation in action — and it's why the type of the average matters as much as the formula.

Step-by-Step Explanation

Let's walk through the program line by line. The comments in the code do the same thing at a high level; this section goes deeper into why each piece is needed.

1. The header include

#include <stdio.h> — a preprocessor directive that pastes the standard I/O header into the source file. That header declares printf and scanf, both of which this program uses. Without it, the compiler would complain about undeclared functions (or, worse, silently assume the wrong return type in old C).

2. The main function

int main(void) — declares the entry point. int means the function returns an integer (0 for success), (void) means it takes no arguments. The body of the function is between the braces { ... }.

3. Declaring the character array for the name

char name[50]; — declares an array of 50 characters. A string in C is stored as a sequence of characters followed by a null byte ('\0'), so this buffer holds up to 49 visible characters plus the terminator. The number 50 is arbitrary — big enough for typical names, small enough to be safe on the stack. scanf("%s", name) reads characters until whitespace and appends the null byte automatically.

4. Declaring the marks, total, and average

double marks1, marks2, marks3; — declares three double variables, one per subject. Multiple variables of the same type can be declared on one line, separated by commas. double total, average; — two more doubles to hold the sum and the mean. Using double throughout means the arithmetic is done in floating-point precision, avoiding truncation at every step.

5. Reading the name

printf("Enter the student's name: "); — prompts the user. scanf("%s", name); — reads a whitespace-delimited word into name. Note there's no &: the array name name already evaluates to the address of its first element, which is what scanf needs. Passing &name would technically also work (same value), but name is conventional and clearer.

A caveat: scanf("%s", ...) has no bounds checking. If the user enters a name longer than 49 characters, the write overflows the buffer. This is a known vulnerability in C programs that use %s without a width specifier. A safer version uses scanf("%49s", name) — the 49 limits input to 49 characters. For this introductory program, the plain %s is fine, but be aware of the danger.

6. Reading the three marks

Each pair of lines follows the same pattern: print a prompt, then read a value. The prompt ends without a newline, so the user types on the same line. scanf("%lf", &marks1) reads a double from standard input and stores it at the address of marks1. The %lf format specifier is essential — using %d (for int) or %f (for float) with a double would be undefined behavior, usually producing garbage.

What happens if the user enters all three marks on one line, separated by spaces? scanf skips leading whitespace (including newlines) before each read, so the three calls consume three tokens regardless of whether they're on one line or three. This is a useful property: scanf is token-based, not line-based.

7. Computing the total

total = marks1 + marks2 + marks3; — adds the three marks and stores the sum in total. All operands are double, so the addition is done in double precision. The result is exact for typical mark values (well within double's 15-digit precision range).

8. Computing the average

average = total / 3.0; — divides the total by 3.0. The key detail is 3.0 rather than 3. In C, division depends on operand types: int / int gives an integer (truncated), double / double gives a double. Since total is a double and 3.0 is a double literal, the operation is floating-point division, and the fractional part is preserved. Writing total / 3 would still produce a double because total is double — the integer 3 would be promoted to 3.0. But writing 3.0 explicitly documents the intent and works correctly even if total is changed to int later.

9. Printing the report

printf("\nStudent Details\n"); — prints a blank line, then the header, then a newline. The leading \n separates the report from the last input prompt. Each subsequent printf prints one line of the report, using %.2lf for numeric values so they appear with two decimal places. %s prints the name as a string.

Why %.2lf instead of %lf? Without the .2, printf prints the full precision, which for a double like 78.0 would show 78.000000 — six zeros. For 83.333333333333, it would show the full 15 digits. The .2 rounds to two decimals, which is what a marks report needs. If you wanted one decimal, you'd write %.1lf; for none, %.0lf.

10. Returning from main

return 0; — signals that the program completed successfully. The operating system sees exit status 0. Nonzero return values indicate errors. For simple programs, the return value is rarely inspected, but it's part of the C standard's contract for int main.

11. The classic integer-division trap

Suppose you wrote the average formula as average = (marks1 + marks2 + marks3) / 3; and declared all variables as int. With marks 70, 71, 73 (sum 214), the division 214 / 3 in integer arithmetic truncates to 71, not 71.33. The error is silent — no compiler warning, no runtime exception, just a wrong answer. This is the single most common bug in average-calculation code, and it's why using double and 3.0 is the recommended pattern.

Even with double variables, a subtle trap remains: if you cast the sum to int before dividing by a double, the fractional part of the sum is lost. The safe rule: keep everything in floating-point from input to output, and use a floating-point divisor.

12. What about the string input?

scanf("%s", name) reads a single word. If the user enters "Alice Smith", scanf reads "Alice" into name and leaves " Smith" in the input buffer. The next scanf (which reads marks1) would then try to interpret "Smith" as a number, fail, and leave marks1 uninitialized — a confusing bug. For a single-word name, no problem. For full names, use fgets(name, sizeof(name), stdin) instead, which reads a whole line including spaces. We'll cover fgets in a later tutorial.

🎯 Key idea: the average is the total divided by the count. In C, the division operator behaves differently for integer and floating-point types. Make the divisor floating-point (3.0) and keep the total as a double — that's the whole fix. Verify your output against a mental estimate: if the printed average has fewer decimals than you expect, suspect integer division.

Frequently Asked Questions

1. Why is the average printed as 85.00 instead of 85?

Because the format specifier is %.2lf, which tells printf to print exactly two digits after the decimal point. If you want no decimal part, use %.0lf or cast to int before printing. The number 85.00 and 85 represent the same value — the difference is only display.

2. Why does scanf("%s", name) not need &, but scanf("%lf", &marks1) does?

name is an array of characters. In most expressions, an array name decays to a pointer to its first element — so name is effectively &name[0], which is exactly what scanf needs. marks1 is a scalar double, so you must explicitly take its address with &marks1.

3. Why divide by 3.0 instead of 3?

If both operands are integers, C performs integer division and truncates the fractional part. If either operand is a floating-point type, the division is floating-point. 3.0 is a double literal, so total / 3.0 is floating-point division. Since total is already a double in this program, 3 would also work — but 3.0 documents the intent and is safe even if total is later changed to int.

4. What happens if the user enters the marks separated by commas?

scanf reads tokens separated by whitespace. Commas are not whitespace, so the input "78, 85, 92" would break: scanf("%lf", &marks1) would read 78, stop at the comma, and leave ", 85, 92" in the buffer. The next call would fail (because the first character is a comma), and marks2 would be uninitialized. Always enter values separated by spaces or newlines.

5. Why use double instead of int for marks?

Marks are often whole numbers, so int would technically work. But fractional marks (78.5, 82.25) are common, and the average is almost certainly fractional. Using double throughout avoids truncation at input and at every intermediate step. The cost is a slightly larger memory footprint (8 bytes per variable instead of 4), which is irrelevant for a program this small.

6. How would I extend this program to calculate grades?

After computing the average, add a chain of if / else if statements: if average ≥ 90, print "A"; if ≥ 80, print "B"; and so on. This requires no new syntax — just an if statement, which is covered in the next section of the course. It's a natural next step once you're comfortable with input, arithmetic, and output.

💡 Tip: once this works, try to generalize it: read the marks for an arbitrary number of subjects (say, 5) by looping with a for loop and adding to total inside the loop. The average formula is then total / count. That's the same program with a loop instead of three hard-coded variables — and it's a useful exercise once you've learned loops.

📖 Related Tutorials

  • Previous: Accept Employee Name and Salary and Display Them
  • Basic Arithmetic Operations on Two Numbers
  • Addition, Subtraction, Multiplication, Division of Two Numbers
  • Built-in Data Types in C
  • Basic Input/Output Statements
  • Operators and Expressions
  • Declaration and Initialization of Variables
  • All 13 Introduction to C Assignments

Previous Topic: -->> 7. Accept Employee Name and Salary and Display Them   ||   Next Topic: -->> Introduction to C Assignments Index


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 Processiong
    • 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.