0
0
Cprogramming~5 mins

Why conditional logic is needed

Choose your learning style9 modes available
Introduction

Conditional logic helps a program make decisions. It lets the program choose what to do based on different situations.

When you want the program to do something only if a condition is true.
When you need to handle different actions for different user inputs.
When you want to check if a number is positive, negative, or zero and act accordingly.
When you want to repeat an action until a certain condition is met.
When you want to stop a program or show an error if something unexpected happens.
Syntax
C
if (condition) {
    // code to run if condition is true
} else {
    // code to run if condition is false
}
The condition is a test that results in true or false.
The else part is optional and runs when the condition is false.
Examples
This checks if someone is 18 or older to allow voting.
C
if (age >= 18) {
    printf("You can vote.\n");
} else {
    printf("You are too young to vote.\n");
}
This gives different messages based on the score.
C
if (score > 90) {
    printf("Excellent!\n");
} else if (score > 75) {
    printf("Good job!\n");
} else {
    printf("Keep trying!\n");
}
Sample Program

This program checks the temperature and prints a message based on whether it is hot or not.

C
#include <stdio.h>

int main() {
    int temperature = 30;

    if (temperature > 25) {
        printf("It's hot outside.\n");
    } else {
        printf("It's not too hot today.\n");
    }

    return 0;
}
OutputSuccess
Important Notes

Conditional logic is like asking a question and choosing what to do next based on the answer.

Without conditional logic, programs would do the same thing every time, no matter what.

Summary

Conditional logic lets programs make choices.

It helps handle different situations and inputs.

Using if and else is the basic way to add decision-making.