C++ Programming Series: Precedence, Order and sizeof()

In the previous post, we learned complex but still, simple looking conditions.

Instead of using boolean variables for complex conditions, we can directly use them in the conditional statements. Below is an example of a ‘complex looking’ complex condition:

int a = 5;
int b = 10;
int c = 15;

if( b == a + a || a == c - b && b != c - a && c > a )
{
  cout << "True!" << endl;
}
else
{
  cout << "False!" << endl;
}

Now, guess the output without executing it (or running it). It looks hard or complex to tell whether it is true or false. Actually, this will run in a specific order due to difference in the precedence. Precedence is the priority to check or run something in a statement. The precedence of AND logical operator(&&) is more than that of OR logical operator(||) which means that first, all AND logical operators will get executed and then, at last, the OR logical operator. The position do not justify the precedence; it is a property of an operator having a specific value.

Precedence helps to reduce errors. But it may be possible that programmer don’t want the order of execution in accordance with the precedence. The precedence factor can be overwritten with the use of round brackets. Following code shows the order of running or executing code due to precedence, using round brackets:

if( (b == a + a || (a == c - b && b != c - a && c > a)) )
{
  cout << "True!" << endl;
}
else
{
  cout << "False!" << endl;
}

The inner round brackets run before the outer ones. If there is only a pair of round brackets, it will run before all other code. This is how, precedence decides it to run. And the output is, “True!”. Now, below is the overwritten precedence order using round brackets:

if( ( (b == a + a || a == c - b) && b != c - a) && c > a )
{
  cout << "True!" << endl;
}
else
{
  cout << "False!" << endl;
}

In the above code, the OR logical operator will be executed first. The change in precedence is clear as the output, this time, is “False!”.

Same is the case with the arithmetic operators i.e +, -, /, *, %, ++, –, and all other operators. Here is C++ Operator Precedence Table (There are many operators that we don’t know yet! It will be helpful in future as well.)

In the post of Primitive Types, we learned types which have different memories. Sometimes, using lesser memory is a good thing and optimizes the program. How can we know the amount of memory allocated (or used) by a type or a variable? The sizeof() operator is for this purpose.

float i_am_float = 10.99f;
double i_am_double = 99.101010;

//sizeof() will return the amount of memory allocated by the type or variable, mentioned in the round brackets.
cout << sizeof(long long int) << endl;
cout << sizeof(char) << endl;
cout << sizeof(i_am_float) << endl;
cout << sizeof(i_am_double) << endl;
cout << sizeof(double) << endl; 
cout << sizeof(string) << endl; //Non-primitive type. Remember, to include string

The memory allocated by the type is not universal for all platforms and IDEs (like Visual Studio).

We will see later on, how important precedence and sizeof() is, to our programming. But for now, just do as many experiments as possible with the precedence thing. Try 2+2-2/2*2 or something like that! Try 2+value++! Just keep trying until you reveal the precedence of the operators you know at that time. Then, get the output of the above sizeof() code.

Programming is something, boring before and interesting after learning!

Advertisements

C++ Programming Series: Complex Conditions

In the previous post, the topic of ‘Using Conditional Statements’ finally, came to an end. But only now, there is something we call as ‘complex’. Actually, from the word, ‘complex’, it means multiple. In fact, complex is always something, multiple. A single complex object is a combination of multiple simple objects.

A simple example of a complex condition is given below:

bool complexOr = 5 < 3 || 2 < 8;</pre>

The whole expression after the assignment operator(or simply, = i.e equals to) gives either true or false and then, stores it in the boolean variable called as complexOr. 5 < 3 is understandable and is a simple condition when used alone. Same is the case for 2 < 8. First one is false and the second one is true. But the new thing is the operator in between these two simple conditions which connects them, forming a complex condition.

This is the OR logical operator(||) and it connects two or more conditions in such a way that:

If anyone of the conditions are true, it will return true.

For the above case, the boolean variable, complexOr will hold true. This is because 2 < 8 is true.

There is another operator of which example is given below:

bool complexAnd = 5 < 3 && 2 < 8;

The two ampersands(&&) is called AND logical operator and it connects two or more conditions in such a way that:

If all of the conditions are true, it will return true.

Therefore, it is pretty, clear that complexAnd will hold false. This is because one of the conditions i.e 5 < 3, is false.

In the next post, we will talk more about complex conditions and calculations. Be easy with yourselves and don’t get panic by the amount of text. Be patient and practice programming on daily basis!

C++ Programming Series: Using Conditional Statements (Part 7, Last)

In this post, we are going to learn the keyword, break. Are we not familiar with this keyword before? Yes, you got it right. We already learned it when we learned the switch-statement where we use break keyword after every case’s code.

The break keyword is only used for stopping loops and ending a switch statement. Now, we know that looping can only be done by while-statement and for-statement. So, break keyword is only used within switch-statement, while-statement(do-while as well) and for-statement.

Here, in the main function, it is used with all three conditional statements.

int value;
cin >> value;
switch(value)
{
  case 2:
  cout <<; "Alpha" << endl;
  break;

  //more cases

  default:
  cout << "Out of my mind!" << endl;
  break;
}

while(true) //an infinite loop
{
  if(value > 100)
  {
    cout << "break keyword makes while finite from infinite" << endl;
    break;
  }
  else
  {
    cout << "while looping " << value << endl;
  }

  value+=25;
}

for(value = 0; value < 100; value+=10) //a finite loop, value is already declared
{
  if(value >= 40)
  {
    cout << "exiting for loop when value gets bigger or equal to 40" << endl;
    break;
  }
  else
  {
    cout << "for looping " << value << endl;
  }
}

If value inputted, is 2 then, output will be:

2
Alpha
while looping 2
while looping 27
while looping 52
while looping 77
break keyword makes while finite from infinite
for looping 0
for looping 10
for looping 20
for looping 30
exiting for loop when value gets bigger or equal to 40

Try to understand the code with the reference to the output. What do you get? The break keyword stops the loop before the condition of the statement is falsified.

Now, there is another keyword for controlling loops. It is called continue. It do not stops the loop but it actually, skips the code after the continue keyword and then, returns to continue looping. The continue keyword is used in while-statement(do-while as well) and for-statement.

In the main function:

int i = 0;
do{
  i++;
  if(i == 5)
    continue;

  //code below continue will not run when i is equal to 5
  cout << "while looping " << i << endl;
}while(i < 10);

for(i = 0; i < 20; i++)
{
  if (i % 2 == 0) //if i is an even number
    continue;

  //code below continue will not run when i is an even number
  cout << "for looping " << i << endl;
}

We will not see, “while looping 5” and “for looping -even number-” because of the continue keyword.

Now, we already know how to compare things of same type. Below is an example of comparing two floats.

float fl1 = 0.1;
float fl2 = 0.1;

if (fl1 == fl2)
  cout << "Floats are equal!" << endl;
else
  cout << "Nah! unequal..." << endl;

if (fl1 == 0.1)
  cout << "True" << endl;
else
  cout << "False" << endl;

if (fl2 == 0.1)
  cout << "True" << endl;
else
  cout << "False" << endl;

It looks normal but its output is unusual.

Floats are equal!
False
False

Can you think of some reason for the fl1 and fl2 not equal to 0.1 but both are equal to each other? No. Just try to make one. It is actually, a simple one.

I ask you, is 0.1 with which we are comparing floats, a float or a double? It is a double. We are comparing a float to a double. Float has precision of 7 decimal places whereas double has precision of 15 decimal places. There is a rule in C++ and that is, comparing types of different precision will often result in unexpected output.

That doesn’t mean that comparing long int and short int will give unexpected output because both long int and short int can have smallest positive value, 1. But float can have smallest positive value, 0.000001 whereas double can have smallest positive value, 0.00000000000001 i.e both have different precision.

Now, we may need some good reason to understand it. And there is a good reason for that! This reason is based on the fact that when a variable is not initialized (or given some value), it will have the garbage value or the value present in the memory at that instance. To compare a float with a double, the float is converted to a double, temporarily i.e its precision will become the same as that of double.

In other words, for the above case, when we initialized float, its value is:

0.100000

But when it is converted to double while comparing it with a double, its value is not initialized for decimal places after 7 and so, decimal places after 7th one, is filled with garbage values. Its value may become:

0.10000020483009 (consider 20483009 as garbage values)

Now, I ask you, is the value 0.10000020483009 equals 0.10000000000000? Of course, they are not equal! I hope that you got it right.

The solution for the above case is really simple and you may know that. Just put an f after double values so, that compiler recognizes it as a float instead of a double.

float fl1 = 0.1f;
float fl2 = 0.1f;

if (fl1 == fl2)
  cout << "Floats are equal!" << endl;
else
  cout << "Nah! unequal..." << endl;

if (fl1 == 0.1f)
  cout << "True" << endl;
else
  cout << "False" << endl;

if (fl2 == 0.1f)
  cout << "True" << endl;
else
  cout << "False" << endl;

Now, we get a proper output!

Floats are equal!
True
True

Phew! At last, ‘Using Conditional Statements’ came to an end! Really, it looks like a series in a series! But it is an extremely important topic! We must know and understand every inch of this topic otherwise we can’t proceed well…

C++ Programming Series: Using Conditional Statements (Part 6)

In the previous posts, we learned very beautiful things of which the most beautiful is game development.

We have covered if-statement, if-else statement, if-else-if-statement, switch-statement, while-statement and do-while statement but there is another very important and most frequently used conditional statement called as the for-statement. It is a bit more complex but neat and short.

Following is the code to which you are already familiar with:

#include <iostream>
using namespace std;

int main()
{
  int loopCounter = 0; //Declaring and initializing a loop counter

  while(loopCounter < 10) //Condition (related with loop counter)
  {
    //All looping codes

    loopCounter++; //Changing loop counter
  }

  return 0;
}

Now, here is the code which is exactly the same as the above code but is neat and short:

#include <iostream>
using namespace std;

int main()
{
  //for(Declaring and initializing loop counter;
  //Condition (related with loop counter);
  //Changing loop counter)
  for(int loopCounter = 0; loopCounter < 10; loopCounter++)
  {
    //All looping codes
  }

  return 0;
}

for loop requires two semi-colon. Leaving them empty i.e for( ; ; ), will cause an infinite loop. Here is the format of for-statement for a quick overview:

for( Initializing variable(s); Condition(s); Changing variable(s) )
{ -Codes to be executed- }

Remember that each variable has a limited scope after which it is destroyed or deallocated from the memory and can not be used after that. Its scope is limited only to its block (or space between any two flower brackets). Hence, there is a definite difference between the loopCounter variables of while and for loops mentioned above.

The one used in the while-statement can be called after the while-statement’s block. The other used in the for-statement can not be called after the for-statement’s block.

It will not effect anything if loopCounter++; or ++loopCounter; is used in the for-statement.

Getting used to such small differences will lead to a better programming style, lesser errors and of course, better programming. Now, you have to use for-statement(s), cout << "*";, cout << " "; and cout << endl; in the best way possible to have that output:

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

Good luck! And come back if there are some doubts…

C++ Programming Series: Using Conditional Statements (Part 5)

Argghhh! When will the topic of conditional statement gets over? Well, we have to be patient while learning something. I hope that you might have done the home task of the previous post. Just keep trying to code things up and try to implement small ideas with your skill, you will see yourself learning and improving!

Below is some similar looking code that we discussed in the previous post:

#include <iostream>
using namespace std;

int main()
{
  //Guess the number game!
  while(value != 7)
  {
    cout << "Enter the value: ";

    int value;
    cin >>; value;
  }

  cout << endl << "Horray! You guessed the number!";

  return 0;
}

Yeah! This time we programmed a very simple game! Guess the number! Sounds cool… Right? No! Why not? At least, we can call this our first GAME! At least, we started learning game development!

Try to run that code! Is it running fine? No! What the compiler said? Oh! It looks very hard… Somewhere, in the output log, it might be written that:

'value': undeclared identifier

Now, what it means? it means that the variable, value is not known to the compiler. Just see the code. The condition in the while-statement comes before the value being declared. Solution can be this:

#include <iostream>
using namespace std;

int main()
{
  //Guess the number game!
  cout << "Enter the value: ";

  int value;
  cin >> value;

  while(value != 7)
  {
    cout << "Enter the value: ";

    //Say No to: int value; Reason: already declared above.
    cin >> value;
  }

  cout << endl << "Horray! You guessed the number!";
  return 0;
}

Even better and a very neat solution is this:

int main()
{
 //Guess the number game!
 int value;
 do {
 cout << "Enter the value: ";
 cin >> value;
 } while(value != 7); //Semicolon is needed here!

 cout << endl << "Horray! You guessed the number!";

 return 0;
}

The code in the do block is first executed even if the condition in the while is not true. Then, it will only be repeated if the condition remains true. Very simple! Also, in this way, the condition will not get the garbage value of uninitialized but declared value as the do code give some value to value i.e initializes value.

Looping plays a key role in game development. Such a loop in which program updates logic and screen of a game is called game loop. Game loop is the heart of any game. A game loop may looks like:

bool quit = false;
while(!quit) //same as "quit == false"
{
  //> > > Polling Events
  //if(quit event happens)
  //  quit = true;
  //else if(key == arrow x)
  //  move player to direction = x;

  //> > > Updating Game Logic
  //if(enemy hits player)
  // player hp--;
  //else if(player hits enemy)
  // enemy hp--;

  //> > > Updating Screen
  //clear screen
  //render enemy
  //render player
  //update screen
}

In future, we will get to this point. But for now, this is a minimal view of a general video game.

Let us talk about another home task. This time it is not a joke! Make a program that takes interview of a user having such questions that have only two answers i.e Yes or No. On the basis of Yes or No of a question, change the route of questioning. In this way, make a hierarchy or tree kind of thing. If possible, comment that code here so, that I can review it! Also, try some experiments with the code in this post and understand it. To learn something like programming, it is necessary to be interested in it…

C++ Programming Series: Using Conditional Statements (Part 4)

In the last few previous posts, we learned some of the conditional statements, user input and basic arithmetic. Now, time to use some bits of all of them in one place!

Just like if-statements, there is another conditional statement called as while-statement. Below is a very simple example of this:

while(true)
{
  cout << "Looping..." << endl;
}

When you run this code, you might be wandering that why the program is not stopping? Well, it’s because it is an infinite loop. After the while keyword, there is a condition just like that of if-statement. The code in the braces, will keep repeating itself while the condition after the while is true. Ofcourse, you got the meaning! It is just like a recurring if-statement.

We can do some interesting things with it like this:

int loopCounter = 0;
while(loopCounter < 10)
{
  cout << "Looping " << ++loopCounter << endl;
}

When we run this code, we see that the word “Looping” along with a increasing number, is printed 10 times. The increasing number starts to print from a value, 1. It will start from a value, 0, with postfix increment operator(loopCounter++). We can also do loopCounter = loopCounter + 1; or loopCounter += 1; at the end or start of the braces of while-statement.

Can you think of some program that uses while-statement along with getline(user input)? Password input! Check out the code below:

#include <iostream>
#include <string>
using namespace std;

int main()
{
  string password = "kabrakadabra";
  string entry = "NULL";

  while(entry != password)
  {
    cout << "Enter your password: ";
    getline(cin, entry);
  }

  cout << "Correct password!" << endl;

  return 0;
}

What if we want to say wrong password each time it is entered wrong! Then, below the getline, we can add:

if(entry != password)
{
  cout << "Wrong password! Please try again!" << endl;
}

Don’t you think that it’s perfect? Woohoo! we are going to be true programmers in the future, don’t we? Yes, but only if you do few experiments with it as a home task!

C++ Programming Series: Using Conditional Statements (Part 3)

In the last two previous posts, you got through the if, else and else-if-statements. The uncertain point is the difference between two if-statements and if-statement with an else-if-statement.

Two if-statements are not connected to each other. They don’t have any relation with each other. The compiler have to pass through all of these statements even if anyone of the conditions is true. Example shows three if-statements:

int value = 6;
if(value > 7)
  cout << "value is bigger than 7" << endl;
if(value > 5)
  cout << "value is bigger than 5" << endl;
if(value > 3)
  cout << "value is bigger than 3" << endl;

Output:

value is bigger than 5
value is bigger than 3

An if-statement with an else-if statement are connected to each other. If anyone of the conditions gets true, all others are skipped. Same example below with some corrections:

int value = 6;
if(value > 7)
  cout << "value is bigger than 7" << endl;
else if(value > 5)
  cout << "value is bigger than 5" << endl;
else if(value > 3)
  cout << "value is bigger than 3" << endl;

Output: (Now, there is no unnecessary outputs. It is pretty nonsense to say that value is bigger than 3 when we already said that value is bigger than 5)

value is bigger than 5

This is very important when it comes to getting user input and then, manipulating it for some change in the output. For example, there is a character variable or variable of type, char called key which takes the character (or letter) that you press on the keyboard and in return, print something for you. (Remember, put single inverted commas and not double, for a character or their variables only)

if(key == 'a')
  cout << "Alpha!" << endl;
else if(key == 'b')
  cout << "Beta!" << endl;
else if(key == 'c')
  cout << "Charlie!" << endl;
else if(key == 'd')
  cout << "Delta!" << endl;
else
  cout << "Unknown input..." << endl;

For such cases, it is better to use another conditional statement called as switch-statement. It is only good for comparison done with equality operator (i.e, ==) and numbers.

switch(key)
{
case 'a':
  cout << "Alpha!" << endl;
  break;
 
case 'b':
  cout << "Beta!" << endl;
  break;
 
case 'c':
  cout << "Charlie!" << endl;
  break;
 
case 'd':
  cout << "Delta!" << endl;
  break;
 
default:
  cout << "Unknown input..." << endl;
  break;
}

This code do the same thing as the above one. You may have figured out some of the things by yourself. But let me explain this.

After switch, we have to type in the variable in the round brackets unlike if-statement. Then, we need to put a case with the value that is to be compared with the variable. At the end of case-value pair, we need to put a colon. Then, put one to many lines of code before the ending flower bracket. What? Did we put a starting flower(or curly) bracket? No! So, that means… there is some other way to put an ending to it. The break keyword is only for switch and loop statements. It is used to skip all the codes below it and is used to skip the whole loop, not just a block (You will understand this later if not now). The default keyword is another case which acts like the else-statement and works only when all the above cases are false.

Want some shortcut to understand switch-statement? Here is the format:

switch( [variable] )
{
case [value]:
  // to be executed when variable's value is equal to that of case's value
  break;
  // ...
// [more cases]
  // ...
default:
  // to be executed when variable's value is not equal to any of the above case's value
  break;
}

Pretty long but looks useless! Nah! These are the basis of all beautiful things that you can imagine to do on the screen…