Summation is the process of adding a sequence of numbers to get their total sum. This fundamental operation is widely used in various applications, such as calculating averages, totals, and other aggregate values.

 

Objective

The objective is to read a series of numbers from the user and calculate their total sum.

 

Steps

  1. Input: Get the number of elements 𝑛 that the user wants to sum.
  2. Loop: Use a loop to read each number and add it to a running total.
  3. Output: Print the total sum of the numbers.

Algorithm in Pseudo-Code

 

 

C Implementation

Here’s a C program to calculate the sum of a set of numbers provided by the user.

 

Explanation of the C Program

  1. Include Standard I/O Library:

    • #include <stdio.h>: This line includes the standard input-output library needed for functions like printf and scanf.
  2. Main Function:

    • int main(): The main function is the entry point of the program.
  3. Variable Declarations:

    • int n, sum = 0, num;: This line declares three integer variables:
      • n: To store the number of elements.
      • sum: To keep a running total of the sum (initialized to 0).
      • num: To store each number entered by the user.
  4. Input from User:

    • printf(“Enter the number of elements: “);: This line prompts the user to enter the number of elements they want to sum.
    • scanf(“%d”, &n);: This line reads the integer input from the user and stores it in the variable n.
  5. For Loop for Summation:

    • for (int i = 0; i < n; i++): This loop iterates n times, starting from 0 to n-1.
    • printf(“Enter number %d: “, i + 1);: Inside the loop, this line prompts the user to enter the next number in the sequence.
    • scanf(“%d”, &num);: This line reads the integer input from the user and stores it in the variable num.
    • sum += num;: This line adds the current number to the running total sum.
  6. Output the Sum:

    • printf(“Sum of the numbers: %d\n”, sum);: After the loop, this line prints the total sum of the numbers.
  7. Return Statement:

    • return 0;: This indicates that the program finished successfully.

 

Sample Output

 

If the user inputs 3 for the number of elements and then inputs the numbers 5, 10, and 15, the program will output:

 

Summary

 

The summation algorithm is a simple yet powerful tool in programming. It demonstrates how to use loops to perform repetitive tasks, how to handle user input, and how to aggregate values. This basic operation forms the foundation for many more complex numerical and data processing tasks in programming.