1.

Compare the use of switch statement with the use of nested if-else statement. 

Answer»

If-else statement: When there are multiple conditional statements that may all evaluate to true, but we want only one if statement's body to execute. We can use an "else if" statement following an if statement and its body; that way, if the first statement is true, the "else if" will be ignored, but if the if statement is false, it will then check the condition for the else if statement. If the if statement was true the else statement will not be checked. It is possible to use numerous else if statements to ensure that only one block is executed. 

#include <Stdio .h>

void main()

{

int age;

printf( "Please enter your age" );

scanf( "%d", &age );

if ( age < 100 ) {

printf ("You are pretty young!\n" ); }

else if ( age == 100 ) {

printf( "You are old\n" );

}

else {

printf( "You are really old\n" );

}

Switch case statements are a substitute for long if statements that compare a variable to several "integral" values ("integral" values are simply values that can be expressed as an integer, such as the value of a char).The value of the variable given into switch is compared to the value following each of the cases, and when one value matches the value of the variable, the computer continues executing the program from that point. The condition of a switch statement is a value. The case says that if it has the value of whatever is after that case then do whatever follows the colon. The break is used to break out of the case statements. Break is a keyword that breaks out of the code block, usually surrounded by braces, which it is in. In this case, break prevents the program from falling through and executing the code in all the other case statements.

#include<stdio .h>

#include<con. h>

void main()

{

int flag;

printf( "Enter any value\n" );

scanf( "%d", &flag );

switch ( flag ) {

case 1:

printf( "It is hot weather!\n" );

break;

case 2:

printf( "It is a stormy weather!\n" );

break;

case 3:

printf( "It is a sticky weather!\n" );

break;

default:

printf( "It is a pleasant weather!\n" ); 

break;

}

getch();

}



Discussion

No Comment Found

Related InterviewSolutions