Você está na página 1de 23

UNIT 7 C++ EXAMPLE PROGRAMS

Structure
7.1 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 Introduction
Objectives

C++ Example Programs

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.10 Data Structures 7.11 Classes and Objects 7.12 Summary

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++.

7.2 ELEMENTS OF A C++ PROGRAM


The basic structure of a C++ program with its elements is shown below in Section 7.2.1. Before starting our study, a quick look at an example program helps to understand how a 43

Object-oriented Programming Using 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.

7.2.1 Program : Welcome to C++


#include <iostream.h> void main() { cout << "Hello, Welcome to C++ ";// This is a statement }

7.3 KEYWORDS AND IDENTIFIERS


Like in other programming languages, there are many keywords defined by the compiler designers. These are reserved and should not be redefined in any program. An identifier is any string of characters not using special characters like ., $, / etc. As the name suggests it identifies a variable. A valid identifier is a sequence of one or more letters, digits or underline characters ( ). Neither spaces nor punctuation marks or symbols can be part of an identifier. Only letters, digits and underline characters are valid. In addition, variable identifiers always have to begin with a letter. They can also begin with an underline character ( ), but this is usually reserved for compiler specific keywords or external identifiers. In no case can they begin with a digit. The keywords should not be used as identifiers. A list of the standard reserved keywords is given in the following box. asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while In the following example program given in Section 7.3.1, the words main, const, float, cin, cout void, endl are all key words in C++ language. Similarly, the words mult, sub, fahr are the identifiers defined by the user.

7.3.1 Program : Temperature Conversion


#include <iostream.h> void main( ) { 44

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; }

C++ Example Programs

7.4 DATA TYPES


It is mandatory to declare the type of data. When a variable is declared as of a particular type it gets memory allocation accordingly. For instance the integer type variable takes 4 bytes or one word. The details for other variable types are given in Table 7.1. The size and range details given here are for a 32 bit machine platform. Table 7.1 : Fundamental Data Types
Name char Character Description Size* 1byte Range* signed: -128 to 127 unsigned: 0 to 255

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

signed: -2147483648 to 4bytes 2147483647 unsigned: 0 to 4294967295 1byte true or false

bool float double long double

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

Object-oriented Programming Using C++

7.4.1 Program : Variable Types


// operating with variables #include <iostream> int main () { // declaring variables: int a, b; int result; // process: a = 5; b = 2; a = a + 1; result = a - b; // print out the result: cout << result; // terminate the program: return 0; } There is another way to initialize the variables right at the time of type declaration. This is illustrated in the following program. Here we initialize the variables a and b with values 5 and 2 respectively (in two different ways).

7.4.2 Program : Initialization of Variables


#include <iostream> int main () { int a=5; int b(2); int result; a = a + 3; result = a - b; cout << result; return 0; } // initial value = 5 // initial value = 2 // initial value undetermined

7.5 BASIC INPUT AND OUTPUT


The default standard output of a program is the screen, and the C++ stream object defined to access it is cout. Cout is used in conjunction with the insertion operator, which is written as << (two less than signs). The default standard input device is usually the keyboard. The standard input in C++ is handled by applying the overloaded operator of extraction (>>) on the cin stream. The operator must be followed by the variable that will store the data that is going to be

46

extracted from the stream. For example, in the program below, the integer value read from the keyboard is assigned to the variable i.

C++ Example Programs

7.5.1 Program : Basic Input/Output Implementation


#include <iostream> using namespace std; int main () { int i; cout << "Please enter an integer value: "; cin >> i; cout << "The value you entered is " << i; cout << " and its double is " << i*2 << ".\n"; return 0; }

7.6 EXPRESSIONS AND CONTROL STRUCTURES


Application programs involve a large number of operations on variables. We need mathematical and logical operators to do those operations. The operators operate on variables (operands) to produce results. We have seen some expressions in the example program 3.The variables a and b are assigned values 5 and 2 respectively. The value of a so assigned is modified later. The variable result gets the value resulting form the operation a-b and the same is printed out. We know that when we have a compound expression involving several operators, there is a precedence rule applied from left to right to evaluate the result. In the example, the calculation of final wage checks whether the worker has worked more than 40 hours using an if else logical control structure. If so, the extra hours worked are multiplied with overtime factor of 1.5. Also, notice the output structure used for printing out the result at the end of this program.

7.6.1 Program : Wages Calculation


// Program to evaluate a wage #include <iostream.h> void main() { const float limit = 40.0, overtime_factor = 1.5; float hourly_rate, // hourly rate of pay hours_worked, // hours worked wage; // final wage

// Enter hours worked and hourly rate cout << "Enter hours worked: "; cin >> hours_worked; cout << "Enter hourly_rate: "; cin >> hourly_rate; 47

Object-oriented Programming Using C++

// 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.

7.6.2 Program : Pythagorean Triples


// Program to produce pythagorean triples with input validation. #include <iostream.h> void main() { int m, n; // entered by user to generate triple

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.

C++ Example Programs

7.6.3 Program : Area and Perimeter of Rectangle


/* Inputs breadth and height of a rectangle and outputs area and perimeter preceded by different messages depending on whether it is a square or a rectangle.*/ #include <iostream.h> void main() { int breadth, height; // of rectangle int perimeter, area; // of rectangle // input breadth and height cout << "Enter breadth and height: "; cin >> breadth >> height; // calculate perimeter and area perimeter = 2*(breadth+height); area = breadth*height; if (breadth == height) cout << "Area and perimeter of square are "; else cout << "Area and perimeter of rectangle are "; // output area and perimeter cout << area << " " << perimeter << endl; } Testing We can now test the above program by giving breadth = 2 and height = 1 as inputs. The following output results : Area and perimeter of rectangle are 2 6. 49

Object-oriented Programming Using C++

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.

7.6.4 Program : Summing Arithmetic Progression


// Summing first n natural numbers, n is input by user #include <iostream.h> void main() { int i, n, sum; cout << "Enter a value for n: "; cin >> n; sum = 0; i = 1; while (i <= n) { sum += i; i++; } cout << "The sum of the first " << n << " numbers is " << sum << endl; } Testing We can now test the above program by giving n = 6 as inputs. The following output results : The sum of the first 6 numbers is 21. Now we can take a slightly detailed program with more calculations to do. We now consider a student marks processing program here. This program takes input data from a class of students and produces statistics on the class. Inputs for each class member are: a candidate number (4 digits), a % exam marks and a % course work marks for each student in each of two subjects. The program outputs the data for each student and also the final mark for each subject. Final marks are calculated from 70% of exam mark plus 30% of coursework marks. A constant declaration is present in this program which declares two constants to be used as weights for exam and course work as follows : const float EXAMPC = 0.7, CWPC = 0.3; User supplies a unique ID No. for each student followed by 4 integer numbers read by the input statements, cin >> candno; 50

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);

C++ Example Programs

7.6.5 Program : Student Marks Processing


// Student marks program #include <iostream.h> void main() { int candno; // candidate number

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

Object-oriented Programming Using C++

<< 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.

7.6.6 Program : Iterative Evaluation of a Square Root


#include <iostream.h> #include <math.h> void main() { const float tol = 0.000005; // relative error tolerance float value; float oldval, newval; cout << "Square root of a number" << endl << endl; cout << "Enter a positive number: "; 52

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

C++ Example Programs

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.

7.6.7 Program : Valid Input Checking


#include <iostream.h> void main() { bool accept; // indicates if value in range 53

Object-oriented Programming Using C++

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.

7.6.8 Program : Calculating Some Simple Statistical Quantities


#include <iostream.h> #include <math.h> int main() { int children, boys, girls; double cSum, bSum, gSum; double cSumSq, bSumSq, gSumSq; double height; char gender_tag; children = boys = girls = 0; cSum = bSum = gSum = 0.0; cSumSq = bSumSq = gSumSq = 0.0; cin >> height >> gender_tag; while(height != 0.0) { children++; cSum += height; cSumSq += height*height; if(gender_tag == 'f') { 54

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

C++ Example Programs

55

Object-oriented Programming Using C++

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.

7.7.1 Program Function : Raising to the Power


// Example program - runs power function #include <iostream.h> #include <iomanip.h> // Function prototype float power(float,int); void main() { int n; float x, y; // Testing function power(x,n) cout << "Testing function power(n)" << endl; cout << "Enter values for x and n: "; cin >> x >> n; y = power(x,n); cout << x << " to the power " << n << " is " << y 56 << endl;

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.

C++ Example Programs

7.8 ARRAYS AND COMPOUND DATA TYPES


An array is an aggregate of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. For example, an array to contain 5 integer values of type int called billy could be represented like this : 57

Object-oriented Programming Using C++

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.

7.8.1 Program : Printing Outliers in Data


// Prints outliers in a data set #include <iostream.h> #include <iomanip.h> void main() { const int NE = 200; // maximum no of elements in array float sum = 0.0; int count = 0; int nogt10 = 0; // accumulates sum // number of elements entered // counts no greater than 10%

// above average float x; // holds each no as input // array to hold input // average value of input values // control variable

float indata[NE]; float average; int i;

// 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.

C++ Example Programs

7.8.2 Program : Test of Random Numbers


#include <iostream.h> #include <stdlib.h> #include <time.h> void main() { const int die_sides = 6; int count[die_sides]; // maxr-sided die // holds count of each // time.h and stdlib.h required 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

Object-oriented Programming Using C++

// 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

mypointer = &firstvalue; actually assigns the address of firstvalue to mypointer variable.


Using a pointer we can directly access the value stored in the variable which it points to. To do this, we simply have to precede the pointers identifier with an asterisk (*), which acts as dereference operator and that can be literally translated to value pointed by. For example in our example program below, the statement

*mypointer = 10; assigns 10 to the variable mypointer.

7.9.1 Program : The First Pointer Program


#include <iostream> int main () { int firstvalue, secondvalue; int * mypointer; mypointer = &firstvalue; *mypointer = 10; mypointer = &secondvalue; *mypointer = 20; cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " << secondvalue << endl; return 0; } Testing Upon running this simple program we get the following output. 60 firstvalue is 10

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.

C++ Example Programs

7.9.2 Program : Pointers and Arrays


#include <iostream> int main () { int numbers[5]; int * p; p = numbers; *p = 10; p++; *p = 20; p = &numbers[2]; *p = 30; p = numbers + 3; *p = 40; p = numbers; *(p+4) = 50; for (int n=0; n<5; n++) cout << numbers[n] << ", "; return 0; }

7.10 DATA STRUCTURES


A data structure is a group of data elements arranged together under one name. These data elements, known as members, can have different types and different lengths. Data structures are declared in C++ using the following syntax : struct structure_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; . } object_names; In the following example program we define a data structure called fruit_t as : struct fruits_t { int weight; float price; 61

Object-oriented Programming Using C++

} 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.

7.10.1 Program : Implementation of Data Structures


#include <iostream> #include <string> #include <sstream> struct fruits_t { int weight; float price; } apple, banana, melon; int main () { float totalprice; apple.price = 40.00; // price per kilogram banana.price = 22.50; // price per kilogram melon.price = 7.50; // price per kilogram cout << "How many kilos of apple?: "<< endl; cin >> apple.weight; cout << "How many kilos of banana?: " << endl; cin >> banana.weight; cout << "How many kilos of melon?: "<< endl; cin >> melon.weight; totalprice=apple.weight*apple.price+banana.weight*banana.price +melon.weight*melon.price; cout << "Your Bill \n "; cout << Item \t Quantity \t Price\n cout << Apple\t<<apple.weight<<\t<<apple.price<< endl; cout << Banana\t<<banana.weight<<\t<<banana.price<< endl; cout << Apple\t<<melon.weight<<\t<<melon.price<< endl; cout << Total\t\t<<totalprice<< endl; return 0; } 62

7.11 CLASSES AND OBJECTS


After studying the data structures we are now ready to understand the object oriented nature of C++ by proceeding to the concept of a class. A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable. Classes are generally declared using the keyword class, with the following format :

C++ Example Programs

class class_name { access_specifier_1: member1; access_specifier_2: member2; ... } object_names;


Where class_name is a valid identifier for the class, object_names is an optional list of names for objects of this class. The body of the declaration can contain members that can be either data or function declarations, and optionally access specifiers. We use a trivial example of calculating the area of rectangle in the programming example given below. Here we declare a class called Crectangle which has two integer variables to store length and breadth of the rectangle and a function to calculate area using these variables. Another small auxiliary routine is included to set the values of these variables (it could be a mechanism to take user input). In the main( ) program we have declared an object called rect which is of type CRectangle and this object is used in later calculations.

7.11.1 Program : Implementation of a Class


#include <iostream> class CRectangle { int x, y; public: void set_values (int,int); int area () {return (x*y);} }; void CRectangle::set_values (int a, int b) { x = a; y = b; } int main () { CRectangle rect; rect.set_values (3,4); cout << "area: " << rect.area()<< sq. units; return 0; } Testing 63

Object-oriented Programming Using C++

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++/

OBJECT-ORIENTED PROGRAMMING USING C++


Object-oriented programming is a move towards writing software, which is based around the idea of constructing specific data structures to signify the parts of the problem and then defining how those data structures correlate and interact with each other. This block provides you an experience for the broad issues of object-oriented programming and C++, including why OOP, and C++ in particular is different. The block is divided into three units and each part is divided on its turn into different sections in which you will learn the fundamental concepts of C++ including object-oriented concepts, program structure, classes, reference types, C++ I/O, virtual functions, inheritance and

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.

C++ Example Programs

65

Você também pode gostar