ES101 - Lesson 5 : Arrays and for Loop
Contents
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:
/**
* i=0 is done once before the loop
* i<3 is checked at the beginning of every loop
* i++ occurs at the end of each loop
*/
for(int i=0; i < 3; i++)
{
printf("Hello World");
}
/**
* Here is how the loop works and prints "Hello World" 3 times:
* i=0, 0 < 3 ? yes --> print "Hello World"
* i=1, 1 < 3 ? yes --> print "Hello World"
* i=2, 2 < 3 ? yes --> print "Hello World"
* i=3 3 < 3 ? no --> Quit the loop
*/
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
- Get the user's first name and store it to a char array
- Declare a character array to hold at least 20 characters.
- Ask for the user's firstname, and store the name into your char array.
- Hint: Use %s for scanf. %s will only scan one word and cannot scan a name with spaces.
- You can use "%s %s" to get first and last name if you wish.
- Get 3 exam scores from the user :
- Declare an array of 3 integers
- Assume the scores are out of 100, and use a for loop to get user's input
- Your prompts should print out which exam score you are asking for:
- Example: "What is the score of exam #1?" ... "What is the score of exam #3?"
- Warning: Be careful of your array indexes!
- Find out the average exam score:
- Use a for loop to calculate the sum of all exams.
- Divide the sum by 3 to get the average and store this data in a variable.
- Print the summary for the user similar to:
- "Hello Charley, based on your exam scores of 80, 90, and 100, your average is 90.0 with letter grade of an 'A'"
- You should re-use your previous code to calculate the grade letter from the average percentage.
Sample Code
int main(void)
{
// Always set variables to zero, including arrays
int scores [3] = { 0 };
// Assume you ask for scores 3 times
// Let's add up the scores:
int sum = 0;
for(int i=0; i<3; i++) {
sum += scores[i];
}
printf("Total sum of your scores: %i\n", sum);
return -1;
}
Questions
int main(void)
{
// Find the output of the following and explain it:
char name[] = "Hello";
name[2] = '\0';
printf("%s\n", name);
return -1;
}