int
is the plans for creating a two-byte number variable, a char
is the plans for creating a one-byte character variable. To create a variable of a specific data type we use the following:[data type] [variable]
x
" we would type the following:int x;
For many of you reading this you no doubt already understand this completely. You're probably impatient and tearing bloody holes in the sides where your clenched fists rest uncomfortably holding the printed copy of this tutorial. So, I'll move on.x
should ever want to hold. The other memory types you're familiar with and use are char
(1 byte), float
(4 bytes), and double
(8 bytes).int
) can handle whole numbers (no decimals) like -4893
and 7
. Characters (char
) store single alpha-numeric symbols. Simply speaking (for all of us who prefer the word letters or numbers over the previous) it can store things like '5'
and 'c'
. When putting these kinds of values into characters you must put the single quotes (apostrophes) around it:
char myvar;
myvar = A; // WRONG! (missing single quotes)
myvar = 'A'; // RIGHT!
You must use this same techinque when comparing characters to constants:
if (myvar == A) // WRONG! (missing single quotes)
{
...
}
if (myvar == 'A') // RIGHT!
{
...
}
And on to the last two data types: floating-point and double precision floating point. Sounds complicated, eh comrade? They're not really. In laymen's terms (the kind I use) they are used for values that go beyond the decimal point like 1.666
and 777.1
. Many people have asked me the difference between the two. Easy, a float
is 4 bytes large while a double
is 8 bytes. What the heck does this mean? Only that a double
can store numbers twice the size that a float
could store. What's the point? At this time you needn't worry, use one or the other. Later on when you want to store giant scientific equations and the national debt down to the nano-penny you'll use a double
, otherwise it doesn't matter which one you choose. Good? Good!long int
) is required. Some of you may have picked up on this. However, if you are using any recent compiler (DJGPP, Visual C++, BC++ Builder) you needn't worry because a normal int
actually takes up 4 bytes rather than 2. In other words, anywhere you see something like "an int
is two bytes" just remember that now-a-days its usually four.
int ssn1;
int ssn2;
int ssn3;
int ssn4;
int ssn5;
This is a lot of work! And just think if we wanted to output each of the variables! We'd have to do it individually ... ack, for me being a lazy programmer this is the kind of thing that drives cruel boredom up the base of my spine. But here I'll show you what we'd have to do to print out each and every one of the social security numbers:
cout << "List of SSNs:" << endl;
cout << ssn1 << endl
<< ssn2 << endl
<< ssn3 << endl
<< ssn4 << endl
<< ssn5 << endl;
Now just think of making a problem to have the user type in 5 social security numbers and then print them out to the screen. Simple right now because there's only 5 variables. Sure sure, but what if suddenly you have to add 5 more? Or 10 more? And then after this what if you have to change how they're outputted to the screen, like instead of one after the other you need commas or something between them. Then you begin to wonder ... is there a better way. OF COURSE! And yup, you guessed it: arrays are the answer (see I had a point for all this rubbish ... and they said I couldn't do it ... they said I was crazy, I'll show them I'll show them! *zzppptt!*
okay, I'm better now).An array is something that you can stick a lot of different things into, but all of them must be the same type. |
An array is a group of thingies that are together because they are the same type not necessarily the same value. |
0 |
1 |
2 |
3 |
4 |
A subscript refers to the order number of a thingie in an array. |
55, 352, 2
/ WRONG: 3.2, 98.2873, 0.001
)
1, 521, 3
/ WRONG: -1, -285, -86
)
0 |
1 |
2 |
3 |
4 |
0 |
1 |
2 |
3 |
4 |
<data type> <array name>[<size>];
int ssn[5];
int ssn[10];
ssn
". You can add to it, output it, input to it, etc. It works just like any normal variable. The only difference is that it is a part of an array and its name is a number.<array name>
[<subscript number>]
ssn[2]
ssn[2]
is treated exactly like a normal variable! How what when where why?x = 258;
Well, an array is made up of a series of single variables. In our case a list of integers. Each part of an array really is just a single variable and behaves like one. Therefore, we could do the EXACT same thing to ssn[2]
! See:ssn[2] = 258;
The above puts the value 258 into the third part (or subscript 2) of our array ssn. Let's say the white letters show the value of each piece of our array. In doing the above our array would now look like this:0 0 |
1 0 |
2 258 |
3 0 |
4 0 |
ssn[4] = 1234;
What we do here is say that we want to use subscript 4 of our array. Then we put the value in. Putting a subscript in the square brackets, is kind of like putting your disk in the drive. You have to do it to access anything in the array. So in my pictionary psuedo code the same thing from above would look like:<-- |
|
cout << "Contents of array SSN:" << endl;
cout << ssn[0] << endl
ssn[1] << endl
ssn[2] << endl
ssn[3] << endl
ssn[4] << endl;
Or, what if we wanted to get input into our array:cout << "Contents of array SSN:" << endl;
cout << "Please input SSN 1: ";
cin >> ssn[0];
cout << "Please input SSN 2: ";
cin >> ssn[1];
cout << "Please input SSN 3: ";
cin >> ssn[2];
cout << "Please input SSN 4: ";
cin >> ssn[3];
cout << "Please input SSN 5: ";
cin >> ssn[4];
Don't get angry on me, I realize that this is just as bad as the first example we saw with the social security numbers. But what I'm attempting to drill into your head is how subscripts work. By this time I hope you can see that you must put in a subscript to use any part of the array. Without a subscript value the array cannot be used by itself./* -example 1--------------------------------------------------------------- */
#include <iostream.h>
void times2(int n); // prototype a function that takes an integer parameter
void main()
{
int x; // create a normal integer variable
int num[5]; // create an array of 5 integers (subscripts 0,1,2,3,4)
x = 843; // give 'x' a value of 843
num[1] = 843; // give subscript 1 (second piece) of 'num' value of 843
times2(x); // pass the value of 'x' to times2()
times2(num[1]); // pass the value of num's subscript 1 to times2()
}
void times2(int n)
{
cout << "The value you passed to this function is " << n << endl;
cout << "This number multiplied by 2 is " << (n * 2) << endl;
}
/* ------------------------------------------------------------------------- */
And here is an example showing simple mathematics with the single part of an array:
/* -example 2--------------------------------------------------------------- */
#include <iostream.h>
void main()
{
int x;
int num[5];
int result;
cout << "Please input a whole number: ";
cin >> x;
cout << "Please input another whole number: ";
cin >> num[3];
result = x + num[3];
cout << endl << "The numbers you entered are " << x << " and " << num[3]
<< "." << endl;
cout << "These numbers added to each other results in " << result << "."
<< endl;
}
/* ------------------------------------------------------------------------- */
int ssn[5];
ssn[0] = 536843329;
ssn[1] = 537853330;
ssn[2] = 538863331;
ssn[3] = 539873332;
ssn[4] = 540883333;
But of course that is really time consuming (which of course I despise). There is a shorter way. Just like you can set every piece of data in a struct at the time of creating it, you can set every part of an array at the time of creating it as well.=
) followed by an open curly brace ({
). Now at this point you can list the values you want to put in the array. Separate each value by a comma (,
) and note that the order you put them in is the order they go into the array. Which means that the first value you type (536843329) will go into subscript zero (0) (ssn[0]), the second value (537853330) into subscript one (1) (ssn[1]), and so on and so forth. When you've listed all the values you want to put in the array, end with a closing curly brace (}
) and a semicolon (;
).int ssn[5] = { 536843329, 537853330, 538863331, 539873332, 540883333 };
That's basically how it works. I have no idea how else to explain it so if you don't understand then try it out a couple times on some dummy programs. Also, note that some compilers need an extra subscript space to put their own information for "ending" the array. What does this mean to you? Well, if you get a funny error like "too many intializers" then just add one to the size of the array where you're declaring it. So if you had int ssn[5];
just make it int ssn[6];
./* -example 3--------------------------------------------------------------- */
#include <iostream.h>
void main()
{
int num[5] = { 0, 1, 2, 3, 4 };
cout << "The values of array 'num' are as follows:" << endl;
cout << "subscript 0 = " << num[0] << endl
<< "subscript 1 = " << num[1] << endl
<< "subscript 2 = " << num[2] << endl
<< "subscript 3 = " << num[3] << endl
<< "subscript 4 = " << num[4] << endl;
}
/* ------------------------------------------------------------------------- */
Try it out, you can see that the value 0 is put in subscript zero (0) because that is the first subscript and 0 was also the first value listed. In simpler terms since we listed the value 0 first, it is put into the beginning subscript, which is always 0. I encourage you to try out the above program or make your own.int ssn[5] = { 536843329, 537853330, 538863331, 539873332, 540883333 };
int |
ssn |
[5] |
= |
{ |
536843329 , |
537853330 , |
538863331 , |
539873332 , |
540883333 |
}; |
array's parts are integers |
array name |
size of array |
going to intialize with values |
begin listing values |
subscript 0 |
subscript 1 |
subscript 2 |
subscript 3 |
subscript 4 |
end of statement |
ssn[2] = 5;
Now, let me show you the same thing except using an index variable. At this point in the program assume that we have already created an integer variable called i
(int i
;):
i = 2;
ssn[i] = 5;
Index variables are integers 99.9% of the time. I highly suggest at this point you use nothing else. The value of an index variable follows the same guidelines as a subscript (must be positive, must be a whole number, etc.).int i = 3;
And so, we could diagram num[i] to look something like:subscript 0 |
subscript 1 |
subscript 2 |
subscript 3 |
subscript 4 |
i |
i
tells us to use the disk labeled subscript 3. In a program the index variable tells the computer to use the value labeled under subscript 3. Drill drill drill. If you don't have this yet then you have to do ANOTHER exercise.
int i;
int num[5];
i = 0;
while (i < 5)
{
num[i] = 0;
i++;
}
In this example we set all five parts of the array num
to zero. This of course isn't really useful to use because we could easily intialize the entire array to zero (see previous section for multi-value intializing). However, what if we wanted to print each of the values in the array:
int i;
int num[5] = { 5, 4, 3, 2, 1 };
cout << "Printing contents of array 'num':" << endl;
i = 0;
while (i < 5)
{
cout << "subscript " << i << " = " << num[i] << endl;
i++;
}
cout << "Thank you for flying the friendly skies ... " << endl;
Wow, so short. We use a couple lines of code to print out several lines to the screen. The output from above would look like this:
Printing contents of array 'num':
subscript 0 = 5
subscript 1 = 4
subscript 2 = 3
subscript 3 = 2
subscript 4 = 1
Thank you for flying the friendly skies ...
What our program does is continually add to i
, but only while it is less than 5
. So the first time we go through the loop i
is 0
. And since we're using i
as our index variable we will be accessing subscript 0
which is of course 5
. And the loop continues to print each of the subscripts. Then outside of the loop we have a simple cout and then end.while
is the most simple kind of looping. In the case of indexing it hardly is the easiest one to use. You have to initialize the variables before the loop, and increment the counter inside the loop somewhere. Hardly efficient and so I suggest the for
loop. for
loops are ideal for counting and with indexing this is usually what we want to do anyway! Here's a good example of a for
loop in action:
// declare and initialize variables
int i;
int numbers[8] = { 98, 987, 876, 765, 654, 543, 432, 321 };
// output
cout << "numbers[8] = { ";
for (i = 0; i < 7; i++)
{
cout << numbers[i] << ", ";
}
cout << numbers[7] << " };";
This section has explained the concept of index variables. If you still don't get it then tell me and what you don't understand. Even if you think the question sounds dumb it'll help me make this better. Thanks!main()
then their shine would dull slightly. We could always make our arrays global, but that is extremely sloppy coding and functions would lose flexibility. Here is an example of an inflexible program:
/* -example 4--------------------------------------------------------------- */
#include <iostream.h>
int numbers[10], i;
void set_array_to_zeros();
void print_array();
void main()
{
set_array_to_zeros();
print_array();
}
void set_array_to_zeros()
{
for (i = 0; i < 10; i++)
{
numbers[i] = 0;
}
}
void print_array()
{
for (i = 0; i < 10; i++)
{
cout << numbers[i];
if (i < 9) cout << ", ";
}
}
/* ------------------------------------------------------------------------- */
This is terribly inextensible. Say perhaps that we wanted to zero-out two different arrays and then print each of those out. Using the previous source as a base, we would have to hard-code (or re-type in) a lot of things. Therefore its almost imperative that you understand how to pass arrays for use in functions.void
func(int p);
In the previous line we create a function called func
which takes a single integer parameter called p
. And, when calling this function we'd simply type in the function name (func
) followed by a single integer variable or constant inside parenthesis:int x = 10;
func(10);
func(x);
func(x + 10);
If you understand this concept (and the previous examples) then you're ready for this section otherwise read up more on function parameters. I'll soon be adding a section for this so you'll be able to read that too. Now, moving on we must find a way to pass an entire array to a function.[]
). It looks like this:type name[]
func
that returns nothing (void
) and takes a single argument (parameter) that is an integer array called arr
:void
func(int arr[]);
arr
. This parameter is of integer type but is not a single piece. The []
tells us that the parameter is an array. To pass an array to a function you simply use its name, nothing else. So if we were to pass our previous array example ssn
to this function func
we would do this:func(ssn);
To use an array parameter in a function we would use it like any normal array, but we'd use the name of that parameter rather than the name of the array that we passed to the function. So say we pass our array ssn
to this function func
. Inside the function we would not be doing things like ssn
[2] = 1011;
. Instead we'd be using the name of the parameter, which in this case is arr
. So what we would be doing is things like arr
[2] = 1011;
. See the only difference is that we're using the name of the parameter rather than the name of the array that we passed to the function./* -example 5--------------------------------------------------------------- */
#include <iostream.h>
void print_array(int arr[], int num_of_parts);
void main()
{
int numbers[10] = { 328, 53, 2049, 6189, 16, 95, 235, 753, 10963, 1 };
print_array(numbers, 10);
}
void print_array(int arr[], int num_of_parts)
{
int i;
for (i = 0; i < num_of_parts; i++)
{
cout << arr[i];
if (i < (num_of_parts-1) ) cout << ", ";
}
}
/* ------------------------------------------------------------------------- */
This was a little bit of an "advanced" version of a function because you can use it to print the contents of any integer array. Its first parameter is an integer array called arr
and its second is a plain integer called num_of_parts
. Because the function does not know how long the array you pass is, we pass a second parameter which tells the function how long the array is. In this example we pass our array called numbers
and the value 10
. The value 10
is of course how long our array (numbers
) is. The function itself uses a for
loop and index variable (i
) to sift through the array and print each of its subscripts (parts). In our case, i
starts at subscript 0
and at the end of each loop iteration, keeps being added to while it is less than 10
(our value of num_of_parts
).numbers
array:int second_array[6] = { 20, 21, 22, 23, 24, 25 };
And then add these two below the line where we call the function print_array()
:cout << endl;
print_array (second_array, 6);
After making these changes to our program (try it out), it will print the contents of two arrays: numbers
and second_array
. And we only had to add a teeny bit of things ./* -example 6--------------------------------------------------------------- */
#include <iostream.h>
void func(int param);
void main()
{
int x = 0;
func(x);
cout << "x = " << x << endl;
}
void func(int param)
{
param = 15;
}
/* ------------------------------------------------------------------------- */
After running this program you will undoubtably get a single line of output:
x = 0
When we changed param
inside func
it did NOT change x
, simply because only x
's value was passed. All the function got was the number 0
(the value of x
), it did NOT get x
itself./* -example 7--------------------------------------------------------------- */
#include <iostream.h>
void func(int param[]);
void main()
{
int x[5] = { 0, 0, 0, 0, 0 };
func(x);
cout << "x[0] = " << x[0] << endl;
}
void func(int param[])
{
param[0] = 15;
}
/* ------------------------------------------------------------------------- */
After running this you will see the line:x[0] = 15
I won't go into the gorey details of why array parameters behave like this. However, just note that when you pass an array to a function, any changes made to the parameter inside the function effect the actual array. This allows us to easily make functions that calculate relations between two arrays and store them into a result array or to copy one array into another. Here's an example of a program which copies the contents of one array into another:/* -example 8--------------------------------------------------------------- */
#include <iostream.h>
void copy_array(int source[], int destination[], int num_of_parts);
void main()
{
int y[5] = { 5, 4, 3, 2, 1 };
int x[5] = { 0, 0, 0, 0, 0 };
copy_array(y, x, 5);
}
void copy_array(int source[], int destination[], int num_of_parts)
{
int i;
for (i = 0; i < num_of_parts; i++)
{
destination[i] = source[i];
}
}
/* ------------------------------------------------------------------------- */
Page Content & Design ©1998 By Neil C. Obremski |
home |
prfce |
loop |
refs |
ptrs |
struct |
class |
array |
rsrc |
site |
indx |
Wed May 12 21:45:26 1999 |