Explanation
The program demonstrates the use of macros in C by calculating the square of a value entered by the user using the SQUARE
macro.
Header
The code begins with including the standard input-output header file using #include <stdio.h>
and defining the SQUARE
macro.
Macro Definition
The program defines a macro SQUARE
to calculate the square of a number:
#define SQUARE(x) ((x) * (x))
: Defines the macro which takes one parameterx
and returns its square.
Variable Declaration
The main()
function is defined, and a variable is declared:
int x;
: Variable to hold the value entered by the user.
Program Description
The program prints a description message for the user to understand its functionality.
User Input
The user is prompted to enter the value of x
:
printf("Enter the value for x: ");
: Prompts the user to enter the value ofx
.scanf("%d", &x);
: Reads the value entered by the user and stores it inx
.
Calculate Square
The program calculates the square of the value using the SQUARE
macro:
int y = SQUARE(x);
: Calls theSQUARE
macro withx
as the argument and stores the result iny
.
Output Result
The program prints the square of the value:
printf("The square of %d is %d\n", x, y);
: Prints the value ofx
and its squarey
.
Program End
The program ends with 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>
#define SQUARE(x) ((x) * (x))
int main()
{
printf("\n\n Program to demonstrate the macro in C by finding the square of the value entered by the user. \n\n");
// Declare a variable and calculate its square using the SQUARE macro
int x;
printf("Enter the value for x: ");
scanf("%d", &x);
int y = SQUARE(x);
// Print the square of x
printf("The square of %d is %d\n", x, y);
return 0;
}
Output
Program to demonstrate the macro in C by finding the square of the value entered by the user.
Enter the value for x: 5
The square of 5 is 25