Condtions allow a program to think for itself. Many times there will be moments when you want your program to decide from different options depending on the input you give to it. This allows your program to have much more diversity, without conditions, your program would run the same way everytime and what's the fun in that? There are a few different conditions that are used if, if else and else. Here is the syntax for an if statement.
if(x > y) { printf("x is greater than y"); }
So if x greater than y do the stuff you want it to. The curly braces aren't necessary in this example because there is only one line of statements but if there were more it would be required. You still can put the curly braces just to be safe so it's entirely up to you. If there are more than one if statements you'd like to use than you can use the else if statement
else if(y >x) { printf("y is greater than x"); }
Other than it be calling an else if, this statement works the same way as an if statement yo do however, have to use an if statement first in order to use an else if. So what if x wasn't greater than y and y wasn't greater than x than we would want the program do to something else well that's exactly what the else statement is for.
else { printf("x and y are equal"); }
The else statement is basically "This statement isn't true and this other statement isn't true so do this." I printed x and y are equal because if neither are greater than or less than one another than they must be equal. One thing I do want to point out is this.
if (x==y) { printf("x and y are equal"); }
Notice the two equal signs, what this means is to check for equality where one equal sign means assignment, x=y, x is equal to y, in comparison to, x==y, check to see if x is equal to y. Okay so lets check out a complete program using the if statement.
#include <stdio.h> #include <stdlib.h> int main() { double x,y; printf("Enter a value for x"); scanf("%lf",&x;); printf("Enter a value for y"); scanf("%lf",&y;); if (x > y) { printf("x is greater than y"); } else if (y > x) { printf("y is greater than x"); } else { printf("x and y are equal"); } system ("pause"); return 0; }
Notice how the last statement, the else statement there is no condition. This is because it doesn't need one, the condition for the else statement is if the other if conditions aren't true than do this. There are number of other operators that you can use with an if statement, these are a few.
(x > y) "x is greater than y" (x >= y) "x is greater than or equal to y" (x < y) "x is less than y" (x <= y) "x is less than or equal to y" (x==y) "Check to see if x is equal to y" (x != y) "x is not equal to y"