Explanation
The program calculates and prints the sum of all 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 three integer variables d
, m
, and j
are declared. Variable j
is initialized to 0 to store the sum of the numbers.
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 find the sum of all the 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 o = d;
: Temporarily storesd
ino
.d = m;
: Assigns the value ofm
tod
.m = o;
: Assigns the stored value ino
tom
.
Sum Calculation
The program calculates the sum of all numbers between d
and m
using a while
loop:
while (d <= m)
: Continuously checks ifd
is less than or equal tom
.j += d;
: Adds the current value ofd
toj
.d++;
: Incrementsd
by 1.
Program End
The program prints the final sum stored in j
and 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, j = 0;
printf("\n\n Program to calculate and print the sum of all numbers between the numbers that the user chooses. Example 1 to 100. \n\n");
printf("Enter two numbers between which you want to find the sum of all the 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 o = d;
d = m;
m = o;
}
printf("\nSum of all the numbers between %d and %d is ", d, m);
while (d <= m)
{
j += d;
d++;
}
printf("%d\t", j);
printf("\n");
return 0;
}
Output
Program to calculate and print the sum of all numbers between the numbers that the user chooses. Example 1 to 100.
Enter two numbers between which you want to find the sum of all the numbers - (Example: 2 100) - and
press enter: 22 34
Sum of all the numbers between 22 and 34 is 364