Here’s a C code example demonstrating conditional statements, including if
, else
, and switch-case
. This example uses user input to illustrate different conditions and branches based on specific values.
#include <stdio.h> int main() { int age; char grade; // Prompt user for age and grade input printf("Enter your age: "); scanf("%d", &age); printf("Enter your grade (A, B, C, D, or F): "); getchar(); // Clear the newline character left by previous input scanf("%c", &grade); // If-else conditional to check age category if (age < 13) { printf("You are a child.\n"); } else if (age >= 13 && age <= 19) { printf("You are a teenager.\n"); } else { printf("You are an adult.\n"); } // Switch-case to evaluate grade switch (grade) { case 'A': printf("Excellent! Keep up the great work.\n"); break; case 'B': printf("Good job! You're doing well.\n"); break; case 'C': printf("Not bad, but there is room for improvement.\n"); break; case 'D': printf("You passed, but consider working harder.\n"); break; case 'F': printf("You failed. Don't give up, keep trying!\n"); break; default: printf("Invalid grade entered.\n"); break; } return 0; }
Explanation of Conditional Statements
1. if
, else if
, and else
statements
These statements allow you to execute different code based on whether a condition is true (1
) or false (0
).
Syntax: The if
statement checks a condition inside parentheses, and if it’s true, the block of code inside {}
runs.
In this example:
if (age < 13) { ... }
checks if the user is under13
; if true, it displays “You are a child.
“else if (age >= 13 && age <= 19) { ... }
checks if the age is between13
and19
, displaying “You are a teenager.
“- else { … } is the fallback for all other values, displaying “You are an adult.”
Logical Operators like &&
(AND) can combine conditions (e.g., age >= 13 && age <= 19
), which must all be true for the whole expression to be true.
2. switch-case
statement
The switch
statement is useful for checking a variable against a set of discrete values, particularly with char
or int
types.
Syntax: Each case
represents a possible value, followed by the code block for that value.
In this example:
switch (grade) { ... }
evaluates thegrade
variable:case 'A'
: executes whengrade
is'A'
, printing a message for excellent performance.- Each
case
is followed bybreak;
to prevent “fall-through” (executing subsequent cases even when one matches). default:
provides a fallback message for any unrecognized grade value (e.g., “Invalid grade entered”).
Summary of Conditional Statements
if
,else if
,else
: Used for conditions that evaluate totrue
orfalse
. They allow flexibility with complex expressions and combinations.switch-case
: Efficient when testing a single variable against several discrete values, as in the case ofgrade
.
Together, these structures let you handle a variety of logical branching scenarios in a C program, enabling tailored responses to different input values.