Tuesday 15 January 2019

Conditions


 #Tutorial5#

Decision Making

In life, we all have to make decisions. In order to make a decision we weigh out our options and so do our programs.
Here is the general form of the decision making structures found in C.


int target = 10;
if (target == 10) {
    printf("Target is equal to 10");
}


The if statement

The if statement allows us to check if an expression is true or false, and execute different code according to the result.
To evaluate whether two variables are equal, the == operator is used, just like in the first example.
Inequality operators can also be used to evaluate expressions. For example:


int foo = 1;
int bar = 2;

if (foo < bar) {
    printf("foo is smaller than bar.");
}

if (foo > bar) {
    printf("foo is greater than bar.");
}
 
We can use the else keyword to exectue code when our expression evaluates to false.


int foo = 1;
int bar = 2;

if (foo < bar) {
    printf("foo is smaller than bar.");
} else {
    printf("foo is greater than bar.");
}
 
Sometimes we will have more than two outcomes to choose from. In these cases, we can "chain" multiple if else statements together.

 
int foo = 1;
int bar = 2;

if (foo < bar) {
    printf("foo is smaller than bar.");
} else if (foo == bar) {
    printf("foo is equal to bar.");
} else {
    printf("foo is greater than bar.");
}





No comments:

Post a Comment

Note: only a member of this blog may post a comment.