C - Conditional Statements
Conditional Statements: Conditional statements are use to check condition.
1. If statement
2. If else statement
3. Nested If statement
4. If else Ladder
5. ?: Operator
6. Switch Case
This statement is
used to execute a statement or group of statements on the basis of a condition.
SYNTAX-
if (Condition)
{
Statement block;
}
statement-x;
EXAMPLE -
main()
{
clrscr();
if ( 4 > 2 )
{
printf(”4”);
}
getch();
}
Output –
4
This statement is
used to execute a statement or group of statements on the basis of a condition.
SYNTAX-
if (Condition)
{
Statement block-1;
}
else
{
Statement block-2;
}
EXAMPLE-
main()
{
if ( 2 > 4 )
{
printf(”4”);
}
Else
{
printf(“2”);
}
}
Output- 2
If condition is true, then statements of block-1 are executed and if condition is false then statement of block-2 are executed.
3. Nested if
else statement:- Using of more than one ’if’ statement is called nested ‘if’.
SYNTAX-
if (Condition)
{
if (Condition)
{
Statement block-1;
}
}
else
{
if (Condition)
{
Statement block-2;
}
}
Another variation on
the themes of nested if statement is the use of the construct on to expand the
if statement for multiple branching.
SYNTAX-
if (Condition)
{
statement1;
}
else if (Condition)
{
statement2;
}
else if (Condition)
{
statement3;
}
else
{
statement4;
}
5. ?:
Operator:-
A ternary operator
"? :" is available in C to construct conditional expression of the
form exp1 ? exp2 : exp3; where exp1, exp2 and exp3 are expressions.
SYNTAX- (Condition)? True Statement : False Statement;
SYNTAX-
Switch (expression)
{
case value1:
statement-1;
break;
case value2:
statement-2;
break;
default:
statement-3;
break;
}
EXAMPLE-
main()
{
int a;
printf(“Enter number “); scanf(“%d”,&a); switch(a)
{
case ‘1’:
printf(“Number is 1”);
break;
case ‘2’:
printf(“Number is 2”);
break;
default:
printf(“Number is %d”,a);
break;
}
}
Output-
Enter number 2
Number is 2
Comments
Post a Comment