introduction to c++ programming. brief facts about c++ evolved from c designed and implemented by...

41
Introduction to C++ Programming

Upload: mikayla-shinners

Post on 01-Apr-2015

219 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Introduction to C++ Programming

Page 2: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Brief Facts About C++

Evolved from C Designed and implemented by Bjarne Stroustrup at the

Bell Labs in the early 1980s “C with classes” Standardized by ISO in 1997

– Includes the C++ standard library– Standard Template Library (STL)

Part of the C++ standard library Readymade classes for data structures and algorithms

Page 3: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Filenames

Can be different from the name of the class or the name of the function in the file

.cpp– Extension for the C++ source code files

.h– Extension for C++ header files– Usually, code for a data structure is put in a header file, and then it can

be added to a program with an include directive, e.g. #include "BasicVector.h"

Name of executable file– In MSVS it’s the name of your project– In g++ it’s either “a.out” or a name you specify

Page 4: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Simple C++ Example

/*FILE: main.cpp*/#include <iostream>#include <string>using namespace std;

int main() {cout << "Enter your first name: ";string name;cin >> name;cout << "Hello, " << name << endl;return 0; //optional

}

Page 5: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

/*FILE: main.cpp*/#include <iostream>#include <string>using namespace std;

int main() {cout << "Enter your first name: ";string name;cin >> name;cout << "Hello, " << name << endl;return 0; //optional

}

Simple C++ Example

Comment

C++ header files fromC++ standard library

“Entry” function

Namespace forC++ standard library

All C++ statementsend with a semicolon

Page 6: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

The main() function

The entry point for your program– Only one main function– Located outside of any class– Located in a .cpp source code file

Return statement inside main()– return 0; //Successful execution– Optional

Two ways to write the signatureint main()

int main( int argc, char *argv[] )

Page 7: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Using Command Line Arguments

Program codeint main( int argc, char *argv[] ){

if( argc>1 ){

cout << "Data file is " << argv[1];

}

}

Open a console window and navigate to the directory where the executable is, then type the name of the executable followed by any argument that must be passed to the program.c:\> demo.exe "Data.txt"

Number of itemson the command line

Array of C-style stringson the command line

Page 8: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Output and Input

cout– #include <iostream>– using namespace std;– operator <<– Represents standard output, usually the screencout << "Enter your first name: ";

cin– <iostream>– operator >>– Reads keyboard input until the first whitespacestring name;cin >> name;

endl– Used to output a newline and flush output buffercout << "Hello, " << name << endl;

Page 9: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Variables and Data Types

Some of the standard C++ data typesbool int floatchar short doubleunsigned char long

Declaring a variable– Allocates storage space in memory– Not automatically initialized

int i; //i is declared but not initializedint j = 0; //j is declared and initializedint k(5); //k is declared and initialized

variable nameijk

300030043008

05

valuememory address

3012

Page 10: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Operators and Expressions

An expression — combining variables and literals with operators to create a new valueExample:

double x, y = 10.0;

x = y / 4.0;

Binary arithmetic operators+ addition

- subtraction

* multiplication

/ division

% modulo (finds the remainder)

variables literaloperators

Page 11: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Integer Division

The remainder is treated differently

Division operatorint m, n = 11;

m = n / 5;

cout << "m = " << m; //What prints?

Modulo operatorint m, n = 11;

m = n % 5;

cout << "m = " << m; //What prints?

Page 12: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Assignment Operator

Assignmentint n = 10;

Binary arithmetic operators can be combined with assignmentn += 5; //same as n = n + 5

n *= 2; //same as n = n * 2

cout << "n = " << n; //What prints?

assignment operator

Page 13: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Equality Operators andRelational Operators

Equality operators– equality operator == (don’t confuse with = )

x == y; //x is equal to y

– operator !=x != y; //x is not equal to y

Relational operators– operator <

x < y; //x is less than y

– operator >x > y; //x is greater than y

– operator <=x <= y; //x is less than or equal to y

– operator >=x >= y; //x is greater than or equal to y

Page 14: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Increment and Decrement

Post-increment operatorint n = 10;n++; //returns n then adds 1 to it

Pre-increment operatorint n = 10;++n; //adds 1 to n then returns it

Post-decrement operatorint n = 10;n--; //returns n then subtracts 1 from it

Pre-decrement operatorint n = 10;--n; //subtracts 1 from n then returns it

Page 15: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Variables and I/O

Values for the fundamental types can be input from the keyboard using cin and output to the screen with cout

double x;cout << "Enter a double: ";cin >> x;int n;cout << "Enter an integer: ";cin >> n;char c;cout << "Enter a char: ";cin >> c;cout << "double = " << x << " int = " << n;

Page 16: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Constants

Use const to declare a constant Must be initialized with a value when it is

declared The name of a constant is usually all caps

const double PI = 3.14159;

const int CAPACITY = 1024;

Page 17: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Conditional Control Structures

Select from different actions, depending on whether a condition is true

if( courseScore >= 91 )courseGrade = "A";

else if( courseScore >= 89 )courseGrade = "A-";

elsecourseGrade = "B";

Page 18: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

switch Structure

Can replace a complicated if/else structure

char grade;cin >> grade;switch( grade ){ case 'A': case 'a': aCount++; break; case 'B': case 'b': bCount++; break; default: cout << "Incorrect input" << endl; break;}

This controlling expression is compared to each of the case labels

Execution continues at the case label that matches

The break causes execution to go to the next line following the switch

Page 19: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Iterative Control Structure

Looping with for

for( int i=0; i<10; ++i ){ cout << i << " ";}

Initialization – assigns the starting value and is executed once.

Condition – tested at the beginning of each loop, and the loop is executed only if it evaluates to true.

Expression – evaluated at the end of each loop

Block of statements executed in

the loop

Page 20: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

A block is needed only if multiple statements are executed in each loop.

for( int i=0; i<10; ++i ){ cout << i; cout << " ";}

for Loop

If only one statement is executed in each loop, it’s not necessary to define a

block with { and }.

for( int i=0; i<10; ++i ) cout << i << " ";

Page 21: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Changes to the Value of i

for( int i=0; i<5; ++i ){ cout << i << " ";}

IterationValue of i

during the loopExpression at the end

of the loop

First loop 0 (starting value) i = i + 1

Second loop 1 i = i + 1

Third loop 2 i = i + 1

Fourth loop 3 i = i + 1

Fifth loop 4 i = i + 1

Page 22: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Nested for Loop

int result = 0;for( int i=0; i<3; ++i ) for( int j=0; j<5; ++j ) result++;

i j result

0 0 1

0 1 2

0 2 3

0 3 4

0 4 5

1 0 6

1 1 7

1 2 8

1 3 9

1 4 10

2 0 11

2 1 12

2 2 13

2 3 14

2 4 15

Page 23: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Nested Loop with Dependent Variable

int result = 0;for( int i=0; i<3; ++i ) for( int j=i; j<5; ++j ) result++;

i j result

0 0 1

0 1 2

0 2 3

0 3 4

0 4 5

1 1 6

1 2 7

1 3 8

1 4 9

2 2 10

2 3 11

2 4 12

Page 24: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

How many iterations?

for( int i=0; i<10; ++i ) cout << i << " ";

for( int i=10; i>0; --i ) cout << i << " ";

int result = 0;for( int i=0; i<2; ++i ) for( int j=0; j<3; ++j ) result++;

Page 25: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Looping with while

int input = 0;while( input != -1 ){cout << "Enter a number(-1 to end) ";cin >> input;cout << "You entered " << input << endl;

}

Page 26: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Array

Collection of elements of the same data type that are stored in adjacent memory locations

Creating an arrayint myArray[5];//created but not initialized

The first element in every array has the index 0 Each element can be accessed by using its index

myArray[0] = 42;cout << myArray[0];//what prints?cout << myArray[3];//what prints?

Initializing the arrayfor( int i=0; i<5; ++i ) myArray[i] = 0;int nextArray[] = {0,0,0,0,0};//created + initialized

Page 27: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Using Arrays

Use a constant int to declare an arrayconst int CAPACITY = 5; //Easier to modify

int newArray[CAPACITY];

for( int i=0; i<CAPACITY; ++i )

newArray[i] = 0;

There is no bounds checking for arrays

cout << myArray[256];//will probably compile!

Common error

int myArray[5] = {0,0,0,0,0};cout << myArray[5];

Page 28: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Class string

C++ uses an object-oriented approach to strings#include <string>using std::string;

Creating a string objectstring s1;string s2("Go Dog");string s3 = "Madam, I'm Adam";

Accessing individual charss2[5] = 'n'; //What changes?int len = s2.length(); //returns 6

Page 29: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Some string Operations

Concatenation with operator +string s1 = "Hello";string s2 = "World";s1 += ", ";string s3 = s1 + s2 + '!';cout << s3; //What prints?

C++ strings can be compared with ==, !=, <, >, <=, and >=string s1 = "Hello", s2 = "World";if( s1 == s2 ) cout << "equal";

Page 30: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

More about I/O (Cont.)

Tip:If you use “cin >>” first and then you use getline(), you must use ignore() to clear the input stream.

int id;

cout << "Please enter your ID number: ";

cin >> id;

cin.ignore(); //clear the input stream

cout << "Please enter your first "

<< "and last name: ";

const int BUFFSIZE = 1024;

char buffer[BUFFSIZE];

cin.getline(buffer,BUFFSIZE);//up to \n

string s = string(buffer);

Page 31: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Functions andArgument Passing

Page 32: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Functions

A small “subprogram” that does a specific task

A complicated C++ program can be divided into smaller, manageable pieces by using functions

Values are passed to a function as arguments

When the function is finished, it can return a value to the caller

We can use functions from the standard C++ library or we can write our own functions

Page 33: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Function Arguments

The variables that are used to pass data into a function or to return results

Examplebool isPalindrome( string forw, string rev ){

if( forw == rev ) return true;

}

Arguments can be passed– By value – the default in C++– By reference

arguments or parametersfunctionname

returntype

Page 34: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Passing Arguments by Value

Used to pass data only into a function When a variable is passed by value, a copy of it is made inside the

function. The copy is destroyed when the function returns. Example: passing an argument by value

void noChange( int n ){n = n + n;

}

int main() {int num = 5;noChange( num );cout << num << endl; //prints 5

}

Page 35: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Reference Argument

Syntaxint &count

Indicates that an alias for the argument is used inside the function

Page 36: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Passing Arguments by Reference

Used to pass data into and out of a function When a variable is passed by reference, no copy is made. Changes to

the reference are passed to the calling variable. Example: passing an argument by reference

void change( int &n ){//n is a referencen = n + n;

}

int main() {int num = 5;change( num );//OK to pass regular varcout << num << endl;//prints 10

}

Page 37: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Using References

Used primarily for function arguments to implement “passing by reference”

Advantage: Efficiency– No copies of the arguments are made inside the

function

– When data structures are passed as arguments, this approach is important

Page 38: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Structs

Page 39: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Keeping Track of Data

Variables are used to keep track of data in the computer’s memory.

Regular variable – keeps track of the value of one data element

Pointer variable – keeps track of the memory address of a data element

Array – keeps track of a collection of related data elements of the same data type

Page 40: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Collection of related data elements that may have different data types

– Each element stored in a struct is called a “member” or “field”– Each field has a name and data type

Defining a structure

struct Person{ int ID; string firstName; string lastName;};

Structure or “struct”

Name

Members or fields

Remember the ‘;’

Page 41: Introduction to C++ Programming. Brief Facts About C++ Evolved from C Designed and implemented by Bjarne Stroustrup at the Bell Labs in the early 1980s

Using structs

The struct’s definition creates a new data type

We can use it to declare a “variable”Person alan;

Each field can be accessed with the “.” operatoralan.ID = 1001;alan.firstName = "Alan";alan.lastName = "Turing";cout << alan.firstName; //What prints?