How to query sum of numbers?

To query the sum of numbers in C, you can use a simple program that prompts the user to enter a series of numbers and then calculates the sum. Here's an example:

#include <stdio.h>

int main() {
    int n;
    float x, sum = 0.0;

    // Ask the user for the number of inputs
    printf("Enter the number of values to sum: ");
    scanf("%d", &n);

    // Get the input numbers and calculate the sum
    for (int i = 0; i < n; i++) {
        printf("Enter number %d: ", i + 1);
        scanf("%f", &x);
        sum += x; // Add the input number to the sum
    }

    // Display the result
    printf("The sum of the entered numbers is: %.2f\n", sum);

    return 0;
}

Steps to Compile and Run:

  1. Create a file named sum_numbers.c:

    cd ~/project
    touch sum_numbers.c
  2. Copy the above code into sum_numbers.c.

  3. Compile the program:

    gcc sum_numbers.c -o sum_numbers
  4. Run the program:

    ./sum_numbers

How It Works:

  • The program first asks the user how many numbers they want to sum.
  • It then uses a loop to read each number from the user and adds it to the sum variable.
  • Finally, it prints the total sum of the entered numbers.

You can modify the program to handle different data types or to include error checking as needed.

0 Comments

no data
Be the first to share your comment!