Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

sum of n numbers in c using for loop

 Here is example of a C program that uses a for loop to calculate the sum of 'n' numbers:

  1. #include

  2. int main() {
  3.     int n, i, num, sum = 0;

  4.     printf("Enter the value of n: ");
  5.     scanf("%d", &n);

  6.     for (i = 1; i
  7.         printf("Enter the number: ");
  8.         scanf("%d", &num);
  9.         sum += num;
  10.     }

  11.     printf("The sum of %d numbers is %d\n", n, sum);

  12.     return 0;
  13. }

In this Program, first, the user is prompted to enter the value of 'n' (the Number of numbers to be added). Then, a for loop is used to iterate 'n' times and prompt the user to enter a number in each iteration. The variable 'sum' is initialized to 0 and it's being used to keep the sum of all numbers entered by the user. In each iteration, the value of 'num' is added to 'sum' using the += operator. Finally, the program prints the sum of 'n' numbers.

In this example, the for loop starts with i=1, and it will run as long as i

It's important to note that, if you want to input the n numbers at once, you can use an array and use a for loop to iterate over the array and add the numbers to the sum variable.

This C program uses a for loop to calculate the sum of 'n' numbers by prompting the user to enter a number in each iteration of the loop, adding it to a running sum, and finally printing the total sum at the end. This is a simple and efficient way to calculate the sum of multiple numbers.



This post first appeared on Java Tutorial - InstanceOfJava, please read the originial post: here

Share the post

sum of n numbers in c using for loop

×

Subscribe to Java Tutorial - Instanceofjava

Get updates delivered right to your inbox!

Thank you for your subscription

×