Home
C Examples
Write a C Program to Find The Sum of Integers Divisible by 2 | C Programming Examples
Subscribe to:
Post Comments (Atom)
CodeShikhi is the free learning platform, প্রোগ্রামিং,Learn Programming in Bangla,Bangla Programming Tutorial,C Programming in Bangla,C in Bangla,C Programming in Bengali,C Programming Bangla Tutorial, URI Online Judge Solution in C C++ Python,JavaScript Full Tutorials , OOP Tutorial in C++, Object Oriented Programming in C++,Learn OOP in C++,C Programming Exercises,C Programming Examples with Code
#include<stdio.h>
int main()
{
int i,sum=0,num1,num2;
printf("Enter Number1\n");
scanf("%d",&num1);
printf("Enter Number2\n");
scanf("%d",&num2);
for(i=num1;i<=num2;i++)
{
if(i%2==0)
{
sum+=i;
}
}
printf("The sum of all integers divisible by 2 between %d and %d is %d\n",num1,num2,sum);
}
We initialized
i---->to use in for loop.
num1-->to store 1st number.
num2-->to store 2nd number.
sum---->to store the sum of all integers that are divisible by 2.
We took the number 1 and 2 from user.(let us take num1=1 and num2 =10)
Now we enter the loop where i=num1-->1 and i<=num2-->10.
Loop 1:
i=1 and as i<=10 the loop executes
then as i%2 (i.e. 1%2) is 1 so the if statement won't execute keeping sum=0
Now the value of i is incremented by 1.Therefore, i=2.
In Loop 2, now i = 2
i=2 and as i<=10 the loop executes
then as i%2 (i.e. 2%2) is 0 so the if statement will execute.
As sum+=i(i.e. same as sum=sum+i). Therefore, sum=0+2=2.
Now the value of i is incremented by 1.Therefore, i=3.
Loop 3: now i=3
i=3 and as i<=10 the loop executes. Then as i%2 (i.e. 1%2) is 1 so the if statement wont execute keeping sum =2
Now the value of i is incremented by 1.Therefore, i=4.
Loop 4: now i=4
i=4 and as i<=10 the loop executes.
Then as i%2 (i.e. 4%2) is 0 so the if statement will execute.
As sum+=i(i.e. same as sum=sum+i).Therefore, sum=2+4=6.
Now the value of i is incremented by 1.Therefore, i=5.
This continues till i becomes 10 where i=5 , i%2=>5%2=1 which is not 0 so sum remains same which is 6.
When i=6,sum=6+6=12
When i=7, if statement will not execute so sum remains 10.
When i=8, sum=12+8=20
When i=9,sum remains same as 20.
When i=10 ,sum=20+10=30.
In this way it will execute till i=10 after that as i becomes 11 the loop terminates.
Then the value in sum is printed which is 30 in this case.
Finally print the result.
Previous Post:
0 Response to Write a C Program to Find The Sum of Integers Divisible by 2 | C Programming Examples
Post a Comment