C Statements - Else...If
(Page 3 of 4 )
The Else...If allows you to evaluate a third condition. In this case, we are going to use it to help us make the program react if the two values are equal:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int yourmom;
int mymom;
printf("Enter your mother's weight: ");
scanf_s("%i",&yourmom);
printf("Enter my mother's weight: ");
scanf_s("%i",&mymom);
if(yourmom>mymom)
{
printf("nnnnYep...yer mom is a big fat pig.nnnnn");
}
else if(yourmom==mymom)
{
printf("nnYou must be my long lost brother! God bless our fat
moms!n");
}
else
{
printf("nnMy mother may be fatter...but yours is still uglyn");
}
}
Now we have all our bases covered. If the mymom is greater than yourmom this prints out:
My mother may be fatter...but yours is still ugly
If yourmom is greater than mymom:
Yep...yer mom is a big fat pig.
And finally, if both our moms are equally as fat:
You must be my long lost brother! God bless our fat moms!
You are not limited to three conditions. With the Else...If we can code till the cows come home, which is forever, because all you care about are your needs. How many times have you given milk to your cows?
In this program, we will create rhymes based on the number a user enters in (ranged 0-5):
#include <stdio.h>
#include <stdlib.h>
void main()
{
int rhyme;
printf("Enter a number from 0-5: ");
scanf_s("%i",&rhyme);
if(rhyme==1)
{
printf("n One...a big fat bun.");
}
else if(rhyme==2)
{
printf("n Two...I hate you");
}
else if(rhyme==3)
{
printf("n Three...You look like Mr. T");
}
else if(rhyme==4)
{
printf("n Four...Don't vote for Al Gore");
}
else if(rhyme==2)
{
printf("n Five...Quit talking Jive");
}
else if(rhyme==0)
{
printf("n Zero...You know I'm yer hero");
}
else
{
printf("nThat number is not between 0-5 you dummy.");
}
}
In this program, we allow the user to pick a number from 0-5. The number they choose is stored in a variable named rhyme. We then go through a series of If and Else...If statements that asks whether the variable is equal to the numbers in the range 0-5. If it is, then it prints the appropriate line; if not, it moves on to the next statement. Finally, if the value is not within the range 0-5, it prints out:
That number is not between 0-5 you dummy.
If the number had been equal to say, three, this would have printed out:
Three...you look like Mr. T
Next: The Case Statement >>
More BrainDump Articles
More By James Payne