19
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 Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

Embed Size (px)

Citation preview

Page 1: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

C++ Tutorial

Hany Samuel and Douglas Wilhelm HarderDepartment of Electrical and Computer Engineering

University of Waterloo

Copyright © 2006 by Douglas Wilhelm Harder. All rights reserved.

ECE 250 Data Structures and Algorithms

Page 2: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

C++ Tutorial

• In this tutorial we will look at:– C++ statements– data types– variables– pointers– arrays– functions– classes

• Examine different examples.

Page 3: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

Built-in Data Types

Built-in Data Types

Integral Numbers “Real” numbers

char 8 bits

0, ..., 28 – 1 = 255

short int16 bits

-215, ..., 215 – 1

int32 bits

-231, ..., 231 – 1

float32 bits

±1.18 10–38

±3.40 10 38

double64 bits

±2.23 10–308 ±1.80 10 308

boolfalse == 0 true == 1

Page 4: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

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.

Page 5: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

Example 1

• A program to calculate the area of a circle given its radius.

#include <iostream>

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

Page 6: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

Example 2

• Operators:– arithmetic: + - * / %

+= -= *= /= %=– increment, decrement: ++ --– bitwise operators:

& | ~ and, or, and complement

<< >> left and right bit shifting

– comparison: < > <= >= != ==– logical conditions:

&& || ! and , or and not

Page 7: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

Example 2

• Loops:for ( initialize; condition; increment ) { }

while ( condition ){ }

do { } while( condition );

• Conditionsif ( condition ) { }

if ( condition ) { } else { }

Page 8: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

Example 2

• A program to find all the numbers divisible by either 3 or 4

#include <iostream>

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;

}

Page 9: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

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

Page 10: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

Example 3

• Iterative calculation: n! = n(n – 1)(n – 2)⋅⋅⋅2⋅1#include <iostream>

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;

}

Page 11: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

Example 3

• Recursive calculation: n! = n(n – 1)!

#include <iostream>

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 ?

Page 12: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

Arrays versus Pointers

• An array of five integers:int numbers[5];

• The variable numbersstores the addressof the first entry

• Access contentsusing numbers[n]

numbers

numbers[2]

&(numbers[2])

numbers[0]

Page 13: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

Example 4 (Arrays)• A program which reads 10 numbers and prints their sum,

average, max and min:

#include <iostream>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<double>(sum)/10.0;

cout << "sum = " << sum << endl << "average = " << ave << endl << "maximum = " << max << endl << "minimum = " << min << endl;

return 0;}

Page 14: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

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;

Page 15: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

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;

Page 16: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

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;

}

Page 17: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

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

Attributes attributes member variables

Operations methods member functions

Page 18: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

Classes#include <iostream>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();

}

Page 19: C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas

Classes (cont)

int main() { Complex z1( 3 ); // 3 + 0j Complex z2( 4, 5 ); // 4 + 5j

Complex w = z1.add( z2 ); print( w );}