Having a program make choices is one of the simplest actions you can do. As
you might have expected, C++ has if statements just like Pascal.
Let's start by using an if statement to see if a variable named
fajita is larger than 10, and if so, let's set it to 3.
Pascal:
if (fajita > 10) then
fajita := 3;
C++:
if (fajita > 10)
fajita = 3;
Immediately you should see two things: that the "then " is missing from the
C++ version, and that C++ uses = to assign values instead of
:=
as Pascal does. You'll find that C++ cuts off a lot of the fat of Pascal. Where
you said "then " after an if statement and
"do " after a
for loop,
you now say nothing. You may be sorry to see them go now, but soon you'll
feel silly for having to type out all those extra words.
Another thing to note is that in C++ the parentheses are required.
The operators you use to say "less than" and "equal to" are for the most part
the same. Let's look at them:
C++ Pascal Meaning
< < Less-Than
> > Greater-Than
<= <= Less-Than or Equal-To
>= >= Greater-Than or Equal-To
! NOT NOT
== = Equal-To
!= <> NOT Equal-To
|| or Or
&& and And
Because we now use
"= " to assign values, we must use something else. Fitting with
C++'s often cryptic nature, AND as well as OR have been replaced with
&& and || .
Let's try a program that uses an if statement:
void main(void)
{
int a;
int b;
a = 10;
b = 5;
if (a > 5) / If a is greater than 5..
a = a + 4;
if (a <= 14) / If a is less than or equal-to 14..
if (b == 5) / And if b is equal to 5..
a = 0;
if (b < a)
b = a;
}
Let's step through that example. First, two integers, a and b are
created. Then, a is assigned 10 and b is given 5. Next, an if statement
checks to see if a is greater than 5. It is, so the instruction
"a = a + 4; " is executed, and a becomes "a+4 ", or 14. After that, another
if statement checks to see if a is less than or equal to 14. It is,
so another if statement is run to see if b is equal to 5. It is, so
the statement "a = 0 " is used, and a becomes 0. The final statement
checks to see if b, which is 5, is less than a, which is 0. Since 5 is greater
than 0, the if statement fails, and nothing is run.
|