C Statements
(Page 1 of 4 )
In our last article we talked about Arrays and Operators in C. In this article we will cover conditional statements like the If statement, the Else clause, and the Case statement. If there is time, we will also begin discussing how to work with loops.
Conditional Statements
When writing programs, we often find ourselves having to respond to something the user has done. Conditionals work, at their very basic level, by stating: if the user does this, do that. It of course gets more complicated than that, but that is where we are going to begin.
Say you set your alarm at night. If it doesn't go off, you have to call your boss and explain why you are such a slacker. That's the basis of an If statement. If this, then that. Here it is in code:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int yourMommasWeight=2000;
if(yourMommasWeight >120)
{
printf("nnnnWow your momma is FAAAAT!nnnnn");
}
}
The above code insults your fat momma. It does so by creating an integer variable named yourMommasWeight and assigning it the value 2000. We then say that if the value of yourMommasWeight is greater than 120, print some text. If the value is less than 120, nothing happens. However, we did make the value of the variable greater than 120, and this is the result:
Wow your momma is FAAAAT!
We could also write a program that compared your mom to my mom to see if your mom was fatter:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int yourMommasWeight=2000;
int mymom=119;
if(yourMommasWeight >mymom)
{
printf("nnnnYep...yer mom is a big fat pig.nnnnn");
}
}
In the above example, we compare two variables: yourMommasWeight and mymom. Again, we set the value of the variables, and since your mother is fatter than mine, it prints out some text. If my mother had been fatter, nothing would have happened. We'll fix that shortly. However, first let's be a little fair and get some input from the user. I mean after all, I may be just a little biased.
#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");
}
}
In this program we create two variables, yourmom and mymom. We then ask the user to enter a number, and store that value in the variable yourmom. Next, we ask the user to give us another number, and store that in the variable mymom. It then compares the values in both variables, and if the value of yourmom is greater than mymom, it prints some text. If the value of mymom is greater than yourmom, nothing occurs.
Okay, let's make the program do something if by some crazy chance my mom is fatter than yours. For this we will need the Else Clause...
Next: ELSE! >>
More BrainDump Articles
More By James Payne