Home Authors Posts by Thameera Senanayaka

Thameera Senanayaka

13 POSTS 0 COMMENTS
Engineer. Loves tic-tac.

5053

International Mathematical Olympiad (IMO) is the world championship in mathematics for students under the age of 20, contested by more than 500 students from over 100 countries worldwide. Sri Lanka Olympiad Mathematics Foundation, the non-profit organization behind driving the Sri Lankan team at IMO, just unveiled its new website at www.slmathsolympiad.org.

SLOMF is headquartered at the Department of Mathematics, Faculty of Science, University of Colombo and is run by lecturers and undergraduates on a voluntary basis. In addition to the IMO, it conducts training and selection for International Mathematics Competition (IMC) as well, which is another challenging mathematics competition for upper primary and lower secondary students worldwide. This year’s IMC will be held in Korea, while the IMO is to be held in Cape Town, South Africa.

The team for the competitions are selected by a series of local competitions. The first is the Sri Lanka Mathematics Competition. Top 40 students from this will be invited to the Sri Lanka Challenge Competition and training programs. After a series of competitions, at most 6 students will be chosen to represent Sri Lanka at the IMO.

sl

Previously you had to go through a tedious process to register for the competition, but now you can do it online via the newly unveiled website. If you were born on or after 9th of July, 1994, head to the site today and follow the instructions. You might be the math genius Sri Lanka is looking for.

2214

Tweeps are generally more up-to-date with the latest technologies and happenings than those from other social networks. The news reaches them the fastest and lots of interesting conversations happen. However, it’s not rare to find them becoming nostalgic every once in a while. Especially with the TweetupSL 4 coming up and a book about the Sri Lankan twittersphere being written, people are digging up their old tweets, reminiscing how their timelines were like back then and remembering the epic moments in the past few years. We love talking about how things used to be.

When someone mentions an unforgettable thing that used to happen when we were young, it is very natural that rekindle the memories of other tweeps who join the conversation and make it a trend. That’s exactly what happened when @GayanMW tweeted about a brand of tinned fish from the 90s.

And thus, the #SriLankaInThe90s tag was born. Other tweeps soon followed suit, tweeting about the fond memories from the 1990s, back when most of them were pretty young. The majority of the tweets were related to the old school nostalgia.

Well, no one can possibly forget one-bump cricket.

Many were reminiscing the popular TV shows, movies and adverts back then.

Lots of tweets reflected how the Sri Lankan society used to be back then.

The Oberoi!

Life wasn’t easy as it is now.

One cannot simply forget the horrible war that was going on back then. War was a major part of everyone’s lives.

Some techy tweeps remembered how the computers used to be back then.

There were quite a few hilarious political mentions as well.

Several tweeps even posted photos of the memories from the 90s.

Many tweeps claimed that #SriLankaInThe90s was trending on Twitter countrywide. The hashtag was becoming popular beyond limits.

#SriLankaInThe90s took everyone to a time when there was no Twitter and things were very different.

We initially planned to feature only 20 tweets. But there were so many good ones, we just could not contain ourselves from featuring more.

This is the second article of our prequel to #TweetupSL4. You can find our first article covering all the interesting tweets that were tweeted under #TweepsAsCabinetMinisters here

1854

Strings

[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!

1742

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: “;
cin>>a;
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.

do{
cout<<“Do you want to continue [Y/N]? “;
cin>>c;
} 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:

#include<iostream>

using namespace std;

int main()
{

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

cout<<“Do you want to continue [Y/N]? “;
cin>>c;
} 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:

cout<<name;

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:

#include<iostream>

using namespace std;

int main()
{

char name[50];

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

system(“pause”);

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!

1614

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:

 

data[2][1]

 

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!

1670

Arrays

[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!

1583

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:

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!

1788

Functions

[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) {
                statements

} 

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!

1600

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:

    statements;

    break;

case const2;

    statements;

    break;

    …

    default:

    statements;

}

You: Oh, that’s real greek!

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

 

#include<iostream>

using namespace std;

int main()

{

int num;

cout<<”Enter a number: “;

cin>>num;

 

switch (num) {

case 1:

cout<<”That’s one!”;

break;

case 2:

cout<<”The smallest prime!”;

break;

case 3:case 4:

cout<<”Less than 5″;

break;

default:

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

}

cout<<endl;

system(“pause”);

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.

 

#include<iostream>

using namespace std;

int main()

{

char c;

int n=0;

do {

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

cin>>c;

switch(c) {

case ‘Y’: case ‘y’:

break;

case ‘N’: case ‘n’:

n=1;

break;

default:

cout<<”Error\n”;

}

} while (n<1);

system(“pause”);

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!

1531

 

Loops

 

[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.

 

#include<iostream>

 

using namespace std;

 

int main()

{

int n=0;

 

while (n<5) {

cout<<n<<endl;

n=n+1;

}

system(“pause”);

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.

 

n=n+1;

n+=1;

n++;

 

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:

n+=5;

 

You: I see.

 

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

++n;

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

 

#include<iostream>

 

using namespace std;

 

int main()

{

int n=0;

 

while (n<5) {

cout<<n++<<endl;

}

system(“pause”);

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:

 

#include<iostream>

 

using namespace std;

 

int main()

{

int n=5;

 

while (n<5) {

cout<<++n<<endl;

}

system(“pause”);

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 {

//statements

} 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:

 

#include<iostream>

 

using namespace std;

 

int main()

{

int n=10;

 

do {

cout<<n–<<endl;

} while (n>5);

system(“pause”);

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) {

//statements

}

 

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.

 

include<iostream>

 

using namespace std;

 

int main()

{

int n=0, i;

 

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

n+=i;

}

 

cout<<n<<endl;

system(“pause”);

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?

 

You:

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) {

n+=i;

i++;

}

 

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:

 

#include<iostream>

 

using namespace std;

 

int main()

{

int n=0, i=1;

 

while (true) {

n+=i;

if (n>=1000) break;

i++;

}

 

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

system(“pause”);

return 0;

}

 

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

 

system(“pause”);

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.

 

#include<iostream>

 

using namespace std;

 

int main()

{

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

if (i==2) continue;

cout<<i<<endl;

}

 

system(“pause”);

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!