Website Hosting for Just 20 ForumCoin ~ Advertise on ForumCoin
ForumCoin is an online community where you earn ForumCoin for making posts and for referring other members. You can use the ForumCoin virtual currency to buy and sell goods and services and to exchange for traditional currencies. Find out more!
Get paid up to 150 ForumCoin to submit your article.

[C Course #4] Operators and Statements [Chance to win 50 FC]

Postby JusApee » 22 Dec 2016, 00:38

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
[+] Spoiler
Code: Select all
()    // used for function calls
[]   // used for data selection in an array
.   // used for calling data in a structured type
->   // used for calling data in a pointer to a structured type

  • Unary operators
[+] Spoiler
Code: Select all
(type)         // used for explicit type conversion
sizeof(type)   // dimension in Bytes of a type
&            // variable's address
*            // the value at a given address
+ -            // the unary version (+a, -a) the sign of a variable
!             // negates the value !true = false, !false = true
~            // bitwise NOT ex: ~10110 = 01001
++            // increment by 1
--            // decrement by 1

  • Multiplicative operators
[+] Spoiler
Code: Select all
*   // basic multiplication
/   // basic division
%   // returns the remainder of the division between a and b
   // 10%4 = 2 why? because 10/4 = 2 remainder 2 (4*2 + 2 = 10)

  • Addition/Subtraction
[+] Spoiler
Code: Select all
+   // addition
-   // subtraction

  • Bitwise shifting
[+] Spoiler
Code: Select all
<<   // shifts the bits to the left, ex: 5(101 binary) << 1 = 2 (010 binary) a 0 was inserted to the right and the first digit was removed
>>  // shifts the bits to the right

  • Relation operators
[+] Spoiler
Code: Select all
<   // less than
>   // greater than
<=   // less or equal
>=   // greater or equal
==   // check if equal
!=   // different from

  • Bitwise operators
[+] Spoiler
Code: Select all
&   // AND between number bits
|   // OR between number bits
~   // mentioned at unary operators, we'll talk about logic NOT, AND, OR below.

  • Logic Operators
[+] Spoiler
Code: Select all
&&   // AND between expressions, ex. (a == 1) && (b == 2) returns true if a = 1 and b = 2
||   // OR between expressions, ex. (a == 1) || (b == 2) returns true if either a = 1, b = 2 or both conditions are true

  • Assignment Operators
[+] Spoiler
Code: Select all
=   // assigns a value to a variable
+=   // adds the value to the variable
-=   // subtracts the value from the variable
*=   // multiplies the variable by the value
/=   // divides the variable by the value
%=   // gets the remainder of division by the value
// a += b is equivalent to a = a + b

  • Conditional operator (ternary)
[+] Spoiler
Code: Select all
?:   // returns a value depending on the condition
// example:
int c = (a == 1)?100:0;

// our variable c will be equal to 100 if a = 1
// or it will be equal to 0 otherwise


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:
Image
Where "non-0" means any possible value but 0.

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

OR (||)
Given a and b:
Image
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):
[+] Spoiler
Code: Select all
#include <stdio.h>
#include <ctype.h>   // including required library

int main() {
   char myChar;
   printf("Insert a character: ");
   scanf("%c", &myChar);   // reading a character
   if (isdigit(myChar)) {   // check if the value returned by the function isdigit is 0 or 1
      printf("Yes, \'%c\' is a digit!", myChar);
   }
   else printf("No, \'%c\' is not a digit!", myChar);
   return 0;
}


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:
[+] Spoiler
char myOperation;
int a, b, res;
scanf("%c", &myOperation);

switch(myOperation) {
case '+': {
res = a + b;
break;
}

case '-': {
res = a - b;
break;
}

case 'x':
case '*': {
res = a * b;
break;
}

case ':':
case '/': {
res = a / b;
break;
}

default: printf("Error!! Operation not existing"); // this can stay as it is since it is the last case
}
[/code]

The difference is that if we read something like "3x7", the x character will match the case and execute everything until the first break. That means that x and * have the same code (and that should be happening since they're both multiplications). Same principle applies to the division ':'.



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:
[+] Spoiler
Code: Select all
#include <stdio.h>

int main() {
   int x, n;
   int result = 1;      // initialized with 1 so that multiplying it by x will still be x
   int i;   // iterator
   scanf("%d^%d", &x, &n);   // I formated the reading such that we can write 2^3 instead of reading the values separately
   for (i = 1;i<=n;i++) {         // of course, you can read however you want as long as it reads the values properly
      result *= x;
   }
   printf("%d^%d = %d", x, n, result);
   return 0;
}

Let's explain the code above, especially the for part. i is called an iterator because it starts from 1 and gets incremented step-by-step until it gets higher than our n. That process of step-by-step incrementing is called iterating, hence, iterator.
We read our base and exponent, then enter the for.
Code: Select all
i starts as 1 (remember expression1 only gets executed ONCE at the beginning of the for)
i <= n ? (depends on the n you've read, but for n = 0 the for won't get executed and result=1 will be printed)
result *= x; (result = result * x)
i++; (i = i+1)
back to condition
i <= n ? (i is higher now, so we have to check again)
      |yes: multiply result again
      |no: print result

It's easy, right?


Another Example: Let us calculate the sum of all the odd numbers from 1 to a number n:
[+] Spoiler
Code: Select all
#include <stdio.h>

int main() {
   int n, i;
   int sum = 0;   // sum is 0 because we don't want an incorrect answer
   printf("n: ");
   scanf("%d", &n);
   for(i = 1;i<=n;i+=2) {      // this time the iterator is incremented by 2, not by 1 (i+=2), starting from 1, we get i = 1, 3, 5...
      sum += i;
   }
   
   return 0;
}



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.
  • 1

JusApee
 
Posts: 46
Reputation: 16
ForumCoin: 341


Your Ad Here.

Return to Articles & Tutorials



Who is online

Users browsing this forum: Yandex [Bot] and 1 guest

Reputation System ©'