Lesson 8 – Arrays

In this lesson, we shall learn a very important data structure that is very commonly used in programming. This data structure is called the array.

When you want to store many information that uses an index to keep track, an array is the data structure to use. Some examples are like storing telephone numbers, marks and grades.

Array

Refer to the C++ documentation on array. There are a few ways to declare an array:

int foo[5]; // declare array with a storage of 5 elements
int foo[5] = {16, 2, 77, 40, 12071}; // declare array with 5 integers inside
int bar[5] = {10, 20, 30};
int baz[5] = {};
int foo[] = {16, 2, 77, 40, 12071}; // automatic resize of array to fit the elements

You can access an array element by using its index.

Using the example in the documentation:

// Program 8.1
#include <iostream>
using namespace std;
int foo [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
    for ( n=0 ; n<5 ; ++n )
    {
        result += foo[n];
    }
    cout << result;
    return 0;
}

Before you type the program, guess what this is going to do. After this, type and run the program. Did you get what was expected?

Characteristics of Arrays

Arrays are very powerful data structures that is widely used in programming. However beginners usually think that you can add elements whenever you want to. This is not the case. An array, once declared, cannot change its number of storage. In some modern programming languages, this limitation is removed such that the array can dynamically change its storage. However, C++ is not such a language.

In the next lesson, we shall discuss array’s more powerful cousin, the vector. For this lesson, let us use arrays to perform some useful operations.

Challenge 2

You are a teacher and you have 10 students. You want to keep all their test marks in an array and use it to calculate the average. Also print out the highest mark and lowest mark.

This challenge is equivalent to the IGCSE Computer Science syllabus requirement for programming.

Input: you will key in ten marks altogether.

Output: Console will print out the average, highest and lowest marks.

Answer

Lesson 7: Functions

Remember that a C++ program always start from the main function? In this lesson, you will learn about what a function is.

An add function

In the earlier, you learned to write a program to add two numbers.

//Program 7.1
int x = 0, y = 0;
int answer = 0;
std::cin >> x;
std::cin >> y;
answer = x + y;

Instead of adding the two numbers inside the main function, now I want to add them in a function. To do this, I need to declare a new function (computer doesn’t know about your new functions unless you declare them, like variables). The way to declare a function is this:

return_type function_name (data_type variable_name, ...)

For example, in the case of an add function, I would need to have two arguments so that I can add them. The two arguments will be declared inside the parenthesis. After adding, I need to return the answer to whatever variable that calls the function.

int add (int x, int y)

Above means that the add function takes in two inputs x and y of the integer type, and returns an integer type. Modify Program 7.1.

// Program 7.2
int add (int x, int y){ 
  return x + y; 
}

int main(int argc, const char * argv[]) {
 
 int x = 0, y = 0;
 int answer = 0;
 std::cin >> x;
 std::cin >> y;

 answer = add(x,y);
 
 std::cout << answer << std::endl;

 return 0;
}

You might ask why not just add the values inside the main function. If your program is large, having many operations inside your main function makes it unreadable. Breaking out the operations into functions make it easier for your program to be read and understand.

Other examples

A function may also return null type. This means that it does not return anything. To declare such type of functions, use the keyword void.

// Program 7.3
void sayHello () {
 std::cout << "Hello" << std::endl;
}

int main(int argc, const char * argv[]) {
 
 sayHello();
 
 return 0;
}

In Program 7.3, you see that the sayHello function does not need any input, and it does not return any type. If a function does not need any arguments, then use a pair of parenthesis ().

Challenge 1

Write a program to add, subtract, multiply and divide two integers. Break out each operation into its respective functions. Ask user to select an operation using 1,2,3 or 4, representing add, subtract, multiply and divide respectively. Also ask user to input two integers.

Output the answer to console.

Challenge 2

A classic programming exercise is called the FizzBuzz Test. The problem is stated below:

“Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.”

Write a program that perform the above test.

 

 

 

 

 

Answers: Lesson 8

// Challenge 2

#include <iostream>

int main ()
{
 int marks[10];
 int total = 0, max = -1, min = 100;
 
 for (int i = 0; i < 10; i++) {
 std::cout << "Enter mark " ;
 std::cin >> marks[i];
 
 total += marks[i];
 if (max < marks[i]) {
 max = marks[i];
 }
 if (min > marks[i]) {
 min = marks[i];
 }
 }
 
 std::cout << "The maximum mark is " << max << std::endl;
 std::cout << "The minimum mark is " << min << std::endl;
 std::cout << "The average mark is " << total/10.0 << std::endl;
 
 return 0;
}

 

Lesson 6: Revision to while

Revise lesson 5 and attempt Challenge 2 and 3 once more.

Intermediate while

while is powerful because it allows a program to run until a certain condition is reach. Remember that you wrote a program to find the first 10 Fibonacci numbers in Lesson 4?

Challenge 1

Now, rewrite you program to find the number of Fibonacci numbers that are less than 1000. You will need to use the while keyword. Hint: you need to use if to check whether the Fibonacci number is greater than 1000. If it is, stop the while loop.

Reading/writing from a file

The programs that you are able to write till now read values from keyboard and output to the console. Sometimes, you might want to read large amount of data and the data is usually presented in a file. In this section, you will learn how to read and write to files on the computer.

filestream

You include the iostream to read from keyboard and print to console. If you are going to read and write to file, then you need to include the filestream library.

#include <iostream>
#include <fstream>

int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}

Go to this web page and read until you reach Text files.

Challenge 2