Download presentation
1
Chapter 1 Basic C++ Programming
Data Structures and Algorithms in C++ Michael T. Goodrich Roberto Tamassia David M. Mount Chapter 1 Basic C++ Programming
2
Contents 1.1 Basic C++ Programming Elements 1.2 Expressions
Control Flow Functions Classes C++ Program and File Organization Writing a C++ Program Exercises
3
1.1 Basic C++ Programming Elements
1.1.1 A Simple C++ Program #include <cstdlib> #include <iostream> /* Inputs two numbers and outputs their sum */ int main( ) { int x , y; std::cout << “Please enter two numbers: “; std::cin >> x >> y; // inputs x and y int sum = x + y; // compute their sum std::cout << “Their sum is “ << sum << std::endl; return EXIT_SUCCESS; // terminates successfully }
4
1.1 Basic C++ Programming Elements
1.1.2 Fundamental Types bool Boolean value, either true or false char character short, int, long short, normal, long integer float, double single-, double- precision floating-point number void nothing enum enum Color {RED, GREEN, BLUE}
5
1.1 Basic C++ Programming Elements
Pointers char ch = ‘Q’; char* p = &ch; cout << *p; ch = ‘Z’;
6
1.1 Basic C++ Programming Elements
Arrays double f[3]; double* p[10]; f[2] = 25.3; p[4] = &f[2]; cout << *p[4];
7
1.1 Basic C++ Programming Elements
Strings #include <string> using std::string; //… string s = “to be”; string t = “not “ + s; string u = s + “ or “ + t; if (s > t) cout << u;
8
1.1 Basic C++ Programming Elements
C-Stype Structures enum MealType { NO_PREF, REGULAR, LOW_FAT, VEGETARIAN }; struct Passenger { string name; MealType mealPref; bool isFreqFlyer; string freqFlyerNo; };
9
1.1 Basic C++ Programming Elements
Pointers, Dynamic Memory, and the “new” Operator Passenger *p; //… p = new Passenger; p ->name = “Pocahontas”; p ->mealPref = REGULAR; p ->isFreqFlyer = false; p ->freqFlyerNo = “NONE”;
10
1.1 Basic C++ Programming Elements
1.1.4 Scope and Namespaces Constants and Typedef const int CUT_OFF[ ] = {90, 80, 70, 60}; const int N_DAYS = 7; const int N_HOURS = 24*N_DAYS; int counter [N_HOURS];
11
1.1 Basic C++ Programming Elements
typedef char* BufferPtr; typedef double Coordinate; BufferPtr p; Coordinate x, y;
12
1.1 Basic C++ Programming Elements
Local and Global Scopes const int cat = 1; int main ( ) { const int cat = 2; cout << cat; return EXIT_SUCCESS; } int dog = cat;
13
1.1 Basic C++ Programming Elements
Namespaces namespace myglobals { int cat; string dog = “bow wow”; } The Using Statement using std::string; using std::cout; using namespace myglobals;
14
1.2 Expressions Member Selection and lndexing class_name . member class/structure member selection pointer -> member class/structure member selection array [exp] array subscripting
15
1.2 Expressions Arithmetic Operators exp + exp addition exp – exp subtraction exp * exp multiplication exp / exp division exp % exp modulo(remainder)
16
1.2 Expressions Increment and Decrement Operators var ++ post increment var - - post decrement ++ var pre increment - - var pre decrement
17
1.2 Expressions Relational and Logical Operators
exp < exp less than exp > exp greater than exp <= exp less than or equal exp >= exp greater than or equal exp == exp equal to exp != exp not equal to ! exp logical not exp && exp logical and exp || exp logical or
18
1.2 Expressions Bitwise Operators ~ exp bitwise complement exp & exp bitwise and exp ^ exp bitwise exclusibe-or exp | exp bitwise or exp1 << exp2 shift exp1 left by exp2 bits exp1 >> exp2 shift exp1 right by exp2 bits
19
1.2 Expressions Assignment Operators int i = 10; int j = 5; int k = 1;
string s = “yes”; i - = 4; j *= -2; k <<= 1; s += “ or no”;
20
1.2 Expressions class_name::member namespace_name::member bool_exp ? True_exp : false_exp stream >> var stream << exp
21
1.2 Expressions 1.2.1 Casting in Expressions Traditional C-Style Casting int cat = 14; double dog = (double) cat; double pig = double(cat);
22
1.2 Expressions Static Casting Static_cast < <desired_type> > ( <expression> ); double d1 = 3.2; double d2 = ; int i1 = static_cast<int>(d1); int i2 = static_cast<int>(d2);
23
1.2 Expressions Implicit Casting int = 3; double d = 4.8; double d3 = i / d; int i3 = d3;
24
1.3 Control Flow If Statement if (<boolean_exp>) <true_statement> [else if (<boolean_exp>) <else_if_statement>] [else <else_statement>]
25
1.3 Control Flow Switch Statement char command; cin >> command;
switch (command){ case ‘I’ : editlnsert(); break; case ‘D’ : editDelete(); case ‘R’ : editReplace(); default : cout << “Unrecognized command\n”; }
26
1.3 Control Flow While and Do_While Loops while (<boolean_expression>) <loop_body_statement> do while ( <boolean_expression> )
27
1.3 Control Flow For Loop for ( [<initialization>]; [<condition>]; [<increment>] ) <body_statement> const int NUM_ELEMENTS = 100; float a[NUM_ELEMENTS]; //… for (int i = 0 ; i < NUM_ELEMENTS; i++) { if (a[i] > 0 ) { cout << a[i] << ‘\n’ ;} }
28
1.3 Control Flow Break and Continue Statements int sum = 0; while (true) { int x; cin >> x; if ( x < 0 ) break; sum += x; } cout << “Sum is “ << x << ‘\n’;
29
1.4 Fuctions bool evenSum(int a[ ], int n ); int main( ) { const int listLength = 6; int list[ listLength ] = {4, 2, 7, 8, 5, 6}; bool result = evenSum( list, listLength); if (result) cout << “even sum. \n”; else cout << “odd sum. \n”; return EXIT_SUCCESS; } bool evenSum( int a[ ], int n) { int sum = 0; for ( int i = 0 ; I < n ; i++ ) sum += a[ i ]; return (sum % 2 ) == 0;
30
1.4 Fuctions 1.4.1 Argument Passing void f(int value, int &ref) {
cout << value << ‘\n’; cout << ref << ‘\n’; } int main( ) { int cat = 1; int dog = 5; f(cat, dog); cout << cat << ‘\n’; cout << dog << ‘\n’; return EXIT_SUCCESS;
31
1.4 Fuctions 1.4.2 Overloading Function Overloading void print( int x ) { cout << x; } void print( const Passenger &pass) { cout << pass.name << “ “ << pass.mealPref; if ( pass.isFreqFlyer ) { cout << “ “ << pass.freqFlyerNo; }
32
1.4 Fuctions Operator Overloading bool operator == ( const Passenger &x, const Passenger &y ) { return x.name == y.name && x.mealPref == y.mealPref && x.isFreqFlyer == y.isFreqFlyer && x.FreqFlyerNo == y.FreqFlyerNo }
33
1.4 Fuctions Using Overloading ostream& operator << (ostream &out, const Passenger &pass) { out << pass.name << “ “ << pass.mealPref; if ( pass.isFreqFlyer ) { out << “ “ << pass.freqFlyerNo; } return out;
34
1.5 Classes 1.5.1 Class Structure class Passerger { private:
string name; MealType mealPref; bool isFreqflyer; string freqFlyerNo; public: //… Passenger( ); bool isFrequentFlyer( ) const { return isFreqFlyer; } void makeFrequentFlyer(const string& newFreqFlyerNo){ isFreqFlyer = true; freqFlyerNo = newFreqFlyerNo; } } ;
35
1.5 Classes 1.5.2 Constructors class Passenger { private: //… public: Passenger( ); Passenger( const string &nm, MealType mpref, string ffn = “NONE” ); passenger( const Passenger &pass) ; };
36
1.5 Classes 1.5.2 Destructors class Vect { private: int* theVect;
int vectSize; public: Vect( int size = 10) { vectSize = size; theVect = new int[ size ]; } //… ~Vect( ) { delete [ ] theVect; } } ;
37
1.5 Classes Vect a(100); Vect b = a; Vect c; c = a;
Classes and Memory Allocation Vect a(100); Vect b = a; Vect c; c = a;
38
1.5 Classes Vect::Vect (const Vect &a) { vectsize = a.vectSize; theVect = new int[ vectSize ]; for (int i = 0; i < vectSize; i++ ) { theVect[i] = a.theVect[i]; }
39
1.5 Classes Vect& Vect::operator = (const Vect &a) { if (this != &a) { delete [ ] theVect; vectSize = a.vectSize; theVect = new int[ vectSize ]; for (int i = 0; i < vectSize ; i++ ) { theVect[ i ] = a.theVect[ i ]; } return *this;
40
1.5 Classes 1.5.4 Class Friends and Class Members class SomeClass {
private: int secret; public: //… friend ostream& operator << (ostream &out, const SomeClass &x); }; ostream& operator <<(ostream &out, const SomeClass &x); { cout << x.secret; }
41
1.5 Classes class Complex { private: class Node { //… };
Nesting Classes and Types within Classes class Complex { private: class Node { //… };
42
1.5 Classes 1.5.5 The Standard Template Library stack Container with last-in, first-out access queue Container with first-in, first-out access deque Double-ended queue vector Resizeable array list Doubly linked list set Set map Associative array ( dictionary) priority_queue Queue orderde by value
43
1.6 C++ Program and File Organization
CreditCard.h #ifndef CREDIT_CARD_H #define CREDIT_CARD_H #include <string> #include <iostream> using std::string; class CreditCard { private: string number; string name; int limit; double balance;
44
1.6 C++ Program and File Organization
public: CreditCard(string no, string nm, int lim, double bal=0); string getNumber() const { return number; } string getName() const { return name; } double getBalance() const { return balance; } int getLimit() const { return limit; } bool chargeIt(double price); void makePayment(double payment) { balance -= payment; } }; std::ostream& operator<<(std::ostream& out, const CreditCard& c); #endif
45
1.6 C++ Program and File Organization
CreditCard.cpp #include "CreditCard.h“ CreditCard::CreditCard(string no, string nm, int lim, double bal) { number = no; name = nm; balance = bal; limit = lim; } bool CreditCard::chargeIt(double price) { if (price + balance > double(limit)) return false; balance += price; return true;
46
1.6 C++ Program and File Organization
std::ostream& operator<<(std::ostream& out, const CreditCard& c) { out << "Number = " << c.getNumber() << "\n" << "Name = " << c.getName() << "\n" << "Balance = " << c.getBalance() << "\n" << "Limit = " << c.getLimit() << "\n"; return out; }
47
1.6 C++ Program and File Organization
TestCard.cpp #include <vector> #include "CreditCard.h“ using namespace std; void testCard() { vector<CreditCard*> wallet(10); wallet[0] = new CreditCard(" ", "John Bowman", 2500); wallet[1] = new CreditCard(" ", "John Bowman", 3500); wallet[2] = new CreditCard(" ", "John Bowman", 5000); for (int j=1; j <= 16; j++) { wallet[0]->chargeIt(double(j)); wallet[1]->chargeIt(2 * j); wallet[2]->chargeIt(double(3 * j)); }
48
1.6 C++ Program and File Organization
cout << "Card payments:\n"; for (int i=0; i < 3; i++) { cout << *wallet[i]; while (wallet[i]->getBalance() > 100.0) { wallet[i]->makePayment(100.0); cout << "New balance = " << wallet[i]->getBalance() << "\n"; } cout << "\n"; delete wallet[i]; int main() { testCard(); return EXIT_SUCCESS;
49
1.7 Writing a C++ Program Design Responsibility Independence Behaviors
Coding Readability and Style Testing and Debugging
50
1.8 Exercises R-1.1 R-1.2 R-1.4 R-1.10 R-1.12
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.