Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Introduction to C++ Programming

2 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

3 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

4 Simple C++ Example /* FILE: main.cpp */ #include using namespace std; int main() { cout << "Enter your first name: "; string name; cin >> name; cout << "Hello, " << name << endl; return 0; //optional }

5 /* FILE: main.cpp */ #include 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 from C++ standard library “Entry” function Namespace for C++ standard library All C++ statements end with a semicolon

6 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 signature int main() int main( int argc, char *argv[] )

7 Using Command Line Arguments Program code int 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 items on the command line Array of C-style strings on the command line

8 Output and Input cout – #include – using namespace std; – operator << – Represents standard output, usually the screen cout << "Enter your first name: "; cin – – operator >> – Reads keyboard input until the first whitespace string name; cin >> name; endl – Used to output a newline and flush output buffer cout << "Hello, " << name << endl;

9 Variables and Data Types Some of the standard C++ data types boolintfloat charshortdouble unsigned charlong Declaring a variable – Allocates storage space in memory – Not automatically initialized int i; //i is declared but not initialized int j = 0; //j is declared and initialized int k(5); //k is declared and initialized variable name i j k 3000 3004 3008 0 5 value memory address 3012

10 Operators and Expressions An expression — combining variables and literals with operators to create a new value Example: double x, y = 10.0; x = y / 4.0; Binary arithmetic operators + addition - subtraction * multiplication / division % modulo (finds the remainder) variables literaloperators

11 Integer Division The remainder is treated differently Division operator int m, n = 11; m = n / 5; cout << "m = " << m; //What prints? Modulo operator int m, n = 11; m = n % 5; cout << "m = " << m; //What prints?

12 Assignment Operator Assignment int n = 10; Binary arithmetic operators can be combined with assignment n += 5; //same as n = n + 5 n *= 2; //same as n = n * 2 cout << "n = " << n; //What prints? assignment operator

13 Equality Operators and Relational 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

14 Increment and Decrement Post-increment operator int n = 10; n++; //returns n then adds 1 to it Pre-increment operator int n = 10; ++n; //adds 1 to n then returns it Post-decrement operator int n = 10; n--; //returns n then subtracts 1 from it Pre-decrement operator int n = 10; --n; //subtracts 1 from n then returns it

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

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

17 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-"; else courseGrade = "B";

18 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

19 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

20 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 << " ";

21 Changes to the Value of i for( int i=0; i<5; ++i ) { cout << i << " "; } Iteration Value of i during the loop Expression at the end of the loop First loop0 (starting value)i = i + 1 Second loop1i = i + 1 Third loop2i = i + 1 Fourth loop3i = i + 1 Fifth loop4i = i + 1

22 Nested for Loop int result = 0; for( int i=0; i<3; ++i ) for( int j=0; j<5; ++j ) result++; ijresult 001 012 023 034 045 106 117 128 139 1410 2011 2112 2213 2314 2415

23 Nested Loop with Dependent Variable int result = 0; for( int i=0; i<3; ++i ) for( int j=i; j<5; ++j ) result++; ijresult 001 012 023 034 045 116 127 138 149 2210 2311 2412

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

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

26 Array Collection of elements of the same data type that are stored in adjacent memory locations Creating an array int 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 array for( int i=0; i<5; ++i ) myArray[i] = 0; int nextArray[] = {0,0,0,0,0};//created + initialized

27 Using Arrays Use a constant int to declare an array const 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];

28 Class string C++ uses an object-oriented approach to strings #include using std::string; Creating a string object string s1; string s2("Go Dog"); string s3 = "Madam, I'm Adam"; Accessing individual chars s2[5] = 'n'; //What changes? int len = s2.length(); //returns 6

29 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 ==, !=,, = string s1 = "Hello", s2 = "World"; if( s1 == s2 ) cout << "equal";

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

31 Functions and Argument Passing

32 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

33 Function Arguments The variables that are used to pass data into a function or to return results Example bool isPalindrome( string forw, string rev ){ if( forw == rev ) return true ; } Arguments can be passed – By value – the default in C++ – By reference arguments or parameters function name return type

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

35 Reference Argument Syntax int &count Indicates that an alias for the argument is used inside the function

36 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 reference n = n + n; } int main() { int num = 5; change( num );//OK to pass regular var cout << num << endl;//prints 10 }

37 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

38 Structs

39 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

40 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 ‘ ; ’

41 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 “.” operator alan.ID = 1001; alan.firstName = "Alan"; alan.lastName = "Turing"; cout << alan.firstName; //What prints?


Download ppt "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."

Similar presentations


Ads by Google