Explanation
The program prints all perfect square numbers between two numbers entered by the user.
Header
The code begins with including the standard input-output header files using #include <stdio.h>
and #include <math.h>
for mathematical functions.
Variable Declaration
The main()
function is defined, and four integer variables d
, m
, j
, and o
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 find and print all perfect square numbers. The input is read using scanf("%d %d", &j, &o);
.
Perfect Square Calculation
The program finds and prints all perfect square numbers between j
and o
using a for
loop:
for (d = j; d <= o; d++)
: Loops through each number fromj
too
.m = sqrt(d);
: Calculates the square root of the current numberd
.if (m * m == d)
: Checks if the square of the square root is equal to the original number, indicating a perfect square.printf("\t %d", d);
: Prints the current number if it is a perfect square.
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>
#include <math.h>
int main()
{
int d, m, j, o;
printf("\n\n Program to print all numbers which are perfect square between user entered values. Example 1681. \n\n");
printf("Enter two numbers between which you want to find the perfect squares and print all such numbers - (Example: 2 100) - and press enter: ");
scanf("%d %d", &j, &o);
printf("All four digit special perfect square numbers between %d and %d are:\n", j, o);
for (d = j; d <= o; d++)
{
m = sqrt(d); // ri = root of i
if (m * m == d)
{
printf("\t %d", d);
}
}
printf("\n");
return 0;
}
Output
Program to print all numbers which are perfect square between user entered values. Example 1681.
Enter two numbers between which you want to find the perfect squares and print all such numbers -
(Example: 2 100) - and
press enter: 23 4443
All four digit special perfect square numbers between 23 and 4443 are:
25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 784 841 900
961 1024 1089 1156
1225 1296 1369 1444 1521 1600 1681 1764 1849 1936 2025 2116 2209 2304 2401 2500 2601 2704 2809 2916
3025 3136 3249 3364
3481 3600 3721 3844 3969 4096 4225 4356