B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP

C Switch Statement

In C, the switch statement is used to perform different actions based on the value of a variable. It is often cleaner than multiple if...else statements.

C में, switch statement का use variable की value के अनुसार अलग-अलग काम करने के लिए किया जाता है। यह कई if...else से बेहतर होता है।

Syntax:

switch (variable) {
    case value1:
        // code
        break;
    case value2:
        // code
        break;
    default:
        // code
}

Example 1: Day of the Week

#include <stdio.h>

int main() {
    int day = 3;
    switch(day) {
        case 1: printf("Monday"); break;
        case 2: printf("Tuesday"); break;
        case 3: printf("Wednesday"); break;
        default: printf("Invalid day");
    }
    return 0;
}

Prints the day name based on the number provided.

दिया गया नंबर के आधार पर दिन का नाम print करता है।

Output: Wednesday


Example 2: Grade Evaluation

#include <stdio.h>

int main() {
    char grade = 'B';
    switch(grade) {
        case 'A': printf("Excellent"); break;
        case 'B': printf("Good"); break;
        case 'C': printf("Average"); break;
        default: printf("Fail");
    }
    return 0;
}

Checks student\'s grade and prints performance.

छात्र का grade चेक करता है और प्रदर्शन print करता है।

Output: Good


Example 3: Simple Calculator

#include <stdio.h>

int main() {
    char op = '+';
    int a = 5, b = 3;
    switch(op) {
        case '+': printf("%d", a + b); break;
        case '-': printf("%d", a - b); break;
        case '*': printf("%d", a * b); break;
        case '/': printf("%d", a / b); break;
        default: printf("Invalid operator");
    }
    return 0;
}

Performs calculation based on the operator.

ऑपरेटर के आधार पर गणना करता है।

Output: 8


Example 4: Vowel Checker

#include <stdio.h>

int main() {
    char ch = 'e';
    switch(ch) {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            printf("Vowel");
            break;
        default:
            printf("Consonant");
    }
    return 0;
}

Checks if a character is a vowel.

जांचता है कि दिया गया अक्षर स्वर है या व्यंजन।

Output: Vowel


Example 5: Traffic Light System

#include <stdio.h>

int main() {
    char light = 'R';
    switch(light) {
        case 'R': printf("Stop"); break;
        case 'Y': printf("Ready"); break;
        case 'G': printf("Go"); break;
        default: printf("Invalid Signal");
    }
    return 0;
}

Shows traffic action based on light color.

लाइट के रंग के आधार पर ट्रैफिक का संकेत दिखाता है।

Output: Stop