3 Decision statement in C

Decision-Making Statements in C

  1. if statement
  2. if–else statement
  3. nested if statement
  4. else–if ladder
  5. switch statement
  6. Conditional (ternary) operator ?:

If Statement
The if statement executes a block of code only when the condition is true.
Syntax
if (condition)
{
statements;
}
Example
#include <stdio.h>
int main()
{
int age = 18;
if (age >= 18)
{
printf(“Eligible to vote”);
}
return 0;
}
If–else Statement
Used when there are two possible conditions.
Syntax
if (condition)
{
statements1;
}
else
{
statements2;
}
Example
int number;
printf(“Enter a number: “);
scanf(“%d”, &number);
if (number % 2 == 0)
printf(“Even Number”);
else
printf(“Odd Number”);
Nested if Statement
An if inside another if statement.
Used when multiple conditions must be checked.
Example
int age = 20;
if (age >= 18)
{
if (age >= 21)
printf(“Eligible for marriage”);
}
Else–If Ladder
Used when there are many conditions to test.
Syntax
if (condition1)
{
statements;
}
else if (condition2)
{
statements;
}
else if (condition3)
{
statements;
}
else
{
statements;
}
Example: Grade System
int marks = 85;
if (marks >= 90)
printf(“Grade A”);
else if (marks >= 75)
printf(“Grade B”);
else if (marks >= 50)
printf(“Grade C”);
else
printf(“Fail”);
switch Statement
Used to select one block of code from multiple options.
Works mainly with integer or character values.
Syntax
switch (expression)
{
case value1:
statements;
break;
case value2:
statements;
break;
default:
statements;
}
Example
int day = 2;
switch(day)
{
case 1:
printf(“Monday”);
break;
case 2:
printf(“Tuesday”);
break;
default:
printf(“Invalid Day”);
}
break prevents execution from continuing to the next case.
Conditional (Ternary) Operator
A short form of if–else.
Syntax
condition ? expression1 : expression2;
Example
int a = 10, b = 20;
int max = (a > b) ? a : b;
printf(“Maximum = %d”, max);
Practice Programs

  1. Largest of Two Numbers

int a, b;
scanf(“%d %d”, &a, &b);
if (a > b)
printf(“A is largest”);
else
printf(“B is largest”);

  1. Check Leap Year

int year;
scanf(“%d”, &year);
if (year % 4 == 0)
printf(“Leap Year”);
else
printf(“Not Leap Year”);

  1. Menu Program Using Switch

int choice;
printf(“1. Tea\n2. Coffee\n3. Juice\n”);
scanf(“%d”, &choice);
switch(choice)
{
case 1: printf(“Tea selected”); break;
case 2: printf(“Coffee selected”); break;
case 3: printf(“Juice selected”); break;
default: printf(“Invalid choice”);
}
Bottom of Form