ES101 - Lesson 5 : Arrays and for Loop

From Embedded Systems Learning Academy
Revision as of 22:49, 6 September 2012 by Preet (talk | contribs) (Assignment)

Jump to: navigation, search

Data Arrays

An array is just a group of variables. If you wanted to allocate 10 integers for common purpose, you don't have to name them or declare them individually. Instead, you can declare an array of integers. See the following code fragment for examples:

int int_array_a[3];             // Array of 3 integers (not assigned)
int int_array_b[3] = {1, 2, 3}; // Array of 3 assigned integers
int int_array_c[]  = {0, 0, 0}; // Auto-sized array of 3 assigned integers

// After you declare an array, you access it using indexes
// Index starts from 0.  Above arrays can be accessed using index 0-2
printf("Array Element 0 = %i\n", int_array_b[0]);

// Get input to last element of the array:
scanf("%i", &int_array_c[2]);

// Print the entire array: 
printf("Array elements are: %i %i %i\n",
        int_array_a[0], int_array_a[1], int_array_a[2]);

Declaring and using arrays are easy as can be seen in the previous code sample. The only pitfall to watch for is using the correct index location. For example, if you access array index 3 or higher, this would produce a run-time error and the result of the code is unpredictable. You as a programmer need to know the desired size of the array, and you must use the index locations of the array carefully to avoid programming errors. Similar concepts apply to other arrays, such as float, and long int, or unsigned int, however, character arrays are slightly different and are covered in the next section.


char Arrays (string)

A char array, or character arrays are often referred to as strings. Although they are very similar in use like the integer and floating-point arrays, there is one exception. Character arrays require one extra memory space to mark the end of the string. To mark the end of the string, a null character is used. A null character is the same as integer 0, or '\0' or the word null.

For example, if you wanted to store “Hello”, you would allocate 6 chars, 5 to store the word “Hello” and one to mark the end of the string. This is required for strings because functions like printf, or other string manipulation functions need to know the end of the string.

char str1[] = "CmpE";
char str2[] = {'C', 'm', 'p', 'E', '\0'};

// str1 and str2 do the same thing.
// str1 automatically gets a NULL character
// str2 manually gets the NULL character

// Let's print out the two strings:
printf("str1=%s, str2=%s\n", str1, str2);

When printf is instructed to print %s, it will print one character at a time of the given char array until it sees a NULL character. This is why you need a null character at the end of a string. In conclusion, when char arrays or strings are used, one extra memory space is used to mark the end of the string. For example, you might declare a string with 32 memory spaces, however, if a user enters a name, it might use only 5 memory spaces out of 32, so 6th memory space is marked as NULL to indicate the actual usage of the string memory.

string Pitfalls

Since string manipulation has to be done character by character, you cannot simply set a string equal to a bunch of characters (the exception being when a string is declared). Similarly, you cannot say if (str1 == str2), because again, the strings have to be compared character by character. Fortunately, a lot of string manipulation functions can be included from #include <string.h> Please see examples at the following website:
C++ Reference

char str1[32];

str1 = "Hello";        // WRONG! You can only use = when declaring an array
strcpy(str1, "Hello"); // Correct method

char str2[] = "world";
if(str1 == str2) {            // WRONG!   You cannot use == on strings
}
if(0 == strcmp(str1, str2)) { // Correct method
}


for Loop

for loops are usually used to iterate through arrays and provide the preferred form of loop iterations. Another common use this type of loop is when the number of iterations is known, and is not dynamic. Let's start with an example first:

for(int i=0; i < 3; i++) 
{
    printf("Hello World");
}

In the example above, notice that for loop has three code statements enclosed on a single line, separated by semicolons. The first statement says that i = 0, which happens prior to starting the loop. The next statement dictates when the for loop should execute the code body, and the third statement says what should happen at the end of the loop iteration. In this example, the “Hello” will be printed three times, when i is equal to 0, 1, and 2, and finally the loop will quit when i equals to 3 since i < 3 condition will turn to false.

In the previous section, you learnt that the null character marks the end of the char array, so next is a for loop that calculates the length of a char array. Notice that the loop continues, without any code in its body because we just want to increment len until the null character is found in the char array.

char name[32];
printf("Enter your first name: ");
scanf("%s", &name[0]);

int len = 0;
for(len=0; name[len] != '\0'; len++)
{
    // Empty loop to just check when we encounter NULL character
}

printf("Your name is %i characters long\n", len);


Assignment

  1. Declare a character array to hold at least 20 characters. Ask for the user's name, and store the name into the character array.
    Hint: Use %s for scanf.
  2. Declare an array of integers of 3 integers to store exam scores of the user. Ask the user to input their last 3 exam scores out of 100, and store the input into individual array elements. Use a for loop for this purpose. #* Your prompt should ask something similar to:
    • What is the score for exam #1?
    • What is the score for exam #2?
    • What is the score for exam #3?
  3. Calculate the average score for the user, and print out the user's name and percentage formatted to 2 decimal places.
    Hint: Use another for loop to add up the elements of the array, then divide by 3.