Arrays

C Language

Overview

Up until this point you are introduced to only simple variables. In this lesson, we will learn about a group of variables together, or arrays, which is very useful in C programming as you need to store a large amount or a group of data of the same kind.


Introduction to Arrays

Arrays are a set of data of the same kind. For example, if you have data about a class's scores on a test for each student, instead of creating on variable for each of their scores, arrays are used to create them simply having one array, containing the scores. In the computer memory, as we talked about in the Basics page, each variable takes up certain amount of memory. An array, in comparison, is actually just multiple variables in the memory together. You can just visualize arrays like this (if a variable itself is a [ ], then an array is the whole thing):
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
As you can see, it is a set of variables, so instead of creating a variable for each of them, you can just create an array that contains all of them. This makes operations much easier. The above is a one-dimensional array, there can be also multi-dimensional arrays, for instance, a two-dimensional array can be visualized like this:
[0,0] [0,1] [0,2]
[1,0] [1,1] [1,2]
[2,0] [2,1] [2,2]
Two-dimensional arrays can be used in situations like a chess board where you need one variable for each space on the board. We will discuss them in this lesson. For now, just remember that arrays are a set of data of the same kind together. In this lesson, we will use an array to store 10 scores of students as an example that we are going to use and do operations with.


One-Dimensional Arrays

Declaration

Since arrays are a form of variable, you will need to declare it before using it just as you need so for regular variables. Since we will be recording 10 scores, our array is an integer array:
int scores [10];
This statement tells the computer to create an array containing 10 integer variables. As you can observe, it is just like a normal variable declaration, except you will add brackets at the end, enclosing how many elements you need in the array.

Accessing Values

To access a value in an array, it is very similar to accessing variables. For example, if I want to set the first score in the array above to 97, I would do:
scores [0]=97;
Note that I put 0 inside the brackets, not 1. This is because in C, the array starts at 0 (for purposes of execution speed and easy calculations). So scores [1] would actually be the second element, scores [2] would be the third... The array would actually end at scores [9] instead of scores [10] (but note that the declaration still uses int scores [10];).

#include <stdio.h>

int main()
{
  /*You can initialize arrays like this just like you can initialize regular variables*/
  int scores [10]={97,95,90,93,87,79,84,100,0,0};
  scores [8]=98; /*This assigns 98 to the 9th element in the array*/
  printf("Enter the score for the last student:");
  scanf("%d",&(scores [9])); /*It is the same when getting inputs from the user, you 
  still needs the '&' sign (I used parenthesis around scores [9] to be safe)*/
  printf("The last three scores are:%d,%d,%d\n",scores [7],scores [8],scores [9]);
}

Enter the score for the last student:76
The last three scores are:100,98,76

As you can see from this example, we first declared an array of ten elements in it and gave them initial values. We then used a simple assigning statement to assign the value 98 to the 9th (remember array index numbers in C starts at 0, not 1) element in the array. Then, getting a value from a scanf statement is demonstrated, and as you can see, it is the same as you would with a normal variable, just with the index number. So we can conclude that the use of array elements is the same as normal variables, just with the index numbers after it.

Let's look at another example.

Example

#include <stdio.h>

int main()
{
  int numbers [3];
  int sum;
  printf("Enter three integers:");
  scanf("%d,%d,%d",&(numbers [0]),&(numbers [1]),&(numbers [2]));
  sum=numbers [0]+numbers [1]; /*We can only do one operation at a time*/
  sum+=numbers [2]; /*Again, += is the same as sum=sum+...*/
  printf("The sum of the three numbers is %d\n",sum);
}

Enter three integers:15,3,2
The sum of the three numbers is 20

In this example, we performed some simple operations with the array to demonstrate doing operations. Again, it is the same as what you would do with normal variables.

Arrays and Loops

Up until this point, operations with arrays are still inefficient because you would still need to do them one by one like you would with normal variables. In this section, we will introduct some of the classic cooperations between arrays and loops in completing operations. The for loop is most used because it takes the least time to write and is very convenient and clear when used with arrays.

Let's first look at an example of using a loop to input 10 numbers and output them with a for loop:

#include <stdio.h>

int main()
{
  int numbers [10];
  int i;
  printf("Input numbers:\n");
  for(i=0;i<10;i++) /*Remember this format! This is very frequently used when you deal with arrays.
We stop at <10 to stop at 9 in the index notation.*/
   {
     scanf("%d",&(numbers [i]));
   }
  printf("Your numbers:\n");
  for(i=0;i<10;i++)
   {
     printf("%d\t",numbers [i]);
   }
}

Input numbers:
3
89
-2
0
5
78
7
98
29
10
Your numbers:
3     89     -2     0     5     78     7     98     29     10

This is a basic example of inputting ten numbers and outputting them with arrays. Note the for loop used here. This format will be very frequently used when you deal with arrays. This is a very convenient format to iterate over an array. Let's look at another example.

Example

#include <stdio.h>

int main()
{
  /*Calculate the mean of a set of given numbers*/
  int numbers [10]={45,78,-3,98,23,36,29,93,92,-89};
  int i;
  int sum=0;
  float mean;
  for(i=0;i<10;i++)
   {
     sum+=numbers [i];
   }
  mean=sum/10.0; /*We divided by 10.0 instead of 10 to make sure the division gets
a decimal result, not just a rounded integer*/
  printf("The mean of the ten numbers is:%f\n",mean);
  /*The result here should be 40.2, but the result printed is 40.200001 because just
like there are repeating decimals in base 10, in binary, some numbers cannot be represented
exactly*/
}
	

The mean of the ten numbers is:40.200001

Multi-Dimensional Arrays

Multi-dimension arrays works just the same as one-dimensional ones. Two-dimensional arrays are mostly used and sometimes three dimensional ones, but seldom the other ones because it is hard for humans to imagine something four-dimensional and above. We would focus on two-dimensional ones in this tutorial.

Two-dimensional arrays are exactly the same as one dimensional ones except that you need two index numbers instead of only one. Let's look back at this diagram:
[ ] [ ] [ ]
[ ] [ ] [ ]
[ ] [ ] [ ]
These elements have both a "row" number and a "column" number. So when you want to access the second element in the first row, you would need to access it through array_name [0][1] (again, the index numbers still start at 0). So if you want to assign 0 to the 2nd element in the 2nd row, you would need to do (the name of the array is numbers): numbers [1][1]=0; Let's look at an example where the program print out a tic-tac-toe board.

#include <stdio.h>

int main()
{
  int board [3][3]={{0,1,1},{2,1,0},{1,2,2}};
  /*Several things here:
    First, as you see, the declaration is exactly the same with one dimensional
ones except the additional index number. Here, we used 3*3 for a tic-tac-toe board
    Second, for the initilization here, we put braces around elements of each row
just to be clear of the rows. It is optional, so that initialization is equivalent of:
  int board [3][3]={0,1,1,2,1,0,1,2,2};
    Note: 0 means empty, 1 means x, 2 means o*/

  int row,col;

  /*Nested for loops are often used in multi-dimensional arrays*/
  for(row=0;row<3;row++)
   {
     for(col=0;col<3;col++)
      {
        if(board [row][col]==1) /*Occupied by x*/
         {
           printf("x ");
         }
        else if(board [row][col]==2) /*Occupied by o*/
         {
           printf("o ");
         }
        else /*Empty space*/
         {
           printf("  ");
         }
      }
     printf("\n"); /*Print out a newline each time a row is finished*/
   }
}
	

  x x 
o x   
x o o 

This program should be able to print out a nice tic-tac-toe board where the x won. We used two nested loops to iterate over the array and print out the board. In each iteration, we used an if structure to print out the pawns, and you can see how we used values in an array as the condition of the structure (just the same as normal variables). After each iteration of the outer loop, we printed a newline to start a new row.

In conclusion, using a multi-dimensional array is just the same as a one-dimensional array, just with additional index numbers.

Strings

Up until this point we've only used integer arrays. Let's look at some other types of arrays: strings. You have probably tried to use a char variable to let the user input a character. But is it possible for the user to input a whole word, sentence, or even paragraph without needing to create many many char variables? The answer is still using arrays just like integer ones. A string of characters is just like an integer array, except that it is characters that are stored in the elements, not numbers, so this way, you can have one variable that stores "This is a string!\n". Once you mastered arrays, strings are very similar and simple, so let's directly jump into an example.

#include <stdio.h>

int main()
{
  char phrase [20];
  /*This line created a string of 20 characters named 'phrase'. You can access 
it just like an integer array (phrase [3]='a';)
    To initialize a string:
    char phrase [20]="This is a string!";
    or
    char phrase [20]={'T','h','i','s',' ','i','s',' ','a',' ','s','t','r','i','n','g','!'};*/

  scanf("%s",phrase);/*Notice: %s means string; IMPORTANT: with strings, you don't need
to put the ampersand (&) before the name of the string in scanfs!*/

  /*For getting a string from the user, another way (also a safer way, but a little more
complicated, we will discuss this further in the File I/O lesson):
  fgets(phrase,20,stdin);
  This also allows the user to input a string of 20 characters from Standard Input and store 
it in phrase*/

  printf("Your phrase is:%s\n",phrase);
}
	  

C Programming
Your phrase is:C Programming

As you see in the above example, using and doing operations with a string is just the same as with a integer array. Just remember several things: use '%s' in printfs and scanfs; you DO NOT need the ampersand in scanfs; still remember index numbers start at 0, not 1; for initialization, you can do char phrase="This is a string!\n"; there is a special character '\0' which indicates empty and end of a string. The computer usually automatically adds a '\0' character at the end of a string to indicate that it ends (we will discuss why this is important in a moment). In conclusion, you can basically treat a string as a normal array and do all the operations.

String Operations

In the header file string.h, there are a set of very useful string operation functions that you can call. Including comparing strings, copying strings, finding the length of a string, string concatenation, etc. To use those operations, you first need to include a new header file beside stdio.h:
#include <stdio.h>
#include <string.h>
Then, you can call on these operations.

strlen

The strlen function calculates the length of a string. For example, if I have char phrase [20]="C Programming"; and call strlen(phrase), 13 will be returned since there are 13 characters in the string. This function works because of the '\0' at the end of the string. The computer normally automatically add the '\0' for you, but sometimes not. Be careful! Here is the program that does this:

#include <stdio.h>
#include <string.h>

int main()
{
  char phrase [20]="C Programming";
  int length=strlen(phrase);
  printf("%d\n",length);
}

13

strcmp

The strcmp(str1,str2); function compares two strings and returns 0 when they are the same; a negative int when str1 is less than str2 (str1's ASCII codes); and a positive int when str1 is greater than str2. Here is an example:

#include <stdio.h>
#include <string.h>

int main()
{
  char phrase [20]="C Programming";
  char cmp_phrase [20]="B Programming";
  int result;
  result=strcmp(phrase,cmp_phrase);
  printf("%s;%s:%d\n",phrase,cmp_phrase,result);
  cmp_phrase [0]='C';
  result=strcmp(phrase,cmp_phrase);
  printf("%s;%s:%d\n",phrase,cmp_phrase,result);
  cmp_phrase [0]='D';
  result=strcmp(phrase,cmp_phrase);
  printf("%s;%s:%d\n",phrase,cmp_phrase,result);
}

C Programming;B Programming:1
C Programming;C Programming:0
C Programming;D Programming:-1

strcpy

The strcpy(destination,source); function copies the string source to the string destination. Make sure the string destination is large enough to hold the string source! Here is the example:

#include <stdio.h>
#include <string.h>

int main()
{
  char phrase [20]="C Programming";
  char copy [20];
  strcpy(copy,phrase);
  printf("%s\n",copy);
}

C Programming

strcat

The strcat function stands for string concatenation. If you call strcat(destination,source); the computer will concatenate, or append, the string source to the string destination. Let's look at the example:

#include 
#include 

int main()
{
  char dest_str [20]="C";
  char append_str [20]="Programming";
  strcat(dest_str,append_str);
  printf("%s\n",dest_str);
}

CProgramming

Practice

Debug the following program:

#include <stdio.h>

int main()
{
  /*Allows the user to input 10 numbers and count how many of them are 0s*/
  int numbers [10];
  int i;
  int count;
  printf("Enter the numbers:");
  scanf("%d",&numbers);
  for(i=0;i<=10;i++)
   {
     if(numbers [i]==0)
      {
        count++;
      }
   }
  printf("There are %d 0s\n",count);
}

Write a program that allows the user to input 5 numbers and store it in arr_1, input another 5 numbers stored in arr_2, and copy the numbers in arr_2 to arr_1, print the result.

Write a program that sorts 10 numbers (inputs) in ascending order. (See link below for additional practices for help and information about Bubble Method (Sort)).

Write a program with this array {1,1,2,3,5,8,13,21,34}. Allows the user to input a number and the program should insert the number into the array in the ascending order.

Test this program and observe its results:

#include <stdio.h>
#include <string.h>

int main()
{
  char input [40];
  char append [20];
  char name [10];
  char temp [30];
  int i;

  printf("What programming language are you learning?");
  fgets(input,40,stdin);
  if(strcmp(input,"C Language\n")==0)
    {
      printf("That's right!\n");
    }
  printf("What other language do you know?");
  fgets(append,20,stdin);
  for(i=0;i<40;i++)
    {
      if(input [i]=='\n')
	{
	  input [i]=' ';
	}
    }
  strcat(input,", ");
  for(i=0;i<20;i++)
    {
      if(append [i]=='\n')
	{
	  append [i]=' ';
	}
    }
  strcat(input,append);
  printf("You know %s!\n",input);
  printf("What is your name?");
  fgets(name,10,stdin);
  strcpy(temp,input);
  for(i=0;i<10;i++)
    {
      if(name [i]=='\n')
	{
	  name [i]=' ';
	}
    }
  strcpy(input,name);
  strcat(input,"knows ");
  strcat(input,temp);
  printf("%s!\n",input);
}

Additional practice on arrays:

Activity 8.2 (Help on sorting numbers and Bubble Method)

<< Previous TOC Next >>