C++ Programming Series: Pointers (Part 2)

In the previous post, we learned how to get the memory address of a variable and how to define a variable that holds the memory address i.e pointer.

Suppose that there is a variable of type int called number. We initialize it with value equals to 10. Now, suppose that it has a memory address 091 (Sounds ridiculous but it’s just a supposition). This memory address is present somewhere in our device’s memory.

Some of the memory addresses are shown in the table below, along with the values present in each.

Address 090 091 092 093 094 095
Value Garbage number number number number Garbage

Now, we know that number has a memory address 091. Then, why 092, 093 and 094 are also filled with value, number? Well, just think a little on why not 095? 095 is just a garbage value!

Okay, okay! Let me clear this confusion. number is of type int and the size of int is 4 bytes. Each memory address carries 1 byte. Therefore, to fit a variable of type int, it requires 4 neighboring memory addresses.

So, number is having memory addresses, 091, 092, 093 and 094. But the only memory address that is useful to us, is the first one i.e 091. Every variable only knows its first memory address and its size. When we know the first memory address of a variable, we can easily get the value of that variable.

Now, suppose that we have a pointer of type int called pNumber. We initialize it with the memory address of the number (How to get memory address of a variable? By putting ampersand(&) behind it).

Now, the pNumber is also 091. We dereference it (i.e we put an asterisk(*) behind the pNumber) to get the value 10.

Actually, when we dereference the pointer, we are actually, looking up the memory address which in this case, is 091. Pointer of type int will suggest that whatever is present in this memory address will be the starting byte of the variable which is of type int.

Please read the above statement twice! It is a bit tricky!

To make it easy, here’s the same table:

Address 090 091 092 093 094 095
Value Garbage number —–> pNumber number number number Garbage

After looking up the memory address, pointer takes the value which in this case, is 10.

If you try sizeof() for pointer of any type, it will tell you that the size of pointer is 8 bytes (or may be different depending on your device). This is because a pointer consists memory address and memory address is a hexadecimal value. Hexadecimal values are big values! Therefore, every pointer resembles to type long int which is also 8 bytes in size.

We can manipulate with the pointers as well. We will discuss it in the upcoming posts in detail. For now, just get along with pointers and the concept described above. It should not be hard now! There is still a huge ground to cover regarding pointers…

Advertisements

C++ Programming Series: Basic Arithmetic

We discussed many things till now. We discussed about printing the variables, primitive types, user input and some conditional statements. What we should discuss right now is the basic arithmetic.

It is very simple to do primitive calculations with primitive types. We will only work with integers here. But it will be applicable to all other primitive types (of course, ‘char’ is one of them).

Addition:

int a = 10;
int b = a + 5;
cout << b << endl; //Prints 15

int c = 12;
c = c + 5;
cout << c << endl; //Prints 17

int d = a + c;
cout << d << endl; //Prints 27

Subtraction:

int a = 10;
int b = a - 5;
cout << b << endl; //Prints 5

int c = 12;
c = c - 5;
cout << c << endl; //Prints 7

int d = a - c;
cout << d << endl; //Prints 3

Multiplication:

int a = 10;
int b = a * 5;
cout << b << endl; //Prints 50

int c = 12;
c = c * 5;
cout << c << endl; //Prints 60

int d = a * c;
cout << d << endl; //Prints 600

Division:

int a = 10;
int b = a / 5;
cout << b << endl; //Prints 2

int c = 12;
c = c / 5;
cout << c << endl; //Prints 2
//For integers and characters, remainder is discarded, it is the quotient which is left.
//For floats and doubles, there is no remainder and precise division is done.
//For the above division, it will be 2.4 for floats and doubles.

int d = a / c;
cout << d << endl; //Prints 5

I hope that you might have understood all primitive calculations. One can understand it easily if he/she knows algebra. I will not tell you what is algebra because it is not the purpose of this place. Just Google it if you don’t know. However, there are some short hand methods to some of them, which are really useful. Following are those methods:

int add = 10;
add += 5; //equivalent to "add = add + 5;"

cout << add << endl; //Prints 15

int sub = 10;
sub -= 5; //equivalent to "sub = sub - 5;"

cout << sub << endl; //Prints 5

int mult = 10;
mult *= 5; //equivalent to "mult = mult * 5;"

cout << mult << endl; //Prints 50

int divi = 10;
divi /= 5; //equivalent to "divi = divi / 5;"

cout << divi << endl; //Prints 2

There are two more methods that are very confusing but produces neatness in one’s coding style.

int a = 10;
a++; //equivalent to "a = a + 1;" but with some exceptions
++a; //equivalent to "a = a + 1;" but with some exceptions

cout << a << endl; //Prints 12
//Similar is for subtraction

The first one (a++) is called as postfix increment operator and the other one (++a) is called as prefix increment operator. They are not the same and are very much confused with each other. Similar is the case for postfix and prefix decrement operators (i.e, a--, --a). This can be proved by the code below:

int print = 25;

//Method 1.
//cout << print = print + 1 << endl; //This gives error and so, is not possible.

//Method 2.
cout << print++ << endl; //Prints 25

//Method 3.
cout << ++print << endl; //Prints 27

Awww… What’s that? It’s a strange looking code! But let me explain all this. Both postfix and prefix increment and decrement methods can be placed with variables in a complete C++ code sentence as well. Same is not true for a = a + 1; or a = a - 1;. In the 2nd method, print is first printed out and then, incremented by 1. So, it prints 25 and then, its value is changed to 26 i.e print = print + 1; is done after being printed. In the 3rd method, print is first incremented by 1 and then, is printed out i.e print = print + 1; is done before being printed (Remember, 2nd method already changed its value to 26 and so, in 3rd method, 27 is printed out). The equivalent code to this is given below:

int print = 25;

//"cout << print++ << endl;" is equivalent to
cout << print << endl; //Prints 25
print = print + 1;

//"cout << ++print << endl;" is equivalent to
print = print + 1;
cout << print << endl; //Prints 27

There is another thing. We can have remainder instead of quotient, in dividing numbers by a special operator called as modulo operator, represented by %.

int a = 14;
int b = 5;
cout << a / b << endl; //Prints 2, we can do temporary calculations and print them.
cout << a % b << endl; //Prints 4 which is the remainder obtained by dividing a by b.

a %= a; //a is now, 0.
b %= 3; //b is now, 2.

This post is too lengthy to explain all basic arithmetics in C++. But length don’t matters! It is your motivation and inspiration that matters!

C++ Programming Series: User Input and Comments

I am too busy last month! Sorry for such a big delay!

In the previous post, we talked about user input. Well, there’s no post about user input until now.

A very simple user input program is given below:

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

int main()
{
  cout << "Enter your name: ";

  string name;
  cin >> name;
 
  cout << "Your name is " << name << "." << endl;
 
  return 0;
}

This program will get the input from us and then, outputs our input. There are many new things to notice:

  • This time, we also included string in our program. String is nothing special, just a group of characters with some useful functions(we will discuss it later, in detail). The only point to get in our minds is that, string is not a primitive type. Just like including string allows us to use strings in our program, including iostream allows us to use cout, endl and cin.
  • endl is not important for using cout. endl can be used anywhere after cout << and is used to skip the present line.
  • cin is the standard method for getting input from user. Once you typed the input, you need to press enter to proceed. For output, we use << and for input, >>.

In the same way, you can input integer. Integer is not a group of characters so, trying to assign an integer, group of characters will give us nothing.

Are you facing some problems? Try to input more than one words like: ‘Robo Tex’. Is there some problem with the output? Here’s the output:

Your name is Robo.

Where’s Tex? The problem is that cin ends when a space comes in its way! Instead of cin, we can use getline:

cout << "Enter your name: ";

string name;
//cin >> name;
getline(cin, name);
 
cout << "Your name is " << name << "." << endl;

This will solve the problem. cin takes a word from input buffer whereas getline takes a line from input buffer. In the getline, you have to specify at least two things. First one is the input method which is cin and the second one is the variable to be filled with input.

Have you noticed that //cin >> name; is not doing anything in the code? This is a single line comment. Whatever is after double slashes, it will not be checked by compiler and will only affect that line. For making multi-line comments, use /* and */. The code between /* and */ is not considered by the compiler.

Commenting never influences the performance of a program. It is used in order to make notes with the code, describe the code for an easy understanding and removing the codes temporarily from the program. It is very useful and so, we will use it so much!

Example of a single line and multi-line commenting:

/*This is a
multi-line comment.
Following code takes a line from input buffer:
*/
cout << "Enter your name: ";

//Getting input.
string name;
//cin >> name;
getline(cin, name);
 
//Outputting the input.
cout << "Your name is " << name << "." << endl;

cin and getline requires pressing enter to shift input to the variable. You can have input without pressing enter by using getch which takes a character from input buffer and also removes that character from the screen unlike cin and getline. We must include conio.h to use getch in our program just like string.

With other includings (e.g iostream), #include <conio.h>

In the main function, (i.e in the flower brackets below int main())

cout << "Enter a character..." << endl;

char input;
//cin >> input;
input = getch();
 
cout << "Character: " << input << endl;

We can do many fun stuff with user input and conditional statements together. But for now, this is it!

Note: We can use string type without including string. This is because it is also in the iostream. But we can’t use it with cout unless we include string.

C++ Programming Series: Primitive Types

In the previous post, we discussed variables and a primitive type called as int. Primitive types are the basic types from which other complex things are derived. Like int, following are some other primitive types.

int int_var = 10;
char char_var = 'b';
bool bool_var = true;
float float_var = 24.12f;
double double_var = 248.123;

They have different sizes and they are calculated in bytes which is a term defined for measuring memory in computers. To find out the size of any type or variable, we can use sizeof().

cout << sizeof(int) << endl;
cout << sizeof(bool_var) << endl;
cout << sizeof(float) << endl;
cout << sizeof(double_var) << endl;

Size of int is 4 bytes, char is 1 byte, float 4 bytes and double 8 bytes. They have some value limits as well. For more information, click here.

char is the short form of character, stores a character and bool is the short form of boolean, can only have anyone of the two states, true and false.

float and double allows us to be precise in calculations. The latter one is more precise than the former one. float can have maximum of 7 decimal places whereas double can have maximum of 15 decimal places.

It is always better to use lesser memory or bytes of a computer. int is the most used variable type but it may be a waste if you just want to have it in a very small range of numbers. You can use short or long to increase or decrease the amount of memory allocated by it. For instance, if value of a regular int gets much greater than the limit, use long to have a much greater limit.

short int small_int = 20000;
long int large_int = 20000000;

By default, variables can have positive as well as negative values. There are many cases when negative values are not needed at all. Such variables having both positive and negative values are called as signed variables and those having positive values only are called as unsigned variables.

int i_am_signed_int1 = -100;
signed int i_am_signed_int2 = -250;
unsigned int i_am_unsigned_int3 = 500;

short, long, signed and unsigned aren’t only used with int but can also be used with some other primitive types.