C Language / Decision making statements

There are 5 decision making statements in c language. They were
1. if statement.
2. if...else statement.
3. Nested if statements.
4. If – else ladder.
5. Switch statement.

if Statement
Block / Lines of code to be executed if the condition is true in if statement.

if statement Syntax
if (condition)
{
// block / Lines of code will be executed if the condition is true
}

Sample Program Output
main()
{
if (5 > 2)
{
printf("5 is bigger than 2");
}
}
5 is bigger than 2

if...else statement
Block1 / Lines of code will be executed if the condition is true in if statement.
Block2 / Lines of code will be executed if the condition is true in else statement.

if...else statement Syntax
if (condition)
{
// block1 / Lines of code to be executed if the condition is true
}
else
{
// block2 / Lines of code to be executed if the condition is false
}

Sample Program Output
main()
{
if (2 > 5)
{
printf("2 is bigger than 5");
}
else
{
printf ("5 is bigger than 2");
}
}
5 is bigger than 2

Nested if statements
One if inside other is called as a Nested if statements
Block1 / Lines of code will be executed if the condition is true in if statement.
Block2 / Lines of code will be executed if the condition is true in if statement.

Nested if statements Syntax
if (condition1)
{
// block1 / Lines of code to be executed if the condition is true
if (condition2)
{
// block1 / Lines of code to be executed if the condition is true
}
}

Sample Program Output
main()
{
if (5> 2)
{
printf("5 is bigger than 2");

if(3>2) {
printf ("3 is bigger than 2");
} }
}
5 is bigger than 2 3 is bigger than 2

else if Statement / if else ladder
Block1 / Lines of code will be executed if the condition1 is true in if statement.
Block2 / Lines of code will be executed if the condition1 is false and condition2 is true.
Block3 / Lines of code will be executed if the condition1 and condition2 is false.

else if Statement / if else ladder Syntax
if (condition1)
{
// block1 code will be executed if condition1 is true
}
else if (condition2)
{
// block2 code will be executed if the condition1 is false and condition2 is true
}
else
{
// block3 code will be executed if the condition1 and condition2 are false
}

Sample Program Output
main()
{
if (2 > 5)
{
printf ("2 is bigger than 5");
}
else if (5 > 2)
{
printf ("5 is bigger than 2");
}
else
{
printf ("Both are equal");
}
}
5 is bigger than 2

Switch Statement
Here one of the blocks is executed based on Condition /switch Value which match with the case value otherwise it will execute the default block.

Switch Statement Syntax
switch(Condition /switch Value)
{
case 1: //block1 break;
case 2: // block2 break;
case 3: // block3 break;
----
----
default: // block4
}

Sample Program Output
main()
{
switch (2)
{
case 1: System.out.println("5>2"); break;
case 2: System.out.println("2>5"); break;
default: System.out.println("Both are equal"); break;
}
}
2 > 5


Home     Back