Back to HomePage Credits Puke SumFuka Saqquara

The IF loop

The if...else clause is the most fundamental of the conditional statements. Chances are, that if you've done any programming from javascript to QuakeC, you'll know how to use this. It provides a way for software developers to pose a question, and based on the answer, perform a given operation or task. Lets take a look at the following example:

```/* tutorial 8 - AGE.C - */
#include <stdio.h>

int main()
{
int age;

printf("How old are you? ");
scanf("%d", &age);
printf("\nBeing %d years old is great!", age);

}
```

First we declared a variable (age) of type integer to store the users input. We then ask for the users age, and stick it in our variable 'age', and then tell the user being his age is great (kinda lame program em?). Now, the problem with this is that we don't have any range checking, thus, if a user types in -21 or 333, your program would still tell the user his age is great:) To fix this, we use the if statement as follows:

```If(condition)
{
true statements;
true statements;
}
else
{
false statements;
false statements;
}

```

First, it checks to see if the condition inside the brackets are true or false. If the statement is true, the program will execute the statements inside the first pair of brackets, and if the condition is false, it will execute the statements in the brackets following 'else'. Easy? Well, lets apply this to our age program like this:

```/* tutorial 8 - AGEFIX.C - */
#include <stdio.h>

int main();
{

int age;

printf("How old are you? ");
scanf("%d", &age);

if ((age < 1) || (age > 120))
{
printf("\nYou bastard! Stop lying");
}
else
{
printf("\nBeing %d years old is great!", age);
}
}

```

The if statement here checks to make sure age is less than 1 or more than 120. If the statement is true, we tell our user he's a bastard, and should stop lying:) Otherwise, if its false we tell the user his age is cool etc etc...

Tutorial by Puke

 Back To Tutorial 7 Forward To Tutorial 9
```

```

 This site, and all content and graphics displayed on it, are ©opyrighted to the Quake DeveLS team. All rights received. Got a suggestion? Comment? Question? Hate mail? Send it to us! Oh yeah, this site is best viewed in 16 Bit or higher, with the resolution on 800*600. Thanks to Planet Quake for there great help and support with hosting. Best viewed with Netscape 4 or IE 3