Code Issues Solver

C Program for Summing User-Input Numbers

This C program prompts users for a count of integers, reads the values while validating input, and computes their sum, ensuring robust error handling and user-friendly interaction.


Empty image or helper icon

Prompt

sum of n numbers in c program

Answer

Problem Statement

The task is to write a C program that computes the sum of n numbers input by the user.

Code Analysis

The solution should handle:

  • Input validation to ensure only numeric values are accepted.
  • Proper memory management if using dynamic allocation (though static allocation suffices for simplicity).
  • Efficient handling of user input and output.

Proposed Solution

We will write a simple C program that:

  1. Prompts the user for the number of elements (n).
  2. Reads n integers from the user and calculates their sum.
  3. Displays the result.

Code Development

Here is the complete C code for the solution:

#include 

// Function to compute the sum of n numbers
int sum_of_numbers(int n) {
    int sum = 0;  // Initialize sum to zero
    int number;

    // Loop to read n numbers
    for (int i = 0; i < n; i++) {
        printf("Enter number %d: ", i + 1);
        // Validate input
        if (scanf("%d", &number) != 1) {
            printf("Invalid input. Please enter an integer.\n");
            // Clear the input buffer
            while (getchar() != '\n');
            i--;  // Decrement i to repeat this iteration
            continue;  // Skip to the next iteration
        }
        sum += number;  // Add the number to sum
    }
    return sum;  // Return the final sum
}

int main() {
    int n;

    // Prompting user for the number of elements
    printf("Enter the number of elements: ");
    
    // Validate input for n
    while (scanf("%d", &n) != 1 || n <= 0) {
        printf("Please enter a valid positive integer for the number of elements: ");
        while (getchar() != '\n');  // Clear the input buffer
    }

    // Calculate the sum of n numbers
    int total_sum = sum_of_numbers(n);
    
    // Output the result
    printf("The sum of the entered numbers is: %d\n", total_sum);

    return 0;  // Exit the program
}

Code Explanation

  • Includes: The #include <stdio.h> directive allows the use of standard input-output functions.
  • sum_of_numbers Function: Contains the logic to read n integers and calculate their sum.
    • Utilizes a for loop to prompt the user for each integer.
    • Input validation ensures that only valid integers are accepted.
  • Main Function:
    • Prompts the user for the total number of integers.
    • Validates the input for n to ensure it is a positive integer.
    • Calls sum_of_numbers to get the total sum and outputs the result.

Usage Example

To use the program, compile it with a C compiler and run it. You will be prompted to:

  1. Enter the number of integers.
  2. Input each integer consecutively.

Example interaction:

Enter the number of elements: 3
Enter number 1: 5
Enter number 2: 10
Enter number 3: 15
The sum of the entered numbers is: 30

Conclusion

This solution efficiently computes the sum of n integers with validation in place to handle erroneous input cases. The structure of the program adheres to best practices in C programming, promoting user-friendly interaction. For further enhancement, consider exploring advanced topics such as dynamic memory allocation or file input/output in C as guided by resources available on the Enterprise DNA Platform.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This C program prompts users for a count of integers, reads the values while validating input, and computes their sum, ensuring robust error handling and user-friendly interaction.