Explanation
The program prints all numbers between two numbers input by the user, incrementing by 1.
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 incrementing by 1. 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
.
Number Printing
The program prints all numbers between d
and m
using a while
loop:
while (d <= m)
: Continuously checks ifd
is less than or equal tom
.printf("%d\t", d);
: Prints the current value ofd
.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 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 numbers with increment of 1 - (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 between %d and %d: \n\t", d, m);
while (d <= m)
{
printf("%d\t", d);
d++;
}
printf("\n");
return 0;
}
Output
Program to print numbers between the numbers that the user chooses. Example 1 to 100.
Enter two numbers between which you want to print all the numbers with increment of 1 - (Example: 2
100) - and press
enter: 2 40
Printing all the numbers between 2 and 40:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
38
39 40