Tutorial 3

Introducing Variables


So you managed to get by on the first one, eh? Well I didn't think that it would cause any problems for you. However tradition made me put that one in there. A long line of programming books have gone before me so I couldn't stray from the way of old. Now we are going to introduce variables. In C++ there are many types of variables. I emphasise the word type as this is what variables are. They are simply a certain type of data. For example if we need to store a number, say a whole number, we would use the type int if we wanted a decimal then we would use float and if the data was alphabetic (or alphanumeric) we would use char. Using these three basic types we can create arrays. An array is what we will learn to be a data structure. To create an array of any type, we simply follow the declaration name with [size], where size is the number of that type that we want in the array. An example declaration would be as follows for a string, an alphanumeric sequence such as a word:


This tells us that we have declared a character array of size 12 that is called my_word. If you can think of a variable as a label for the data we are storing. it tends to be much easier to understand. Writing a program using variables is our next step on the way to successful programming. At this moment in time I would like to remind those who have programmed before that these pages are intended for those who have never programmed as well as those who already know all this stuff about variables and the likes. Please be patient and if not then check out something a little more taxing like my tutorial on classes.

Write a program to take in a character string from the user. The user then is prompted for a number (whole) and the program prints out the string that number of times. We will have to use a for loop structure here to print out the string a number of times.



The for loop structure. A loop by definition goes around. Using loops in programming allows us to perform a task several times without the need to type it several times. In the above program we created a for loop that went from 0 to num_times. This meant that our counter i, initially at 0, allowed the loop to continue until the value of num_times was reached. The i++ statement is what increments the counter each time the loop goes around. As soon as the condition for the loop is met, i.e. the counter reaches num_times in value, the loop terminates handing control back to the rest of the program. There are three basic loops in C++. The for loop (most common), the while loop and the do while loop. Each of these loops have their own characteristics and can suit some situations better than other loops. As you learn more you will soon see which loop serves the best purpose.

Previous Index Next


© Redsetter 2000