If I did my homework, then I'd have a better grades. That statement would be conditional statement. This lesson is all about conditional statements. In a conditional statement we use, if you haven't guessed it yet, the "if" statement.

The syntax are:

if (condition) statement;

if (condition)
{
statement
statement
}

if (condition is true) execute this; else execute this instead;

That's all there is to it. If the condition is true then it runs the statement if not and else is specified it runs that instead.

Here are the symbols used in a conditional statement:

>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
==are equal

* Notice the condition "are equal" are two equal sign. If you use only one equal sign, it assigns the value on the right to the variable on the left. For example x=1+2; the value of x will become 3; and x==1+2, if x=3 then the condition is true.

Here's an example of a program that determines if a number inputed is positive or negative.

#include
#include

int n;

void main() {
clrscr();
printf("Enter a number, positive or negative: ");
scanf("%d", &n);
if (n>=0) printf("%d is a positive number", n);
else printf("%d is a negative number", n);
getch();
}

That wasn't so hard wasn't?
Now here's your homework:

Write a program that ask user their age and outputs a comment based on the their input. If the user enters 0 to 2 it outputs "Still a baby", 3 to 12 "Children", 13 to 17 "Teenager", 18 to 26 "Young Adult", 27 to 39 "Middle age", 40 to 79 "Grand Parents", 80 and higher "Wow". That's all, have fun.

Click here to see what I did.

<<back<< >>Next>>