Today’s lesson will focus on commonly used operators that you will need for writing C programs. But before we do that, we are also going to get familiar with something called if statements.
An if statement checks whether a particular condition is true and performs the corresponding action. Let us take an example:
printf(“a is greater than 4”);
This program checks if the value of a is greater than 4, and if it is indeed greater than 4, it will do whatever is written in the statement immediately afterward and before the next semicolon. You can read it as “if a is greater than 4, display ‘a is greater than 4‘”.
See the > symbol? It is an operator. The equality symbol (=) is also an operator.
Operators are symbols that tell your computer to perform a specific operation. For example, the + operator performs addition.
List of common operators:
< : less than
<= : less than or equal to
>= : greater than or equal to
!= : not equal to
== : equality comparison
The equality comparison operator (==) is used to compare two values, while the equality operator (=) is used to assign a value. Let me clarify with an example:
printf(“a is equal to 5”);
Note that when we write a=5 we are assigning the value 5 to the variable a, but when we write a==5, we are checking whether or not the value of a is equal to 5. A common mistake is when people write if(a=5) instead of if(a==5). What happens if you do this is the value 5 gets assigned to the variable a instead of checking whether or not the value of a is equal to 5, which ultimately leads to incorrect results.
Other commonly used operators that you should know about are the logical AND and OR operators.
The AND operator is specified by the symbol && and checks whether both the conditions specified are true, while the OR operator is specified by the symbol || and checks if at least one of the conditions specified is true.
Let’s see an example:
if(a>0 && a<10)
printf(“This is a positive non-zero number less than 10”);
Now what happens if we need to do two different things based on whether or not a condition is satisfied? Well, C has got your back. Just use the else keyword.
You can make your program do more than one operation if it satisfies a condition. In such cases, you need to enclose all the statements within curly braces.
int number1=10, number2=5;
printf(“%i \n”, number1/number2);
printf(“Cannot divide by zero!”);
That’s all for today. Look out for tomorrow’s email for the next lesson. Till then, keep practicing.
Share with friends