C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas Wilhelm Harder. All rights reserved. ECE 250 Data Structures and Algorithms
C++ Tutorial In this tutorial we will look at: –C++ statements –data types –variables –pointers –arrays –functions –classes Examine different examples.
Built-in Data Types Integral Numbers char 8 bits 0,..., 2 8 – 1 = 255 short int 16 bits -2 15,..., 2 15 – 1 int 32 bits -2 31,..., 2 31 – 1 bool false == 0 true == 1 “Real” numbers float 32 bits ± –38 ± double 64 bits ± –308 ±
Example 1 The basic parts of the c++ main function. How to declare and initialize variables. How to define constants. How to perform simple input/output operation.
Example 1 A program to calculate the area of a circle given its radius. #include using namespace std; int main() { double radius; const double PI = 3.14; cout << "Please enter the radius: "; cin >> radius; double area = PI*(radius*radius); cout << "the area is = " << area << endl; return 0; } Variable declarations and initialization (compare with C#) Preprocessor directives Defining constants
Example 2 Operators: –arithmetic: + - * / % += -= *= /= %= –increment, decrement: –bitwise operators: & | ~ and, or, and complement > left and right bit shifting –comparison: = != == –logical conditions: && || ! and, or and not
Example 2 Loops: for ( initialize; condition; increment ) { } while ( condition ){ } do { } while( condition ); Conditions if ( condition ) { } if ( condition ) { } else { }
Example 2 A program to find all the numbers divisible by either 3 or 4 #include using namespace std; int main() { int n; cout << "please enter n: "; cin >> n; for( int i = 1; i <= n; ++i ) { if ( i % 3 == 0 || i % 4 == 0 ) { cout << i << endl; } return 0; }
Example 3 Java and C# require that functions be defined together with their declaration In C++, functions –need only be declared in the class –the actual definition may be elsewhere Example declaration: int factorial( int ); // parameter name optional
Example 3 Iterative calculation: n! = n(n – 1)(n – 2) ⋅⋅⋅ 2 ⋅ 1 #include using namespace std; // declaration of factorial int factorial(int); // declaration and definition // of main int main() { int n; cout << "Please enter n: "; cin >> n; int result = factorial( n ); cout << result << endl; return 0; } // definition of factorial int factorial( int n ) { int result = 1; for ( int i = 2; i <= n; ++ i ) { result *= i; } return result; }
Example 3 Recursive calculation: n! = n(n – 1)! #include using namespace std; // declaration of factorial int factorial(int); // declaration and definition // of main int main() { int n; cout << "Please enter n: "; cin >> n; int result = factorial( n ); cout << result << endl; return 0; } // definition of factorial int factorial( int n ) { if( n == 0 || n == 1 ) { return 1; } return n * factorial( n – 1 ); } Question: Is this program is better: this recursive version or the previous iterative version? Why ?
Arrays versus Pointers An array of five integers: int numbers[5]; The variable numbers stores the address of the first entry Access contents using numbers[n] numbers numbers[2] &(numbers[2]) numbers[0]
Example 4 (Arrays) A program which reads 10 numbers and prints their sum, average, max and min: #include using namespace std; int main() { int numbers[10]; for( int i = 0; i < 10; ++i ) { cin >> numbers[i]; } int min; int max; int sum; double ave; min = max = sum = numbers[0]; for( int i = 1; i < 10; ++i ) { if( numbers[i] < min ) { min = numbers[i]; } if( numbers[i] > max ) { max = numbers[i]; } sum += numbers[i]; } ave = static_cast (sum)/10.0; cout << "sum = " << sum << endl << "average = " << ave << endl << "maximum = " << max << endl << "minimum = " << min << endl; return 0; }
Pointers A pointer is simply a variable which stores a memory address The type of the variable stored at that address should be known int * ptr1; double * ptr2; Example: int x = 5; int * address; address = &x; cout << “The number at location " << address << " is = " << *address;
Pointers and Dynamic arrays Array size must be specified at compile time. What about run time ? Pointers solve that: int * numbers = new int[n]; Never forget to deallocate the memory: delete [] numbers;
Arrays Dynamic allocation of an array – new typename[n] requests memory from the OS – delete[] returns the memory to the OS –the new typename[n] operator returns a pointer Example: int main() { int n, *dynarray; cin >> n; // console in (keyboard) dynarray = new int[n]; // use the array dynarray... delete [] dynarray; return 0; }
Classes An object may be described by: –attributes(descriptions, properties, nouns) –operations(behaviours, verbs) The following table is a summary of the language-specific terminology: C#C++ Attributesattributesmember variables Operationsmethodsmember functions
Classes #include using namespace std; class Complex { private: double re; double im; public: Complex( double r = 0, double i = 0 ):re(r),im(i) { // empty } double real() const { return re; } double imag() const { return im; } void setReal( double r ) { re = r; } void setImag( double i ) { im = i; } Complex add( Complex z ) { double r = re + z.re; double i = im + z.im; return Complex( r, i ); } friend void print( Complex ); }; void print ( Complex z ) { cout << z.real() << " + j " << z.imag(); }
Classes (cont) int main() { Complex z1( 3 ); // 3 + 0j Complex z2( 4, 5 ); // 4 + 5j Complex w = z1.add( z2 ); print( w ); }