Heriot-Watt logo
CEE logo


Information Resource Pages

Welcome to the Software Engineering module for MSc Information Technology Students. These pages are intended to complement the course and contain details of the course as well as some additional material.


Aim of Course


Structure of Course


Teaching Details

This module should consist of approximately 100 hours of student effort. This will consist of 3 taught lectures per week and 2 hours for computing labs when help will be available.

Note that you will be given exercises for each aspect of the programming which you are advised to attempt before coming to the help sessions. This will enable you to gain the optimum usage of the help sessions.

One of the aims of this module is to gain experience on the use of UNIX workstations. However, there is no lab of workstations which is large enough to accommodate this class. Therefore the lab sessions will use PC-Caledonia in room 2.50/2.52 and eXceed to access UNIX workstations. At other times, you are encouraged to use the UNIX workstations elsewhere in the department - e.g. the Linux Boxes in rooms G.46 & G.47.

Information is given here on using eXceed.

 

Information is given here on using Unix Workstations directly.

 

Information is given here on installing GCC Compiler on your PC at HOME. 

You will be examined on this work as part of the MSc exam in April and you will have to submit an assignment at the end of the course. This assignment will be a larger programming exercise combining the individual elements of programming you have already been taught into a larger project. This assignment will be issued mid term, at the end of the taught programming part of the course and the beginning of the software engineering principles.


ASSIGNMENT

Feedback on Assignment


Introduction to Computing and Information Technology


C++ Programming

The outline of the programming part of the course is detailed below, and from the links on each of the topics you can access copies of all the source code listed in the notes, some additional example programs and some additional suggested exercises.

The source code given can be copied and compiled as detailed here.

Programs and Programming

Variables, Data Types, Constants and Operators

Control Constructs

Iteration

Arrays and Structures

Functions

Pointers

File Input and Output

Introduction to Classes

First Lecture 


Software Engineering Principles


More on Unix operating systems


Recommended Text

There is no specific recommended text. People tend to have different ideas about what they want from a text book, therefore I would recommend that you look in the bookshop and see what you think of the books. Any book on C++ programming, which starts from the very basics, should cover the C++ programming required for the course. Note that some books may aasume that you have programmed in C before.

 If you have NEVER programmed before, I personally would choose books such as:

Steve Oualline, "Practical C++ Programming", O'Reilly Associates

John Hubbard, "Programming with C++", Schaums Outline Series

NOTE: Full detailed notes will be provided at the lectures.


Announcements

Any announcements regarding the course will be detailed here.


If you have any queries please send email to me at jmb@cee.hw.ac.uk

NOTE: Clipart from http://www.signgray.demon.co.uk/clipart/


Disclaimer: As ever, these pages are still under construction, and bugs in the programs are an added bonus to the learning experience! However, please email reports of any bugs to me.
 
 


 

Programs and Programming


Learning Objectives

 

Understand the terms source code and executable

 

Be able to use an editor to enter a source program into a file

 

Be able to compile the source code to produce the executable

 

Be able to run the program

 

Understand the basic layout of a simple program - including the keyword main, the use of the semi-colon and the cout statement

 

Combine the above to be able to write simple programs to output text to the screen

Source Code from Notes

Additional Examples

Quick Check Exercises

Additional Exercises to try


Home

Next Lecture

Basic Programming

Source Code from Notes





Example

   // Program written October 1997
   // by jmb

#include <iostream.h

main()
{
        cout <<< "Hello World!\n";
        // \n causes new line 
}


Back to Main Page for Lecture 1 

Basic Programming

Case Study





PROBLEM:

Write a program to display the text, This is my first program, on the screen.


SOLUTION:

The program must start with #include as the the program will output text to the screen.

The main body of the program is contained within curly braces which follow the keyword main().

The text is displayed on the screen using the cout statement. Note that this statement requires a semi--colon at the end to indicate the end of the statement.

Comments have also been included to make the programme easier to understand.

// My first program
// Written by jmb
// October 1998

#include <iostream.h

main()
{
        cout <<  "This is my first program \n";
        // \n is required to produce newline 
}


Basic Programming

Additional Exercises


    1. Write a program to display your name, address and telephone number on the screen.
    2. Correct the mistakes in the following program, type it in and compile the program.
// Example Program
   Week 1
   April 1997 
//
mAin(

        / display data to screen 
        cout << "Example Program\n";
        cout << 'for Introduction to Programming Class\n 
        cout  " Autumn Term 1999/n";
        cout  " Illustrates the basic components of C++\n;
}


 

Programs


    1. What is the purpose of #include <iostream.h ?
    2. What is a source program? An executable?
    3. Is a semi-colon required after a comment?
    4. What is wrong with the following statement?
    5. cout << Hello World\n;
    6. What is wrong with the following statement?
    7. COUT << "Hello World\n";
    8. What is wrong with the following statement?
    9. cout   "Hello World\n";
    10. What is the purpose of the \n ?
    11. What is wrong with the following statement?
cout << "Hello World"\n;



 


    1. It includes the header file iostream.h into the source code. This file is required for input and output to the program. Therefore, if the cout statement is used to output text/data to the screen it is required.
    2. Source code is the actual C++ program which is typed into the file. This is then compiled into machine code which can be executed by the computer.
    3. No - a comment is not a program statement, so does not require to be terminated by a semi-colon.
    4. The text to be printed must be within double quotes.
    5. cout << "Hello World\n";
    6. Keywords in C++ must be lowercase COUT must be written as cout
    7. The output operator is << and not
    8. The \n causes the a new line. It is required at the end of Hello WOrld to ensure the cursor returns to the next line.
    9. The \n (newline) is text to be printed and must be within the double quotes.


 

 





 

Variables, Data Types, Constants and Operators


Learning Objectives

 

Be able to declare variables

 

Be able to write simple arithmetic expressions

 

Be able to input values typed at the keyboard into a program using cin

 

Be able to output values to the screen using cout 

 

Be familiar with the concept of constants 

 

Be able to combine above to write simple programs which require the use to input values, make calculations and output the results

Source Code from Notes

Additional Examples

Quick Check Exercises 

Additional Exercises to try

Test Cases for Tutorial


Variables, Data Types, Constants and Operators

Source Code from Notes





Example 1

//  program to add two integer values 
//  and display result                 

#include <iostream.h

main()
{
        // declare variables 
        int     value1, value2, sum;

        // assign values and compute the result 
        value1 = 32;
        value2 = 27;
        sum = value1 + value2;

        // display the result 
        cout << "The sum of " << value1 << " and  << value2  << " is " <<
                sum << "\n" ;
}


Example 2

This is the example program to calculate the area of a rectangle

#include <iostream.h

main()
{
        // type definitions 
        // 3 variables - length, breadth and area 

        float   length, breadth, area;

        // input phase - read length and breadth from user 

        cout << "Enter the length and breadth\n";
         cin  length  breadth;

        // computation - calculate area 

        area = length * breadth;

        // output phase 

        cout << "The area of the rectangle with length  " << length << " and breadth "
             << breadth  << " is " << area << "\n"; 

}


Example 3

This example calculates the average value of three numbers entered by the user.

// Program to calculate the average of three numbers
#include <iostream.h

main()
{
        float   number1,number2,number3;
        float   average;

        // Enter values
        cout << "Enter three numbers: ";
        cin  number1  number2  number3;

        // calculate average
        average = (number1 + number2 + number3)/3.0;

        // Output result
        cout << "The average value of " << number1 << " , " << number2 <<
             " and " << number3 << " is "  << average << "\n";
}


Example 4

This example prompts the user to input a number and then calculates the reciprocal of this number.

// Program to calculate the reciprocal of a number
#include <iostream.h

main()
{
        float   number;
        float   reciprocal;

        // Enter Value
        cout <<"Enter a number: ";
        cin  number;

        // Calculate reciprocal
        reciprocal = 1.0 / number;

        // output result
        cout << "The reciprocal of " << number << " is " << reciprocal << "\n";
}


Example 5

This example illustrates the use of constants. It calculates the area and circumference of a circle, when given the radius.

// program to calculate circumference and area of circle 

#include <iostream.h

main()
{
        const float PI = 3.14156;
        // define variables
        float   radius,circumference,area;

        // Input radius
        cout << "Enter the radius: ";
        cin  radius;

        // calculate radius and circumference
        circumference = PI * 2 * radius;
        area = PI * radius * radius;

        // display results
        cout << "The circumference is " << circumference << " and the rea is " << area 
             << "\n"; 
                                           
}


Variables, Data Types, Constants and Operators

Case Study





PROBLEM:

Write a program to calculate an employees wages. They are paid at a basic rate of &pound;6.65 hour, but are taxed at a rate of 23% and pay a pension contribution of 4% and pay a union subscription of 1.25 per week.

Write a program to read in the hours worked and calculate the take home weekly wages of the employee.


SOLUTION:

The structure of the program will take the following form:-

#include <iostream.h

// Declare constants 

main()
{
        // declare variables 

        // prompt user to enter number of hours worked and read in value 

        // Calculate wages 

        // output weekly wages 
}

Constants

We are told that the employee is paid 6.65 per hour is taxed at a rate of 23%, pays 4% pension contributions and a union fee of 1.25. We should make these values be constants - since they have been given to use. In addition, this makes it easier to change these values at a later date and if we use meaningful names will make the program easier to read. Therefore we will declare:-

const float hourly_rate = 6.65;
const float tax_rate    = 0.23;
const float pension_rate = 0.04;
const float union_fee   = 1.25;

I have converted the percentages to floating point values, since for example 23% = 23/100 * value.

Variables

We are obviously going to require a variable to store the number of hours worked, which we will assume can be a fractional number of hours and therefore use a floating point value. We will also use variables for the gross_pay, pension, tax, deductions and total_pay. All of which will be floating point values.

        float   hours, gross_pay, tax, pension, deductions, total_pay;

Input

We require to prompt the user to enter the number of hours worked and then read this into the variable hours .

        cout << "Enter the number of hours worked \n";
        cin  hours;

Calculation

There are a number of different ways this could be implemented. I have chosen here to do it in a number of different stages. Calculating initially the gross wages and then the deductions.

        gross_pay = hours * hourly_rate;
        tax = gross_pay * tax_rate;
        pension = gross_pay * pension_rate;
        deductions = tax + pension + union_fee;
        total_pay = gross_pay - deductions;

Output

Finally we have to output the result. This can be achieved by the statement

        cout << "The total weekly pay is " << total_pay << "\n";

Total Program

#include <iostream.h


main()
{
        // Declare constants 
        const float hourly_rate = 6.65;
        const float tax_rate    = 0.23;
        const float pension_rate = 0.04;
        const float union_fee   = 1.25;
        //declare variables 
        float   hours, gross_pay, tax, pension, deductions, total_pay;

        //prompt user to enter number of hours worked and read in value 
        cout << "Enter the number of hours worked \n";
        cin  hours;

        // Calculate wages 
        gross_pay = hours * hourly_rate;
        tax = gross_pay * tax_rate;
        pension = gross_pay * pension_rate;
        deductions = tax + pension + union_fee;
        total_pay = gross_pay - deductions;

        // output weekly wages 
        cout << "The total weekly pay is " << total_pay << "\n";
}


Variables, Data Types, Constants and Operators

Additional Exercises





    1. Write a program which prompts the user to enter 2 integer values. The program will then print their sum, difference, product, quotient and remainder.
    2. Write a program which will prompt the user to enter a positive floating point number. The program will then display the integral part and the fractional part of the number.
    3. For example:-
      number = 2.33
      integral = 2
      fractional = 0.33
    4. Write a program which prompts the user to enter a number of days, hours and minutes. The program will then calculate and display this as a total number of minutes.
For example
days = 1
hours = 12
minutes = 15
Total number of minutes = 2175


 

Variables, Data Types, Constants and Operators


  1. What is wrong with this program?
  2. main()
    {
            p=47;
            cout << p;
    }
  3. What is wrong with this declaration?
  4. 
    int x = y = 95;
  5. Write four different C++ statements that subtract 1 from the integer variable x.
  6. Which of the following are valid C++ statements? Evaluate the ones which are valid.







      1. The #include <iostream.h is missing and the variable p has not been declared.
      2. The equals sign can only be used in a declaration to initialise a variable. Therefore it should be
int     x=95, y =95;
x = x - 1;
x --;
--x;
x -= 1;

















 

Control Constructs


Learning Objectives

 

Know the relational and logical operators

 

Be able to use the if statement 

 

Be able to use the if....else statement

 

Be able to use the else ... if statement to implement multi-way branching

 

Know when it is suitable to use the switch statement for multi-way branching and be able to implement it

   

Source Code from Notes

Additional Examples

Quick Check Exercises 

Additional Exercises to try

Test Cases for Tutorials


Control Constructs

Source Code from Notes





Example 1

//Program to calculate absolute value of an integer

#include <iostream.h

main()
{
        int     number;

        //Enter number
        cout << "Enter a number: ";
        cin  number;

        //test if negative
        if (number < 0)
                number = -number;

        //output results
        cout << "The absolute value is " << number << "\n";
}


Example 2

//Program to test if number is even or odd

#include <iostream.h

main()
{
        int     number,remainder;

        cout << "Enter a number: ";
        cin  number;
        
        remainder = number % 2;

        if (remainder ==0)
                cout << "The number is even\n";
        else
                cout << "The number is odd\n";

}


Example 3

//Program to illustrate the use of nested if statements

#include <iostream.h

main()
{
        int number;

        cout << "Enter a number between 1 and 99: ";
        cin  number;

        if (number  0 && number < 100 ) 
        {
                if (number < 10)
                        cout <<  "One digit number\n";
                else
                        cout << "Two digit number\n";
        }
        else
                cout << "Number not in range\n";

}


Example 4

#include <iostream.h

main()
{
        int number, n_digits = 0;

        cout << "Enter a number: ";
        cin  number;

        if (number = 100)
                n_digits = 3;
        else if (number =10)
                n_digits = 2;
        else if (number =0)
                n_digits = 1;
        else
                cout <<  "Value out of range\n";

        if (n_digits  0)
                cout << "The number has " << n_digits << " digits\n";
}


Example 5

#include <iostream.h

main()
{
        char    day;


        cout << "Which day?";
        cin  day

        switch(day){
                case 's': cout << "Weekend\n";
                          break;
                case 'm': cout << "Week day\n";
                          break;
                case 't': cout << "Week day\n";
                          break;
                case 'w': cout << "Week day\n";
                          break;
                case 'f': cout << "Week day\n";
                          break;
                default:  cout << "Not a day\n";
        }
}


Example 6

#include <iostream.h

main()
{
        char    day;

        cout << "Which day?";
        cin  day;

        switch(day){
                case 's': case 'S': cout << "Weekend\n";
                          break;
                case 'm': case 'M': cout << "Week day\n";
                          break;
                case 't': case 'T': cout << "Week day\n";
                          break;
                case 'w': case 'W': cout << "Week day\n";
                          break;
                case 'f': case 'F': cout << "Week day\n";
                          break;

                default:  cout << "Not a day\n";
        }
}


Example 7

#include <iostream.h

main()
{
        int     input_value;

        cout << "Which day?";
        cin  input_value;


        switch (input_value){
                case 1: cout << "The day is Monday\n";
                        break;
                case 2: cout << "The day is Tuesday\n";
                        break;
                case 3: cout << "The day is Wednesday\n";
                        break;
                case 4: cout << "The day is Thursday\n";
                        break;
                case 5: cout << "The day is Friday\n";
                        break;
                case 6: cout << "The day is Saturday\n";
                        break;
                case 7: cout << "The day is Sunday\n";
                        break;
                default : cout << "Invalid Input\n";
                        break;
        }
}


Control Constructs

Case Study





PROBLEM:

Write a program to calculate the commission based wages of a computer salesman. His basic wage is &pound;50 per week and he is expected to sell at least 10 computers. If he sells more than 10 computers, he receives an extra &pound;5.50 per computer he sells after the 10th computer.


SOLUTION:

The basic algorithm could be drawn as:-
 
 


 





The structure of the program would then be:-

DECLARE CONSTANTS
DECLARE VARIABLES

PROMPT USER TO ENTER NUMBER OF COMPUTERS SOLD 
READ IN NUMBER



CALCULATE PAY
        IF SELLS MORE THAN 10 
                CALCULATE COMMISSION

OUTPUT PAYMENT

adding the actual code to the above:-

#include &ltiostream.h


main()
{
         //DECALRE CONSTANTS
        const float BASIC_PAY = 50;
        const int LEVEL = 10;
        const float COMMISSION = 5.50;

         //DECLARE VARIABLES
        float pay, commission_pay;
        int num_computers;


        //PROMPT USER TO ENTER NUMBER OF COMPUTERS SOLD 
        cout << "Please enter number of computers sold: \en";
        //READ IN NUMBER
        cin  num_computers;


        //CALCULATE PAY 

        if (num_computers  level)
        {
                commission_pay = (num_computers - LEVEL)* COMMISSION;
                pay = BASIC_PAY + commission_pay;
        }
        else
                pay = BASIC_PAY ;

        //OUTPUT PAYMENT
        cout << "Your wage for this week is " << pay << " pounds\en";


}

NOTE that this is only one possible solution to the problem.

Try to think of some alternative methods of solving this problem.


Control Constructs

Additional Exercises





    1. An employee in a company is paid at a rate of &pound;5.20 per hour. The standard rate is paid for up to 37 hours worked in a week, after which 1.5 times the standard rate is paid. 22% tax is deducted from the gross pay as well as 5% for national insurance and 6% for the company pension scheme. If the employee works less than 20 hours a week, the income tax rate is only 20%.

    2.   Write a program to read in the hours worked and calculate the employees pay, displaying the gross salary and all the deductions as well as the net take home pay.

      Remember to make proper use of constants.

    3. A leap year is a year which is exactly divisible by 4, unless it is exactly divisible by 100 in which case it is only a leap year if it is exactly divisible by 400. Write a program which prompts the user for a year and then displays if it is a leap year or not.

    4.  

      Control Constructs


    5. What is wrong with the following?
    6. int x;
      if (x=1)
              x++;
    7. What is wrong with the following?
    8. int x, y, z;
      
      if (x  y && < z)
              x = y;
    9. Write an extract of code to test if the variable x is a positive number?
    10. Write an extract to test if the variable x is a positive and even number?


    11.  

        
       


    12. The test should be x== 1, with x=1 this will assign the value of 1 to x rather than checking if x is a 1.
    13. Assuming that it is intended to compare z to z, the test should be x y && x < z
    14.  if (x  0)
       if (x  0 && x%2 == 0)

       


      
      


       

      Iteration


      Learning Objectives

       

      Be able to use a while loop

       

      Be able to use a do..while loop 

       

      Be able to use a for loop

       

      Know how to change from one type of loop to another

       

      Know when one form of loop is more suitable than another i.e. would not use for loop when checking if input to program is within desired range.

         

      Source Code from Notes

      Additional Examples

      Quick Check Exercises 

      Additional Exercises to try


      Iteration

      Source Code from Notes





      Example 1

      This example reverses the digits of a number, and prints out the number in the reverse order. Each digit is displayed as it is extracted by the program. The final call to \fC\s8printf\fR\s0 returns the cursor to the next line as the newline character has not been included within the loop.

      #include <iostream.h
      
      main()
      {
              int     number, right_digit;
      
              cout << "Enter your number\n";
              cin  number;
      
              while (number !=0)
              {
                      right_digit = number % 10;
                      cout  right_digit;
                      number /= 10;
              }
      
              cout << "\n";
      }


      Example 2

      This example checks that the input value is in the desired range

      #include <iostream.h
      
      main()
      {
              int     number;
      
              const int min = 1;
              const int max = 100;
      
              number = 0;
      
              while ( number < min || number  max)
              {
                      cout << "Enter a number in the range 1 to 100\n";
                      cin  number;
              }
              cout << "the number is in range\n";
      }
      


      Example 3

      #include <iostream.h
      
      main()
      {
              char    letter;
      
              cout << "Press Y to continue\n";
              do
              {
                      letter = getchar();
              } while (letter != 'y' && letter != 'Y');
      
              cout << "program execution will continue\n";
      
      }


      Example 4

      The following program creates a conversion table for converting inches to centimetre. The values in the table are calculated for inches in the range 1 to 10 in half inch increments.

      #include <iostream.h
      
      main()
      {
              float   inches,centimetres;
      
              // print table header
              cout << "inches\t centimetres\n";
      
              //calculate and print table entries
              for (inches = 1; inches <=10 ; inches += 0.5)
              {
                      centimetres = 2.54 * inches;
                      cout << inches << centimetres << "\n";
              }
      
      
      }


      Iteration

      Case Study





      PROBLEM:

      Write a program to calculate the average marks for a class of students. The program will initially prompt for the number of students to be entered and then for each student will ask for their marks for each of the 4 exams the student sat. The program will then calculate the average mark for each student and the average mark for the whole class.


      SOLUTION:

      The solution to this will take the form:-
       
       


       

      where the program repeats for each student the code to enter the student's marks and calculate their average.

      This could be implemented using a while loop to produce

      //Using While Loop 
      
      #include <iostream.h
      
      main()
      {
      
              int     num_students, count;
              float   mark1, mark2, mark3, mark4;
              float   student_average, class_total = 0, class_average;
      
      
              // Enter no. of students
              cout << "Please enter the number of students in the class: ";
              cin  num_students;
      
      
              // set count to zero
              count = 0;
      
              while (count < num_students)
              {
                      // enter 4 marks for each student
                      cout << "Please enter the marks for student "
                           << count << "\n";
                      cin  mark1  mark2  mark3  mark4;
      
                      // Calculate average
                      student_average = (mark1 + mark2 + mark3 + mark4) / 4;
      
                      // Add average to total
                      class_total += student_average;
      
                      // Display average
                      cout << "The average mark for student " << count 
                           << " is " << student_average << "\n\n";
      
                      // Increment count for next student
                      count ++;
      
              }
      
      
              // Calculate class average 
              class_average = class_total / num_students;
      
              // Output Class average
              cout << "The class average is " << class_average << "\n";
      
      }

      When this program is run it produces the following output ( with sample figure inserted):-

      Please enter the number of students in the class: 4
      Please enter the marks for student 0
      23 45 63 54
      The average mark for student 0 is 46.25
      
      Please enter the marks for student 1
      67 87 67 87
      The average mark for student 1 is 77
      
      Please enter the marks for student 2
      54 65 34 76
      The average mark for student 2 is 57.25
      
      Please enter the marks for student 3
      34 35 36 25
      The average mark for student 3 is 32.5
      
      The class average is 53.25

      The program can be drawn schematically to show how it fits in to the flow structure given above. The code used for each part is shown alongside.

      The same program could be converted to a for and only the initialisation, loop statement and increment need to be changed. Here is the same program but written with the for loop.

      //Using For Loop 
      
      #include <iostream.h
      
      main()
      {
      
              int     num_students, count;
              float   mark1, mark2, mark3, mark4;
              float   student_average, class_total = 0, class_average;
      
              // Enter no. of students
              cout << "Please enter the number of students in the class: ";
              cin  num_students;
      
              // for statement includes initialisation, test and increment
              for (count = 0 ; count < num_students ; count ++)
              {
                      // enter 4 marks for each student
                      cout << "Please enter the marks for student "
                           << count << "\n";
                      cin  mark1  mark2  mark3  mark4;
      
                      // Calculate average
                      student_average = (mark1 + mark2 + mark3 + mark4) / 4;
      
      
                      // Add average to total
                      class_total += student_average;
      
                      // Display average
                      cout << "The average mark for student " << count
                           << " is " << student_average << "\n\n";
      
              }
      
      
              // Calculate class average 
              class_average = class_total / num_students;
      
              // Output Class average 
              cout << "The class average is " << class_average << "\n";
      
      }


      Iteration

      Additional Exercises





    15. In the train time table program, add loops to check that the times entered are valid (ie times entered are between 0 and 24 hours for the start and stop times and that the frequency and journey times are between 1 and 60 minutes).

    16.  

       

      Prevent the program from proceeding until suitable values are entered.

    17. Write a program which reads in a set of positive value real number values terminated by a negative value and prints out the sum of all these values.
    18. Write a program to find the largest, smallest and average values in a collection of n numbers entered by the user where n is the first data item entered.

    19.  

      Iteration


    20. Change to following code to a while loop.
    21. int     x, y;
      for (x=1; x < 57; x+= 2)
              y = x;
    22. What is wrong with the following?
    23. int     n=0;
      while (n < 100)
              value = n*n;
    24. Write a while loop that calculates the sum of all numbers between 0 and 20 inclusive?
    25. Convert the above loop to a do ... while loop.
    26. Convert the above loop to a for loop.
    27. What is wrong with the following?
    28. i = 1;
      while (i <= 10 )        
              cout << i;
              i++;


      
      


      x = 1;
      while (x < 57)
      {
              y = x;
              x += 2;
      }
    29. The value of n within the loop is never incremented. It will therefore always have a value of 0, which is less than 100, and hence this will produce an infinite loop which will never terminate. The program will therefore never end.
    30. int     i, sum =0;
      i = 0;
      while (i <= 100)
      {
              sum += i;
              i++;
      }
      int     i, sum =0;
      i = 0;
      do
      {
              sum += i;
              i++;
      }while (i <= 20);
      int     i, sum =0;
      for (i=0; i <= 20; i++)
      {
              sum += i;
      }
    31. There are no braces around the cout and increment i statements, therefore it will execute only the cout statement within the loop, and an infinite loop will again occur.

    32.  

       



       

      Arrays and Structures


      Learning Objectives

       

      Be able to declare an array

       

      Be able to access elements of an array

       

      Be able to sequentially access arrays using loops

       

      Be able to initialise arrays

       

      Understand the use of structures

       

      Be able to declare a structure and access the members of a structure variable

      Source Code from Notes

      Additional Examples

      Quick Check Exercises

      Additional Exercises to try


      Arrays and Structures

      Source Code from Notes





      Example

      Program to input each of the temperatures over the 30 days to calculate the average temperature during the period.

      // Program to input 30 temperature samples and calculate their average 
      #include <iostream.h
      
      main()
      {
              const int DURATION = 5;
              int     day;
              float   temperature[DURATION];
              float   average, total;
      
              //Enter temperature values 
              for (day =0; day < DURATION ;day++)
              {
                      cout << "Enter temperature of day " << day << "\n";
                      cin   temperature[day];
              }
      
              // initialise total variable 
              total = 0.0;
      
              // sum temperatures for each day 
              for (day=0; day < DURATION; day++)
              {
                      total += temperature[day];
              }
      
              // calculate average 
              average = total/DURATION;
      
      
              //output result 
              cout  << "The average temperature is"  << average << "\n";
      
      }


      Example

      The following example reads in a sentence which is terminated by a full stop and calculates the number of lower case vowels in the sentence. An array of char elements is defined. The length of this array is limited to 100 elements.

      // Program to count for number of vowels in a sentence 
      // the sentence must be terminated by a full stop (.)  
      #include <iostream.h
      
      main()
      {
              const int max_length = 100; //max number of characters in sentence 
              char    sentence[max_length];
              int     i,count,length;
      
              i = 0;
              count = 0;
      
              // enter the sentence 
              cout << "Enter a sentence terminated by a full stop \n";
              do {
                      cin  sentence[i];
                      i++;
              } while(sentence[i-1] != '.' && i < max_length);
      
              // number of characters in sentence 
              length = i;
      
              // count number of lower case vowels 
      
              for (i=0;i < length;i++) {
                      if (sentence[i] == 'a' || sentence[i] == 'e' || sentence[i]
                         == 'i' || sentence[i] == 'o' || sentence[i] =='u') {
                              count++;
                      }
              }
      
              // output number of vowels 
              cout << "The number of lower case vowels is " << count << "\n";
      
      }


      Example

      Two dimensional array example where the average temperature each month for the last 20 years is declared and the user is then prompted to enter the values

      #include <iostream.h
      
      main()
      {
              const int NO_MONTHS = 12;
              const int NO_YEARS = 20;
              float   temperature[NO_YEARS][NO_MONTHS];
              int     years,month;
      
              // input values to array 
      
              for (years = 0;years < NO_YEARS;years++)
              {
                      for (month=0;month < NO_MONTHS;month++)
                      {
                              cout << "Enter temperature ";
                              cin   temperature[years][month];
                      }
              }
      }


      Arrays and Structures

      Additional Examples


      PROBLEM:

      Write a program which will read in a sequence of positive integers terminated by -1 to indicate the end of the input. These values will be read into an array and the program should then determine if the sequence is a palindrome.

      A palindrome is a sequence of number/characters/words etc which is the same when read from either direction. For example:

      2 3 4 5 4 3 2

      is a palindrome, since the sequence is the same when read from left to right or from right to left.

      2 3 4 5

      Is NOT a palindrome.

      SOLUTION:

      The program does not know how big a sequence will be entered so an array of characters larger than required is declared. The program then reads in the sequence of integers one at a time into the array. After it has read in each integer it checks if it was a -1, if it was -1 it stops reading in. It also checks to ensure that we can't read in any more integers than the size of our array.

      Once it has completed reading in the integers, the number of values read in can be determined, as i - 1 since we are not interested in the -1.

      We can then search through the array comparing the 1st element with the last, the 2nd element with the 2nd last etc. As soon as we find that they don't match we can terminate the search as we know that the sequence is not a palindrome.

      Note that we only have to loop for i < length/2 as we compare the first half of the array to the second half.

      #include <iostream.h
      
      main()
      {
              const int SIZE = 100;
              int     array[SIZE];
              int     i=0, length, palindrome = 1;
      
      
              cout << "Enter A sequence of positive integer numbers\n";
              cout << "terminated by -1\n";
      
              do
              {
                      cin  array[i]);
                      i++;
              }while(array[i-1] != -1 && i < SIZE);
      
              length = i -1; //don't need -1
      
      
              for (i=0; i < length/2 && palindrome == 1 ;i++)
              {
                      if (array[i] != array[length - i - 1])
                              palindrome = 0;
              }
      
      
              if (palindrome == 1)
                      cout << "array is a palindrome\n";
              else
                      cout << "array is not a palindrome\n";
      }
      


      Arrays and Structures

      Additional Exercises





      1. Write a program to read N integers into each of two arrays X and Y of size 20. The program will prompt the user to enter the values into each of the arrays. The program will then compare each of the elements of X to the corresponding element in Y. Then, in the corresponding element of a third array Z, store:-
      2. 1
        if X is larger than Y
        0
        if X is equal to Y
        -1
        if X is less than Y

        Then print out a three column table displaying the contents of the arrays X, Y and Z, followed by a count of the number of elements of X that exceed Y, and a count of the number of elements of X that are less than Y. Make up your own test data.

        Declare your arrays to be of a size greater than you will require, (larger than N).

      3. Define a structure to store the x and y coordinates of a point. The user should then be prompted to enter the x and y coordinates for two points, and the program should make use of the structure. The program will then calculate the distance on the x axis between the two points and the distance on the y axis between the two points.

      4.  

        Arrays and Structures


      5. Write a declaration for an array of 100 floats.
      6. Initialise all elements in this array to have a value of 0
      7. Assign a value of 10.5 to the 5th element in the array you have just declared.
      8. What is wrong with the following?
      9. int array[10],i;
        for (i=0;i < 10;i++)
                array[i] = array[i+1];
      10. What is wrong with the following?
      11. float   index;
        float   array[9];
        
        for (index=0; index < 9; index++)
                array[index] = index;



      12. float a[100];
      13. int i;
        for (i=0;i<100;i++)
                a[i] = 0.0;
      14. a[4]=10.5;
      15. The array has 10 elements,with indexes from 0 to 9, but the last time round the loop i = 9, and hence the code tries to do array[9] = array[10], which would result in an error since a[10] does not exist.
      16. The array index must always be an integer and hence the first line should have been
int     index;



 

Functions


Learning Objectives

 

Understand the use of the function definition and declaration

 

Be able to write a function definition given a specification

 

Be able to call a function

 

Understand the use of void

 

Be able to use standard functions

 

Understand the scope of variables in functions

 

Understand the use of recursive functions

 

Understand the use of refernce variables and be able to use them to alter values sent to a function

 

Understand the concept of Default Arguments and be able to use them 

 

Understand the concept of function overloading 

Source Code from Notes

Additional Examples

Quick Check Exercises 

Additional Exercises to try

Test Cases for Tutorial 6

Extra Examples on Recursion


Functions

Source Code from Notes





Example 1

The following program uses a function to calculate the volume of the cube with the largest volume from the dimensions entered by the user for two cubes.

#include <iostream.h

// function declaration 
float cube_volume(float length, float height, float width);

// main body of program 
main()
{
        float   length1,width1,height1,volume1;
        float   length2,width2,height2,volume2;

         // input cube dimensions 
         cout << "Enter dimensions of cube 1\n";
         cin   length1  height1  width1;

         cout << "Enter dimensions of cube 2\n";
         cin   length2  height2  width2;

        // calculate volume 
         volume1 = cube_volume(length1,height1,width1);
         volume2 = cube_volume(length2,height2,width2);

        // output results 
        if (volume1  volume2)
                cout << "Cube 1 is largest, its volume is " 
                      << volume 1 << "\n";
        else if (volume2  volume1)
                cout << "Cube 2 is largest, its volume is "
                     << volume2 << "\n";
        else
                cout << "both cubes have equal volumes of "
                     << volume1 << "\n";
}


// function definition 
float cube_volume(float length, float height, float width)
{
        float           volume;
        
        volume = length * width * height;
        return(volume);
}


Additional Example - convert Train Timetable from Iteration Tutorial to use functions

// Calculate train time table - using functions

#include <isotream.h

//Function declarations
int     to_24hr(int mins);
int     to_mins(int hr_24);

main()
{
        const int wait = 5;
        int     start, stop, time;
        int     start_min, stop_min;
        int     journey_time, freq_time;
        int     dep_red,dep_green,dep_yellow,arr_blue;
        int     dep_red_min,dep_green_min,dep_yellow_min,arr_blue_min;

        cout << "Enter the journey time (minutes)\n";
        cin  journey_time;

        cout << "Enter the first train time\n";
        cin  start;

        cout << "Enter the last train time\n";
        cin  stop;

        cout << "Enter the frequency time\n";
        cin  freq_time;

        // convert start and stop times to minutes
        start_min = to_mins(start);
        stop_min = to_mins(stop);

        // table header
        cout << "RED \t GREEN \t YELLOW \t BLUE\n";

        for (time=start_min; time<=stop_min; time+=freq_time)
        {
                // Calculate Times 
                dep_red_min = time;
                dep_green_min = (time + journey_time + wait);
                dep_yellow_min = (time + 2*(journey_time + wait));
                arr_blue_min = time + 3*journey_time +2*wait;

                // Convert times to 24 hour clock to display 
                dep_red = to_24hr(dep_red_min);
                dep_green = to_24hr(dep_green_min);
                dep_yellow = to_24hr(dep_yellow_min );
                arr_blue = to_24hr(arr_blue_min);

                cout << dep_red << "\t" << dep_green << "\t"
                     << dep_yellow << "\t" << arr_blue << "\n";
        }
} // end of main program 

// Definition of to_24hr function 
int     to_24hr(int mins)
{
        int     hr, min, total;
        hr = mins/60;
        min = mins%60;
        total = hr*100 + min;

        return (total);
}

// Definition of to_mins function 
int     to_mins(int hr_24)
{
        int hr, min, total_mins;

        hr = hr_24/100;
        min = hr_24%100;
        total_mins = hr*60 + min;

        return(total_mins);
}


Example - Recursion

// Program to calculate the factorials of positive integers 
// Program prints results for integers from 0 to 10        

#include <iostream.h

long factorial (int n);

main()
{
        int j;

        for (j=0;j < 11;j++)
                cout << j << "! = " << factorial(j) << "\n";

}

long factorial (int n)
{
        long result;

        if (n==0)
                result = 1;
        else
                result = n * factorial(n-1);

        return(result);
}


Example

The following program prompts the user for the coordinates of 2 points. It then calculates the length of the line joining the two points.

#include <math.h
#include <iostream.h


struct coord {
        float    x,y,z;
};

// function declarations
float length (coord point1, coord point2);
float square (float x);

void main (void)
{
        coord   p1, p2; 
        float   line_length;


        cout << "Enter coords of point 1 : ";
        cin  p1.x  p1.y  p1.z;

        cout << "Enter coords of point 2 : ";
        cin  p2.x  p2.y  p2.z;

        line_length = length(p1, p2);
        cout << "Length = " << line_length << "\n";
}


float length (coord point1, coord point2)
{
        float   xlen,ylen,zlen;
        float   len_sqr;

        xlen = point1.x - point2.x;
        ylen = point1.y - point2.y;
        zlen = point1.z - point2.z;

        len_sqr = square(xlen) + square(ylen) + square(zlen) ;
        return (sqrt(len_sqr));
}


float square (float x)
{
        return ((x)*(x));
}


Example - Reference Variables

This example illustrates how reference variables can be used to permit a function to change values in the calling program.

#include <iostream.h
void swap(int &ra, int &rb);

main()
{
        int a,b;

        a = 10;
        b = 12;
        swap (a,b);
}
void swap(int &ra, int &rb)
{
        int temp;

        temp = ra;
        ra   = rb;
        rb   = temp;
}


Example

This example sends an array to the function. The function then calculates both the largest and smallest value stored in the array. These maximum and minimum values stored are then returned to the main calling program as function arguments.

There is a msitake in the notes, the following program is correct and has made MAX be global so the function also knows its value. An alternative solution is given below where MAX is local and is sent to the function.

#include <iostream.h
#include <math.h

void max_min(float &max, float &min, float array[]);

const int MAX = 5;

main()
{
        float array1[MAX];
        float array2[MAX];
        float   max1, min1;

        float   max2, min2;
        int     i;

        for (i=0; i<MAX;i++)
        {
                cout << "Enter value  "<< i << " of array1\n";
                cin  array1[i];
        }
        for (i=0; i<MAX;i++)
        {
                cout << "Enter value  "<< i << " of array2\n";
                cin  array2[i];
        }

        max_min(max1,min1,array1);
        max_min(max2,min2,array2);

        cout << "Array 1 : max = " << max1 << " min = " << min1 << "\n";
        cout << "Array 2 : max = " << max2 << " min = " << min2 << "\n";
}

void max_min(float &max, float &min, float array[])
{
        int     i;

        min = array[0];
        max = array[0];

        for (i=1;i < MAX;i++)
        {
                if (array[i]  max)
                        max = array[i];
                if (array[i] < min)
                        min = array[i];
        }
}


Alternative Solution

#include <iostream.h
#include <math.h

void max_min(int size_array, float &max, float &min, float array[]);


main()
{
        const int MAX = 5;
        float array1[MAX];
        float array2[MAX];
        float   max1, min1;

        float   max2, min2;
        int     i;

        for (i=0; i<MAX;i++)
        {
                cout << "Enter value  "<< i << " of array1\n";
                cin  array1[i];
        }
        for (i=0; i<MAX;i++)
        {
                cout << "Enter value  "<< i << " of array2\n";
                cin  array2[i];
        }

        max_min(MAX, max1,min1,array1);
        max_min(MAX, max2,min2,array2);

        cout << "Array 1 : max = " << max1 << " min = " << min1 << "\n";
        cout << "Array 2 : max = " << max2 << " min = " << min2 << "\n";
}

void max_min(int size_array, float &max, float &min, float array[])
{
        int     i;

        min = array[0];
        max = array[0];

        for (i=1;i < size_array;i++)
        {
                if (array[i]  max)
                        max = array[i];
                if (array[i] < min)
                        min = array[i];
        }
}


Example - Sports Timer

A sports timer can time an event returning the elapsed time in seconds. Write a function to convert the time in seconds to hours, minutes and seconds, returning these values as function arguments. The function should be called from a main calling program where the user is prompted to enter the elapsed time in seconds.

Reference variable must be used in the function arguments for hours, minutes and seconds.

#include <iostream.h
#include <math.h


// Function Declaration
void change_time(int elapsed_seconds, int &hours, int &mins, int &seconds);

main()
{
        int     elapsed_time;
        int     time_hours, time_minutes, time_seconds;


        cout << "Enter the time for the event\n";
        cin  elapsed_time;

        //Function call - send address of variables to change 
        change_time(elapsed_time, time_hours, time_minutes, time_seconds);


        // Use variables as normal 
        cout << "The number of hours is " << time_hours << " \n";
        cout << "The number of minutes is "<< time_minutes << " \n";
        cout << "The number of seconds is " << time_seconds << " \n";
        cout << "The number of seconds is " << time_seconds << " \n";

}

// Function to convert total in seconds to hours, mins and seconds 
void change_time(int elapsed_seconds, int &hours, int &mins, int &seconds)
{
        int     tmp_minutes;

        seconds = elapsed_seconds%60;

        tmp_minutes = elapsed_seconds/60;

        mins = tmp_minutes%60;

        hours =  tmp_minutes /60;
}


Functions

Additional Examples





There are three additional worked examples:-

Example 1

Example 2 - using reference variables 

Example 3 - Functions and arrays


 

Example 1

PROBLEM:

Write a function that will display a line of n asterisks on the screen. n will be passed as a argument to the function. After writing the line of n asterisks a new line should be printed.

Write a program to call this function, using it to display a grid of m times n asterisks. The user should be prompted to enters the values for m and n.


SOLUTION:

Considering initailly the function, the first thing to consider is

What arguments are to be sent to the function?

Obviously, it need to be told how many asterisks to write, in this case n which will be integer?

The next thing to consider is what will be returned by the function?

Obviously, the function only prints to screen and therefore does not need to return anything to the main calling program. The return type is therefore void

We can now continue and write the function.

void line (int n)
{
        int i;

        for (i=0; i < n;i++)
                cout << "*";
        cout << "\n";
}

The complete program, has to call this function m times, and so a loop will be used to call the program. The complete solution is then.

#include <iostream.h

// function declaration */
void line( int n);

main()
{
        int     i;
        int     m,n;

        cout << "Enter  values for m and n \n";
        cin  m  n ;

        // Loop to call function m times 
        for (i=0; i < m; i++)
                line(n);
}


// function definition 
void line (int n)
{
        int i;

        for (i=0; i < n;i++)
                cout << "*";
        cout << "\n";
}


ADDITIONAL EXERCISE

Amend the main program written above, so that the following type of pattern is displayed. This is shown for the case of m = 5.

*
**
***
****
*****


SOLUTION

Note that no changes are required to the function, we simply need to amend the main calling program.

#include <iostream.h

// function declaration 
void line( int n);

main()
{
        int     i;
        int     m;

        cout << "Enter  a value for the number of rows\n";
        cin   m ;

        //Call to function in loop 
        for (i=1; i <= m; i++)
                line(i);
}


 

Example 2

PROBLEM:

Consider the calculation of the roots of the quadratic equation ax&sup2;+bx+c=0, assuming that a is non-zero:-

 
 
 

Write a function in C++ which will take a, b and c as arguments and returns the roots as function arguments root1 and root2 (as appropriate). The number of roots will be returned through the type specifier.

Write a main program which prompts the user to enter the values of a, b and c. Then after using a call to the function written above, the program will display the number of roots and their values as appropriate.


SOLUTION:

The function has to be sent the arguments a, b and c, it also requires two arguments for the roots. These values will be altered by the program so must be refernec variables. The function returns an integer number for the number of roots. The function declaration will therefore be:-

int root (float a, float b, flot c, float &root1, float &root2);

The rest of the function can now be written.

int root (float a, float b, float c, float &root1, float &root2)
{
        float   tmp;

        tmp = b*b - 4*a*c;

        if (tmp  0)
        {
                root1 = (-b + sqrt(tmp))/(2*a);
                root2 = (-b - sqrt(tmp))/(2*a);
                return 2;
        }
        else if (tmp == 0)
        {
                root1 = -b/(2*a);
                return 1;
        }
        else
                return 0;
}

The main program can now be written. Remember to include the function declaration and math.h as the sqrt function was used.

#include <iostream.h
#include <math.h

int root (float a, float b, float c, float &root1, float &root2);

main()
{
        float   a,b,c,root1,root2;
        int     num_roots;

        cout << "Enter values for a, b and c\n";

        cin  a  b  c;

        num_roots = root(a,b,c,root1, root2);

        if (num_roots == 2)
                cout << "There are 2 real roots with values  " << root1 
                     << " and " << root2 << " \n";
        else if (num_roots == 1)
                 cout << "There is 1  real root with value " << root1 <<"
\n";
        else
                cout << "There are no real roots\n";
}


 

Example 3

Arrays can also be sent to functions. Arrays are also special in that the function can change the contents of the array and the main calling program will know about the changes after the function is called.

PROBLEM: Write a function which when sent an array will fill each element of the array with an integer number which is equal to the element number. The function will also be sent the size of the array.

Write a main program to call this function, and then print out the contents of the array.


SOLUTION:

The function will not return anything - hnece the type specifier is void. The function will be sent an array of integers and an integer for the size. In the function prototype, teh size of the array is not enetered in the square brackets for the array - this is left blank. The empty square brackets simply indictate that an array will be sent to the function.

void fill_array(int array[], int size)
{
        int i;
        
        for (i=0; i < size; i++)
                array[i] = i;

        return;
}

The main program will then take the form:-

#include <iostream.h

// function declaration
void fill_array(int array[], int size);

main()
{
        int size = 100;
        int array[size];

        // call function
        fill_array(array, size);

        // write out contents of array
        for (i=0; i < size ; i++)
                cout << i << "\t" << array[i] << endl;
}

Note: That to call the function, only the name of the array to sent to the function needs to be given in the function call. (In the notes on points it mentions how the name of an array is a synonym for a pointer to the beginning of the array - hence only the mname needs to be given. 



 
 

Recursion

These pages contain some further examples of recursion and may help those students who undertake the coursework for AI given by Dr Nick Taylor. The minimax function required for this is best implemented using recursion.

Hints from Nick about the minimax function


What is recursion?

Recursion is a technique whereby functions can call themselves. Simple recursive functions always have an if..else type of structure. The condition of the if provides an exit from the recursion and is always tested before the recursive call. If this condition is not true, the else part calls the function again, but this time the value of one of the arguments sent to the function will have changed (typically the value of the variable tested in the condition). The value of the argument is changed in such a manner that ultimately the base condition will be true.

This is explained more easily by considering the following examples. For each problem both a recursive and an iterative solution to the problem are presented - compare the structures of each!


Recursion Examples

Example 1 

Multiplication by repeated addition

Example 2 

Euclids Algorithm for Greatest Common Divisor

Example 3

Factorial Example

Example 4

Fibonacci Sequence


Multiplication by repeated addition

PROBLEM:

Write a recursive function to perform multiplication of two positive integers (m and n) using only addition. The function will take as its arguments two integers to multiply together ( m x n ) and will return the product.

Hint: consider the following:

6 x 1  =  6
6 x 2  =  6 + (6 x 1)
6 x 3  =  6 + (6 x 2) = 6 + [6 + (6 x 1)] = 6 + 6 + 6


SOLUTION

This could be extended to the general case that

m x n = m + (m x (n-1))

Therefore, from the above we can repeat the multiplication process by repeatedly calling the function, each time with n decreasing by 1.

The function stops calling itself once n reaches 1. This therefore gives the condition to stop calling the function, since m x 1 is simply m and the result m is returned.

int multiply(int m, int n)
{
        int result;

        if (n == 1)
                result =  m;
        else
                result =  m + multiply(m, n-1);
        return(result);
}

A recursive function always has a structure using an if..else statement. This allows the function to repeatedly call itself, but provides the condition on which to stop.


EXAMPLE OF OPERATION

Consider what would happen if this function is called for m=6 and n=3. The function tests if n is equal to 1, it isn't so

result = 6 + multiply(6,2);

so the function is recalled this time with m = 6 and n = 2. The function tests if n is equal to 1, it isn't so

result = 6 + multiply(6,1);

so the function is recalled this time with m = 6 and n = 1. The function tests if n is equal to 1, it is so it sets

result = 6;

and returns this value. This then completes the statement

result = 6 + multiply(6,1);

providing the value result equal to 12. This value is then returned, and this then completes the statement

result = 6 + multiply(6,2);

and finally the answer of 18 is returned.


ITERATIVE SOLUTION

This problem could also have been tackled using an iterative solution. An iterative solution uses a loop.

int multiply (int m, int n)
{
        int tot =0;

        while ( n  0O
        {
                tot += m;
                n--;
        }
        return tot;
}

Back to top of page

 
 
 


Euclid's Algorithm for Greatest Common Divisor

PROBLEM 2:

Euclids algorithm for calculating the greatest common divisor (GCD) of two positive integers, GCD(m,n) is defined recursively below. The greatest common divisor of two integers is the largest integer that divides them both. For example, the GCD of 9 and 30 is 3.

Write a C++ function to implement this algorithm.


SOLUTION

In this case we require an else..if structure because there are 3 possible routes depending on the values of m and n.

      1. If n is less than m and n divides m exactly (ie n%m ==0), then we can stop and the answer is n.
      2. If m is less than n, then recall the function but swap m and n
      3. otherwise, recall function with arguments n and the remainder of m divided by n (m%n)
      4. This is implemented below.

        int GCD (int m, int n)
        {
                if (n<=m && m%n == 0)
                        return n;
                else if (m < n)
                        return GCD(n,m);
                else 
                        return GCD (n, m%n);
        }

        Back to top of page

         
         
         


        Factorials

        PROBLEM 3:

        Write a recursive function to calculate the factorial of n (n!)

        0! = 1
        1! = 1
        2! = 2 x 1 = 2 x 1!
        3! = 3 x 2 x 1 = 3 x 2! 
        4! = 4 x 3 x 2 x 1 = 4 x 3! 
        5! = 5 x 4 x 3 x 2 x 1 = 5 x 4! 
        etc.
        
        n! = n x (n-1)!


        SOLUTION:

        From the above it is obvious to see a pattern emerging and

        n! = n x (n-1)!

        Therefore, we can calculate the factorial of n, by multiplying the factorial of n-1 by n. We can calculate the factorial of n-1, by calling the function again, but this time sending it n-1.

        This is then repeated since,

        (n-1)! = (n-1) x (n-2)!

        We want to stop repeatedly calling the function, once n is 0. Hence the condition on the if statement is that the recursion is terminated once n is equal to 0. Otherwise, it recalls the function, but with n-1.

        long factorial (int n)
        {
                long result;
        
                if (n==0)
                        result = 1;
                else
                        result = n * factorial(n-1);
                return(result);
        }


        ITERATIVE SOLUTION

        This could also be implemented iteratively using a loop.

        long factorial (int n)
        {
                long result;
                int i;
        
                result = 1;
                for (i=n; i 0 ; i--)
                        result *= i;
        
                return (result);
        }

        Back to top of page

         
         
         


        Fibonacci Sequence

        PROBLEM 4:

        The Fibonacci numbers are generated by adding together the two previous numbers in the sequence, initialising the 1st two numbers (F1 and F2) to 1. The sequence

                1 1 2 3 5 8 13 21 .......

        is then produced, where F3=F2+F1=2, F4 = F3+F2 =3, F5= F4+F3 = 5 etc.

        Write a recursive function which returns the nth Fibonacci number (Fn), where n is sent to the function as an argument.


        SOLUTION:

        The Fibonacci sequence can be generated by repeated calls to the function. We want to keep on calling the function to calculate the 2 previous numbers in the sequence. We want to stop calling the function if n is 1 or n is 2, whereby we know the 1st Fibonacci number (F1) is 1 and the 2nd Fibonacci number (F2) is 1.

        int fib (int n)
        {
                if (n == 1 || n == 2)
                        return 1;
                else
                        return (fib(n-1) + fib(n-2));
        }


        Iterative Solution

        This could also have been implemented iteratively as:-

        int fib_iterative (int n)
        {
                int fib, fib_old1, fib_old2, i;
        
                if (n <= 2 )
                        return 1;
                else
                {
                        fib_old1 = 1;
                        fib_old2 = 1;
                        for (i=3; i <=n; i++)
                        {
                                fib = fib_old1 + fib_old2;
                                fib_old2 = fib_old1;
                                fib_old1 = fib;
                        }
                        return (fib);
                }
        }

        Compare this to the Recursive Solution.
         
         
         

        Back to top of page

         
         
         


        Functions

        Additional Exercises





      5. The following function raises an integer to a given power ( X^n )
      6. int power (int x, int n)
        {
                int p;
                for (p = 1; n  0; n--)
                        p = p * x;
                return p;
        }

        Add a main program to prompt the user to enter a integer and the desired power then call the function, and finally print out the answer. Remember to add a function prototype.

        Revision

        The power to raise the integer to, n must be a positive integer. Check that the value entered is positive, if it is not do not let the user proceed until a positive value is entered (see notes on Iteration).

      7. The above is an iterative method of calculating the value of X^n, write a recursive function to calculate the value of a number (base) raised to a power (power). Assume the power is positive.
      8. The Arrays Example looked at writing a program to determine if an array contained a palindrome. Rewrite this exercise, so that you now have a function that when sent an array, will return a 1 if the array is a palindrome and will return a 0 otherwise. The function will be sent the array of integers.

      9.  

         

        Now re-write the main program to call this function and then display if the array is a palindrome.
         
         


         

        Functions


      10. Explain the difference between a function declaration and a functions definition? Where is the function declaration placed?
      11. Given the following function declarations, explain the meaning of each.
        1. int function1(int a, float b);
        2. void function2(float a, float b, float c);
        3. int function3(void);
        4. float function4(float x);
        5. void function5(void);
      12. Write an appropriate function call for each of the function declarations given above.
      13. What does the following function do?
      14. float function(float a, float b, float c)
        {
                float tmp;
        
                tmp = (a + b + c )/ 3.0 ;
        
                return tmp;
        }
      15. Give an example function call for the above function.
      16. Give the function declaration for the function given in question 4.
      17. 
        


      18. The declaration is contained within the program before the function is called. It is usually outside any function, including the main program. It contains details of the function name, the return type and the types of the function arguments.

      19.  

         

        The definition contains the actual code of what is to be implemented when the function is called.

        1. The function is sent an integer argument which it will refer to as a within the function and a floating point variable, which it will refer to as b within the function. The function will return an integer quantity.
        2. The function is sent 3 floating point arguments and returns no value to the calling program.
        3. The function is sent no arguments but returns an integer.
        4. The function is sent one floating point argument and returns a floating point argument.
        5. The function is sent no variable and returns nothing.
      20. Example calls are given below,
      21. int x, z;
        float y;
        
        // x and y are assigned some values in the program 
        
        z = function1(x, y);
        float   x,y,z;
        
        // x, y and z assigned values in program 
        
        function2(x, y, z);
        int a;
        
        a = function3();
        float a, b;
        
        // b assigned a value in program 
        a = function4(b);
        function5();
      22. It returns the average value of the three values sent to it.
      23. x = function(a,b,c);
      24. float function(float, float, float); or float function(float a, float b, float c);


      25.  

        Pointers


        Learning Objectives

         

        Understand the concept of pointers which point to memory locations

         

        Know how * and & are used with pointers and what they do 

         

        Be able to use command line arguments to input data to programs

         

        Understand the concept of linked lists

           

        Source Code from Notes

        Additional Examples

        Quick Check Exercises 

        Additional Exercises to try

        Test Cases for Tutorial 7


        Pointers

        Source Code from Notes





        Example

        Example program to read in two numbers from the command line and add them together.

        #include <iostream.h
        #include <stdlib.h
        
        main(int argc,char *argv[])
        {
                float           a,b,answer;
        
                // ensure correct number of arguments 
                if (argc != 3)
                {
                        cout << "Wrong number of arguments for program\n";
                        exit(1);
                }
        
        
                /* convert argument string to float */
                a = atof(argv[1]);
                b = atof(argv[2]);
        
                answer = a + b;
                cout << "Answer = " << answer << "\n";
        }


        Example

        This example is more complex and is for a program which requires a flag to indicate what operation should be performed on the two numbers. The flags are indicated by the minus (-) sign.

        #include <iostream.h
        #include <stdlib.h
        
        main(int argc,char *argv[])
        {
                int     add_flag = 1;
                int     sub_flag = 0;
                int     mult_flag = 0;
                float   a,b;
        
                argc--;
                argv++;
        
                while ((argc  0)&&(**argv == '-')){
                        switch(*++*argv){
                                case 'a' : // add 
                                           add_flag = 1;
                                           break;
                                case 's' : // subtract 
                                           sub_flag = 1;
                                           add_flag = 0;
                                           break;
                                case 'm' : // multiply 
                                           mult_flag = 1;
                                           add_flag = 0;
                                           break;
                                default  : cout << "Unknown flag\n";
                                           exit(1);
                        }
                        argc--;
                        argv++;
                }
        
                if (argc != 2)
                {
                        cout << "Wrong number of arguments for program\n";
                        exit(1);
                }
        
                a = atof(argv[0]);
                b = atof(argv[1]);
        
                if (add_flag == 1)
                        cout << "answer = " << a+b << "\n";
                else if ( mult_flag == 1)
                        cout << "answer = " << a*b << "\n";
                else if (sub_flag ==1)
                        cout << "answer = " << a-b << "\n";
        
        }
        
        


        Pointers

        Additional Example





        PROBLEM:

        Write a program which prompts the user to enter 10 integer numbers into an array. The program will then search the array to find if a zero is present in the array. If a zero is present it will print out the number of elements in the array before the zero occurs.

        Write this program making use of pointers to search the array and compare it to writing the solution using arrays only.


        SOLUTION:

        The program will still need to declare an array of 10 elements as normal. It will also declare a pointer to an integer.

                int     array[10];
                int     *array_ptr;

        The program will then prompt the user to enter the elements into the array. It uses the variable index to count when 10 integers have been entered. The integers are read into successive elements. The name of the array is a pointer to the beginning of the array, this pointer is moved along the array by adding the index to it.

                cout << "Enter 10 numbers \n";
                for (index =0; index < 10; index ++)
                        cin  *(array + index);
        

        The pointer is then set to point to the beginning of the array.

                array_ptr = array;

        The program then increments along the array looking for a zero and checking that it has not reached the end of the array.

                while (*array_ptr != 0 && (array_ptr - array < 10))
                        array_ptr ++;

        This checks if the contents of the array poistion the array_ptr is pointing to contains a zero and if it has yet looked at 10 elements. If both condtions are false it increments the pointer to point to the next element in the array.

        Final Program:

        #include <iostream.h
        
        main()
        {
                int     array[10];
                int     *array_ptr;
                int     index;
        
        
                cout << "Enter 10 numbers \n";
                for (index =0; index < 10; index ++)
                        cin  *(array + index);
        
                array_ptr = array;
        
                while (*array_ptr != 0 && (array_ptr - array < 10))
                        array_ptr ++;
        
                if (array_ptr - array < 10)
                        cout << "There are " << array_ptr - array << 
                                " elements before the zero\n";
                else
                        cout << "There is no zero in the array\n";
        }

        The same program could also have been written using the array and the integer index. No pointers are required.

        #include <iostream.h
        
        main()
        {
                int     array[10];
                int     index;
        
        
                cout << "Enter 10 numbers \n";
                for (index =0; index < 10; index ++)
                        cin  array[index];
        
                // reset index back to 0
                index = 0;
        
                while (array[index] != 0 && index < 10)
                        index ++;
        
                if (index < 10)
                        cout << "There are " << index << 
                                " elements before the zero\n";
                else
                        cout << "There is no zero in the array\n";
        }

        Both programs perform the same task.


        Pointers

        Additional Exercises





      26. Write a function strn_comp to compare two strings. The function will return a value TRUE if the strings are the same and FALSE otherwise. Call this function from a main program.

      27.  

         

        The return value will be of type int with TRUE indicated by a value of 1 and FALSE indicated by a value of 0.

        Note: this can be achieved using array indices or pointers to manipulate the string.

      28. Rewrite the main program for the example given under Additional Example 2 for Functions to take the values of a, b, and c as command line arguments, instead of prompting the user to enter the values.

      29.  

         


         

        Pointers


        1. How do you access the memory address of a variable?

        2.  

           
           
           

        3. How do you access the contents of a memory location whose address is stored in a pointer?
        4. Given the following declarations:
        5. int     *p, *q;
          int n;

          Which of the following is valid?

          1. p+q
          2. p+n
          3. p-q
          4. q-n
          5. n-p
        6. Given the following declaration
        7. float   a[10];
          float   *a_ptr;

          What do the following statements do? Assume that they are executed in the order given.

          a_ptr = a;
          a_ptr ++;
          *a_ptr = 3.5;
          a_ptr = a_ptr + 5;
          *a_ptr = a[1];
        8. When referring to command line arguments what is the argument count?

        9.  

           

          How many arguments are in the following command line?

          prog -x -a file1 13

          What is stored in argv[2]?


          
          


        10. The memory address of a variable is accessed using the address operator &. Given the variable x it's address is &
        11. The contents of a memory location pointed to by a pointer are accessed using the de-referencing operator (*). The contents of the memory location pointed to by p are accessed by *p.
          1. p+q - This is invalid. We cannot add two pointers.
          2. p+n - This is valid. It increments the memory address p points to by n.
  1. p-q - This is valid. The subtraction of the two pointers gives the number of integer variables stored between the two locations
  2. q-n - This is valid. It decrements the memory address q points to by n
          1. n-q - This is invalid. We cannot subtract a pointer from an integer.
             
          2. This makes the pointer a_ptr point to the beginning of the array (element number 0 of array a)
          3. This increments the pointer so it now points to a[1]. The contents of a[1] then becomes 3.5.
          4. It increments the pointer by 5 places - so it now points to a[6]. It then copies the value of a[1] (3.5) to a[6].
        1. The argument count is the number of arguments specified on the command line to run the program.

        2.  

           

          There are 5 arguments.

          argv[2] contains -a


          
          
          
          
          
          
          


           

          File Input and Output


          Learning Objectives

           

          Be able to open a file to read from or write to

           

          Understand the different modes in which files can be opened

           

          Know how to check if the file has been opened correctly 

           

          Be able to read from or write to the file

           

          Be able to close a file after use

           

          Understand how to use functions such as eof()

          Source Code from Notes

          Additional Examples

          Quick Check Exercises 

          Additional Exercises to try

          Test Cases for Tutorial 8


          File Input and Output

          Source Code from Notes





          Example 1

          Example using command line arguments to provide the filenames of the files to be opened.

          #include <iostream.h
          
          main(int argc,char *argv[])
          {
                  istream fin;
                  ostream fout;
          
                  if (argc != 3) {
                          cerr  << "USAGE: program input_file output_file\n";
                          exit(1);
                  }
                  
                  fin.open(argv[1]);
                  fout.open(argv[2]);
          
                  if (!fin)
                  {
                          cerr << "Can't open file " << argv[1] << " for reading\n";
                          exit(1);
                  }
                  if (!fout)
                  {
                          cerr << "Can't open file " << argv[2] << " for writing\n";
                          exit(1);
                  }
          
                  // rest of program 
          
          }


          Example

          For example to open a file called Myfile and write some data to it

          #include <fstream.h
          main()
          {
                  // open text file Myfile for writing
                  // now
                  ofstream my;
                  my.open("Myfile");
          
                  if (!my)           // if open didn't work..
                  {
                          cerr << "Error opening file \n";
                          exit();         // output error and quit
                  }
          
                  // write to the file
                  my << "My name is Judith Bell \n";
          }


          Example - reading from file and detecting feof

          This example opens a file called test. We will assume this file contains a list of floats, which could for example represent the temperature each day for several days. We will then read in these values andcalculate the average value stored in the file.

          Note: This program will read the last item in the file twice, since it does not detect the end of file until it tries to read past it.

           // Program to read integers from  an input file
           // called test  and calculate average
          
          
          #include<iostream.h
          #include<fstream.h
          
          main()
          {
          
                  ifstream fi;
                  float input_value, sum = 0.0, average;
                  int     no_values = 0;
          
                  fi.open("test");
          
                  if (!fi)
                  {
                          cout << "Can't open file test\n";
                          exit(0);
                  }
          
                  while (!fi.eof())
                  {
                          fi  input_value;
                          sum += input_value;
                          no_values ++;
                  }
          
                  average = sum / no_values;
          
                  cout << "The average value in file test was "
                       << average << "\n";
          
                  fi.close();
          }

          Corrected Program

          #include<iostream.h
          #include<fstream.h
          
          main()
          {
          
                  ifstream fi;
                  float input_value, sum = 0.0, average;
                  int     no_values = 0;
          
                  fi.open("test");
          
                  if (!fi)
                  {
                          cout << "Can't open file test\n";
                          exit(0);
                  }
          
                  fi  input_value;
                  while (!fi.eof())
                  {
                          sum += input_value;
                          no_values ++;
                          fi  input_value;
                  }
                  average = sum / no_values;
          
                  cout << "The average value in file test was "
                  << average << "\en";
          
                  fi.close();
          }
          

          Corrected Program - using arrays

          Note: this program also reads file name in as specified by the user.

          #include <iostream.h
          #include <fstream.h
          
          main()
          {
                  ifstream fi;
                  const int max = 100;   // declare a larger array than required
                  float input_value[max], sum = 0.0, average;
                  int     i, no_values = 0;
                  char    file_name[20];
          
                  cout << "enter filename";
                  cin  file_name;
          
                  fi.open(file_name);
          
                  if (!fi)
                  {
                          cout << "Can't open file test\n";
                          exit(0);
                  }
          
                  i =0;
                  while (!fi.eof())  // read data into array
                  {
                          fi  input_value[i];
                          i++;
                  }
          
                  no_values = i-1;  // discard last element in array
          
                  for (i=0; i< no_values;i++)   // sum together all values in array
                          sum += input_value[i];
          
                  average = sum / no_values;
          
                  cout << "The average file in file test was "
                       << average << "\n";
          
                  fi.close();
          }


          Example

          Here is a program that creates an output file, writes information to it, closes the file and opens it again as an input file and reads in the information.

          #include <iostream.h
          #include <fstream.h
          
          main()
          {
                  ofstream        fo;
          
                  fo.open("test_file");
          
                  if (!fo)
                  {
                          cout << "Cannot open test_file\en";
                          exit(0);
                  }
          
                  fo << "Hello\en";
                  fo << 101.7;
          
                  fo.close();     // close the file
          
                  ifstream        fi;
                  fi.open("test_file");
          
                  if (!fi)
                  {
                          cout << "Cannot open test_file\en";
                          exit(0);
                  }
          
                  char    str[80];
                  float   x;
          
                  fi  str;
                  fi  x;
          
                  cout << str << "\en" << x << "\en";
          
                  fi.close();
          }


          File Input and Output

          Additional Example





          PROBLEM:

          Write a program which reads in text from a file character by character and then writes out the text to another file, but this time in CAPITAL (or UPPER case) letters.

          The input and output filenames will be specified as command line arguments.

          You will need to use the function toupper(). This function is declared in ctype.h. It is sent a character and returns the character in upper case through the type specifier.

          You will need to use the fgetc() function to preserve the white spaces.

          Create your own input file - ie. in nedit create a file called test_in and type in some text. For example

          The cat sat on the mat

          The output file obtained by running the program should then contain

          THE CAT SAT ON THE MAT


          SOLUTION:

          The first thing the program should do, is check the number of command line arguments and ensure that it is correct (In this case 3 - program name, input filename and output filename). It can then open the input and output files and check that they have been opened, if they are not correctly opened the program will stop.

          The program can then proceed and read character by character from the input file. Each character read will then be converted to a capital letter and written to the output file before the next character is read in.

          #include <iostream.h
          #include <fstream.h
          #include <ctype.h
          
          main(int argc, char *argv[])
          {
                  ifstream fi;
                  ofstream fo;
                  char    lower, upper;
          
                  if (argc != 3)
                  {
                          cerr << "USAGE: program input_file output_file\n";
                          exit(1);
                  }
                  
                  fi.open(argv[1]);
          
                  if (!fi)
                  {
                          cout << "Can't open input test file " << argv[1] << "\n";
                          exit(0);
                  }
                  fo.open(argv[2]);
                  if (!fo)
                  {
                          cout << "Can't open output test file " << argv[2] << "\n";
                          exit(0);
                  }
          
                  lower = fi.get();
          
                  while (!fi.eof())
                  {
                          upper = toupper(lower);
                          fo << upper;
                          lower = fi.get();
                  }
          
                  fi.close();
                  fo.close();
          }
          
          

          Note carefully the loop for reading in and converting the characters. The loop is written in this way to ensure that the End of File is correctly detected. C programs will not detect the end of file until they have tried to read the end of file. Therefore, you will not that the order ensures that the next step afet reading a characetr, is checking if it is the end of file. This is illustrated in the figure below.

          If the code had been written as

                  while (!feof(fi))
                  {
                          lower = fgetc(fi);
                          upper = toupper(lower);
                          fo << upper;
                  }

          This would have produced an additional characetr on the end of the output file, since it would have read the end of file character, tried to convert it to upper case and written it to the output file before it checked if it was the end of file. As shown below


          If reading values from a file and checking for the end of file always be careful of the End of File Character and take care in the order in which you construct any loops


          File Input and Output

          Additional Exercises





        3. Write a program to read in the marks for a class. The file contains a number to indicate how many students are in the class, and then the name of a student followed by four marks, one for each of the subjects they are studying. The format of the input file is shown below:-
        4. 3

          bob

          10

          10

          10

          10 

          fred

          2

          12

          14

          15 

          john

          3

          4

          5

          The program will then calculate the average mark for each student, it will write the name of the student and their average mark to another file. For the example above, the output file will contain

          bob 

          10 

          fred 

          10.75 

          john 

          4.5 

          In addition the program will print the overall average for the class to the screen.

          NOTE:
          You can assume that the maximum length of the name for any student is 10 characters.


           

          File Input and Output


        5. Declare a file pointer, fi
        6. Using this file pointer, open the text file file.txt for reading only.
        7. Add code to check that the file has been opened correctly.
        8. How would the code for question 2 be changed if you wished to oen the file for writing rather than reading.
        9. Assuming that the file file.txt opened for reading contains a column of integers, give some example to code to read all the numbers into an array.

        10.  

           
           
           


          Answers

          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          


        11. ifstream fi;
        12. fi.open("file.txt");
        13. if (!fi ) 
          {
                   cout << "Can't open file file.txt for reading\n";
                   exit(1);
          }
        14. oftream fi;

        15.  

           

          fi.open("file.txt");

          fi  array[i];
          while (!fi.eof())
          {
                  i++;
                  fi  array[i];
          }


          
          
          
          
          
          
          


           

          Introduction to Classes


          Learning Objectives

           

          Understand the basic concepts of classes and object orientated programming

           

          Understand the concepts of member functions and member data

           

          Be able to declare a class

           

          Be able to access the members of class

           

          Understand the terms private and public

           

          Be able to create a constructor for a class

          Source Code from Notes

          Additional Examples

          Quick Check Exercises 

          Additional Exercises to try

          Test Cases for Tutorial 9


          Introduction to Classes

          Source Code from Notes





          Example

          Example to illustrate accessing member data and member functions for a class

          #include <iostream.h
          
          //Declaration of Class
          
          class Savings
          {
                  public:
                  unsigned      account_number;
                  float         balance;
          
                  unsigned deposit(unsigned amount)
                  {
                          balance += amount;
                          return balance;
                  }
          };
          
          //main program which uses class Savings
          main()
          {
                  Savings a;   // declare an object a of data type Savings
                  Savings b;   // declare an object b of data type Savings
          
                  a.account_number = 1;  // set account number for a to 1
                  a.balance = 0.0;       // set balance for a to 0
                  a.deposit(10.0);       // deposits 10 pounds to a
          
                  b.account_number = 2;  // set account number for b to 2
          }


          Example

          #include <iostream.h
          // class declaration
          class Rational
          {
                  public:
                          void assign (int, int);
                          double convert ();      // convert fraction to double
                          void invert ();         // invert fraction
                          void print ();          // print as a fraction
                  private:
                          int     num, den;
          };
          // main program
          main()
          {
                  Rational x;
          
                  x.assign(22,7);
                  cout << " x = " ;
                  x.print();
                  cout << " = " << x.convert() << "\n";
                  x.invert();
                  cout << "1/x = ";
                  x.print();
                  cout << "\n";
          }
          
          //Rational function definitions
          void Rational::assign(int n, int d)
          {
                  num = n;
                  den = d;
          }
          double Rational::convert()
          {
                  return double(num)/den;
          }
          void Rational::invert()
          {
                  int temp = num;
                  num = den;
                  den = temp;
          }
          void Rational::print()
          {
                  cout << num << "/" << den;
          }


          Example - Constructor

          Add Constructor to Student class example

          #include iostream.h<
          class Student
          {
                  public:
                  Student()
                  {
                          module_hours = 0;
                          average_marks = 0.0;
                  }
                  //marks - returns average marks
                  float marks()
                  {
                          return average_marks;
                  }
          
                  //hours_worked - returns number of study hours
                  float hours_worked()
                  {
                          return module_hours;
                  }
          
          
                  // other public functions
          
                  private:
                  int     module_hours;
                  float   average_marks;
          };
          
          int main()
          {
                  Student s; // create the object and initialise it
          
                  // print out initialised values
                  cout << "hours " << s.hours_worked()
                       << " average_marks " << s.marks() << "\n";
          
                  // rest of main 
          }


          Constrcutor Example - Rational Class

          class Rational
          {
                  public:
                          Rational(int n, int d)
                          {
                                  num = n;
                                  den = d;
                          }
                          void print();
                  private:
                          int num,den;
          };
          main()
          {
                  Rational x(22,7), y(-2,5);
                  cout << "x = ";
                  x.print();
                  cout << "y = ";
                  y.print();
          }


          Introduction to Classes

          Additional Example





          PROBLEM:

          Implement a Time class. Each object of this class will represent a specific time of the day, storing the hours and minutes as integers. Include a constructor, access functions, a function advance(int h, int m) to advance the current time of day by the specified amount and a function reset(int h, int m) to reset the current time to the specified time. Also include a print function.

          Remember to include a normalise() function which checks that 0 <= minutes < 60 and 0 <= hours < 24. If the minutes are outside the specified range increment the hours and calculate the minutes in the correct range. If the number of hours are greater than 24 then decrement by 24. This function will be called automatically each time the time is changed \fIie.\fR by the constructor, the reset and advance functions.

          Write a short main program which declares objects of type Time and manipulates them using the functions given.


          SOLUTION:

          #include <iostream.h
          #include <math.h
          
          class Time
          {
                  public:
                          Time(int h, int m)
                          {
                                  hour = h;
                                  min  = m;
                                  normalise();
                          }
                          int  hours() { return hour;}
                          int  mins()  { return min;}
                          void advance(int h, int m);
                          void reset(int h , int m);
                          void print();
                  private:
                          int     hour, min;
                          void normalise();
          };
          
          void Time::advance(int h, int m)
          {
                  hour += h;
                  min += m;
                  normalise();
          }
          void Time::reset(int h, int m)
          {
                  hour = h;
                  min = m;
                  normalise();
          }
          void Time::print()
          {
                  cout << hour << ":" << min << "\en";
          }
          void Time::normalise()
          {
                  while (min  60)
                  {
                          min -= 60;
                          hour++;
                  } 
                  while (hour  24)
                          hour -= 24;
          }
          
          
          main()
          {
                  Time time1(9,31), time2(10, 25);
          
                  cout << "Time1 is ";
                  time1.print();
          
                  time1.advance(11,35);
                  cout << "Time 1 is ";
                  time1.print();
          
                  time1.advance(11,35);
                  cout << "Time 1 is ";
                  time1.print();
          
                  cout << "Time 2 is ";
                  time2.print();
                  time2.reset(12,11);
                  cout << "Time 2 is ";
                  time2.print();
          
          }

          The main program is simply to test the class and its member functions

          If run the program will produce the following output

          Time 1 is 9:31
          Time 1 is 21:6
          Time 1 is 8:41
          Time 2 is 10:25
          Time 2 is 12:11

          On entering the main program, the contsructor is called to initialse Time1 to containg the time 9:31 and it is called again to initialsise Time2 to be 10:25. The print() member function is then called to display the value of Time1. This is then advanced by 11 hours and 35 minutes and the new time is printed. This is repeated. Time2 is then prointed and is the reset to the time of 12:11 and thus new time is displayed.


          Introduction to Classes

          Additional Exercises






          Introduction to Classes


          1. Example the difference between a public and a private member of a class.
          2. Example the difference between a constructor and a destructor
          3. What name must a constructor have?
          4. What name must a destructor have?

          5.  

             
             
             


            Answers

            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            


          6. A public member is accessible from outside a class. A private member can only be accessed within the class.
          7. A constructor function is called automatically whenever we instantiate (create) an object of that class and can be used to inialise the object. A destructor is called automatically whenever the scope of the object terminates (ie at the end of the program)
          8. A constructor always has the same name as the class


 

 

A destructor has the same name as the class but prefixed with a ~ (tilde)