Code Fragments.

Q3. Consider the following two code fragments for counting spaces and newlines:

//version 1

:

if ( ch= = ‘  ‘ )

spaces + + ;

if ( ch = = ‘ \ ‘ )

newlines + + ,

//version 2

:

if ( ch= = ‘  ‘ )

spaces + + ;

else if ( ch = = ‘ \n ‘ )

newlines + + ;

What advantages, if any, does the second version have over the first?

Ans. Version 1 uses two separate if statements. Thus, two times the conditions are tested whereas the Version 2 uses an if-else construct. If the first condition is true in Version 2, the second condition is never tested in contrast to Version 1 where both conditions are always tested irrespective of whether the first condition is true or false.

Therefore, the Version 1 take more processing time as compared to Version 2 ( in case the first condition is true). The Version 2 is more efficient compared to Version 1.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s