Here is example of a C program that uses a for loop to calculate the sum of 'n' numbers:
- #include <stdio.h>
- int main() {
- int n, i, num, sum = 0;
- printf("Enter the value of n: ");
- scanf("%d", &n);
- for (i = 1; i <= n; i++) {
- printf("Enter the number: ");
- scanf("%d", &num);
- sum += num;
- }
- printf("The sum of %d numbers is %d\n", n, sum);
- return 0;
- }
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 <= n, with i being incremented by 1 in each iteration.
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.
No comments