Explain if else statement with example
if else Statement
if
Only performs an action if the condition is true
if/else
Specifies an action to be performed both when the condition is true and when it is false
Psuedocode:
If student’s grade is greater than or equal to 60Print “Passed”
elsePrint “Failed”
Note spacing/indentation conventions
C code:
if ( grade >= 60 )
printf( "Passed\n");
else
printf( "Failed\n");
Ternary conditional operator (?:)
Takes three arguments (condition, value if true, value if false)
Our pseudocode could be written:
printf( "%s\n", grade >= 60 ? "Passed" : "Failed" );
Or it could have been written:
grade >= 60 ? printf( “Passed\n” ) : printf( “Failed\n” );
Compound statement:
Set of statements within a pair of braces
Example:
if ( grade >= 60 )
printf( "Passed.\n" );
else {
printf( "Failed.\n" );
printf( "You must take this course again.\n" );}
Without the braces, the statement
printf( "You must take this course again.\n" );
would be executed automatically