C++ Programming for Non-C Programmers Supplement
ii C++ Programming for Non-C Programmers C++ Programming for Non-C Programmers Published by itcourseware, 10333 E. Dry Creek Rd., Suite 150, Englewood, CO 80112 Contributing Authors: Jeff Howell, Danielle Waleri Editor: Danielle Waleri Special thanks to: Many instructors whose ideas and careful review have contributed to the quality of this workbook, including Evans Nash, and the many students who have offered comments, suggestions, criticisms, and insights. Copyright 1998 by itcourseware, Inc. All rights reserved. No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage retrieval system, without permission in writing from the publisher. Inquiries should be addressed to itcourseware, Inc., 10333 E. Dry Creek Rd., Suite 150, Englewood, Colorado, 80112. (303) 874-1099. All brand names, product names, trademarks, and registered trademarks are the property of their respective owners.
Table of Contents iii Contents Chapter 1 - Course Introduction... 7 Course Objectives... 9 Course Overview... 11 Chapter 2 - Getting Started... 13 Chapter Objectives... 15 The First Program (hello.cpp)... 17 Compile Steps... 19 How to Compile and Run a Program... 21 Exercises... 23 Chapter 3 - Data Types and Variables... 25 Chapter Objectives... 27 Fundamental Data Types... 29 Data Type Values and Sizes... 31 Data Type Values and Sizes... 33 Variable Declarations... 35 Variable names... 37 Constants... 39 Character Constants... 41 String Constants... 43 Exercises... 45 Chapter 4 - Operators and Expressions... 47 Chapter Objectives... 49 What are expressions?... 51 Arithmetic Operators... 53 Relational Operators... 55 Assignment Operator... 57 Expressions have resulting values... 59 True and False... 61 Logical Operators... 63 Increment and Decrement Operators (++ and --)... 65 Increment and Decrement Operators: Examples... 67 'Operate-Assign' Operators (+=, *=,...)... 69 Conditional Expression... 71 Operator Precedence... 73 Precedence and order of evaluation... 75
iv C++ Programming for Non-C Programmers Evaluation of Logical Operators... 77 Type Conversions... 79 Type conversions (cont.)... 81 The cast operator... 83 Exercises... 85 Chapter 5 - Control Flow... 87 Chapter Objectives... 89 Statements... 91 if - else... 93 if() - else if()... 95 switch()... 97 Example: Switch()... 99 switch() (cont.)... 101 while()... 103 do - while()... 105 for()... 107 The for() loop - diagram... 109 Example: for() loop...111 The break statement... 113 The continue statement... 115 Exercises... 117 Chapter 6 - Functions... 119 Chapter Objectives... 121 What is a function?... 123 Example: findbig3()... 125 Why use functions?... 127 Anatomy of a function... 129 Example: find_big_int()... 131 Arguments passed by value... 133 When to Use the return Statement... 135 Returning Non-integer Values... 137 Example: Returning Non-integer Values... 139 Functions in Multiple Source Files... 141 The Concept of Variable Scope... 143 Automatic Variables... 145 Global (external) variables... 147 Example: Global Variables... 149 Static Variables... 151 External Static Variables... 153 Exercises... 155
Table of Contents v Chapter 7 - Pointers and Arrays... 157 Chapter Objectives... 159 What is a pointer?... 161 Pointer Operators... 163 Example: pointers... 165 Why use pointers?... 167 Example... 169 Arrays:... 171 Arrays (a picture)... 173 The & Operator... 175 Pointers and arrays... 177 Passing arrays to functions... 179 Initializing arrays... 181 Strings and character pointers... 183 What is char s[7]???... 185 Arrays of pointers... 187 Arrays of pointers - diagram... 189 Command-line arguments... 191 Exercises... 193 Chapter 8 - Structures... 195 Chapter Objectives... 197 Comparison of structures and arrays... 199 Structure definitions... 201 Structure declarations... 203 Arrays of structures... 205 Exercises... 207
vi C++ Programming for Non-C Programmers
Chapter 1 Course Introduction 7 Chapter 1 - Course Introduction
8 C++ Programming for Non-C Programmers Notes
Chapter 1 Course Introduction 9 Course Objectives Write applications using the C++ programming language. Use all of the basic syntax and semantics of the C and C++ languages. Write modular programs using functions. Use pointers and arrays to maintain data. Create classes that represent real-world objects with data and functionality. Inherit classes from existing classes to gain a reuse of functionality. Properly use references and constants to maintain data integrity and minimize errors. Write your own operators to work with the new data types that you create. Create template classes to avoid redundant coding and increase code reuse. Program object-oriented applications of moderate complexity.
10 C++ Programming for Non-C Programmers Notes
Chapter 1 Course Introduction 11 Course Overview Audience: This course is designed for programmers who want to move from procedural thinking to object-oriented programming using C++. Prerequisites: This course assumes that the student is an experienced professional programmer. Student Materials: Student workbook. A C++ text. Reference sheets. Classroom Environment: One terminal per student using the UNIX operating system, or a PC with a current C++ compiler.
12 C++ Programming for Non-C Programmers Notes
Chapter 2 Getting Started 13 Chapter 2 - Getting Started
14 C++ Programming for Non-C Programmers Notes
Chapter 2 Getting Started 15 Chapter Objectives Compile and run a program. Become familiar with your environment. Get "hands on" the machine immediately.
16 C++ Programming for Non-C Programmers Notes The following line: using namespace std ; is neccessary when including standard header files, like iostream. It will be discussed later in the course.
Chapter 2 Getting Started 17 The First Program (hello.cpp) /* hello.cpp */ #include <iostream> using namespace std ; int main(void) { cout << "hello, world" << endl; return 0; } /* int main(void) */
18 C++ Programming for Non-C Programmers Notes
Chapter 2 Getting Started 19 Compile Steps The source code file is the file that you create with an editor. The compiler compiles the source into an object file from which the linker creates an executable file. hello.cpp Source Code File hello.o Compile Object Code File hello Link Executable Binary File
20 C++ Programming for Non-C Programmers Notes
Chapter 2 Getting Started 21 How to Compile and Run a Program The linker needs to know the names of all of the object files that are part of your executable program. On a Unix platform, you create a makefile that contains the names of all of your files, then run the utility called make which compiles and links your code. In an Integrated Development Environment (IDE) such as Borland C++ or Microsoft Visual C++, you create a project that contains the names of all of your files, then running your program will first cause it to be compiled and linked.
22 C++ Programming for Non-C Programmers Notes
Chapter 2 Getting Started 23 Exercises 1. Edit hello.cpp such that it does not print the endl. Compile and run it. 2. Edit your solution so that it uses a second cout statement to print the endl. 3. Finally, have it print hello followed by your name.
24 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 119 Chapter 6 - Functions
120 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 121 Chapter Objectives Understand the use of functions in program structure. Write modular programs consisting of functions. Pass data to functions by value and by reference. "Build" a program from multiple source files. Initialize variables at definition time. Understand the scope of variables. Know when to use global variables.
122 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 123 What is a function? A function is a set of instructions. A function may operate on data passed to it. A program "calls" a function, passing it data, if required. A function can be called with different data and from different places. A function can "return" data to its caller.
124 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 125 Example: findbig3() /* findbig3.cpp */ #include <iostream> using namespace std ; int find_big_3(int, int, int); int main(void) { int x,y,z; int largest; x = 10; y = 15; z = 12; largest = find_big_3(x, y, z); cout << "Largest: " << largest << endl; return 0; } /* int main(void) */ /* --- Function find_big_3 --- */ int find_big_3(int a, int b, int c) { int big; big = a > b? a : b; /* Bigger of a and b */ big = big > c? big : c; /* Bigger of big and c */ return big; } /* int find_big_3(int a, int b, int c) */
126 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 127 Why use functions? To design a program into modules. To perform the same instructions on different sets of data. To create a library of reusable tools.
128 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 129 Anatomy of a function void main(void) { int arg1; float arg2; char arg3; func(arg1, arg2, arg3); /* Three arguments passed */ func(100, 85.463, 'X'); /* Constants as arguments */ } /* void main(void) */ /* Function returns a float, takes three parameters */ float func(int p1, float p2, char p3) /* Arguments in calls to func agree with */ /* parameters in number and type. */ /* They need not be of same name. */ {... define any needed local variables... operate on parameters... calculate a result (the function s "return value") return 3.14F; }/* float func(int p1, float p2, char p3) */
130 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 131 Example: find_big_int() /* findbigi.cpp */ #include <iostream> using namespace std ; int find_big_int(int [], int); int main(void) { int a[5]; a[0] = 985; a[1] = 255; a[2] = 868; a[3] = 1105;; a[4] = 499; cout << "Biggest: " << find_big_int(a, 5) << endl; return 0; } /* int main(void) */ /* --- Function find_big_int --- */ int find_big_int(int a[], int num_elem) /* int a[] - Tells compiler that a is an array */ /* int num_elem - Size of array passed in */ { int i; /* Automatic local variables */ int big; big = a[0]; /* To start, assume first element is biggest */ cout << big << endl; for (i = 1; i < num_elem; i++) if (a[i] > big) { /* If i'th element is bigger, */ big = a[i]; /* then update big holder */ cout << big << endl; } return big; } /* int find_big_int(int a[], int num_elem) */
132 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 133 Arguments passed by value The data passed to a function are copies of the caller's actual data. Functions can use passed in variables, but can't change them. /* passval.cpp */ #include <iostream> using namespace std ; int passval(int); int main(void) { int x; x=99; cout << "x before call: " << x << endl; passval(x); cout << "x after call: " << x << endl; return 0; } /* int main(void) */ /* --- Function passval --- */ int passval(int a) { a = a * 10; return a; } /* int passval(int a) */ Program will print: x before call: 99 x after call: 99
134 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 135 When to Use the return Statement Typically, use return when the function calculates and returns a single value. Use pass-by-reference when multiple values will be returned. In the second case, maybe you need more than one function.
136 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 137 Returning Non-integer Values By default, functions are assumed to return type int. If return value type is non-int, there must be two declarations: 1. The function type must be declared. 2. The calling function must declare the called function (usually in a prototype).
138 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 139 Example: Returning Non-integer Values /* max3.cpp */ #include <iostream> using namespace std ; int main(void) { float one, two,three, big, max3(float, float, float); cout << "Enter three float values: "; cin >> one >> two >> three; big = max3(one, two, three); cout << "Big = " << big << endl; return 0; } /* int main(void) */ float max3(float a, float b, float c) { float big; big = a > b? a : b ; big = big > c? big : c ; return big; } /* float max3(float a, float b, float c) */
140 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 141 Functions in Multiple Source Files Functions can reside in separate source files. They are compiled separately then linked together to form the executable program: On Unix: CC main.cpp func1.cpp func2.cpp -o progname In an IDE: Add main.cpp, func1.cpp and func2.cpp to your project. Each file is compiled separately and automatically linked together to create the executable.
142 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 143 The Concept of Variable Scope Variables are "written to" and "read from". The scope of a variable is all the functions in a program that can access that variable. Variables can be automatic (local), global, static or extern.
144 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 145 Automatic Variables Are local to a function (including main()). Are accessible only to the function in which they are defined. Are created "automatically" each time the function is called. Memory locations that store automatic variables are deallocated upon function exit.
146 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 147 Global (external) variables Are defined outside of any function. Are available to all functions, even those compiled separately (by using the extern keyword). Provide an alternative to function arguments and return values for communicating between functions. Local variables with same name as global will prevail.
148 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 149 Example: Global Variables /* gcount.cpp */ #include <iostream> using namespace std ; void f(void); int count; /* Global variable */ int main(void) { count = 0; f(); /* Once */ f(); /* Twice */ f(); /* Thrice */ cout << "f called " << count << " times" << endl; return 0; } /* int main(void) */ void f(void) { count++; } /* void f(void) */
150 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 151 Static Variables Two uses for static (We'll see the second in a minute). Within a function, static variables retain their values "for next call" when a function exits. /* statv.cpp */ #include <iostream> using namespace std ; void statfunc(int); int main(void) { statfunc(10); statfunc(20); return 0; } /* int main(void) */ void statfunc(int i) { static hold = 0; cout << "Previous hold: " << hold << endl; hold = i; cout << "Current hold: " << hold << endl; } /* void statfunc(int i) */
152 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 153 External Static Variables External (defined outside any function) static variables are only accessible within that source file. Useful for preventing name conflicts between separately compiled modules. Because... identically named external statics in different files are different, not the same (huh?).
154 C++ Programming for Non-C Programmers Notes
Chapter 6 Functions 155 Exercises 1. Write a program that reads four numbers from the keyboard and prints out the minimum, maximum, and average of the numbers. Define four separate float variables for the numbers. BE SURE to modularize the program into separate tasks that input the data, perform the calculations, and report the results. Do you think that an array version of this program would be better? 2. Starting with swmenu.cpp (from the previous chapter), create a menu-driven user interface for a program. Loop till the user chooses exit, and call a function for each switched choice. For now, just confirm to the user that the program entered the function. 3. Split the program from Exercise 1 into separately compilable source files, then compile and run the executable. 4. Write a simple program that calls a function which adds two floats and returns the sum.
156 C++ Programming for Non-C Programmers Notes