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

Slides:



Advertisements
Similar presentations
1 Demo Reading Assignments Important terms & concepts Fundamental Data Types Identifier Naming Arithmetic Operations Sample Programs CSE Lecture.
Advertisements

While Loops Programming. COMP102 Prog Fundamentals I: while Loops/Slide 2 Shortcut Assignments l C++ has a set of shortcut operators for applying an operation.
C++ Basics Prof. Shermane Austin. Learning Programming Language Basics Data Types – simple Expressions Relational and Logical Operators Conditional Statements.
Computer Science 1620 Functions. Given a number n, the factorial of n, written n!, is computed as follows: note: 0! = 1 examples: n! = n x (n-1) x (n-2)
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
Lecture 1 The Basics (Review of Familiar Topics).
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Programmer-defined functions Development of simple functions using value parameters.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Loops Programming. COMP104 Lecture 9 / Slide 2 Shortcut Assignment l C++ has a set of operators for applying an operation to a variable and then storing.
Basic Elements of C++ Chapter 2.
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
Elements of a C++ program 1. Review Algorithms describe how to solve a problem Structured English (pseudo-code) Programs form that can be translated into.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
February 11, 2005 More Pointers Dynamic Memory Allocation.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
ECE 250 Algorithms and Data Structures Douglas Wilhelm Harder, M.Math. LEL Department of Electrical and Computer Engineering University of Waterloo Waterloo,
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
C++ Programming: Basic Elements of C++.
Pointers OVERVIEW.
While Loops Programming. COMP102 Prog Fundamentals I: while Loops/Slide 2 Shortcut Assignments l C++ has a set of shortcut operators for applying an operation.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Department of Electrical and Computer Engineering Introduction to C++: Primitive Data Types, Libraries and Operations By Hector M Lugo-Cordero August 27,
A first program 1. #include 2. using namespace std; 3. int main() { 4. cout
C++ / G4MICE Course Session 2 Basic C++ types. Control and Looping Functions in C Function/method signatures and scope.
Computing and Statistical Data Analysis Lecture 2 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Variables, types: int, float, double,
Review 1 List Data Structure List operations List Implementation Array Linked List.
GE 211 Dr. Ahmed Telba. // compound assignment operators #include using namespace std; int main () { a =5 int a, b=3; a = b; a+=2; // equivalent to a=a+2.
C++ / G4MICE Course Session 1 - Introduction Edit text files in a UNIX environment. Use the g++ compiler to compile a single C++ file. Understand the C++
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
1 10/3/05CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
1 Introduction to C++ Noppadon Kamolvilassatian Department of Computer Engineering Prince of Songkla University.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
Simple Data Types Chapter Constants Revisited t Three reasons to use constants –Constant is recognizable –Compiler prevents changes in value.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
Variables and memory addresses
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Lecture 01a: C++ review Topics: Setting up projects, main program Memory Diagrams Variables / Types (some of) the many-types-of-const's Input / Output.
11 Introduction to Object Oriented Programming (Continued) Cats.
Lecturer: Nguyen Thi Hien Software Engineering Department Home page: hienngong.wordpress.com Chapter 2: Language C++
1 CSC103: Introduction to Computer and Programming Lecture No 16.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
A Sample Program #include using namespace std; int main(void) { cout
Intro. to Computer Programming Eng. Nehal A. Mohamed Spring Semester-2016.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
Pointers and Arrays Dynamic Variables and Arrays.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Bill Tucker Austin Community College COSC 1315
Chapter 1.2 Introduction to C++ Programming
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
While loop statement condition list
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Basic Elements of C++.
Functions and an Introduction to Recursion
New Structure Recall “average.cpp” program
Basic Elements of C++ Chapter 2.
Dynamic Memory Allocation Reference Variables
Chapter 2 Elementary Programming
Arrays Topics to cover: Arrays Data Types One-dimensional Arrays
Functions and an Introduction to Recursion
Engineering Problem Solving with C++ An Object Based Approach
Engineering Problem Solving with C++ An Object Based Approach
Presentation transcript:

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