Unit 7
Unit 7
Structure
7.1 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 Introduction
Objectives
Elements of a C++ Program Keywords and Identifiers Data Types Basic Input and Output Expressions and Control Structures Functions Arrays and Compound Data Types Pointers
7.1 INTRODUCTION
In this unit, we will try to introduce the C++ programming using example programs useful for the students of mechanical engineering. Many times we just learn the theoretical aspects without resorting to the concepts we learn to test. However, when we try to learn from practical point of view we face the real problems. By solving such problems one really learns to program and the design intent of a particular feature existing in C++. In this unit, we start with simple and trivial programs in C++ just to enable the student to grasp the basic features of the C++ language. Later on, slightly larger and more involved programming examples are presented. It is common sense that unlike the other units here the student needs a C++ compiler and a computer to try out the examples discussed here. Instead of just going through the text you are advised to type out the small program examples and compile and see its working. These programs are designed for use with any C++ compiler (i.e. Borland Turbo C++) either on windows or on Linux operating system.
Objectives
After studying this unit, you should be able to understand the elements of C++ program, use keywords and identifiers, use different data types, use expressive and control structures, create your functions in C++, use arrays and pointers efficiently, and create your classes and objects in C++.
C++ program looks. Study carefully the following program in Section 7.2.1. It has all the essential features of a complete program. Notice the following elements in this program : (a) (b) (c) (d) (e) (f) Preprocessor directive to include a header file #include <iostream.h>. The main( ) function with void qualifier. The output statement which displays the string inside quotes "Hello, Welcome to C++ ". Note the semicolon (;) at the end of the statement. The pair of curly braces { } after the main( ) function signify the beginning and end of the program. Redirection of the string using << to cout. A comment starting with two forward slashes // This is a statement
Thus, this trivial program has all skeletal features of a C++ program.
const float mult = 5.0/9.0; // 5/9 returns zero // integer division const int sub = 32; float fahr, cent; cout << "Enter Fahrenheit temperature: "; cin >> fahr; cent = (fahr - sub) * mult; cout << "Centigrade equivalent of " << fahr << " is " << cent << endl; }
int
Integer
signed: -2147483648 to 1word 2147483647 unsigned: 0 to 4294967295 2bytes signed: -32768 to 32767 unsigned: 0 to 65535
short int
Short Integer
long int
Long integer
Boolean value. It can take one of two values : true or false Floating point number Double precision floating point number Long double precision floating point number
4bytes 3.4e +/- 38 (7 digits) 8bytes 1.7e +/- 308 (15 digits) 8bytes 1.7e +/- 308 (15 digits)
* The values given above are for a 32bit system. The actual values of columns Size and Range depend on the architecture of the hardware. In the example program given below we have integer variables a, b and result declared in the beginning of the program. 45
46
extracted from the stream. For example, in the program below, the integer value read from the keyboard is assigned to the variable i.
// Enter hours worked and hourly rate cout << "Enter hours worked: "; cin >> hours_worked; cout << "Enter hourly_rate: "; cin >> hourly_rate; 47
// calculate wage if (hours_worked <= limit) wage = hours_worked * hourly_rate; else wage = (limit + (hours_worked - limit) * overtime_factor) * hourly_rate; // Output wage cout << "Wage for " << hours_worked << " hours at " << hourly_rate << " is " << wage << endl; } Let us look at another simple example wherein we calculate and print Pythagorean triples given by the expressions t1 = m*m-n*n; t2 = 2*m*n; t3 = m*m+n*n; where m and n are any two integers such that m > n which is ensured in the very beginning of the calculation. If it is not true an error message is printed to inform the user that m must be greater than n.
int t1, t2, t3; // The values of the triple // input from user cout << "Input values for m and n, m > n : "; cin >> m >> n; // now validate m and n if (m > n) { t1 = m*m-n*n; t2 = 2*m*n; t3 = m*m+n*n; cout << "The triple corresponding to " << m << " and " << n << " is " << t1 << " " << t2 << " " << t3 << endl; 48 }
else cout << "m must be greater than n!" << endl << "you entered m as " << m << " and n as " << n << endl; } Testing Let us test the above program by giving m = 2 and n = 1 as inputs. The following Pythagorean triple results : 3 4 5 Another example given below illustrates the use of if else construct to find out whether the given geometrical shape is a square or a rectangle. Here the user supplies the input breadth and height and the program calculates the perimeter and area as output.
To test the other case we give breadth = 3 and height = 3 as input values. The following output results : Area and perimeter of square are 9 12. In the following example we use a simple while loop to find the sum of first n natural numbers. Note that the loop index variable i is initialized as 1 and the variable sum is initialized to zero to begin with. The expression with a unary operator i++ increments the index variable by one every time the loop is executed. Similarly the expression sum+= i adds the new number to the variable sum.
cin >> s1 >> cw1 >> s2 >> cw2; Also, observe the mechanism to count the student numbers. A counter count is initialized to zero in the beginning is incremented by count++. Another feature to be noticed is the integer conversion of the expression for final marks as follows : final1 = int(EXAMPC*s1 + CWPC*cw1);
int s1, cw1, s2, cw2; // candidate marks int final1, final2; // final subject marks int count; int sum1, sum2; // number of students // sum accumulators
int subav1, subav2; // subject averages const float EXAMPC = 0.7, CWPC = 0.3; // initialise sum1 = 0; sum2 = 0; count = 0; // enter candidate number cout << "Input candidate number: "; cin >> candno; while (candno >= 0) { // enter marks cout << "Input candidate marks: "; cin >> s1 >> cw1 >> s2 >> cw2; // process marks count++; final1 = int(EXAMPC*s1 + CWPC*cw1); final2 = int(EXAMPC*s2 + CWPC*cw2); sum1 += final1; sum2 += final2; // output marks cout << candno << " " << s1 << " " << cw1 << " " << s2 << " "<< cw2 <<" " << final1 << " " << final2 51
<< endl; // enter candidate number cout << "Input candidate number (negative to finish): "; cin >> candno; } // evaluate averages subav1 = sum1/count; subav2 = sum2/count; // output averages cout << endl << "Subject1 average is " << subav1 << endl << "Subject2 average is " << subav2 << endl; } Testing We can now test the above program by giving some test values for two students with candno, s1, cw1, s2, cw2 as 1100 77 83 75 88 1101 68 71 65 70 and enter -10 to exit. The following answer is produced: 1100 77 83 75 88 79 79 1101 68 71 65 70 69 67 Subject1 average is 74 Subject2 average is 73 In the next example we use <math.h> header file for using the mathematical functions library. This program uses an iterative method to evaluate the square root of a positive number entered by the user. If a negative number is entered it gives an error message. In this program we have made use of if statement for testing data to take an appropriate action on it. Later on the while statement is used as a means of looping till the answer converges to the limiting value of tol.
cin >> value; if (value < 0.0) cout << "Cannot find square root of negative number" << endl; else if (value == 0.0) cout << "square root of " << value << " is 0.0" << endl; else { oldval = value; // take value as first approximation newval = (oldval + value/oldval)/2; while (fabs((newval-oldval)/newval) > tol) { oldval = newval; newval = (oldval + value/oldval)/2; } cout << "square root of " << value << " is " << newval << endl; } } Testing For testing this program let us input value = 3. The following output results : Square root of 3 is 1.732051 The following simple program validates an input value to lie within given bounds. Forces user to enter value until it is within bounds. Notice the declaration of a Boolean variable : bool accept; // indicates if value in range
A do ( ..) while( condition) construct is used to repeatedly ask the user for a valid input. This way no invalid input is acceptable. The moment the variable accept is true the control jumps out of this loop.
float x;
// value entered
float low, high; // bounds for x // assume low and high have suitable values low = 5.0; high = 10.0; do { cout << "Enter a value (" << low <<" to " << high << "):"; cin >> x; if (low <= x && x <= high) accept = true; else accept = false; } while (!accept); cout << "Value entered was " << x << endl; } Here is another example program which involves int, double and char data types. The program calculates some statistical quantities from the given data.
girls++; gSum += height; gSumSq += height*height; } else { boys++; bSum += height; bSumSq += height*height; } cin >> height >> gender_tag; } double average; double standard_dev; cout << "The sample included " << children << " children" << endl; average = cSum / children; cout << "The average height of the children is " << average; standard_dev = sqrt( (cSumSq - children*average*average) / (children-1)); cout << "cm, with a standard deviation of " << standard_dev << endl; cout << "The sample included " << girls << " girls" << endl; average = gSum / girls; cout << "The average height of the girls is " << average; standard_dev = sqrt( (gSumSq - girls*average*average) / (girls-1)); return 0; } When run on the following input data : 135 f 140 m 139 f 151.5 f 133 m 148 m 144 f 146 f 142 m 144 m 0m
55
The program produced the following output (verified using a common spreadsheet program) : The sample included 10 children The average height of the children is 142.25cm, with a standard deviation of 5.702095 The sample included 5 girls The average height of the girls is 143.1cm, with a standard deviation of 6.367888 The sample included 5 boys The average height of the boys is 141.4cm, with a standard deviation of 5.549775.
7.7 FUNCTIONS
Using functions we can structure our programs in a more modular way, accessing all the potential that structured programming can offer to us in C++. A function is a group of statements that is executed when it is called from some point in another program. The following is its format : type name ( parameter1, parameter2, ...) { statement } In the following example a simple function to calculate the power of a positive number is illustrated. See the prototype of the function given in the very beginning. The return type of the function is float. There are two arguments to this function a base of type float and a power of type int.
y = power(x,-n); cout << x << " to the power " << -n << " is " << y << endl; cout << "Tested" << endl; } // End of main // Function Definition float power(float x, int n) { float product = 1.0; int absn; int i; if ( n == 0) return 1.0; else { absn = int(fabs(n)); for (i = 1; i <= absn; i++) product *= x; if (n < 0) return 1.0 / product; else return product; } } // end of power Testing The interaction with the program is as follows : Testing function power(n) Enter values for x and n: 2 3 2 to the power 3 is 8 2 to the power -3 is 0.125 Tested.
In the following program an array is built up from the input data values. Up to a maximum of 200 numbers can be stored in this array. The array is used to calculate the average of the data and is also used to find the number of values lying 10% above the average value.
// above average float x; // holds each no as input // array to hold input // average value of input values // control variable
// Data entry, accumulate sum and count // number of +ve numbers entered cout << "Enter numbers, -ve no to terminate: " << endl; cin >> x; while (x >= 0.0) { sum = sum + x; indata[count] = x; count = count + 1; cin >> x; } // calculate average average = sum/count; // Now compare input elements with average for (i = 0; i < count; i++) { if (indata[i] > 1.1 * average) nogt10++; 58
} // Output results cout << "Number of values input is " << count; cout << endl << "Number more than 10% above average is " << nogt10 << endl; } Here is another small program to illustrate the use of arrays in C++. Here the array is used to count the random numbers which simulate the throwing of a dice. It counts how many times each possible outcome occurs. User is asked to input the number of trials required. Note the inclusion of <time.h> header file for obtaining the time for random number generation.
// possible value int no_trials, roll, i; float sample; // number of trials // random integer // control variable // random fraction 0 .. 1
// initialise random number generation and count // array and input no of trials srand(time(0)); for (i=0; i < die_sides; i++) count[i] = 0; cout << "How many trials? "; cin >> no_trials; // carry out n trials for (i = 0; i < no_trials; i++) { sample = rand()/float(RAND_MAX); roll = int ( die_sides * sample); // returns a random integer in 0 to die_sides-1 count[roll]++; } // increment count 59
// Now output results for (i = 0; i < die_sides; i++) { cout << endl << "Number of occurrences of " << (i+1) << " was " << count[i]; } cout << endl; }
7.9 POINTERS
The computer memory can be imagined as a contiguous arrangement of memory cells, each one of the minimal size that computers manage (one byte). These single-byte memory cells are numbered in a consecutive way, so as, within any block of memory, every cell has the same number as the previous one plus one. The address that locates a variable within memory is what we call a reference to that variable. This reference to a variable can be obtained by preceding the identifier of a variable with an ampersand sign (&), known as reference operator, and which can be literally translated as address of . In our example program given below, the statement
secondvalue is 20 Now let us learn some more details about pointers by comparing pointers and arrays. In the example that follows we define an array of 5 elements, numbers [5] and also a pointer to integer variable int *p. We explore how to access the elements of the array by pointing to the first element and incrementing it to access the successive elements.
} apple, banana, melon; We make use of this type to define three objects viz. apple, banana and melon. Notice how we can access its component fields. We assign unit price of each of these fruits by accessing the respective field as follows : apple.price = 40.00; // price per kilogram banana.price = 22.50; // price per kilogram melon.price = 7.50; // price per kilogram We ask the user to input the values of weight for each fruit and calculate the total cost of fruits in this program. The same is printed out at the end.
Upon running this program which requires no inputs from the user, the following output results : area: 12 sq. units.
7.12 SUMMARY
In this unit, you learnt C++ from practical point of view. We have studied different program and different issue related to object oriented programming and design. You must implement these example programs again in your computers and verify the output. These programs are designed for use with any C++ compiler (i.e. Borland Turbo C++) either on windows or on linex operating system.
FURTHER READINGS
Bjarne Stroustrup, Addison-Wesley, The C++ Programming Language, Third Edition. Stan Lippman, Josse Lajoie, Addison Wesley, C++ Primer, Third Edition. Al Stevens, Teach Yourself C++, Fifth Edition, MIS : Press. Jesse Liberty, Teach Yourself C++ In 21 Days, Second Edition, Sams Publishing. http://www.zib.de/Visual/people/mueller/Course/Tutorial/tutorial.html http://www.isd.mel.nist.gov/projects/rcslib/quickC++.html http://www.macs.hw.ac.uk/~pjbk/pathways/cpp1/node2.html http://www.cs.wust.edu/~schmidt/C++/
64
overloading. The last unit includes different examples that describe the use of newly acquired knowledge in the previous units. It is recommended to read these examples before passing to the next example. A good way to gain experience with a programming language is by modifying and adding new functionalities on your own to the example programs that you fully understand. Several compilers for C++ are available for you, e.g. Borland C++, Microsoft C++, GNU C++, etc. You can use these compiler for compiling, executing and testing your programs.
65