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.
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.
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.
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.
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.
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
// Program written October 1997 // by jmb #include <iostream.h main() { cout <<< "Hello World!\n"; // \n causes new line }
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
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 }
Additional Exercises
// 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; }
cout << Hello World\n;
COUT << "Hello World\n";
cout "Hello World\n";
cout << "Hello World"\n;
cout << "Hello World\n";
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
// 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" ; }
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"; }
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"; }
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"; }
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"; }
Case Study
PROBLEM:
Write a program to calculate an employees wages. They are paid at a basic rate of £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"; }
Additional Exercises
main() { p=47; cout << p; }
int x = y = 95;
int x=95, y =95; x = x - 1; x --; --x; x -= 1;
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
//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"; }
//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"; }
//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"; }
#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"; }
#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"; } }
#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"; } }
#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; } }
Case Study
PROBLEM:
Write a program to calculate the commission based wages of a computer salesman. His basic wage is £50 per week and he is expected to sell at least 10 computers. If he sells more than 10 computers, he receives an extra £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 <iostream.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.
Additional Exercises
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.
int x; if (x=1) x++;
int x, y, z; if (x y && < z) x = y;
if (x 0) if (x 0 && x%2 == 0)
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
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"; }
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"; }
#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"; }
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"; } }
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"; }
Additional Exercises
Prevent the program from proceeding until suitable values are entered.
int x, y; for (x=1; x < 57; x+= 2) y = x;
int n=0; while (n < 100) value = n*n;
i = 1; while (i <= 10 ) cout << i; i++;
x = 1; while (x < 57) { y = x; x += 2; }
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; }
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
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"; }
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"; }
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]; } } }
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"; }
Additional Exercises
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).
int array[10],i; for (i=0;i < 10;i++) array[i] = array[i+1];
float index; float array[9]; for (index=0; index < 9; index++) array[index] = index;
int i; for (i=0;i<100;i++) a[i] = 0.0;
int index;
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
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); }
// 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); }
// 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); }
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)); }
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; }
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]; } }
#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]; } }
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; }
Additional Examples
There are three additional worked examples:-
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); }
PROBLEM:
Consider the calculation of the roots of the quadratic equation ax²+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"; }
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.
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.
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!
Example 1 |
||
Example 2 |
||
Example 3 |
||
Example 4 |
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
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.
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.
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; }
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.
In this case we require an else..if structure because there are 3 possible routes depending on the values of m and n.
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); }
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)!
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); }
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); }
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.
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)); }
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.
Additional Exercises
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).
Now re-write the main program to call this function and then display if the array is a palindrome.
float function(float a, float b, float c) { float tmp; tmp = (a + b + c )/ 3.0 ; return tmp; }
The definition contains the actual code of what is to be implemented when the function is called.
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();
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
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"; }
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"; }
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.
Additional Exercises
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.
int *p, *q; int n;
Which of the following is valid?
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];
How many arguments are in the following command line?
prog -x -a file1 13
What is stored in argv[2]?
There are 5 arguments.
argv[2] contains -a
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
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 }
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"; }
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(); }
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(); }
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
Additional Exercises
3 |
||||
bob |
10 |
10 |
10 |
10 |
fred |
2 |
12 |
14 |
15 |
john |
3 |
4 |
5 |
6 |
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.
if (!fi ) { cout << "Can't open file file.txt for reading\n"; exit(1); }
fi.open("file.txt");
fi array[i]; while (!fi.eof()) { i++; fi array[i]; }
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
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 }
#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; }
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 }
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(); }
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.
Additional Exercises
A destructor has the same name as the class but prefixed with a ~ (tilde)