Home Classroom C++



[You're Ted and you decide to learn some C++ from your friend Barney. This is the eleventh day of the class]

You: Hi, Barney!

Barney: Hi, Ted! You’re real late today.

You: Got a little late. Life’s problems, you know.

Barney: That ain’t a good excuse. Never mind. So what were we doing last time?

You: Mm, we talked about character sequences and you told that we’ll be learning about strings today.

Barney: Fine. First of all, do you know what a string is?

You: A sequence of characters?

Barney: Exactly! The character arrays we talked about last time could also handle such sequences. What do you think is the difference between a normal character array and a string?

You: Mm, not exactly sure, but I think strings are more powerful than usual character arrays.

Barney: Of course. When you deal with arrays, it’s quite difficult to handle them, especially when it comes to characters. The string library has made manipulating character sequences easy. For this, there is a separate data type called ‘string’. Let’s look at an example:

You: So we have to include ‘string’ to use strings?

Barney: Yes, but in some compilers it will work without that too. But it’s safe to include that.

You: Okay.

Barney: As you can see, we have declared a string s and assigned it with the string “Hello there!”. And then we simply printed it. Ain’t that easy?

You: Yeah, so far so good.

Barney: What we saw was a simple string constructor. A constructor is how you initialize a data type, object, etc. There are more than one way of constructing a string, but for the time being, the method we saw will do. Okay, now that we have a string, what kind of things do you think that we may need to do with it?

You: Mmm, to know what the first letter of that string is and to know how many letters there are in that string, etc?

Barney: Yes. For each of the ones you mentioned and many other useful operations there are simple methods in strings. For example, if you need to get the first letter of a string, you consider the string just as an array. So if you want to get the first letter of the string s you would simply..?

You: Type s[0]?

Barney: You’re a real fast learner Ted! Proud of you.

You: Lol

Barney: Right, so you understand that we can access any character in a string like in an array. Now, the second thing you mentioned was finding how many letters there are in a string. For this, the method is simpler. The statement s.length() will give you the length of s.

You: But why the two brackets?

Barney: If you remember correctly, we used such double brackets somewhere else during our journey.

You: Yes, in functions.

Barney: Yes, and there are such functions defined in the string library. Length() is one of them. It returns the length of the string with which you used it. Let’s look at a simple example:

You: I see. It seems strings are very powerful.

Barney: You still haven’t seen the real power of strings. There are several other functions you can use to manipulate strings. Suppose you need to attach one string to the end of another string. What do you think is the way to do that?

You: Mm, supposing the two strings are α and b, we can do something like α=α+b?

Barney: Exactly! It’s as simple as that. Or you can use the append function in the strings library. For example, a.append(b) will do the same trick you just did.

You: I see.

Barney: Now suppose you need to erase some characters off the string. There’s a simple erase function for that. What do you think the statement a.erase(2,5) will do?

You: Erase the characters from 3rd to the 6th?

rd character, 5 characters will be erased.>

You: Ah, okay.

Barney: The command erase has yet another syntax. Suppose you need to erase the characters of the string starting from the 3rd character and until the 3rd from the last. What will you have to do?

You: We can get the length of the string using the length() function we discussed earlier and take away… mmm… 6 from that value and get to know the number of characters we have to delete?

Barney: That’s one possible way. There’s another easier method. You can do the same thing by the statement α.erase(α.begin()+3, α.end()-3).

You: What are those begin and end for?

Barney: They’re called iterators. They give the positions of the first and last characters of the string respectively. So you can understand what that statement does, can’t you?

You: Yes, I get it.

Barney: Good. Now suppose you need to insert some characters into the middle of some string. The function insert comes to the rescue. Its syntax as simple as originalstring.insert(starting pos, string to insert). Let’s look at an example.

As you can imagine, the output of the above is,

You: Hmm, nice.

Barney: So this is only a start. We discussed only a handful of functions we can use to manipulate strings. There’s a lot more functions which you can find in the internet. For example, http://www.cplusplus.com/reference/string/string/ has a listing with explanations and examples. The next time we meet, let’s write a really useful program using what we learned about strings.

You: Okay, thanks a lot. Bye Barney!

Barney: Bye, Ted! By the way, don’t get late the next time!

You: Sure!


Characters and their arrays

[You're Ted and you decide to learn some C++ from your friend Barney. This is the tenth day of the class]

You: Hi, Barney!

Barney: Hi, Ted! I was waiting for you.

You: I was a bit late, had some homework to do.

Barney: Oh, I know the kind of homework you do, he he. Anyway, where did we stop last time?

You: We discussed about arrays for two days.

Barney: Ah, yes. Then, enough of arrays. Now that you know how arrays operate, let’s talk about characters and their arrays, or strings, as we usually call them.

You: Okay.

Barney: So you know what a character is?

You: I think I do. It’s a single letter like ‘a’ or ‘b’, right?

Barney: Yes, not only letters, digits, punctuation marks like dots, commas, and special symbols, all of these belong to the set of characters. In fact the ASCII system has 256 characters in it.

You: Yeah, I’ve heard of that.

Barney: Good. We use the ‘char’ data type to identify characters in C++. Let’s see how they work from an example. Suppose you need to write a program where you need to do something and then prompt the user to ask whether he needs to do that again. If the user says yes, the process will be repeated. Let’s write a program that gives the two times of a given input.

You: He he, that’s a nice thing to program.

Barney: Just for the sake of exploring the use of ‘char’. First we ask the user to input an integer and we double it and print it in the screen. It’s as simple as this:

cout<<“Enter a number: “;
count<<“Two times”<<a<<” is “<<(a*2)<<“\n”;

You: Okay.

Barney: Right, now the problem is how to ask the user to enter a value. We can use ‘cin’ for this. Also we can check his input using an ‘if’ condition. But we have to repeat the above code after that. How can we achieve that?

You: By using a loop, perhaps?

Barney: Exactly! We can use a while loop to do that. Let’s see how.

cout<<“Do you want to continue [Y/N]? “;
} while (c==‘y’ || c==‘Y’);

You: I see, it’s not that difficult. That ‘c’ should be declared as a ‘char’, right?

Barney: Of course. Let’s now complete the program:


using namespace std;

int main()

int a;
char c;
cout<<“Enter a number: “;
cout<<“Two times “<<a<<” is “<<(a*2)<<“\n”;

cout<<“Do you want to continue [Y/N]? “;
} while (c==‘y’ || c==‘Y’);

return 0;


And let’s see if it works:

You: Hmm, works as expected.

Barney: Yes. That’s about chars. Now let’s talk about sequences of characters. We can define them using character arrays like this:

char name[]={‘d’,‘i’,‘g’,‘i’,‘t’,‘\0′};

You: But what’s that ‘\0’ thing at the end?

Barney: It’s called the null character. It signals that the character sequence ends there. Otherwise compiler doesn’t know where to stop. You’ll understand it more when we deal with pointers.

You: Okay.

Barney: For now, keep in mind that you have to add the null terminator when you declare character arrays like that. After assigning such an array we can print the whole word like this:


You: I see. So you need not print character by character?

Barney: Of course not. But declaring strings in the above way is hard work. We can simplify this by using double quotes like this:

char name[]=“digit”;This one does the same job as our previous statement.

You: But what about the null character?

Barney: When you put double quotes, the null character is automatically appended. We call this adding the null character ‘implicitly’. In the former method we put it ‘explicitly’.

You: Okay.

Barney: Let’s see how to use such a character array in a program. Let’s write a program which asks the user to input his name and prints it back and mention the second letter in his name:


using namespace std;

int main()

char name[50];

cout<<“Enter your name: “;
cout<<“Your name is “<<name<<” and the second letter in your name is”<<name[1]<<“\n”;


return 0;


You: But why name[50] instead of name[] ?

Barney: As in usual arrays, name[50] tells that the maximum number of characters we store in ‘name’ is 50. Of course it can be lesser than that, but not more.

You: I see. Shall we run it and see?

Barney: Go ahead.

Barney: He he, you know that name is banned in here these days.

You: Yeah, yeah, it’s the trending topic these days ne ;)

Barney: Alright then, that’s a brief introduction to character arrays. The next day we’ll talk about strings, and the string library functions C++ provides for us.

You: Okay, thanks. Bye Barney!

Barney: Bye, Ted!


Arrays – Part 2

[You're Ted and you decide to learn some C++ from your friend Barney. This is the ninth day of the class]

You: Hi, Barney!

Barney: Hi, Ted!

You: So what are we going to do today?

Barney: Last time we talked about arrays, right?

You: Yeah, arrays.

Barney: And we didn’t talk about multidimensional arrays?

You: Mmm, nope.

Barney: Well, then, what do you think multidimensional arrays are?

You: Arrays with more than one dimension?

Barney: Exactly. The arrays we talked about last time had only one dimension. That is, they go only in one direction. But we can have arrays with several dimensions. We have to use two dimensional arrays in most of the programs. A two dimensional array is just like a table, it has rows and columns.

Suppose we want to store prices and taxes of several items in our program:

Price Tax
Item 1 120 12.5
Item 2 200 17.5
Item3 60 17.5
Item 4 150 7.5

How would you store these if you use the arrays like we did last time?

You: Mm, we can make one array with prices and another array with taxes.

Barney: Right. If there were more columns in the table, we’ll have to create more arrays. This is where 2D arrays come to help. Let’s see how we can declare a 2D array in the above scenario.


double data[4][2];


Here, data is the name of the array. The next two arguments tell that it has 4 rows and 2 columns.

You: Ah, I get it. But how can we assign the values to the array?

Barney: It’s like this. You assign the values row by row. We have 4 rows here. We consider them as 4 separate arrays, and we join them to build a 2D array like this:


double data[4][2]={{120,12.5}, {200,17.5}, {60,17.5}, {150,7.5}};


You: I see. How do you access them afterwards?

Barney: It’s simple. If you want to access the tax of item 3, that is third row’s second value, we can use:




You: 2 and 1? Not 3 and 2?

Barney: Remember, arrays, as we talked last week, are zero-based. The first element is zero, the second one, and so on.

You: Ah, yes, I forgot. I understand now. So if you want the first row’s first column you may enter data[0][0]?

Barney: Exactly. Let’s write a small program to calculate the final price of each item:

Can you understand what the program does?

You: Mmm, it first declares the 2D array and assigns values. Then there’s a loop which will run 4 times from 0 to 3. In each turn, it computes the final price from the data in the array and display them. Is that it?

Barney: Exactly. Let’s run and see the output.

You: I see.

Barney: You can use for loops to process the elements in arrays. When we use loops to manipulate 2D arrays, we need to put one loop inside another, like this:


for (int i=0; i<5; i++) { for (int j=0; j<12; j++) { // //Do sth with array[i][j] // } }


We call a loop that lies inside another a loop, a subordinate loop. With such loop structures, manipulation of large arrays become real easy.

You: Hmm. So we can make arrays with more than two dimensions?

Barney: Definitely. We come upon such arrays from time to time. But 2D arrays are the most popular.

You: Okay.

Barney: Now let’s write a program that actually uses arrays. Suppose you want to let the user input several integers and find its maximum. We write a program like this:

Now, Ted, try to explain the program.

You: Okay. First we declare an array called marks with length 5. Then we run a loop to let the user enter values to that loop one by one. Then..mm..

Barney: Yes, we declare a variable called max and assign the first value in the array to it. What the next loop does is it iterates over the other elements of the array to find values greater than the current value in max. When it lands upon such values, it assigns that new value to max so that it can check for higher values.

You: I see, I see. At the end of the loop, the variable max should contain the maximum value in the list. Fantastic!

Barney: Yes, let’s run the program and see.

You: Yeah, works the way we expected.

Barney: In fact, to get the maximum use of any programming language, one has to master the concept of arrays. And the best way to do that is to write many programs by yourself using arrays. So I think that’s it for today. See you next time!

You: Okay, I’ll try to write more. Thanks, Barney! Bye!

Barney: Bye, Ted!



[You're Ted and you decide to learn some C++ from your friend Barney. This is the eighth day of the class]

You: Hi, Barney!

Barney: Hi, Ted! I was waiting for you.

You: Great! What shall we be doing today?

Barney: Now that we’ve almost done with functions, let’s turn to arrays today. Suppose you have to store the marks of hundred student in your program. What would you do?

You: Mmm, let’s see. Okay, I have to store them in variables.

Barney: And how much variable do you need?

You: Oh, I need hundred, don’t I?

Barney: Exactly. But is that method fine?

You: Oh, no! Declaring hundred variables is tragedy!

Barney: Certainly, and that’s when arrays come to the rescue. In short, you can store many values inside a single variable by making the variable an array. Suppose we define an array called marks with a length of 100. Then this array can handle 100 values, and we call these marks[0], marks[1], up to marks[99].

You: And what about marks[100]?

Barney: This array has 100 elements and it starts from 0. So it should end at 99. In other words, every array starts with 0 so if its length is n then its last element should be n-1.

You: Ah, okay, I get it. So this array can hold hundred values of any type?

Barney: No, when we declare an array we must specify the data type its going to hold too. Let’s see this in a small program.

You: Hmm, defining an array seems to be so complex!

Barney: No, of course not! Actually we have done several things in one line, that’s why it may seem complex. To define the array with five elements, we’d have simply used

int marks[5];

But here, after defined that we have also assigned five values to the elements of the array. We include the values to be assigned to the array inside curly brackets, and these elements should be separated by commas.

You: Ah, right, now it’s clear.

Barney: Okay, so what do you think the program would output?

You: Mmm, marks[1] should mean the second value in the array, so it should print 56.

Barney: Yes, let’s see.

Good! Let’s expand our program to see the real benefits of using arrays. Suppose we want to take the sum and the average of the marks. How are we to do that?

You: We should add the numbers and divide by 5.

Barney: Yes, but this becomes quite easy when using arrays. We can use loops to manipulate them, you see?

You: How?

Barney: Let’s write a program and find out:

You: Ah, yes, I see. You can address the whole array in a single loop.

Barney: Exactly. When array operations are combined with loops the whole thing becomes quite efficient. Now let’s see what the output is.

You: Oops! The average is not right, is it?

Barney: Yeah, and why do you think it has gone wrong?

You: I have no idea.

Barney: Well, consider the statement avg=sum/5; Here, the variable avg is a double but sum is an integer. So when the program is run, the statement sum/5 evaluates to an integer. This can be corrected by casting the variable sum to a double. We will learn more about casting some other day. Until then, just keep this in mind. We have to change that line to:

The variable sum is casted into a double by adding (double) before it. Now let’s see the output:

You: Ah, now it’s okay.

Barney: Yes. I’ll teach you about casting another day.

You: Okay, and now I have to be going. Have to pick my sister from a class. Thanks Barney!

Barney: No problem, Ted. Bye!

You: Bye, Barney!


More on Functions

[You're Ted and you decide to learn some C++ from your friend Barney. This is the seventh day of the class]

You: Hi, Barney!

Barney: Hi, Ted! How are you?

You: Fine as always! And you?

Barney: Never better! So what were we doing last time?

You: Mm, we wrote some functions and you said we will be discussing about global variables this time.

Barney: Ah, yes, we did write two programs using both global and local variables, didn’t we?

You: Yeah, and the one with global variables seemed easier.

Barney: Well, Ted, it may seem easy at first, but when you go deeply into programming global variables can be a real mess. And do you know why? Global variables have the vulnerability of being possibly changed by a function or code anywhere in the programme, so when something goes wrong while debugging it becomes a hell of a work to find out where the bug comes from, because it may have arisen from anywhere.

You: And with local variables?

Barney: And with local variables, since they are only limited in scope to the function they’re declared in, debugging would be limited to that function. Usually we don’t want our variables to be interfered by outside forces.

You: But how can we possibly mess up with the variables when we’re quite aware that we’ll be messing up if we changed the values in a bad manner?

Barney: That’s only when you’re writing the whole programme, buddy. Possibly different functions may be written by different people and when each other does not exactly know the behavior of these variables it can become a real mess.

You: Ah, I get it.

Barney: Okay, so let’s see about assigning default values to the parameters of a function. These default values are used when the person who calls the function does not send enough parameters to the function. Today we will be using the VI editor in Linux, instead of Visual Studio we used in Windows. VI is one of the coolest text editors you can use in Linux.

You: Aren’t there IDEs like Visual Studio for linux?

Barney: Of course there are, like Code::Blocks, Anjuta, NetBeans and Eclipse and even other sophisticated text editors like Emacs. But I personally prefer VI.

You: Okay

Barney: Look at this programme:

See how the value of b is set to 1 in the function? So in the main function, when the user does not pass a second value to the function, it automatically assigns 1 to b.

You: So the answer to multiply(3) will be 3 itself?

Barney: Exactly. Let’s run and see:


You: Yeah.

Barney: Okay. In this programme we could only multiply integers. What if we also want to multiply doubles as well?

You: Mmm, may be we’ll have to write another function for that.

Barney: Yes, but there’s a way to avoid writing duplicate functions for this by using a type called templates. But this is a rather advanced topic so we’ll deal with that later on. However, there’s another interesting technique called operator overloading which lets us write several functions with the same name and parameters but different data types for those parameters. Let’s write one first and you’ll understand this. Let us expand our previous programme like this:

You: So how does the compiler know what function to call when multiply is called?

Barney: The compiler looks at the data types of the parameters passed. If they’re integers it will call the first function and if they’re doubles the second one will be called. What will happen if the parameters belong to none of these types?

You: Compile error?

Barney: Yes, an error will be given because there are no functions with a signature similar to the given syntax. Let’s see the output of this programme:

That wasn’t that difficult, wasn’t it? Hope you don’t need any more explanation on operator overloading.

You: Yeah, it’s crystal clear.

Barney: Good. Now that you know how to handle basic functions, let’s write a programme that actually uses them.
This will be a daunting one at first, but if you observe the functions separately it’s very simple.

You can see how all the big work is broken into small functions and the main function merely controls them.

You: Wow, it seems writing functions can really simplify the things!

Barney: Yeah, try to write some by your own. So let’s meet again next time!

You: Okay, thanks a lot! Bye, Barney!

Barney: Bye, Ted!



[You're Ted and you decide to learn some C++ from your friend Barney. This is the sixth day of the class]

You: Hi, Barney!

Barney: Hi, Ted! I was waiting for you.

You: I was a little late. So what shall we be doing today?

Barney: We’ll be discussing about functions today. Take a seat.

You: Thanks!

Barney: You see, Ted, all the programmes we wrote until now were stuffed inside the main method. But when our programmes become complex, this main method may get too long and too difficult to handle. What would you do to prevent your programme getting too long?

You: Mmm, break it into parts?

Barney: Exactly. When we break a programme into parts or “modularize” it, everything becomes easy to handle. One way to modularize our programmes is to break them into functions. There are two kinds of functions, built-in ones and user-defined ones. Built-in functions are provided by C++ libraries, we’ll get to know them as we progress. For now let’s consider about the user-defined ones.

You: Okay.

Barney: Functions are meant to perform some action specific to them. For example, say we have to write a function that would give you the square of a number. What data does the function need to calculate the square?

You: The number, of course.

Barney: Yes, we have to “pass” the number to the function as a “parameter” and the function would “return” us its square. The syntax of a function is as follows:

return_type function_name (parameters) {


You: Hmm, that’s a pretty complex syntax to have.

Barney: Not after now. Let’s write a sample function, one that would return the square of the input parameter.


You: Okay, you’ll have to explain me that from top to bottom.

Barney: It’s like this. First, you mention the return type. Since we’re going to input an integer into the function, the return type would also be an integer. Next comes the function name “square”. You can choose any name you want here, just like in variables, but make sure you choose a descriptive name. What do you call the “int x” part within the brackets?

You: The parameters?

Barney: Yes, in this case there is only one parameter. If there were more, we would have to separate those using commas. So this ends the “header” of the function. Next is the body of the function. And that is where the actual function statements go.

You: Okay, I think I understand what the body part does. It assigns the square of the given value to an integer and returns that value.

Barney: Yes! You’re really smart! This function is only a part of the programme. Let’s write a complete one with this. Functions are written outside the main method, like this:

Let’s run it and see:

You: Hmm, works fine.

Barney: Note that in our function we used:

However we could have achieved the same thing from a single statement, like this:

You: Ah, yes.

Barney: Okay, so let’s move ahead and write another function that would take two integers as parameters, or “arguments”, and returns their multiplication. Can you do it by yourself?

You: Let me try.

Barney: Wow! You’re a real fast learner! Well done! Let’s put this in a complete programme, too. This time we will put the function at the end of the programme. This is done usually because if there are a lot of functions, it would become difficult to read the code. However, even if you place your functions at the end, you must mention their “signatures” at the beginning of the programme.

You: Signatures?

Barney: Yes, the headers of the functions. Take a look at this example:

You: Ah, I get it. By the way you put a semicolon to the end of the signature?

Barney: Yes, that’s because we’re only declaring how the function behaves at the signature. Also note that unlike in the previous example, we have called the function in the same line we are printing it. This does not actually matter: we need not assign the return value of the function to a variable because we’re not gonna use that again.

You: Okay.

Barney: So let’s write another programme with more than one function and using floating point numbers.

You: Mmm, yes, but still I’m not confident about the variables thing here. Why do you have “double r” declared at main and both the other two functions?

Barney: That’s because once you declare a variable inside a function, it becomes “local” to that function, that is the other functions cannot access that variable. The three r’s in the three functions (you know, main is a function, too) are different. However, we could have used a single r in the whole programme like this:

Here, r is a global variable because it’s been declared outside the functions, so it can be used by all the functions.

You: So why don’t we always declare global variables? Doesn’t it easier than declaring them over and over again?

Barney: Well, it may seem that using global variables is quite easy, but that is not actually the case. Let’s see why next time.

You: Okay, thanks Barney! Bye!

Barney: Bye, Ted!


Switch – case


[You're Ted and you decide to learn some C++ from your friend Barney. This is the fifth day of the class]

You: Hi, Barney!

Barney: Oh hi, Ted. How are you doing?

You: Great! And you?

Barney: Not bad at all. Come along. Let’s continue with our C++. So, where did we stop last time?

You: Mmm, we finished loops.

Barney: Ah, okay. Did we talk about the switch-case structure?

You: No.

Barney: Alright, let’s have a look at that today. I’m a bit busy today so today’s lesson will be a bit short. The switch-case structure is used to make decisions, just like the if-else statements. Its syntax goes like this:

switch (expression) {

    case const1:



case const2;







You: Oh, that’s real greek!

Barney: You think so? Not after the next example. Let’s write a programme to illustrate this.



using namespace std;

int main()


int num;

cout<<”Enter a number: “;



switch (num) {

case 1:

cout<<”That’s one!”;


case 2:

cout<<”The smallest prime!”;


case 3:case 4:

cout<<”Less than 5″;



cout<<”That’s an odd number to think about!”;




return 0;


You: Hmm, isn’t it something like that if-else thing?

Barney: Exactly. Switch-case does exactly what the if-else does. This programme outputs “That’s one” when num is equal to one, “The smallest prime” when num is two, “Less than 5” when num is 3 or 4, and “That’s an odd number” for any other value of num.

You: Right, but I don’t think I still get how it has been done.

Barney: Alright, let’s go step by step. First the user is prompted to enter an integer. Next we ask the compiler to switch to num. What do you think that means?

You: May be we’re asking it to consider the variable num?

Barney: Exactly. We’re telling it that the following statements will have to deal with the value of num so take note of it. Then we break down the cases. How many cases do you see here?

You: Mmm, three, four?

Barney: Five, to be precise. It’s like this. The first case activates when num is equal to one, the second when num is two. When we want several cases to do the same thing we group them as in

case 3: case 4:

We can add more to this list, of course, like:

case 3: case 4: case 5: case 6:

and so on. And when none of these cases are satisfied the default case is activated.

You: I still don’t completely get it. What are these break statements for?

Barney: Suppose the user enters 2. Then when the compiler enters the switch statement it sees that the case 1 is not satisfied, so it skips it. Then it finds that case 2 is satisfied, so it starts executing the commands under it. When it lands on the break statement it exits from the switch structure. Otherwise, it will keep executing the next commands as well.

You: Ah, okay. Then we need to put a break at the end of every case statement?

Barney: In most cases, yes. But there may be situations when you want to execute the rest of the structure, too, so keep that on mind.

You: And the default case is like the else in the if-else structure?

Barney: Exactly. It is executed when no other cases are satisfied. However it is not compulsory to add a default case.

You: Okay, it’s somewhat clear now. Can we check characters with switch-case?

Barney: Of course! Let’s try an example. This will be a little tricky, so try to understand properly.



using namespace std;

int main()


char c;

int n=0;

do {

cout<<”This is a loop. Do you want to continue [Y/N]? “;


switch(c) {

case ‘Y’: case ‘y’:


case ‘N’: case ‘n’:






} while (n<1);


return 0;


You: It doesn’t seem that difficult. This will keep repeating until we press N, right?

Barney: Yeah, you’re catching up fast! Let’s run it and see.


You: Hmm, exactly as I imagined. So can we use this swich statements to compare strings?

Barney: No, it’s not a good idea to compare strings with this. When we are learning strings we will see how to handle them. And we should not compare floats and doubles also with switch.

You: Why is that? Aren’t they just numbers?

Barney: These are called floating point numbers. We usually don’t “equate” them. That’s because you can never be sure that a floating point number will be exactly some value. In most cases they are “around” and “close” that value.

You: Okay, then. Just asked.

Barney: Alright, let’s wind up for today now. Next day’s lesson will be a big one. So don’t miss it!

You: Aniwaa! Thanks a lot! Good bye, Barney!

Barney: Good bye, Ted!





[You're Ted and you decide to learn some C++ from your friend Barney. This is the fourth day of the class]


You: Hi, Barney!


Barney: Hi, Ted! What’s up?


You: Don’t tell me that you weren’t expecting me to show up for the C++ lesson today!


Barney: Oh, almost forgot that. I was busy reading the novels I bought at the book fair. Bought some romance this time. So, so, what were we doing last time?


You: Mmm, we learned how to get the user input and how to use the if-else statements.


Barney: Okay, good. Then we will see how to use loops today. Computers become really useful when we want to repeat things over and over again. We will have to repeat certain instructions ten or fifteen times, and sometimes a million times, and even infinitely.


You: Infinitely?


Barney: Yes, in certain instances we have to run the programme indefinitely, may be until a certain event happens. That is when we need to use infinite loops. We’ll see how to code them soon.


You: Okay.


Barney: We call these repetitions loops in programming terms. There are three main kinds of loops. The while loop, the do-while loop and the for loop. Let’s first deal with the while loop. It’s syntax is like this:


while (condition) {

// statements



You: Oh, you’ll have to explain me this.


Barney: It’s simple. The compiler looks at the condition we have given, and executes the statements within the curly braces repeatedly until the condition becomes false. Let’s try an example.




using namespace std;


int main()


int n=0;


while (n<5) {





return 0;



You: Oh, that seems greek to me!


Barney: Only for now. Let’s run the programme and see first.

You: Hmm, that’s pretty interesting. How does that happen?


Barney: It’s like this. You have written a while loop that would run while n is lesser than 5. At the beginning n is set to 0 so the loop would run. First it will print 0 and the value of n is incremented. Now the loop checks the condition again and finds n is still less than 5. So the statements inside the loop are run again. This will repeat until n’s value is set to 5, when the loop will eventually stop.


You: Oh, I see, that’s wonderful!


Barney: The best things are yet to come. We have incremented n by one in this programme. Incrementing and decrementing variables by one is something we always have to do in our programmes. There are two more ways we can write the above incrementing statement.






All these above statements are equivalent, they increment the value of n by one.


You: But the last one seems more convenient.


Barney: Yes. We almost never use the first statement. When we want to increment by one we almost always use the third option.


You: Then what about the second one?


Barney: The second one comes handy when we need to increment by a value different to one. For example, we can increment n by 5 by using:



You: I see.


Barney: And there is one more variant in incrementing. We could also ask the variable to increment like this:


To see how n++ and ++n work differently, let’s try another programme. Or, rather, let’s change our current programme like this:




using namespace std;


int main()


int n=0;


while (n<5) {




return 0;




What will happen?


You: Mmm, let’s see. N is printed and it is incremented. Perhaps it gives the same output as before?


Barney: Exactly.

This happens because n is incremented after it is printed in the screen, just as our previous programme did.

Now suppose we replaced it with ++n instead. What will happen now?


You: Wouldn’t it give the same result? Well, it will depend on whether n is incremented before or after n is printed, won’t it?


Barney: There! You get it! Yes, in ++n, n is incremented before anything happens. Let’s see what happens.

You: Hmm, exactly what I expected.


Barney: Yeah, it won’t need any explanation. Consider this programme:




using namespace std;


int main()


int n=5;


while (n<5) {




return 0;



We have set the initial value of n to 5. What will happen?


You: Mmm, now that the condition is not satisfied at the beginning, the loop won’t run?


Barney: Yes, since the while loop initially checks whether the condition is true or false, the statements inside the loop won’t be executed. However, there are certain times when you want your loop run at least once, no matter whether the condition is satisfied or not. This is when we’re going to use the do-while loop. It has a syntax like this:


do {


} while (condition);


As you can see, the statements are executed once first and then the condition is checked. If the condition is true, the loop will keep repeating until it becomes false. In this way, we can assure that the statements inside the loop are executed at least once. Let’s try an example:




using namespace std;


int main()


int n=10;


do {


} while (n>5);


return 0;



We have used the decrement operator – here. It works similar to the increment operator, except for the fact it reduces one from the variable. So, Ted, what do you think would be the output of this?


You: Well, n is 10 at the beginning. 10 is printed first, and decremented. Now n is 9. The condition is true. So the loop repeats. It should stop once n becomes 5. But by then 5 would not have printed. So the programme should print from 10 to 6.


Barney: Let’s see what happens:




Yes, you’re correct. This programme didn’t make much difference. We could have obtained the same from the while loop. Now suppose initially n was set to 0. What would have happned?


You: Sure enough, it would print 0 and terminate, because the condition is checked only after the statements are run for the first time.


Barney: Yeah, that’s how it works. Seems you understand thedo-while loop really well. By the way did you notice the semicolon at the end of the loop?


You: Oh, saw it only now. We didn’t use one in the while loop, did we?


Barney: Of course we didn’t. The do-while loop is not ending with curly braces so we need to tell the compiler that the line ends there by using the semicolon.


You: I get it.


Barney: Right, the next and final type of loop we’re going to look at is the for loop. It has a syntax similar to this:


for (initialization; condition; increment) {




You: Oops, that seems to be complex than the other two.


Barney: It may seem so, but it’s actually pretty simple. We’ll see about that in an example first.




using namespace std;


int main()


int n=0, i;


for (i=1;i<=10;i++) {






return 0;


You: Oh, you’ll have to explain me that from the beginning.


Barney: It’s like this. First you declare two integers n and i and initialize n to zero. Then comes the for loop. We’ll better understand that if we split that into parts and see. Can you split the statement inside these brackets according to the syntax?



Initializer: i=1

Condition: i<=10

Increment: i++

Is that it?


Barney: Yes. As you can see, now the loop seems simpler than before. The initialize initializes i to one. The condition is i<=10 so the loop will run while is lesser than or equal to 10. The increment is i++, so each time the loop repeats, the value of i will be incremented by one.


You: Hmm, it is understandable when you dissect it like that. I think I understand what the rest of the programme does.


Barney: Yes, go ahead!


You: Each time the loop runs, the value of i is added to n. Since the loop runs while i=1,2,…,10, the final value of n will be equal to n=1+2+…+10


Barney: Exactly! You have always been a fast learner! So the programme should print that sum at the end. What exactly would it print?


You: Mmm, 55 of course. Good that I still remember high school math!


Barney: Let’s see.




you: There! Didn’t I tell ya? He he.


Barney: Good. When someone like you is around here, one don’t need to write a programme to find such a total. But I know you understand the significance of these loops in programming sure enough.


You: Yeah, yeah, I do. I was kidding!


Barney: Good. Now one more thing is that in the increment part, actually we can perform any mathematical operation, even decrementing. So something like this will also work:


for (i=10;i>=1;i–)


You: Hmm, I see.


Barney: And there are two more commands that I want to teach you now. They’re the break and continue statements. They’re really useful when dealing with loops. What do you think the break command does?


You: Mmm, perhaps it breaks the loop? Hehe.


Barney: Yes. If you want your loop to stop looping at some point, you can break it using this. This is really useful when you make use of infinite loops. What does this loop do?


int n=0, i=1;


while (true) {





You: Hmm, it will also calculate the sum 1+2+3+… but the condition is true, what happens then?


Barney: Well, since the condition remains true always, the loop will never stop. This is an example for an infinite loop.


You: What’s the use of that anyway, Barney?


Barney: Well, it’s like this. Suppose you need to find out when the sum 1+2+3+… reaches 1000. Then you can do some trick like this:




using namespace std;


int main()


int n=0, i=1;


while (true) {


if (n>=1000) break;




cout<<”The sum reaches 1000 when i=”<<i<<endl;


return 0;



cout<<”The sum reaches 1000 when i=”<<i<<endl;



return 0;



You check the value of n at each iteration, and once you find that it has exceeded 1000 you tell the loop to break. So what will be printed is the value of i required to make n>=100. So, genius, what will be printed as the output?


You: Oh, I’m not sure. Let’s run the programme and see.


Barney: Here we go!




You: Hmm, that’s interesting.


Barney: The continue statements asks the loop to go and start a new iteration without executing the rest of the code in the loop. An example will make this clear.




using namespace std;


int main()


for (int i=0;i<6;i++) {

if (i==2) continue;





return 0;




Note that I have declared the integer i in the initialize itself. It is common practice to declare such temporary variables like this. Back to the programme, when i reaches 2, the continue statement asks the programme not to execute the following code an start a fresh iteration. So what will be the output?


You: It should print from 0 to 5, but since it continues at two, it should miss 2.


Barney: Okay, let’s see.




You: Yeah, I get that.


Barney: Good. Now you have a good understanding in the basics of loops. However to master it you need to practice. So keep writing different programmes to illustrate how loops can be used in different situations. And now since we have spent too much time on this I think it’s time we wind up for today.


You: Yeah, let’s break for today and continue the next day.


Barney: Okay, so bye then, Ted!


You: Bye, Barney!


Getting user input and conditional statements

[You're Ted and you decide to learn some C++ from your friend Barney. This is the third day of the class]

You: Hey, Barney! I’m here again!

Barney: Hi, Ted! So? Ready to proceed with C++?

You: Oh, yes. What shall we be doing today?

Barney: Today we’ll go to a more practical stage where you let the user to enter some input so you can process it. This is actually quite easy. To give an output to the console we used the command cout. In the same way to get an input from the console we use the command ‘cin’.

You: Hmm, sounds easy.

Barney: Yes. Let’s write a small programme to demonstrate this. Look at this programme:


using namespace std;


int main()


int age;


cout<<”Enter your age: “;



cout<<”You’re “<<age<<” years old”<<endl;


return 0;



You: That seems greek to me. What does this do?

Barney: It’s like this. You need to get the age from the user and output it. Now this input we get from the user should be stored in a variable, and obviously we should choose int.

You: So we first declare this variable called age.

Barney: Yes. Then we need to get the input. And before that we must ask the user to enter it. So we use cout to do that. Then, to get the input we use cin. Together with cin we must use the operator >>.

You: With cout this is the other way around, right?

Barney: Yeah, that’s the difference. And right after that we mention the variable where the user’s input should be stored. Get it?

You: Yep, and I think I understand the rest. You use cout again to output that age again.

Barney: That’s it. So let’s run the programme and see.

You: That’s interesting!

Barney: Yeah, by being able to take input from the user you are able to all sorts of useful things in your programme. Can you now write a programme to ask the user to input two integers and output their sum?

You: Mmm, well, yes, that won’t be too difficult, will it?

Barney: Of course not. Go ahead!

You: Here we go:


using namespace std;


int main()


int a,b,c;

cout<<”Enter a number: “;


cout<<”Enter another number: “;



c = a + b;

cout<<”The sum is “<<c<<endl;


return 0;



Note that I have included the string header file so that you’ll be able to play with strings.

You: Right. So here we go!



Barney: That’s great! You’re a real fast-learner.


You: Ha ha! Thanks. Can one input a string?


Barney: Of course, but then you will have to use the string data type. Let’s try that too:





using namespace std;


int main()


string name;

int age;

cout<<”Enter your name: “;


cout<<”Enter your age: “;



cout<<”You’re “<<name<<” and you’re “<<age<<” years old”<<endl;


return 0;



Note that I have included the string header file so that you’ll be able to play with strings.


You: Right. So here we go!


Hmm, that’s awesome!

Barney: Wait. Run this programme again and enter your full name and see.

You: Why? Okay.

Oh, what happened?

Barney: This is because once you press space, cin stops reading from the console. It receives the next thing you type as the input for the next variable. And that’s why it didn’t ask for your age.

You: Oh, that’s bad. What can we do about it?

Barney: Simple. If you need to get a string of words, you use the getline method, like this:

cout<<”Enter your name: “;


Try that now, again.

You: Hmm, that works fine.

Barney: Yes. And there are times when you need more control over the strings your user inputs. Suppose you have a string which contains two integer values and you need to extract them. This is when string stream comes to the rescue.

cout<<”Enter your age and her age separated by spaces: “;

getline(cin, ages);


You: That’s an odd way to ask for two integers.

Barney: Mmm, yes, it may seem so, but when you go ahead programming you will understand that at most times you don’t get your input the way you want to.

You: He he, okay. So what can we do now?

Barney: Now that we need to extract the two integers from ages we go ahead and use the string stream. Make sure that you need to include the sstream header file to do this.





using namespace std;


int main()


string ages;

int yourAge, herAge;

cout<<”Enter your age and her age separated by spaces: “;

getline(cin, ages);



cout<<”You have an age difference of “<<(yourAge – herAge)<<endl;


return 0;


You: That’s a bit complex.

Barney: Actually it’s not that complex. String streams make your life easier. You will practice using it on the go. It also can be used to convert integers to strings. We’ll talk about those when we’re dealing with strings.

You: Okay.

Barney: You tired?

You: Oh, not at all!

Barney: Okay, let’s now see how we can get more control over our programmes by deciding what to do. You have to take certain decisions according to the input. Suppose you ask the user to input his age and decide whether he is old or young. For this, you can use the if statements.

if (age>30)

cout<<”You’re too old”;


You: That’s pretty straight forward.

Barney: Yes, quite intuitive. You can extend it like this:


if (age>30)

cout<<”You’re too old”;


cout<<”You’re a young soul!”;

You can easily see what this code does, can’t you?

You: Yes, it seems simple.

Barney: Now if you need to put more than one line of code in an if-else statement, you have to use the curly braces.



if (age>30) {

cout<<”You’re too old”;

cout<<”But start learning now and you’ll never regret!”;



cout<<”You’re a young soul!”;


And you can use the else if structure to get the most out of the if statements.


if (age>30) {

cout<<”You’re too old”;

cout<<”But still too young to start learning!”;


else if (age==30)

cout<<”That’s a wonderful age to be!”;


cout<<”You’re a young soul!”;


You: Yeah, cool! But why did you use two equal signs there?

Barney: Yes, that’s because we don’t want to make age 30, but to check whether age is 30. If you use only one equal sign, you’re telling the compiler to equate them. But here you’re just comparing them.

You: Okay.

Barney: Alright. Now let’s use what we have learned and write a simple programme which prompts the user to enter his marks and calculates the grade.



using namespace std;


int main()


int marks;

cout<<”Enter your marks: “;



if (marks>100 || marks<0)

cout<<”Invalid value”;

else if (marks>=50)

cout<<”Congrats! You’re pass!”;


cout<<”Sorry, buddy, you’re fail!”;




return 0;


You: Oh, what are these vertical lines for?

Barney: Hmm, I forgot to mention, this is the OR sign. These two vertical lines are called pipes. This will set to true if at least one of the conditions is true. Here, this will be true if marks exceeds 100 or is below 100. Right?

You: Yeah.

Barney: And also you can use && for the AND operation. This is set to true when both the conditions are true. For example, you could have typed:

if (marks<=100 && marks>=50)

cout<<”Congrats! You’re pass!”
with the same effect.

You: I get it.

Barney: Okay, so let’s test the programme.

You: Hmm, works as expected, isn’t it?

Barney: Exactly. You understand it now, don’t you?

You: Completely!

Barney: There is another important method of conditional statements called switch-case structure. We’ll deal with that the next day. Until then you can practice what we learned up to now. Try to make a more serious programme that calculates grade based on marks. You can allocate grades like A, B, C, etc for certain ranges.

You: Yes, will do that today! This is really interesting! Thanks, Barney!

Barney: Oh, no problem, chap!

You: Bye, Barney!

Barney: Bye, Ted!


Data types

[You're Ted and you decide to learn some C++ from your friend Barney. This is the second day of the class]

You:Hey, Barney! Here I am, again!

Barney:Ah, welcome back, buddy! So how was your C++?

You:Great! I tried both in Visual C++ and gedit. But I’d prefer Visual C++ because it’s so simple.

Barney:Yes, but if you need a more user-friendly IDE for Linux I recommend using NetBeans or . It works in both Windows and Linux.

You:Okay, I’ll try those. So what are we going to do today?

Barney:Right, let’s start with comments. Comments are the remarks you make in the C++ code. They have no effect on the compiler, so it just ignores them.

You:If it is not compiled why do we use comments anyway?

Barney:Well, comments are intended for the programmers, may be you or another programmer who would later view your source code. If not for comments, he would have to spend a considerable time trying to guess what your code is doing. It’s a very good practice to comment as much as you can.

You:I see.

Barney:There are two kinds of comments in C++. Line comments and block comments.


//This is a line comment


/* This


a block



As you see, you can place several lines of remarks within a block comment. However you can achieve the same with several line comments. The choice of the type of comments is personal. But the thing to keep in mind is that you have to comment whenever you can.


Barney:Now let’s move into C++ data types. Our previous programme had no use, except for printing some lines in the screen, which of course is an odd thing to use a computer language for.

You:I was also thinking that, but didn’t tell ya. ;-)

Barney:Yes, the real value of a computer programme comes when it can handle various data and give you outputs after analyzing them. In short, your programmes should be able to handle data. To be able to handle data, you need to know about certain data types that are used in C++. Can you tell some types of data you would want your programme to handle?

You:Mmmm, numbers, words, pictures?

Barney:Yes, you can handle all those in your programmes, although it is complex to handle pictures and videos. There are several data types that you can use to handle numbers. “int” can handle integers, “float” and “double” can handle numbers with decimal points, that is fractions, etc. For example, you can declare an integer called a with a value of 5 like this:


int a=5;


You:What is this a about?

Barney:You should give a name to every variable you declare. We call a a variable because its value can be changed later, that is, not a constant. We may define several of these variables in a programme, so all of them should have different names. We call these names ‘identifiers’.

You:So the identifier is a and it has a value of 5?

Barney:Absolutely. We can declare the variable first and assign a value later on, like this:


int a;



You:I get it. So let me declare a float.


float a=4.5;


Am I correct?


Barney:There you go! But keep in mind, you cannot declare a variable whose identifier is already used, even if it is used with another data type. Okay?




Barney:Good. Now take a look at this table. It lists some of the common numerical data types you can use in C++.


Data type Description Size Range
short int (short) Short Integer 2 bytes -32768 to 32767
int Long Integer 4 bytes -2147483648 to 2147483647
float Floating point number 4 bytes +/- 3.4e +/- 38 (~7 digits)
double Double precision floating point number 8 bytes +/- 1.7e +/- 308 (~15 digits)


As you see, you can use “short int” or simply “short” to store integers but it has a limited range. Why would someone need “short” when they already have “int”?

You:Mmm, perhaps it can be used to conserve memory because a short needs only two bytes?

Barney:There you go! If we want to store a large number of integers and if we know they’re in the range of “short”, that will be the best choice, since it takes only half the space as “int”.


Also, as you can see from the table, you can use “float” or “double” when you need to store numbers with fractional parts or very high values, but “double” has more range and precision than “float”. The range of a float is ±3.4 x 10±38 with a precision of 7 significant digits.


Alright, now you can store numbers in your programme, what more would you want to do with these numbers?


You:Well, I may need to add them, multiply them and do all sorts of arithmetic.

Barney:Of course, yes. Doing arithmetic with these variables is quite intuitive. To add 16 and 27, we would write a programme as follows:


int i = 16 + 27;


Now i will have a value of?




Barney:You’re really good at arithmetic! Okay. Likewise, we can subtract, multiply, divide and find residues. Let’s see some examples:


int a=14-32;      //Gives -18

int b=7*8;        //Gives 52

int e=12/9;         //Gives 1, because int cannot hold fractions

float c=12/9;     //Gives 1.3333333…

int d=40%9;       //Gives 4, which is the residue when 40 is divided by 9


You:I see. It’s really simple!

Barney:Yes. You can also do this operations with variables, like this:


int p=22, q=6;

int r=p*q;


Now, Ted, how would you print the results of these operations on screen?

You:You could use “cout”, couldn’t you?

Barney:Exactly. We can use “cout” to print variables also.


int p=123, q=4;

int r=p%q;



You can use a little formatting here, like this:

cout<<p<<” % “<<q<<” = “<<r;

What would be the output?

You:Mmm, I’ll write it down:

               123 % 4 = 3


Barney:Yeah, now I think you understand how “cout” works. You can use the << operator to separate stuff within “cout”. Also now you may understand the use of double quotes.

You:Yeah, I think I get it.

Barney:You’ll soon forget these if you didn’t try them by yourself. So make sure you try out the things we learnt in different ways.

You :Okay.

Barney:Alright, Ted, let’s see some other types of variables. Suppose you need to use a variable to store logic or binary values, that is, true and false. You can use the “bool” data type for this. A bool can contain only two values, true or false, or, in other words, 1 or 0. Let’s see an example:

bool b1=true;

bool b2=fals;

bool b3=1;


You:What happened to b3?

Barney:You can use 0 and 1 instead of false and zero. 1 means true and 0 means false.

You:Ah, I see. That can be handy.

Barney:Yes, the bool is quite a useful type in many programming situations. You’ll learn more of this on the go. So, Ted, what other data types would you need to store in a variable?

You:Well, we surely need words to be stored.

Barney:Yes, though we don’t use the word “word” to call them. We call a single letter “a character” and a sequence of these characters “a string”. To store a character we can use the data type “char”.


char c=’A';

char d=’m';

You:What are the single quotes for?

Barney:You need to contain the characters within single quotes. Otherwise, if we had used


char d=m;


then, it means that we are equating “d” to another character variable “m”.

You:I get it.

Barney:But char can hold only one character. When you need to store more than one character in a single variable, you need to use the type “string”.


string myname=”ted”;

string myfriend=”barney”;


You:We should use double quotes there?

Barney:Yes, we must put strings inside double quotes. And also notice that I have used long identifiers. This is really useful to avoid confusion. It’s always recommended that you use descriptive identifiers. For example if we need two integers to hold the balance of this year and previous year in a shop, you could well use:

int m=2800, n=3220;

but it would be more reasonable to use:

int thisYearBalance=2800, lastYearBalance=3220;


Although these identifiers are long, they’re quite clear and will save you a lot of time when you return to check your source code some time later.


You:Yeah, I see it. So it’s better never to use one letter identifiers, I guess?

Barney:No, you always need short identifiers, especially for temporary variables which are used only in a limited scope of the programme. But you should use descriptive ones for variables which affect most parts of the programme and those which are of critical importance.


Barney:And one more thing about strings. You can join several strings very easily using the + operator, like this:


string a=”Hey “;

string b=”there!”;

string c=a+b;



This will print Hey there! in a single line in the screen.


You:It’s pretty simple.

Barney:Yeah, but sometimes string manipulation can get complex and this is an area every programmer should master. We’ll discuss this in detail later.

You:So these are all the variable types we have?

Barney:No, of course not. There are many more types. But for the time being the ones we learned today suffice for now. You’ll learn about more complex types like vectors, stacks, etc in the days to come. So, Ted, I think it will be enough for today. I need some time for myself.

You:Oh, alright! Let’s meet some other day again. Thanks a lot!

Barney:And if you have to send me any questions or suggestions please mail them to thameera123@gmail.com.

You:Sure! Bye, Barney!

Barney:Bye, Ted!