C program to find sum of even numbers from 1 to n
C program to find sum of even numbers from 1 to n
In this post, we will develop a C program to find the sum of even numbers from 1 to n. To find the sum of even numbers we need to iterate the numbers from 1 to n.
C Program
#include
int main()
{
int n;
//initialize sum variable
int sum = 0;
int i = 2;
printf("Please input the number n:");
scanf("%d",&n);
while (i <= n)
{
sum = sum + i;
i =i + 2;
}
printf("Sum of even numbers from 1 to n is:= %d\n", sum);
return 0;
}
–

To find the sum we have initialized a variable sum to 0. We accumulate the sum of the even numbers from the range 1 to n.
To get the even number we will start with the 2 and in each iteration
we will increment the i variable with 2.
i = i + 2;
Sample Output
Please input the number n:15
Sum of even numbers from 1 to n is:= 56

The IDE used in the tutorial is Code:: Blocks.
To download and install Code Blocks follow the link:
https://www.testingdocs.com/download-and-install-codeblocks/
For more information on Code Blocks IDE, visit the official website of Code blocks IDE: http://www.codeblocks.org/