in Algorithms recategorized by
2,513 views
18 votes
18 votes

In the following Pascal program segment, what is the value of X after the execution of the program segment?

X := -10; Y := 20;
If X > Y then if X < 0 then X := abs(X) else X := 2*X;
  1. $10$
  2. $-20$
  3. $-10$
  4. None
in Algorithms recategorized by
2.5k views

3 Comments

If X > Y then if X < 0 then X := abs(X) else X := 2*X;

It is looking something like conditional operator like we can write :

if ( X > Y ) ? if ( X < 0) ? X= abs( X) : X = 2 * X

associativity from right to left

So, we can write ,

if ( X > Y ) ? ( if ( X < 0) ? X= abs( X) : X = 2 * X)

Anyone confirm is my thinking is correct??

0
0
It depends on the programming language – for C, that is correct. “else” matches to the nearest “if”.
0
0
Thanks sir...
0
0

1 Answer

30 votes
30 votes
Best answer

The answer of $X$ remains unchanged. As the if condition becomes false.

X := -10

The answer is C . This is a classic example of an $\text{if-else}$ issue. Always $else$ matches for nesting to the closest $\text{if}$ in C Programming & Pascal .
https://en.wikipedia.org/wiki/Dangling_else

if (x>y)
{
   if (x<0)
       x=abs(x)
    else
       x=2*x
}
edited by

4 Comments

When having confusion, always try to match else with last unmatched if condition.

This is usually the solution the compiler follows for dangling else problem during compilation of a program.

Reference: Ullman for compilers
5
5

@Ayush Upadhyaya

I havenot got your point

always try to match else with last unmatched if condition.
 

means?

0
0
Means

if(a>b) then if(b>c) then t=x else v=y will be

if(a>b) then

      if(b>c) then

          t=x

      else

      v=y
0
0
Answer:

Related questions