Write a Program to find the sum of all even numbers from 1 to N where the value of N is taken as input.

Write a Program to find the sum of all even numbers from 1 to N where the value of N is taken as input.

In this post, we have discussed how to write a program to find the sum of all even number from 1 to n, write a program to print all even numbers.


At first, we have declear and initialize N and sum =0. Now take the input in N. And after that again we have declared an integer variable named i. Then we have initialize for loop. 


How to use for Loop:

For Loop is almost similar to the while loop ( if you don't know about loop then go first and check this post first here ) the only difference is its format. It is represented as 
for(initialization; condition; increment/ decrement)

Body of the loop 

               }


Here in the code below inside the for loop, we have to initialize i=2 that means the value of ' i ' start from 2 and then in the condition part we had put the condition 'i<=N' that means the loop will continue as long as i <N. Let assume that we have given the input value 15 i.e value of N=15. 

Write a Program to find the sum of all even numbers from 1 to N where the value of N is taken as input.

Now At the first time i=2 that means the condition i<N is true.
Now the body of the loop will be executed that is this  if(i%2==0) statement will execute and check the condition of the if statement if the condition becomes true then the number (i.e value of i) will be added in sum. At first case the condition i % 2 = =0 i.e the condition is true and the value of sum became 2. Then the value of 'i' increase 3 and again check the loop condition again it's true and all of the above steps will follow again. At last when the value of 'i' equal to ' N ' then it will exit from the loop and print the value of  'sum' i.e 56.

The following code is for Write a Program to find the sum of all even numbers from 1 to N where the value of N is taken as input.


#include <stdio.h>
void main()
{
int N, sum=0;
scanf("%d", &N); /* The value of N is taken from input */

int i;
for(i=2;i<=N;i++)
{
  if(i%2==0)
          sum=sum+i;
}
printf("Sum = %d", sum);
}

15
 Sum = 56

If you have any question or any quarry feel free to ask in the comment section.

Post a Comment

0 Comments