Menu
×
Tutorials Ms Word Tutorial Ms Excel Tutorial Ms PowerPoint Tutorial C Language Tutorial C++ Tutorial C Sharp Tutorial Visual Basic Tutorial HTML Tutorial CSS Tutorial JavaScript Tutorial WordPress Tutorial
     ❯   

ADVERTISEMENT

Sum of All Integers Divisible By 2 Between Two Numbers

This code takes two user-defined numbers, num1 and num2, and calculates the sum of all even numbers within the range [num1, num2]. It uses a for loop to iterate through the numbers and an accumulator variable sum to keep track of the total sum of even numbers.

#include<stdio.h>
main()
{
 int i,sum=0,num1,num2;
 printf("Enter 1st number: ");
 scanf("%d",&num1);
 printf("Enter 2nd number: ");
 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);
}
C Programming Examples
OUTPUT
Enter 1st number: 4
Enter 2nd number: 8
The sum of all integers divisible by 2 between 4 and 8 is 18
C Programming Examples

Explanation:

This C program calculates the sum of all integers between two user-defined numbers (num1 and num2) that are divisible by 2 (i.e., even numbers). Here’s a step-by-step explanation of the code:

Header File:

  • The program includes the standard C library header <stdio.h> for input and output operations.

Main Function:

  • The main function is the entry point of the program.

Variable Declaration:

Three variables are declared:

  • i (int): It is used as a loop counter to iterate through the integers.
  • sum (int): This variable will store the sum of even numbers between num1 and num2.
  • num1 (int) and num2 (int): These variables store the user inputs for the two numbers between which the program will find even numbers.

User Input:

The program prompts the user to enter two numbers:

  • “Enter Number1” for num1.
  • “Enter Number2” for num2.
  • The user’s inputs are read and stored in num1 and num2 using scanf.

For Loop:

  • The for loop is used to iterate from num1 to num2, including both num1 and num2.
  • i is initialized to num1, and the loop continues as long as i is less than or equal to num2.

Checking for Even Numbers:

  • Within the loop, each value of i is checked to determine if it’s an even number.
  • This is done by using the condition i % 2 == 0.
  • If the remainder when i is divided by 2 is 0, it means i is even, and in that case, it is added to the sum.

Accumulating Sum:

  • If i is even, it is added to the sum. The sum variable accumulates the sum of even numbers within the specified range.

Print Result:

  • After the loop completes, the program uses printf to display the sum of even numbers within the range. The format specifier %d is used to print the integer values of num1, num2, and sum.

End of Program:

  • Once the result is displayed, the program reaches the end of the main function and terminates.
Spread the love
Scroll to Top
Scroll to Top