C program to find the sum of the first 100 natural numbers
Introduction:
Summing up the first 100 natural numbers is a fundamental mathematical operation that is often used in various applications. In programming, we can write a C program to find the sum of the first 100 natural numbers. In this article, we will discuss how to write a C program to calculate the sum of the first 100 natural numbers and provide an explanation of the code.
Calculating the Sum of the First 100 Natural Numbers:
To calculate the sum of the first 100 natural numbers, we need to add up all the numbers from 1 to 100. We can use a loop to add up these numbers and store the result in a variable. The C code for this operation is as follows:
#include <stdio.h>
int main()
{
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum =sum+i;
}
printf("The sum of the first 100 natural numbers is: %d\n", sum);
return 0;
}
In the above code, we start by initializing a variable called sum to zero. We then use a for loop to iterate through all the natural numbers from 1 to 100. During each iteration of the loop, we add the current value of i to the sum variable using the += operator. Finally, we print out the value of the sum variable to the console.
Explanation of Code:
- We include the standard input/output library using the #include <stdio.h> directive.
- We define the main function, which is the entry point for all C programs.
- We declare an integer variable called sum and initialize it to zero.
- We use a for loop to iterate through all the natural numbers from 1 to 100. We use the int i variable to keep track of the current number being added.
- During each iteration of the loop, we add the current value of i to the sum variable using the += operator. This operator is a shorthand way of writing sum = sum + i.
- Finally, we use the printf function to print out the value of the sum variable to the console. We use the %d format specifier to print out an integer value.
Output:
Conclusion:
Calculating the sum of the first 100 natural numbers is a simple yet fundamental mathematical operation. In programming, we can use a C program to find the sum of the first 100 natural numbers. By using a loop and a variable to keep track of the sum, we can easily perform this operation. In this article, we have explained how to write a C program to calculate the sum of the first 100 natural numbers and provided an explanation of the code. With this knowledge, you can apply these techniques to perform other mathematical operations in C programming.
You can also Read:
No comments:
Post a Comment