Explanation
The program prints all numbers divisible by 5 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 numbers divisible by 5. 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
.
Divisibility by 5
The program prints all numbers divisible by 5 between d
and m
using a while
loop:
while (d <= m)
: Continuously checks ifd
is less than or equal tom
.if (d % 5 == 0)
: Checks if the current value ofd
is divisible by 5.printf("%d\t", d);
: Prints the current value ofd
if it is divisible by 5.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 all numbers which are divisible by 5 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 numbers divisible by 5 - (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 numbers divisible by 5 between %d and %d: \n\t", d, m);
while (d <= m)
{
if (d % 5 == 0)
{
printf("%d\t", d);
}
d++;
}
printf("\n");
return 0;
}
Output
Program to print all numbers which are divisible by 5 between the numbers that the user chooses. Example 1 to 100.
Enter two numbers between which you want to print all the numbers divisible by 5 - (Example: 2 100)
- and press enter: 2
55
Printing all the numbers divisible by 5 between 2 and 55:
5 10 15 20 25 30 35 40 45 50 55