In the first chapter, we saw that there are many programming languages. Some of them even look alike: for instance, PHP is heavily inspired by C, even though PHP is mainly used for building websites rather than programs.
The C language was actually created quite a while ago, which is why it has influenced many newer languages. Most programming languages end up looking similar, borrowing their core ideas from the ones that came before.
Speaking of core ideas — we're right in the thick of it now. We've already learned how to create variables and do calculations with them (a concept that's common to all programming languages!), and now we're going to take a look at conditions.
Without conditions, computer programs would pretty much just do the same thing over and over — and let's be honest, that would get boring real fast.
The "if... else" condition
Conditions are used to test variables. For example, we might want to say, "If the variable thingy equals 50, then do this..." But it would be a shame if we could only test for equality! We'd also want to check if the variable is less than 50, less than or equal to 50, greater than, greater than or equal to...
Don't worry — C has got it all covered.
But before we get into how to write an "if... else" statement in C, there are a couple of symbols you'll need to know. These are essential for writing conditions.
A few symbols you should know
Here's a quick table of C symbols you should memorize :)
Symbol | Meaning |
---|---|
== | Is equal to |
> | Is greater than |
< | Is less than |
>= | Is greater than or equal |
<= | Is less than or equal |
!= | Is not equal to |
Pay close attention: you need two equals signs ==
to test for equality. A common beginner mistake is to use just one =
, which doesn't mean the same thing in C. I'll explain more about that a bit later.
A simple if
Alright, let's jump right in :)
We'll start with a simple test that tells the computer:
Simple test IF the variable equals this THEN do that
In C, the keyword for this is if. You follow it with parentheses, and inside those, you write your condition.
Then, you open a curly brace {
and close it a bit further down }
. Everything inside those braces will only be executed if the condition is true.
So here's what the syntax looks like:
if (/* Your condition */) { // Instructions to run if the condition is true }
Where it says "Your condition," we'll write something to test a variable. Let's say we have a variable age
that stores your age.
For practice, let's test if you're an adult — that is, if your age is 18 or more:
if (age >= 18) { printf("You're an adult!"); }
The symbol >= means "greater than or equal to," as we saw earlier.
If there's only one instruction inside the braces, then the braces become optional. So you can also write:
if (age >= 18) printf("You're an adult!");
Try it out.
To test the above code and see how if works, you'll need to place it inside a main function and declare a variable age with a value of your choice.
This might seem obvious to some, but apparently it wasn't to everyone — so I added this little note just in case ;)
Here's a complete piece of code you can test:
#include <stdio.h> #include <stdlib.h>int main(int argc, char *argv[]) { int age = 20; if (age >= 18) { printf("You're an adult!\n"); } return 0; }
Here, age is set to 20, so "You're an adult!" will be displayed.
Try changing the value to something like 15 — the condition will be false, so this time "You're an adult!" won't show up :)
Feel free to reuse this basic code to test all the other examples in this chapter.
Keeping things clean
How you open the braces doesn't affect the program — it'll still work even if you write everything on one line, like this:
if (age >= 18) { printf("You're an adult!"); }
But while you can write it like that, it's highly discouraged. Putting everything on one line makes your code harder to read. If you don't get into the habit of keeping your code tidy now, you'll really struggle to make sense of it later when your programs get longer.
Try formatting your code the way I do: one brace per line, your instructions indented with a tab (to shift them to the right), then the closing brace on its own line. I only recommend putting everything on one line for very short and simple conditions.
There are several good ways to format code. It doesn't change how the program runs, but it's part of your "coding style," if you will ;) If you come across someone else's code that's styled a bit differently, that's probably just their personal style. The important thing is that the code stays clean and easy to read.
The else to say "otherwise"
Now that we've got basic tests down, let's go a little further: if the test fails (i.e. the condition is false), we'll tell the computer to do something else instead.
That would look like:
Test with otherwise IF the variable equals this THEN do that ELSE do something else
To do this, just add the word else
right after the closing brace of your if
.
Here's an example:
if (age >= 18) // If age is 18 or more { printf("You're an adult!"); } else // Otherwise... { printf("Too bad, you're still a minor!"); }
Pretty straightforward: if age is 18 or more, display "You're an adult!" Otherwise, display "You're a minor."
The else if to say "otherwise, if..."
We've seen how to do an "if" and an "else." You can also add "else if" to test another condition if the first one fails. The "else if" goes between the if and the final else.
So you'd be telling the computer:
With else if IF the variable equals this THEN do that ELSE IF it equals this THEN do that ELSE do something else
In C, that becomes:
if (age >= 18) { printf("You're an adult!"); } else if (age > 4) { printf("Okay, you're not *that* young..."); } else { printf("Aga gaa aga gaaa gaaa"); // Baby language — you wouldn't get it ;o) }
The computer checks each condition in order:
- First, it checks the initial if. If it's true, it runs that block and skips the rest.
- If not, it moves to the else if and tests that. If it's true, it runs that block.
- If none of the tests work, it runs the final else block.
else
and else if
are optional. To write a condition, all you really need is an if (makes sense — without it, there's no condition!)You can chain as many else if statements as you want, like this:
Multiple else ifs IF the variable equals this THEN do that ELSE IF it equals that THEN do this ELSE IF it equals that THEN do that ... ELSE do something else
Testing multiple conditions at once
Sometimes, you'll want to check several things at once. For example, you might want to test if age is more than 18 AND less than 25.
For that, we use new symbols:
Symbol | Meaning |
---|---|
&& | AND |
|| | OR |
! | NOT |
AND test
To write the example above, you'd do:
if (age > 18 && age < 25)
The && means "AND." This reads: "If age is greater than 18 AND less than 25."
OR test
To write an OR test, use two pipe symbols ||.
Let's imagine a silly program that decides if someone can open a bank account. As everyone knows, to open an account, you'd better not be too young (let's say you need to be at least 18), or you need to have tons of money (because even if you're 10, banks love rich kids :D )
Here's how you'd write that:
if (age > 18 || money > 1000000) { printf("Welcome to ScroogeBank!"); } else { printf("Out of my sight, peasant!"); }
This condition is true if the person is over 18 or has more than 1,000,000 money ;)
NOT test
Last but not least is the exclamation mark ! — in programming, it means "NOT."
You place it before your condition to say, "If this is not true":
if (!(age < 18))
This means: "If the person is not a minor."
If you removed the !, it would mean the opposite: "If the person is a minor."
Common beginner mistakes
Don't forget the double equals ==
To test if someone is exactly 18, you must write:
if (age == 18) { printf("You've just become an adult!"); }
==
) in a condition. If you write just one =
, it will assign the value 18 to the variable (like we saw in the variables chapter). But what we want here is to test the value, not change it! Be careful — many beginners use just one =
and then wonder why their program doesn't work.The sneaky semicolon
Another classic mistake: putting a semicolon at the end of an if line. But an if is a condition, not an instruction — and semicolons are for instructions.
The following code won't behave as expected because of the semicolon:
if (age == 18); // ← That semicolon should NOT be there! { printf("You just turned 18"); }
Booleans, the heart of conditions
Now we're going to take a closer look at how an if... else condition actually works. See, conditions rely on something in programming called booleans.
It's a really important concept, so perk up your ears — err, I mean your eyes. A few little tests to get the idea
Back in high school physics class, my teacher used to start new topics with a quick experiment or two. I'm going to steal that move today.
Here's a very simple bit of code — go ahead and run it:
if (1) { printf("It's true"); } else { printf("It's false"); }
Result:
Oh, but it does — just hang on :p
Try the same code again, but this time replace the 1 with a 0:
if (0) { printf("It's true"); } else { printf("It's false"); }
Result:
Now try using other numbers instead of 0 — like 4, 15, 226, -10, -36, whatever... What do you get each time? The program prints: It's true
. So what's going on here?
Here's what's happening:
Every time you do a test in an if condition, that test actually gives back a number:
- 1 if the test is true
- 0 if the test is false
Take this for example:
if (age >= 18)
Here, the test you're doing is age >= 18.
Let's say age is 23. That makes the condition true. So the computer "replaces" age >= 18 with 1. It's like the computer sees: if (1). And as we saw earlier, 1 means true — so it runs the code and displays "It's true!"
If the condition is false, the computer replaces age >= 18 with 0, and just like that, the condition is considered false — so it runs the code in the else block.
Storing the result of a condition in a variable
Let's try another little trick: assign the result of a condition to a variable — just like you would with any other operation (because for the computer, it is an operation!).
int age = 20; int isAdult = 0;isAdult = age >= 18; printf("isAdult is: %d\n", isAdult);
As you can see, the condition age >= 18 returned 1 because it was true. So the variable isAdult
now holds 1.
You can even verify that with the printf, which confirms the value has changed.
Try the same code again but with age == 10
. This time, isAdult
will be 0. That "isAdult" variable? It's a boolean.
Here's the key idea:
- A variable that holds either 0 or 1 is called a boolean.
And:
- 0 = False
- 1 = True
To be precise, in C, 0 is false, and any other number is treated as true. (You already saw that in the earlier tests.) But to keep things simple, we'll just stick to 0 and 1 to mean false and true.
Now, in the C language, there's no built-in boolean type. There's no bool like you have for double, char, etc.
The bool type was actually added later in C++. In C++, you can write:
bool isAdult = true;
But since we're working with plain C right now, we don't have a special type for booleans. So we use an int or sometimes a char to store boolean values.
Using booleans in conditions
It's super common to test a boolean variable in an if:
int isAdult = 1;if (isAdult) { printf("You're an adult!"); } else { printf("You're a minor."); }
Here, isAdult
is 1, so the condition is true — and the message "You're an adult!" is printed.
The cool thing is: it reads really naturally. You see if (isAdult)
and your brain goes: "If you're an adult..."
Boolean tests are super readable and easy to understand — as long as you give your variables clear names (which I've been telling you since day one! ;) )
Here's another imaginary test:
if (isAdult && isBoy)
This means: "If you're an adult AND a boy..."
Here, isBoy is another boolean variable: it's 1 if you're a boy, and 0 if you're... a girl! Congrats — you've got it!
Booleans are how you express truth and falsehood in code
Booleans are super useful for expressing whether something is true or not. What I just explained is a foundation you'll come back to all the time as you keep learning C programming.
if (isAdult == 1)
? Does that work too?Absolutely! That works just fine.
But the whole point of booleans is to make your conditions shorter and easier to read. Let's be honest — if (isAdult)
is cleaner and just as clear, right? ;)
So remember this:
- If your variable is meant to hold a number, write your test like if (variable == 1).
- If your variable is a boolean (i.e., 0 or 1 for false/true), you can just write if (variable).
The "switch" condition
The "if... else" condition we just covered is the one you'll use the most in C programming. Truth is, there aren't that many ways to write conditions in C — "if... else" can pretty much handle every scenario.
But sometimes, "if... else" can get a bit... repetitive. Take a look at this:
if (age == 2) { printf("Hey baby!"); } else if (age == 6) { printf("Hey kid!"); } else if (age == 12) { printf("Hey youngster!"); } else if (age == 16) { printf("Hey teen!"); } else if (age == 18) { printf("Hey adult!"); } else if (age == 68) { printf("Hey grandpa!"); } else { printf("I don't have a phrase ready for your age."); }
Building a switch
As we've seen, programmers hate repeating themselves ;)
So, when you need to check different values of the same variable, instead of writing endless "else if", C gives you another structure: switch
.
Here's the same example rewritten using a switch:
switch (age) { case 2: printf("Hey baby!"); break; case 6: printf("Hey kid!"); break; case 12: printf("Hey youngster!"); break; case 16: printf("Hey teen!"); break; case 18: printf("Hey adult!"); break; case 68: printf("Hey grandpa!"); break; default: printf("I don't have a phrase ready for your age."); break; }
Study this example and use it as a model for writing your own switches. We don't use them as often as if... else, but they sure come in handy — less typing and easier to read!
Here's the general idea: you write switch (myVariable) to say "I'm going to test the value of this variable". You then open a set of curly braces and write out each case inside.
You must include a break; at the end of every case. Why? Because if you don't, the program will keep going and execute the instructions of the following cases — even if they don't match!
Basically, break;
tells the computer "Okay, I'm done here, you can leave the switch block now."
The default case is like a classic else: if none of the previous cases match, the program runs this one.
Making a menu with a switch
The switch statement is especially useful when building console menus. And I think it's time for a little hands-on practice ;)
Let's get to work!
To create a menu in a console program, you display options using printf, each with a number. The user enters the number of the option they want.
Here's what your console should show:
=== Menu ===1. Quarter Pounder 2. Bacon McDouble 3. Double Colonel Burger 4. Classic Big Mac
Your choice?
Your mission: recreate this menu using printf (easy), add a scanf to record the user's choice in a variable called choiceMenu (even easier :p), and finally use a switch to display a message like "You chose the Quarter Pounder."
Ready? Go for it.
The solution
Here's what I hope you came up with:
#include <stdio.h> #include <stdlib.h>int main(int argc, char *argv[]) { int choiceMenu;
printf("=== Menu ===\n\n"); printf("1. Quarter pounder\n"); printf("2. Bacon McDouble\n"); printf("3. Double Colonel Burger\n"); printf("4. Classic Big Mac\n"); printf("\nYour choice? "); scanf("%d", &choiceMenu);
printf("\n");
switch (choiceMenu) { case 1: printf("You chose the Quarter pounder. Nice choice!"); break; case 2: printf("You chose the Bacon McDouble. Yikes, too much sauce."); break; case 3: printf("That's from KFC you idiot..."); break; case 4: printf("You chose the Big Mac. You must be original!"); break; default: printf("You didn't enter a valid number. No food for you!"); break; }
printf("\n\n");
return 0; }
And there you have it.
Hope you didn't forget the default at the end of the switch!
So, always stay alert: never trust user input. They might type anything. Whether you're using switch or if, always include a default or else just in case.
I recommend getting comfortable with how menus work in console programs. You'll see them come up quite often, and they're really practical.
Ternary Operators
There's actually a third way to write conditions — less common, but still worth knowing.
It's called the ternary operator.
In practice, it works like an if... else, but squished into one line!
Rather than explaining it for hours, let me just show you two versions of the same condition. First, written the classic way. Then, rewritten using a ternary.
A familiar if... else
Let's say we've got a boolean variable called isAdult, which is 1 if someone is an adult, 0 otherwise.
We want to set the value of age depending on whether isAdult is true or false.
We'll put 18 if they're an adult, 15 if they're not. Yes, it's a bit of a silly example, but it's perfect to show how ternary expressions work.
Here's how it would look with an if... else:
if (isAdult) age = 18; else age = 15;
Notice I've left out the braces — remember, they're optional if there's only one statement.
The same logic using a ternary
Now here's the exact same logic, rewritten using a ternary expression:
age = (isAdult) ? 18 : 15;
Ternary operators let you update a variable based on a condition, all in one line. Here, the condition is just isAdult, but it could be anything more complex too!
The question mark basically says "Are you an adult?"
- If yes, age becomes 18.
- If not (that's what the
:
stands for), age becomes 15.
Ternaries aren't essential — you can totally live without them. Personally, I don't use them every time because they can make code a bit harder to read. But still, it's good to be familiar with them — just in case you stumble upon some code that's full of them!
We've now seen several core ideas in programming. From here on, you'll be using conditions everywhere in your programs — so practice is key! :D
Just to recap one crucial takeaway from this chapter: booleans. It's super-mega-ultra-important to remember that booleans are variables that mean "true" or "false", depending on their value (0 = false, 1 = true).
In the next chapter, we'll be using booleans again and building on everything we learned here — so make sure you're solid before jumping in ;)
Enjoyed this C / C++ course?
If you liked this lesson, you can find the book "Learn C Programing for Beginners" from the same authors, available on SiteRaw, in bookstores and in online libraries in either digital or paperback format. You will find a complete C / C++ workshop with many exclusive bonus chapters.