Explanation
The program prints all even numbers between two numbers input by the user.
Header
The code begins with including the standard input-output header file using #include <stdio.h>
.
Variable Declaration
The main()
function is defined, and two integer variables d
and m
are declared.
Program Description
The program prints a description message for the user to understand its functionality.
User Input
The user is prompted to enter two numbers between which they want to print all the even numbers. The input is read using scanf("%d %d", &d, &m);
.
Swapping Logic
If the user enters the larger number first, a conditional statement swaps the values of d
and m
to ensure d
is always the smaller number:
if (d > m)
: Checks ifd
is greater thanm
.int j = d;
: Temporarily storesd
inj
.d = m;
: Assigns the value ofm
tod
.m = j;
: Assigns the stored value inj
tom
.
Even Number Printing
The program prints all even numbers between d
and m
using a while
loop:
while (d <= m)
: Continuously checks ifd
is less than or equal tom
.if (d % 2 == 0)
: Checks if the current value ofd
is even.printf("%d\t", d);
: Prints the current value ofd
if it is even.d++;
: Incrementsd
by 1.
Program End
The program ends with printf("\n");
to print a new line and return 0;
to indicate successful execution.
Code
/*
* -----------------------------------------------------------
* Logic Building with Computer Programming (CSU1128)
* Instructor: Dr. Pankaj Vaidya | Author: Divya Mohan
*
* This code is a part of the educational initiative by dmj.one
* with aim of empowering and inspiring learners in the field of
* Computer Science and Engineering through the respective courses.
*
* (c) 2022, Divya Mohan for dmj.one. All rights reserved.
* -----------------------------------------------------------
*/
#include <stdio.h>
int main()
{
int d, m;
printf("\n\n Program to print even numbers between the numbers that the user chooses. Example 1 to 100. \n\n");
printf("Enter two numbers between which you want to print all the even numbers - (Example: 2 100) - and press enter: ");
scanf("%d %d", &d, &m);
// if loop to swap max number if user enters a bigger number first.
if (d > m)
{
int j = d;
d = m;
m = j;
}
printf("\nPrinting all the even numbers between %d and %d: \n\t", d, m);
while (d <= m)
{
if (d % 2 == 0)
{
printf("%d\t", d);
}
d++;
}
printf("\n");
return 0;
}
Output
Program to print even numbers between the numbers that the user chooses. Example 1 to 100.
Enter two numbers between which you want to print all the even numbers - (Example: 2 100) - and
press enter: 23 54
Printing all the even numbers between 23 and 54:
24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54