Understanding the “IF-ELSE” Statement in C Programming

Hello, young coder!
Let’s learn about something super cool in C programming called the “IF-ELSE” statement. Just like in real life, when you make a decision, sometimes there’s more than one possibility. If something happens, you do one thing, but if it doesn’t happen, you do something else. This is where the “IF-ELSE” statement comes in!


What is an IF-ELSE Statement?

The “IF-ELSE” statement allows your program to make a choice between two things. You can tell the computer, “If this condition is true, do this; otherwise, do something else.”

Syntax of IF-ELSE Statement

Here’s how you write it in C programming:

  • Condition: This is a test that can be either true or false.
  • If Block: The code inside the first curly braces {} runs if the condition is true.
  • Else Block: The code inside the second curly braces {} runs if the condition is false.

Real-Life Example of IF-ELSE

Let’s say you’re deciding whether to go outside and play or stay inside:

  • If it’s sunny, you’ll play outside.
  • Else (if it’s not sunny), you’ll stay inside and read a book.

Here’s how you tell the computer to make this decision:


Flowchart of IF-ELSE Statement

To make it easier to understand, let’s draw a flowchart of how the “IF-ELSE” statement works.

  1. Start
  2. Check the condition.
  3. If the condition is true, follow the “YES” path and run the code in the IF block.
  4. If the condition is false, follow the “NO” path and run the code in the ELSE block.
  5. End

Programming Example

Let’s write a fun program where the computer checks if a number is greater than 10.

Explanation:

  • We check if the number is greater than 10.
  • If true, it will print “The number is greater than 10.”
  • If false, it will print “The number is 10 or less.”

Output 1:

For number = 15, the output will be:

The number is greater than 10.

Output 2:

For number = 5, the output will be:

The number is 10 or less.

Real-Life Fun Example

Here’s a more playful example. Let’s check whether you have enough money to buy ice cream:

  • If you have more than 20 rupees, buy ice cream.
  • Else, buy a candy.

Output 1:

For money = 25, the output will be:

You have enough money to buy ice cream!

Output 2:

For money = 10, the output will be:

You don't have enough money for ice cream. Buy a candy!

Summary

  • The “IF-ELSE” statement is like a choice: do one thing if something is true, and do something else if it’s false.
  • It’s like asking, “If it’s sunny, play outside, otherwise, stay inside and read.”
  • The flowchart helps show how the computer decides which path to follow.

With “IF-ELSE” statements, you can make your programs even smarter by teaching them how to make decisions just like you!


error: Content is protected !!
Open chat
1
Hi,how Can We Help You ?
Exit mobile version