|5. Conditional Statements
Chapter 5C Language Tutorial~1 min read

Conditional Statements

if/else आणि switch — Decisions

Conditional statements वापरून program decisions घेऊ शकतो. Condition true असेल तर एक block run होतो, false असेल तर दुसरा. C मध्ये if-else आणि switch-case वापरतात.

if / else if / else

Grade calculator

c
#include <stdio.h>

int main() {
    int marks;
    printf("Marks टाका: ");
    scanf("%d", &marks);

    if (marks >= 90) {
        printf("Grade: A+\n");
    } else if (marks >= 80) {
        printf("Grade: A\n");
    } else if (marks >= 70) {
        printf("Grade: B\n");
    } else if (marks >= 60) {
        printf("Grade: C\n");
    } else if (marks >= 40) {
        printf("Grade: D — Pass\n");
    } else {
        printf("Grade: F — Fail\n");
    }

    return 0;
}

Ternary Operator

Short if-else in one line

c
int age = 20;

// Ternary: condition ? value_if_true : value_if_false
char *status = (age >= 18) ? "Adult" : "Minor";
printf("Status: %s\n", status);   // Adult

int a = 10, b = 20;
int max = (a > b) ? a : b;
printf("Max: %d\n", max);   // 20

switch-case

switch — fixed values साठी

c
#include <stdio.h>

int main() {
    int day;
    printf("Day number टाका (1-7): ");
    scanf("%d", &day);

    switch (day) {
        case 1:
            printf("सोमवार (Monday)\n");
            break;   // break नसेल तर पुढचे cases पण run होतात!
        case 2:
            printf("मंगळवार (Tuesday)\n");
            break;
        case 6:
            printf("शनिवार — Weekend! 🎉\n");
            break;
        case 7:
            printf("रविवार — Holiday! 😴\n");
            break;
        default:
            printf("Weekday\n");  // कोणताही case match नाहीतर
    }

    return 0;
}
📌

switch मध्ये break विसरू नका! break नसेल तर "fall-through" होते — match झालेल्या case नंतरचे सगळे cases पण execute होतात.

Key Points — लक्षात ठेवा

  • if (condition) { } else if { } else { } — multi-branch
  • Ternary: condition ? true_val : false_val
  • switch (variable) — int किंवा char साठी best
  • break — switch मधून बाहेर पडतो
  • default — कोणताही case match न झाल्यास
0/12 chapters पूर्ण