Introduction
When developing a program, you have to look at different scenarios which the user of the program will choose. If a user selects an option in a program, you have to create from a semantic logical real life scenario to syntax, which the code places conditional statements in what to execute.
In C, there are two main selection structures which are used, the if and switch statements. They are syntactically different, but do the same job by following the condition set. So for example if a user enters '1' for a selection in the menu, which edits details on the system; the code will use the condition that if '1' has been entered, the statement will execute the segment of code assigned within that conditional statement. An simple real time algorithm is shown below.
Conditions in Practice
In a real time solution, the procedure above is pretty straight forward. Now the coding should be just as logical. The two main selection structures if and switch statements can sort out which task will run in the code.
First, we will go through the if statement.
if(condition)
{
// STATEMENT - CODE GOES HERE
......
}
This determines if a statement should be executed. It could be done like this brief example below.
Using Operators within Conditions
if(work ==1)
printf("Work Equals One!");
The snippet checks to see the work variable value is equal to 1. In the parenthesis, you can see work variable followed by ==, which is the equal operators. There are different relational and logical operators, that can be used, which in this case is the equal operator (Too see other operators see table below).
If the condition is met by the work variable; being equal in value to the conditional value set, which is 1, then the following line which prints a line will be executed. If you were to place place more than one line of code, you are best advised to place the block of code inside curly brackets (in scope), otherwise it will only place the first line within the conditional statement.
What if you want to check if a condition is lesser or greater in value, you can create a statement that does so; by using the less < and/or greater than > operators.
if(work > 2)
{
PrintMoreThanTwo();
}
if(work < 10)
{
PrintLessThanTwo();
}
The table below shows the Relational and Logical operators used within conditions.
< |
Less Than |
&& |
Logical AND |
> |
Greater Than |
|| |
Logical OR |
<= |
Less Than or Equal To |
! |
Logical NOT |
>= |
Greater Than or Equal To |
|
|
== |
Equal To |
|
|
!= |
Not Equal To |
|
|
Using Else within a Conditional Statement
Now you know what operators do what, nothing that we will do from now on in these subsequent tutorials will leave you confused. If you forget, do not panic, just go back to the table for reference. It is good to be selecting a block of code with a simple condition, but what if you want to select, only one of two statements. This is possible by using the else keyword like shown by the example below.
if(work == 1)
{
printf("Work Has Selected One");
}
else
{
printf("Item Not Found!");
}
If-Else Conditional Statement
Even better, if you have more than two statements, you can use else if, which works like this.
if(work == 1)
{
printf("Work Has Selected One");
}
else if(work == 2)
{
printf("Work Has Selected Two");
}
else if(work == 3)
{
printf("Work Has Selected Three");
}
It works all well and good, but these conditional statements can become cumbersome, unyielding, and awkward to work around in some circumstances; when you are using more than several statements. So in this scenario, it is best to use Switch Statements.
Switch Statements
switch (expression)
{
case (value A):
// ...... statement
break;
case (value B):
// ...... statement
break;
default:
// ...... statement
break;
}
A Switch Statement simply selects between one of a number of different statements. An expression data value is evaluated and executes the statement with the case value which matches the expression data value. If none of the case values match the value of the expression, then it will call the default label statement. At the end of each statement, it is always followed by the break keyword. This is necessary, as without it; the execution of the code will go through all statements that follow the case which was used. One break is executed, it will allow the program to finish and exit the switch statement. The below example shows how to implement a simple switch statement.
switch (day)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
default:
printf("No Day was Selected");
break;
}
Ternary Operator
There is a third selection structure you can use, albeit rather limited compared to if, and switch statements; and that is the Ternary Conditional Operator, which uses the ? operator as an expression. It is straight forward in its operation, as many describe it as a simplified inline if statement, in that works similar to the if... else conditional expressions mentioned before, but with less code.
condition ? (value if true) : (value if false)
The condition is evaluated by either true or false as a boolean expression, thus returns a value whether the condition is true or false. In the example below, we will revisit the if... else code example used previously in this article, and show the ternary version which does exactly the same thing.
// IF ... ELSE VERSION
if(work == 1)
{
printf("Work Has Selected One");
}
else
{
printf("Item Not Found!");
}
// TERNARY OPERATOR VERSION
(work==1) ? printf("Work Has Selected One"):
printf("Item Not Found!");
The best thing with the Ternary operator, you can use it to return a value based on a condition.
int t_number = (work==1) ? 10:0;
This example shows that if the work value is one, then the t_number variable will be assigned the value of ten; due to the work value condition being true, otherwise it will assign zero. Some developers will use ternary operators as it is small on the eye and to code (In many cases faster to execute code according to some software engineers). If statements are great for executing blocks of code within curly bracket scope, there as the Ternary operator is good for single line function calls (like the first ternary example) or more importantly returning different data values. You will see Ternary operators in different guises in later tutorials and more importantly any major software source code.
Example Code In Detail
Now we are going to develop a small program which handles both the if and switch statements. This program is simple, as all it does is takes the user's input which they enter both a level which they are at, and a score which they have achieved. Once that data is entered, it will follow the basic conditional statements. Once the user enters the level and score numbers, the program will multiply the score by the level number entered. It is pretty straight forward enough for you to get the main guts of the program.
First, we are going to declare global identifier variables which will be needed for collecting inputted data and the final calculation (If needed!).
// Global Variables
int score;
int level;
int finalscore;
Now inside the main function entrance point, we begin with allowing the user to enter the data. It asks the user to input a value of 0 to 1000 for the Score, and 1 to 10 for the Skill level. This section below shows the input and output interface code.
printf("What Is your Skill Level (1 - 10)... ");
scanf("%d", &level);
printf("\nEnter your Overall Score (0 - 1000)... ");
scanf("%d", &score);
Once that is done, now with the main conditional statements. The condition in the snippet below will begin as a scope which will check if the conditions match. There are two Relational Operators conditions which deals with both the score and level values which are encapsulated by parenthesis to clarify the code. The AND Logical Operators (&&) in between the two encapsulated conditions are used to make sure both conditional values are met; Even if one of the conditional values meet with the input, that will not be enough.
// CONDITION WILL MAKE SURE THAT THE ENTERED VALUES FOR LEVEL IS BETWEEN 1 TO 10
// AND THE SCORE VALUE IS BETWEEN 0 TO 1000, OTHERWISE, THE STATEMENT WILL NOT EXECUTE
if((level >= 1 && level <= 10) && (score >= 0 && score <= 1000))
So the condition checks to see if both the Level value is between 1 to 10 and the Score value is between 0 to 1000. The statement code below will execute. In this example, you can see that there is a switch statement. Each case statement will basically print a message according to the level value that was entered and sent through the switch statement expression. So for example if your level value is one, then you will get the message "Basic Level Stuff" display in the program. You may have noticed that case statement 4 or 5 do not have any code inside the statement or a break keyword. That is because it will be carried into the case 6 statement, hence the lack of statement code and more importantly no break following case four 4 case 5. So case value 4, 5 and 6 share the same statement code. The default statement would not be applicable as there should not be a level value outside the ones set in the if conditional statement; range from 1 to 10. Default keyword and statement are only there just as an example.
{
// PRINTS A MESSAGE DEPENDING ON WHAT USER ENTERS AS THEIR LEVEL
switch(level)
{
case 1:
printf("Basic Level Stuff");
break;
case 2:
printf("Such a Long, Long Way to Improve");
break;
case 3:
printf("Poor, Room for Total Improvement....");
break;
case 4:
case 5:
case 6:
printf("Intermediate - Middle of the Road Stuff");
break;
case 7:
printf("Decent Going, You must be more than Okay at this");
break;
case 8:
printf("Great Effort, Skill Level is so Good. So Close, So Far!");
break;
case 9:
printf("You are so close to being INVINCIBLE!");
break;
case 10:
printf("FANTASTIC - Congratulations - Most Skilled");
break;
default:
printf("Cannot get that one!");
break;
};
finalscore = score * level;
printf("\nYour final score is %d", finalscore);
}
If the main if conditional value do not match then this statement code will run instead with the else statement.
else
{
printf("\nInvalid Values, Final Score will not be generated");
}
Summary
There now you have it; in C things are very logical and knowing how conditions work is something you should get used to as it is crucial part of programming. Play with the code provided with this tutorial, so you can become acclimatised to working around conditional statements. If you are more ambitious, write your own code from scratch if you can. There is nothing wrong with using this article as reference, as long as you are sensible, you can create your own interactive program.