The if Statement

So far, your programs have run every statement, one after another, from top to bottom. But a program often has to decide what to do: show a warning only if a password is too short, or give a discount only if the customer is a student. We make decisions like this all the time: if it rains, I'll take an umbrella.

In C, a decision is written with the if statement:

int temperature = 30;

if (temperature > 25) {
    printf("It's hot, take a cap\n");
}
printf("Have a nice day\n");

This prints:

It's hot, take a cap
Have a nice day

The if statement has three parts:

  • the keyword if. A keyword is a word with a special meaning in C, which is why you can't use it as a variable name;
  • the condition in parentheses: (temperature > 25). A condition is a question that can only be answered yes (true) or no (false): is the temperature greater than 25? The parentheses around the condition are required;
  • the block of code in curly braces { }. The block runs only if the condition is true.

After the block, the program continues as usual, so Have a nice day is printed either way. If temperature were 10, the condition would be false: the program would skip the block and print only Have a nice day.

In a condition, you can compare with > (greater than) and < (less than), just like in math. You'll meet the other comparison operators in a moment.

The curly braces are needed whenever the block has more than one statement. This course writes them always, even around a single statement. You'll see why in the next exercise.

There's no semicolon after the ) or after the }. If you forget the parentheses around the condition, the compiler reports error: expected '(' after 'if'. A semicolon after the condition is more treacherous:

int temperature = 10;

if (temperature > 25); {
    printf("It's hot, take a cap\n");
}

This prints:

It's hot, take a cap

And it's only 10 degrees. The semicolon after the parenthesis ends the whole if statement, so only an empty statement belongs to the condition. The block in curly braces has nothing to do with the condition and always runs. The compiler only gives a warning about it, and warnings aren't shown on this site. So when a block runs although it shouldn't, look for a semicolon after the condition first.

Instructions

In place of the comment, write an if statement with the condition monitor_price < 4000. In its block, print I'll buy the monitor.

Below the block, write a second if statement with the condition monitor_price > 4000 that prints It's too expensive. Run the program: it still prints only The monitor costs 3000 and I'll buy the monitor, because 3000 isn't greater than 4000, so the second block is skipped.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

1/12