Introduction to Programming

Arrays


If variables are like boxes, then arrays are like rows of boxes.

To declare one integer variable, we already know looks like this:
int my_integer;
To define an array of integers looks like this:
int my_array[20];
I just declared 20 integers all at once. Just like that! This is a great way to create a whole lot of storage in a small amount of code. Now lets look at how to get at some of those integers...
int my_array[20];
my_array[0] = 5;
my_array[6] = 30;
my_array[19] = 12;
printf("The first element in my array is: %d\n", my_array[0]);
One important thing to keep in mind is that the elements of a 20-element array are not numbered 1 to 20, they are numbered 0 to 19. This is just one of the ways computers do things -- they start with 0 instead of 1.

Can you think of a quick way to get at all the elements in an array, one after the other, without typing 20 lines of code? Did I hear someone say "a loop"? Good idea! :)
int i;
int my_array[20];
for (i=0; i<20; i++)
{
    my_array[i] = 0;
}
The above code sets all the elements of my_array to 0. Don't forget to set all your variables' values before you read them! There might be garbage in there if you don't. ;)

Challenges

  1. Write a loop that gets 20 integers from the user, and then write another loop that prints them all back out.
  2. Use the random number example from earlier to generate 20 random numbers, each number from 0 to 30. Then write another loop that, for each number, prints out that many spaces on the screen and puts a star *. If you do it right, it should look a little like a star field in space! :) Hint: Call "srand" only once at the beginning. "rand" is the function you should call 20 times. Hint #2: You will need a loop within a loop to do the printing.


Next: Strings

Previous: Loops


Introduction to Programming

Home