Explanation
The program demonstrates the use of macros in C by calculating the cube of a value entered by the user using the f(x)
macro.
Header
The code begins with including the standard input-output header file using #include <stdio.h>
and defining the f(x)
macro.
Macro Definition
The program defines a macro f(x)
to calculate the cube of a number:
#define f(x) x * x * x
: Defines the macro which takes one parameterx
and returns its cube.
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 a 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 Cube
The program calculates the cube of the value using the f(x)
macro:
int result = f(x);
: Calls thef(x)
macro withx
as the argument and stores the result inresult
.
Output Result
The program prints the cube of the value:
printf("f(%d) = %d\n", x, result);
: Prints the value ofx
and its cuberesult
.
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 f(x) x * x * x
int main()
{
int x;
printf("\n\n Program to demonstrate the macro by finding the cube of the value entered by the user. \n\n");
printf("Enter a value for x: ");
scanf("%d", &x);
// Use the macro f(x) to calculate x*x
int result = f(x);
printf("f(%d) = %d\n", x, result);
return 0;
}
Output
Program to demonstrate the macro by finding the cube of the value entered by the user.
Enter the value for x: 5
f(5) = 125