C Programming - Course #3
Operators and Statements (Part I)
ThinkIT! Win 50 FC...
Look around the course for ThinkITs and answer them. The one who has the most ThinkITs at the end of the course (the entire course, not just course #2) gets 50 FC. If more of you have the maximum amount of ThinkITs, I'll choose two of you with random.org
Please comment your answers and try not to copy others' answers. I can figure out who copied who.
What are operators?
Operators are, just like in math, used to change the value of a variable or to create new values. There are three types of operators:
- unary - operators that require only one operand -a -> returns the opposite of a
- binary - operators that require two operands a+b -> returns the sum of a and b
- ternary - operators that require three operands (someCondition)?ifTrueStatement:ifFalseStatement -> we'll talk about this later
A list of all operators can be found here:
- Primary operators
- Unary operators
- Multiplicative operators
- Addition/Subtraction
- Bitwise shifting
- Relation operators
- Bitwise operators
- Logic Operators
- Assignment Operators
- Conditional operator (ternary)
Expressions?
A combination of operators and operands that has a result (unique result) is called an expression.
- Code: Select all
// expression example:
int a = 1;
int b = 20;
int myVar = ((a == 1)?b:0) + 27;
Here we have an assignment operator, a conditional one and an addition.
Expressions are easy... Let's talk about Statements
A statement is basically an instruction sent to the computer. A statement always ends with a semicolon (';'). Forgeting the semicolon at the end of a statement will result in a syntax error.
Blocks of instructions
- Code: Select all
{ // the block starts from here
statement1;
statement2;
...
statementN;
} // and it ends here
Any number of statements can be entered in {} and the compiler will treat all the chunk of code inside those brackets like a (single) statement. This lets us have any number of lines of code inside an if statement or a for.
if statement
The if statement lets us execute a certain sequence of code only if it meets the condition.
- Code: Select all
int myVar = 25;
if (myVar == 25)
do_something;
Alternatively, I personally like doing this:
- Code: Select all
int myVar = 25;
if (myVar == 25) {
do_something;
}
Having brackets there does nothing, in this case, because we only have one statement. But say we want to add a second line of code under that condition. What do we do?
- Code: Select all
if (myVar == 25)
do_something;
do_somethingElse;
This won't work. The second statement will ALWAYS be executed, regardless of myVar's value. Instead, we have to use this:
- Code: Select all
if (myVar == 25) {
do_something;
do_somethingElse;
}
Why is that? Because as I said earlier, the code inside the brackets is interpreted like a single statement.
In conclusion: if lets us execute a certain statement (only one) ONLY if the requirements are met.
The interesting part about ifs is that it comes in pair with else. If the condition is not met, the else block of code is executed instead.
- Code: Select all
float myNum, someNumber = 0;
scanf("%f", &myNum);
if (myNum < 0) {
printf("Negative number");
}
else printf("Positive number");
This code is equivalent with the following:
- Code: Select all
float myNum, someNumber = 0;
scanf("%f", &myNum);
if (myNum < 0) {
printf("Negative number");
}
if (!(myNum < 0)) { // equivalent with if(myNum >= 0)
printf("Positive number");
}
The difference between the first and the second code is that the code under the else is executed without checking the negated condition. This means that if myNum is not < 0, it won't check if myNum is >= 0, but instead it will directly print that it's positive.
Additionally, let's say we want to be alerted if the inserted number is 0. What do we do in this case? Here's the code:
- Code: Select all
if (myNum < 0) {
printf("Negative number");
}
else if (myNum == 0) {
printf("Number is equal to 0");
}
else {
printf("Positive number");
}
Here you can see some else if chains. If the number is less than 0, it will follow the first if. Otherwise, it goes straight to the first if's else and is checked to be equal to 0. If it still isn't, the second else is executed. That's how chaining else if works.
What means that the condition is true or false
There are two "truths" in C language:
- false - the value 0
- true - ANY value besides 0
A true condition is ALWAYS replaced by a non-zero value, while a false condition is always replaced by a 0.
- Code: Select all
int a = 5;
if (a > 3) { // 5 > 3 so obviously this is true. a>3 equals 1 (logical true)
do_something;
} else { // this would imply 5 <= 3 which is obviously false. a<=3 equals 0.
do_somthingElse;
}
.............................
int myNumber = 23;
if (myNumber) { // such an if ALWAYS checks (myNumber != 0) so that's a 1.
do_something;
}
.............................
int a, b;
a = 10; b = -a;
if (a + b) { // a + b equals 0, so that's an if(0 != 0) which is false because 0 is not different from 0
do_something;
}
!! Note: Comparing real numbers is harder because the computer does a lot of approximations. Let's take this:
- Code: Select all
float a = (float)(3*(1/3)); // 3 * 0.3333 = 0.99999, but mathematically, 3 * 1/3 is equal to 1.
if (a == 1) // I converted the result of those operations to float by using a conversion operator
return true; // this won't ever happen, because 0.99999999999 != 1.0000
How can we solve this problem? Here's the code:
- Code: Select all
const float eps = 0.0001; // this is the error we let our computer make due to approximations made
float a = (float)(3*(1/3));
if (abs(1-a) <= eps) // this means that the difference between our number and 1 is less than that error
return true; // now this will happen
// abs(1-a) is the modulus (absolute value) of 1-a, this is not predefined, you have to define it yourself.
Logic Operators
NOT (!)
Given the value of a we have the following table:

Where "non-0" means any possible value but 0.
AND (&&)
Given a and b:

Where "non-0" means any possible value but 0.
OR (||)
Given a and b:

Where "non-0" means any possible value but 0.
Some examples of if codes:
Problem 1: Check if a character read from the console is a digit. For this, you may use the function isdigit(char) from the ctype.h library (add #include <ctype.h> at the beginning after including stdio.h).
The code is here (try to do it yourselves, though, and verify yourself with my code):
ThinkIT! #1: Replace the if with:
- Code: Select all
if (myChar >= '0' && myChar <= '9') {
printf("Yes, \'%c\' is a digit!", myChar);
}
What is the output in this case? Why?
Switch statement
- Code: Select all
switch(expression) {
case const1: {
statement1;
..
statementN;
}
..
case constN: {
statement1;
..
statementN;
}
default: { // optional
statement1;
..
statementN;
}
}
What's a switch? It is actually a replacement for an else if chaining. The switch gets the expression's value and checks for every case. If it finds the correct result among the cases, it executes that code and ALL the cases below it.
Why would we use this? Let's discuss.
- Code: Select all
char myOperation;
int a, b, res;
scanf("%c", &myOperation);
switch(myOperation) {
case '+': res = a + b; // a single statement so we can omit brackets
case '-': res = a - b;
case '*': res = a*b;
case '/': res = a/b;
default: printf("Error!! Operation not existing"); // this is the final ELSE in an else if, right?
}
Would this work? No. Why? Because if we read the '+' character, it matches the first case, res = a+b, then it executs all the following cases, so res = a-b, res = a*b and finally res = a/b.
So our result will be a/b. How can we avoid this? By using the break keyword. What does the break keyword do? It takes you out of the current statement (works for switch, for, while statements). That would look like this:
- Code: Select all
char myOperation;
int a, b, res;
scanf("%c", &myOperation);
switch(myOperation) {
case '+': {
res = a + b;
break;
}
case '-': {
res = a - b;
break;
}
case '*': {
res = a * b;
break;
}
case '/': {
res = a / b;
break;
}
default: printf("Error!! Operation not existing"); // this can stay as it is since it is the last case
}
Here is an alternate code that would make use of the switch's property:
Repetitive statements
Take a look at the increment/decrement operators before reading any further.
There are three repetitive statements:
- for - known number of steps
- do...while - unknown number of steps
- while - unknown number of steps
Before starting, I told you to look back at the increment/decrement operators. Here's some more:
- Code: Select all
int a = 5;
int myVar = a++; // myVar gets a's value, then a is incremented by 1, so myVar = 5, a = 6
int my2ndVar = ++a; // this time, a gets incremented (a = 6+1), then my2ndVar gets assigned its value (6+1 = 7)
Putting the increment operator AFTER the variable, makes the compiler use that variable's value and increment it right AFTER its usage.
Putting the increment operator BEFORE the variable, makes the compiler increment that variable first and only after that use it.
The same things can apply to the decrement operator.
while statement
- Code: Select all
//Format:
while(condition) {
statement1;
..
statementN;
}
The code under the while executes repetitively for as long as the condition is met. How does it work?
The while checks the condition, if it is met, it executes the code under it. After that, it goes back up and checks the condition again. If the condition is met again, it executes the code under it yet again. That keeps repeating until the condition is not met anymore.
Be careful! If the condition is never going to be false, you find yourself in an infinite loop. As I said in the first course, the infinite loops are going to crash your application if they're not under control, so pay attention when dealing with them. A loop ALWAYS needs a way out, be it by breaking it.
do...while statement
- Code: Select all
//Format:
do {
statement1;
..
statementN;
} while(condition);
This is exactly a while. The only difference is that the code gets executed once before the first condition check, so the code will get executed once no matter what, the condition only dictates if it gets repeated.
for statement
This one is a bit more complicated to explain.
- Code: Select all
// Format:
for (expression1; expression2; expression3) {
statement1;
..
statementN;
}
How does it work?
It executes expression1, then checks for expression2. If expression2 is true, it executes all the code under the for, THEN it executes expression 3. It goes back to expression2, checks it again, and if it's false, it gets out, otherwise, it repeats the code.
Example: Let us calculate a number x to the power of n. You can try it yourself if you want. If you have trouble with it, here's the code:
Another Example: Let us calculate the sum of all the odd numbers from 1 to a number n:
In the end...
That would be it for today, guys. Thanks for reading my courses. I'll see you in the next course which will be the second part of this one, containing the last operators and statements you need to know.






