(a) C/C++/Java and Perl share similar syntax for an if-then-else statement. Howe
ID: 3830211 • Letter: #
Question
(a) C/C++/Java and Perl share similar syntax for an if-then-else statement. However, C/C++/Java allows the then- and else-clauses to be either a single statement or a compound statement (using {}), while Perl requires that all then- and else-clauses must be compound. Provide a reason to justify the Perl design. (b) What is the output of the following Ruby code? (c) Explain why in Python, writing a multiple selection using else-if clauses (elif) is more readable than using nested if-then-else statements. Use some Python code to illustrate your answer.Explanation / Answer
a.
To remove the ambiguity of 'If-else' statements, perl syntactically upgraded to use {} even if its single statement of block.
correct syntax:
if(condition){
statements
}
else
{
statements
}
Syntax error example :
if(condition)
$x = 1;
$y = 2; //syntax error
else
$z = 3
To omit these kind of errors and make error free platform, Perl only accepts {braces} for if-else statements.
b.
The output of the above code is : 1 -2 6 4 -12 -14
c.
The if-elif is more readable than nested if-else.
Because we will use conditions in all the if and elif statements and there will be only one else statement in if-elif which looks more understandable for the users. In if-elif, if one condition gets true then it will ignore remaining statements.
If a<10:
print a
elif b<10:
print b
elif c<10:
print c
else:
print else
The nested if-else looks some ambiguity because we have to use seperate else statement for all the if conditions. Nested if-else works only when the conditions of all if becomes true or else it will go to else block.
if a <10:
if b<10:
if c<10:
print a,b,c
else:
print 'C less than 10'
else:
printf 'B less than 10'
else:
print 'A less than 10'
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.