- In this video, we're going to start
a series of discussions about if-statements
and see how they can allow us to make decisions,
change the course of action,
and do very sophisticated logic things in our programs.
Let's recall the definition introduced earlier
for a simple if-statement.
It is simply a way to instruct the program
to do different things outside the order
that the code is serially written.
Unless otherwise told, a C program, like any other program,
will execute all the command lines in the order entered.
The simplest form of an if is,
if (condition) then doSomething.
The word then is unnecessary.
The condition can be a simple expression
or a very complex one or even a code to a function,
as we will see soon.
Let's look at the simple statement.
If x is less than zero, meaning x is negative,
we would like to make it positive
by multiplying it by minus one.
Very simple use of if.
Let's go to the code
and do a little bit more interesting things.
This program will ask the user to enter a number,
and then based on the number entered,
a decision will be made,
and feedback will be sent to the screen.
For example, the number the user is asked to enter
is between zero and a hundred.
There is a function in line 21 that will take care of
asking the user the number and processing the data,
return the result into a variable called num.
Let's see how this function works.
It's a simple print of question.
The scanf to get the number,
and then we return the value, which is int,
to agree with the data type of the function getNumber.
Once num has been given a value, it can be tested.
Line 23 tests if the number is less than zero,
in which case we would like to call a function tooSmall.
Line 26 tests whether the number is larger than 100.
Line 29 checks whether the number is exactly within range.
In each one of those cases, we are calling a function
that in turn provides the adequate message.
You might ask yourself, isn't this redundant a little bit?
In some ways it is, however, the purpose of this video
is not to create the best logic implementation
but to show you different things
you can do with an if-statement,
in particular, line 29, in which we are
combining two expressions in a logical end
to make a more complex decision.
We will see in the upcoming videos
as we can improve the if, the logic, which they are part of,
the expressions they process, and so on.
Let's run the program and see how this all works.
I'm going to enter a number between zero and 100.
I'm going to start with a small one.
The number is too small.
I'm going to run it again.
This time, I'm going to give it a very large number.
The number is too large.
And now I'm going to type one which is just within range,
and the program works as planned.