Thread: C tutorial
View Single Post
 
 
Posted 2004-12-24, 06:46 PM in reply to Demosthenes's post starting "Chapter 3: Loops and Conditionals ..."
Chapter 4: Arrays & Strings

Disclaimer: This is not meant to be a comprehensive guide to programming C. I guess I should've put that in the first chapter. I'm by no means a great C programmer. A lot of people in IRC have not liked this tutorial that I'm writing too much. If you are serious about getting into C programming, I suggest picking up a book written by a professional. Now, on a side-note, I don't think my tutorial is that bad, so feel free to follow me, but don't take every single thing that I say here to heart. There's a good possibility that what I'm doing isn't the best way to do things. Anyway, without further ado, lets get into the chapter.

Introduction Section 4.1

So far we've been doing a lot of work with numbers and single characters. That's all good, since you have to have the basics down before you get too deep into the language. Now, we all know that modern programs usually aren't strictly single-number or single-character based. They usually allow you to input words.

Also, many times you'll have a list of numbers that you're going to need to perform calculations on. Using individual variables for every single one would get to be extremely tedious.

In this chapter, I hope to show you how to deal with strings, and also how to deal with arrays of numbers more efficiently than using individual variables to store the list of numbers. I will do so by introducing the concept of arrays to you.

Arrays are, simply, a list of variables of the same type (int, char, double etc.) that are addressed by using a common name. An individual variable held in an array is called an element. The list of variables are usually stored in contiguous memory locations. For instance, lets say you have an array that holds three elements. If the first element is located at 'memory address 1', then the next element would be located at 'memory address 2', and the last element would be stored at 'memory address 3'. If you don't understand how an array works yet, no need to fear. As always, once you get acquainted with them, it should all fall into place for you, and you will have a much better understanding of how they work once we get into pointers. That will come in the next chapter, though.

One-dimensional arrays Section 4.2

When you declare an array, it's quite similar to declaring a variable. You have the type of the array first, followed by the name we will be using to address the array, followed by an open-bracket, then a number denoting the size of the array, followed by a closed bracket, and then, of course, a semicolon.

All that the size of an array means is how many elements that the array can hold. So, lets say you declared an array with the size of 20. It would be capable of holding 20 different elements, or variables.

Here's the general format of how you'd declare an array:

PHP Code:
type array-name[size]; 
And an example of an actual declaration:

PHP Code:
int grades[20]; 
All that does so far is reserve some memory for us that we can address using the handle "grades".

Now, we want to be able to actually put numbers in there. What good would that do us if we couldn't use numbers? There are many ways of assigning a number to each individual element in an array. The easiest way to pick out a certain element and assign a number to it would be doing this:

PHP Code:
grades[1] = 6
That will assign grades[1] the value of 6. The 1 inside the brackets is known as the index number, because it is indexing the element known as grades[1]. Now, a little thing you must know about arrays in C is that the index number begins with 0. That means when you use grades[1] you are actually indexing the second element in the array. To index the first element you would use grades[0]. Also, keep in mind, since indexing begins with 0, the greatest index number you could use in this instance is 19, because we've only set aside 20 elements.

You can use this simple indexing scheme with normal functions. You can use the individual elements just as you would any other variable, so it would be perfectly fine using them with scanf() or printf().

Now if you want to initialize an array you would do so like this:

PHP Code:
int grades[5] = {961007590100}; 
The syntax is simple. It's just like you're declaring an array, except instead of an immediate semicolon, you use an equal sign, followed by a curly-brace, and then the values for each individual element separated by commas, followed by another curly brace and then a semicolon. In the example above, grades[0] would be 96, grades[1] would be 100, grades[2] would be 75, grades[3] would be 90, and grades[4] would be 100. Remember, it can only index up to 4. Initializing char variables is slightly different. I'll cover that in the next section.

Now, I'm going to write a simple program that prompts a user for 10 grades, inputs them to a variable, and finally asks the user to input an assignment number to find out what grade they made on that assignment.

PHP Code:
#include <stdio.h>

int main(void)
{
  
int grades[10];
  
int i;
  for(
i=0i<10i++)
  {
      
printf("Please input grade for assignment # %d\n"i+1); 
      
scanf("%d", &grades[i]);
  }

  
printf("Please eneter the assignment number you'd like to look up\n");
  
int assignmentNumber;
  
scanf("%d", &assignmentNumber);
  
printf("The grade you made on assignment number %d was %d\n"assignmentNumbergrades[assignmentNumber-1]);
  
  return 
0;
    } 
The first thing this simple program does is declare an array of integers with the handle grade, and gives it a size of 10. Then it declares another integer, i, which is used as our loop control variable. It then goes into a loop, which loops ten times. Inside the loop, it prompt the user to input a certain assignment. The reason we use i+1 in the printf() is because the index starts at 0, and usually people start counting from 1. Then it has a scanf() statement which inputs a number and stores it at location grades[i] (it uses the loop control variable to store a variable at the element's location). Once it's out of the loop it prompts the user to enter the number of the assignment that they'd like to look up. It declares another integer variable, called assignmentNumber which stores the number that the user enters. It then prints that number. The reason we use [assignmentNumber-1], again, is because the user will enter starting from #1, while the computer starts from 0.

Strings Section 4.3

Strings Basics Section 4.3.1

Strings, in C, are just an array of characters, which are terminated by a null byte. A null byte in C is simply a byte which contains 0 (zero, not the letter O). That means when you declare a string, it must be able to hold one character extra than the largest string it needs to hold, as it must be able to hold the null value at the end of the array, which denotes that the string has ended.

Let’s say, for example, we have a null-terminated string, c, which holds the value “that”. We would need an array which could hold 5 char variables. Here’s what each individual element in the array would hold: c[0] would hold the character ‘t’, c[1] would hold the character ‘h’, c[2] would hold the character ‘a’, c[3] would hold the character ‘t’, and c[4] would hold the value ‘\0’. The ‘\0’ is how you typically assign the null variable.

Initializing Strings Section 4.3.2

Now, initializing a string can be done very much the same way as initializing a regular array, but that’s not the easiest way to do it, and I will show you why later. For learning purposes, here is an example of how to initialize a string in the not-so-efficient way:

PHP Code:
char c[5] = {‘t’‘h’‘a’‘t’‘\}; 
Take note that when you are initializing an array of chars then you must use the single-quotes as I have done above.

There is a much easier way to initialize a string, though. Instead of putting every value in single quotes, separated by a comma, you can simply use double-quotes. When you do this, you don’t need to separate every value by a comma, and you don’t need to add the null character at the end of the string. C takes care of that for you. Here’s an example:

PHP Code:
char c[5] = “that”
String Functions Section 4.3.3

There are many ways to get string input, but the function that I use is gets(). gets() is located under the stdio.h header file. The gets() function is unbelievably simple. It takes one argument, the name of the array you want to store the value that the function gets. It reads characters from the keyboard until you press enter. The value for enter is not stored, and is instead replaced with a null-terminator.

There is one potential problem with gets(). It provides no bounds-checking whatsoever, so if you were to enter more characters than the array is capable of holding, then the array would overflow, and the extra characters could be saved over other memory that is important to the program, possibly causing the program to crash. Later, in this tutorial, I will show you alternatives to gets(), but for now, it should do.

Now, you can output a string in many ways as well, but for now we’ll continue to use printf(). I will show you other functions for outputting a string later. printf() works just as we’ve been using it all along, except for the fact that instead of using the %d format specifier like we have been thus far, we will use %s.

Here’s a short and simple program demonstrating how to use gets() and printf(). All this program will do is ask a user to input any string they want up to 20 characters, and print it back out to them.

PHP Code:
#include <stdio.h>

int main(void)
{
    
printf(“Please enter a string up to 20 characters.\);
    
char str[21]; // one extra for null-terminator
    
gets(str);
    
printf(“You inputed %str);
    return 
0;

As you can see, using either of the two functions that I’ve covered above is quite easy.

Now, aside from basic input/output, there are four string functions that you should commit to memory, and that you will probably use fairly often. These are strcmp(), strlen(), strcpy(), and strcat(), all of which lie in the string.h header file. I will cover what each of these functions do in the following paragraphs.

strcmp() simply compares to see if two strings are the same. This function is case-sensitive. strcmp() takes two arguments, both arrays of chars. It returns 0 (zero) if the strings are the same, less than zero if the first argument would appear before the second argument in the dictionary, and greater than zero if the first argument would appear after the second argument in the dictionary. Simple. Here’s the general format:

PHP Code:
strcmp(str1str2); 
And a simple program that asks you to enter the word “hello.”

PHP Code:
#include <stdio.h>
#include <string.h>

int main(void)
{
    
char str[10]; 
    while(
strcmp(str“hello”) != 0)
    {
  
printf(“please input the word \”hello\”\);
  
gets(str);
    }
    
    return 
0;

strlen() takes one string argument, and returns its length. It doesn’t count the null-terminator, so if you had a string that held the word “that”, strlen() would return 4. Here’s strlen()’s general format:

PHP Code:
strlen(str); 
And as always, a simple program to demonstrate its usage.

PHP Code:
#include <stdio.h>
#include <string.h>

int main(void)
{
    
char str[80];
    
printf(“Please enter a string“);
    
gets(str);
    
printf(“\n%s contains %d characters”strstrlen(str));

    return 
0;

strcpy() takes this general format:

PHP Code:
strcpy(str1str2); 
strcpy() copies the string in str2 to str1. It performs absolutely no size-checks, so you, the programmer must make sure that str1 is big enough to hold
str2.

Here’s a simple program to demonstrate its usage:

PHP Code:
#include <stdio.h>
#include <string.h>

int main(void)
{
    
char str[80];
    
strcpy(str“hello”);
    
printf(“%str);

    return 
0;

This program should print “hello”.

And last, but not least, is our strcat() function. It performs concatenation on a string. All concatenation is, is the process of taking the contents of one string, and tagging it along to the end of another. strcat() takes two arguments. It takes the contents of the second argument, and adds it along to the end of the first argument. Here it is in action:

PHP Code:
#include <stdio.h>
#include <string.h>

int main(void)
{
    
char str[20] = “hello “;
    
strcat(str“there”);
    
printf(“%str);
    return 
0;

That program should output the phrase “hello there”.

Multi-dimensional arrays Section 4.4

A two-dimensional array is basically just an array of arrays. That probably sounds pretty confusing, but don’t worry; you’ll see what I mean soon enough.

Using a two-dimensional array is not much different than using a one-dimensional array. You simply add another set of brackets. Here’s a two-dimensional int array:

PHP Code:
int x[3][3]; 
That declares a two-dimensional integer array which is capable of holding nine different values. If a single-dimensional int array with the size of three is a list of three numbers, you can think of the example above as three separate lists, each capable of holding three numbers.

Everything stored in a two-dimensional array is still done in contiguous memory. The number on the right changes quicker than the number on the left. Here’s how the above example would look in memory:


x[0][0] = ‘location 1’
x[0][1] = ‘location 2’
x[0][2] = ‘location 3’
x[1][0] = ‘location 4’
x[1][1] = ‘location 5’
x[1][2] = ‘location 6’
x[2][0] = ‘location 7’
x[2][1] = ‘location 8’
x[2][2] = ‘location 9’


Of course, in reality the memory address would be something more like 0x10000, not ‘location 1’, but you get the picture. In memory, the array x[3][3]; would be the exact same thing as x[9]; but two-dimensional arrays provide a nice way to address things.

You are free to add as many dimensions to an array as you want, for all practical purposes. All you have to do to add additional dimensions is add the size of the new dimension along with the declaration of the array. The rightmost dimension changes quickest in memory.

You may have been wondering how to create an array of strings. Two-dimensional arrays are the answer. Here’s an example of an array of strings:

PHP Code:
char c[5][20]; 
You can think about that as five different words, each capable of holding 20 different characters. Using two-dimensional arrays with string functions are just as easy. You specify which string you want to operate on by using the name of the array, followed by a single set of brackets with the number of the word you want to work on inside the brackets. Here’s a couple of examples:

PHP Code:
gets(c[2]); 
And another:

PHP Code:
printf(“%c[2]); 
Those two examples should be pretty self-explanatory. The first one gets input from the keyboard, and proceeds to take that input and put it as the third word. The second one simply prints the third word to the screen.

To demonstrate this in a real life example, I’ve made a program that asks for five words as input, sorts them alphabetically, and prints them back out for the user.

PHP Code:
#include <stdio.h>
#include <string.h>

int main(void)
{
    
char words[5][20];
    
    
printf("Please enter five words less than 20 characters long:\n");
    
    
int i;
    for(
i=0i<5i++)
    {
          
gets(words[i]);
    }

    
int j;
    for(
0i<4i++)
    {
  for(
j=0;j<4;j++)
  {
      if(
strcmp(words[j], words[j+1])>0)
      {
    
char temp[20];
    
strcpy(tempwords[j+1]);
    
strcpy(words[j+1], words[j]);
    
strcpy(words[j], temp);
      }
  }
    }
    
    
printf("\nAnd here are the words sorted:\n");
    for(
i=0i<5i++)
    {
  
printf("%s\n"words[i]);
    }

    return 
0;

This code is a little tough to understand. If you don’t understand how this works, don’t worry. The biggest thing you need to get out of reading this code is to understand how multidimensional arrays work, and how to invoke string functions while using multidimensional arrays. That said, I’ll still walk you through this code.

The first part should be pretty easy for you to understand by now. The first thing this code does is declare a two-dimensional array, called words, which is capable of holding five words, each twenty characters long. After that, it prompts the user to input five different words.

It goes into a loop, which will repeat five times. Each time the loop runs through, the gets() function is called. When it says gets(words[i]); all it’s doing is taking the input the user gives, and putting it in [i]words. i of course is however many times the loop has iterated.

Now comes sorting, the tricky part. The type of sort that I’ve used is called a bubble sort. It uses a nested loop for the sorting. What it does is it runs through the list, comparing each string with the one stored next to it. If the one stored next to it comes before lexicographically, then it swaps the position of the two strings. It goes through the entire list of strings. It repeats itself 4 times, thus making sure that the list is, in fact, sorted.

Take a look inside the loop, and lets go through the code to find out how it works. If strcmp() returns greater than one (which means words[j+1] comes before words[j] lexicographically) then the two strings swap positions. The way they are swapped deserves some attention. First a new string, called temp, is created. It is used to store the word at words[j+1]. After that we copy words[j] into words[j+1]. We now have one of the strings exactly where we want, and the other stored in a temporary array. All that’s left from there is copying temp into words[j] and the swap is done.

If you don’t quite understand how the bubble sort works right now, don’t fret. I hadn’t originally planned on covering the bubble sort in this tutorial. If you want more information on how the bubble sort works, google it. Always remember, Google is a programmer’s best friend.

Conclusion Section 4.5

Hopefully you have an understanding of arrays now. Keep up your programming skills by making everything you can write. If you have any questions, suggestions, or just want to talk, feel free to PM me. I’d like to hear what you think.
Old
Profile PM WWW Search
Demosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to beDemosthenes seldom sees opportunities until they cease to be
 
Demosthenes