21 votes 21 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; $10$ $-20$ $-10$ None Algorithms gate1995 algorithms identify-function easy + – Kathleen asked Oct 8, 2014 recategorized Apr 25, 2021 by Lakshman Bhaiya Kathleen 3.9k views answer comment Share Follow See all 3 Comments See all 3 3 Comments reply Kiyoshi commented Jun 5, 2021 reply Follow Share 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 votes 0 votes Arjun commented Jun 5, 2021 reply Follow Share It depends on the programming language – for C, that is correct. “else” matches to the nearest “if”. 1 votes 1 votes Kiyoshi commented Jun 5, 2021 reply Follow Share Thanks sir... 0 votes 0 votes Please log in or register to add a comment.
Best answer 32 votes 32 votes 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 } Akash Kanase answered Dec 17, 2015 edited Apr 25, 2021 by Lakshman Bhaiya Akash Kanase comment Share Follow See all 7 Comments See all 7 7 Comments reply Arjun commented Dec 17, 2015 reply Follow Share else matches to closest if in all languages? 0 votes 0 votes Akash Kanase commented Dec 17, 2015 reply Follow Share For sure in C & Pascal ! We don't get any other languages in GATE ! 3 votes 3 votes Himanshu1 commented Dec 18, 2015 reply Follow Share But here x < y i.e. -10 < 20 3 votes 3 votes Akash Kanase commented Dec 18, 2015 reply Follow Share Yes you seem correct. Updated. 0 votes 0 votes Ayush Upadhyaya commented Dec 18, 2017 reply Follow Share 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 votes 5 votes srestha commented Dec 19, 2018 reply Follow Share @Ayush Upadhyaya I havenot got your point always try to match else with last unmatched if condition. means? 0 votes 0 votes Ayush Upadhyaya commented Dec 20, 2018 reply Follow Share 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 votes 0 votes Please log in or register to add a comment.