C Programming - C Preprocessor - Discussion
Discussion Forum : C Preprocessor - Find Output of Program (Q.No. 2)
2.
What will be the output of the program?
#include<stdio.h>
#define SQUARE(x) x*x
int main()
{
float s=10, u=30, t=2, a;
a = 2*(s-u*t)/SQUARE(t);
printf("Result = %f", a);
return 0;
}
Answer: Option
Explanation:
The macro function SQUARE(x) x*x calculate the square of the given number 'x'. (Eg: 102)
Step 1: float s=10, u=30, t=2, a; Here the variable s, u, t, a are declared as an floating point type and the variable s, u, t are initialized to 10, 30, 2.
Step 2: a = 2*(s-u*t)/SQUARE(t); becomes,
=> a = 2 * (10 - 30 * 2) / t * t; Here SQUARE(t) is replaced by macro to t*t .
=> a = 2 * (10 - 30 * 2) / 2 * 2;
=> a = 2 * (10 - 60) / 2 * 2;
=> a = 2 * (-50) / 2 * 2 ;
=> a = 2 * (-25) * 2 ;
=> a = (-50) * 2 ;
=> a = -100;
Step 3: printf("Result=%f", a); It prints the value of variable 'a'.
Hence the output of the program is -100
Discussion:
18 comments Page 2 of 2.
SonaliA said:
1 decade ago
As C language considers from left 2 right associative.
it should be as fallows.
2*(-50)/2*2
-100/2*2
-50*2
-100
it should be as fallows.
2*(-50)/2*2
-100/2*2
-50*2
-100
Rupinderjit said:
1 decade ago
@Chetan is quite right in his explanation.
Akhila said:
1 decade ago
But C language considers from left 2 right associative
2*(-50)/2*2
-100/2*2
-50*2
-100
2*(-50)/2*2
-100/2*2
-50*2
-100
Pruthvi said:
1 decade ago
As / and * have equal priority then we should conside associativity na... as it is from left to right then how come we divide it first..??
C H said:
1 decade ago
When we define the macro, we should define it with a ( ) to avoid the confusion.
This is a simple mistake for programmer.
#define SQUARE(x) (x*x)
Then the answer will be -25 .
This is a simple mistake for programmer.
#define SQUARE(x) (x*x)
Then the answer will be -25 .
( # e t # @ n said:
1 decade ago
But C language considers from left 2 right associative
2*(-50)/2*2
-100/2*2
-50*2
-100
2*(-50)/2*2
-100/2*2
-50*2
-100
Maithili said:
1 decade ago
But,
2*(-50)/2*2
= 2*(-25)/2
= -25
2*(-50)/2*2
= 2*(-25)/2
= -25
Srivibha said:
1 decade ago
a = 2 * (-50) / 2 * 2 ;
As per c language *,/,% has same precedence.
so it should evaluate 2*(-50) first. but why its evaluating (-50)/2 first?
As per c language *,/,% has same precedence.
so it should evaluate 2*(-50) first. but why its evaluating (-50)/2 first?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers