Contact Learn C
Copy

Program 11:Sum of all integers divisible by 2 between two numbers

Program 11:
 
#include<stdio.h>
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 between %d and %d is %d\n",num1,num2,sum);
}
Explanation:
  1. 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.
  2. We took the number 1 and 2 from user.(let us take num1=1 and num2 =10)
  3. 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.
    • 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
    • When 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.
Output:

Sum of all integers divisible by 2 between two numbers
Donate

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide