When you write a program sometimes you want it to do different things
depending on certain situations.You can use an "if" statement to tell the program
to do one thing or jump to another part of the program to do
another. You use the word "if" and then put paranthesis
around the conditional statement. The conditional
statement is a true or false condition, if the condition
is true then the if statement executes, if not then the
else statement executes. Finally, the block of code that
you want to execute with the if statement must be in
curly braces. Confused yet? I'll give you some snippets
here to make it more clear...
int myNumber = 5;
//first we test to see if myNmber is less than 10
if ( myNumber <= 10 )
{
//if it is less than or equal to 10 we print out a
//message telling the user that
printf( "the number %d is less than or equal to 10", myNumber );
}
else
{
//this "else" block executes if the "if" statement fails
printf( "the number %d is greater than 10", myNumber );
}
That is the basics of the "if" statement. If nothing should
happen when the number is greater than 10, then you don't
need to put an "else" block. Lets say we want 3 things to
happen, you can use an "else if" statement for that. You can
use as many "else if" statements as you want after the
first "if" statement
int myNumber = 5;
//first we test to see if myNmber is less than or
//equal to 10
if ( myNumber <= 10 )
{
//if it is less than 10 we print out a message
//telling the user that
printf( "the number %d is less than or equal to 10", myNumber );
}
else if ( myNumber <= 15 )
{
//if the first "if" statement fails then the
//number is greater than 10so now we check and see if it's less
//than or equal to 15
printf( "the numer %d is less than or equal to 15", myNumber );
}
else
{
//this else block executes if the "if" statement fails
printf( "the number %d is greater than 15", myNumber );
}
The most used conditional operators in the "if" statement are as follows
< (less than) example: if ( a < b )
<= (less than or equal to ) example: if ( a <= b )
> (greater than) example: if ( a > b )
>= (greater than or equal to ) example: if ( a >=b )
== (equal to ) example: if ( a == b) Important note: It is a double
equal sign here. The single equal sign would actually assign the value
of b to a.
!= (not equal to ) example: if ( a != b) note: the exlamation point
always means NOT in C and C++. More about that later.
___________________________________________________________
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <conio.h>
void main( void )
{
int input;
printf ("\n Enter access code: ");
scanf( "%d", &input );
if (input == 123)
{
printf("\n Correct access code!");
}
else if (input == 345)
{
printf("\n Correct access code!");
}
else
{
printf( "\n Incorrect access code!" );
}
getch();
}