ECE 264 Object-Oriented Software Development Instructor: Dr. Michael Geiger Spring 2009 Lecture 2: Basic C++ Programs
Lecture outline Announcements / reminders Web page is now online: Additional lab notes/policies If you have a laptop, please bring it 24 machines in lab, but 32 / 25 students in W / F sections Remember: place a photo of yourself (photo.jpg) in your M:\drive (Quick) Pretest review Basic C++ programs 10/20/2015 ECE 264: Lecture 2 2
10/20/2015 ECE 264: Lecture 2 3 Pretest review Pretest intended to review the following Control structures (if/else, switch, loops) Basic data types Array accesses C output
Pretest review: if/else statements int x, y;. if (x < 5) { y = x + 1; } else { y = x – 2; } 1. At the end of the if/else statement above, if x = 4, y is equal to: a. 1b. 2 (1 person)c. 4d. 5 (55 correct) 2. Now, if x = 5, y is equal to: a. -2b. 3 (55 correct)c. 5d. 6 (1 person) 10/20/2015 ECE 264: Lecture 2 4
Pretest review: loops int x = 1; int i = 0; while (i <= 3) { x = x * 2; i++; } 3. Fill in the blank: The body of the while loop executes ______ times. a. 2b. 3 (7 people)c. 4 (49 correct)d. an infinite number of 4. The final value of x is: a. 2(3 people)b. 3 (1 person)c. 8 (12 people)d. 16 (40 correct) 5. Which of the following is a for loop that can replace the while loop and produce the same result for x? a. for (i = 1; i < 4; i++) (14 people) b. for (i = 0; i < 3; i++) (4 people) c. for (x = 0; x <= 3; x++) (3 people) d. for (i = 3; i >= 0; i--) (35 correct) 10/20/2015 ECE 264: Lecture 2 5
Pretest review: arrays, I/O int A[5] = {0, 7, 13, 12, 5}; for (i = 0; i < 5; i++) { printf(“A[%d] + 3 = %d\n”, i, A[i] + 3); } 6. In the first iteration, the program will display the following text on the screen: a. A[%d] + 3 = %d\n(1 person) b. A[i] + 3 = A[i] + 3(2 people) c. A[0] + 3 = 3 (53 correct) d. A[1] + 3 = The value of A[4] is: a. 4 (1 person)b. 5 (31 correct)c. 12 (19 people) d. non-existent (5 people) 10/20/2015 ECE 264: Lecture 2 6
Pretest review: switch statements switch (var) { case 0: case 1: x = x + var; break; case 2: x = x – var; case 3: x = x * var; break; default: x = var; } Assume x always equals 5 at the start of the switch statement. What is the value of x at the end of the statement if: 8. var = 1? a. 1(5 people)b. 4 (2 people)c. 5 (7 people)d. 6 (42 correct) 9. var = 2? a. 2(8 people)b. 3 (39 people) c. 6 (7 correct)d. 7 (1 person) 10. var = 5? a. 0 (1 person) b. 5 (51 people)c. 10 (2 people) d. 25 (1 person) 10/20/2015 ECE 264: Lecture 2 7
Basic C++ programs We’ll cover the following today Basic structure of a C++ program Constants and variables Identifiers C++ operators Standard input and output 10/20/2015 ECE 264: Lecture 2 8
Example program #1 /* Simple C++ Program */ /* This program computes the */ /* distance between two points. */ #include // Required for cout, endl. #include // Required for sqrt() using namespace std; int main() { // Declare and initialize objects. double x1(1), y1(5), x2(4), y2(7), side1, side2, distance; // Compute sides of a right triangle. side1 = x2 - x1; side2 = y2 - y1; distance = sqrt(side1*side1 + side2*side2); // Print distance. cout << "The distance between the two points is " << distance << endl; // Exit program. return 0; } 10/20/2015 ECE 264: Lecture 2 9
Comments Comments help people read code, but are ignored by the compiler C++ (like C) has two types of comment // Single line comments end at the end of a line /* Delimited comments start and end as shown here and can span multiple lines. */ Good programming practice to Start file with comment describing purpose Comment functionality of each section of code 10/20/2015 ECE 264: Lecture 2 10
Preprocessor directives Provide instructions to the compiler that are performed before the program is compiled. Begin with a # Example: #include The #include directive instructs the compiler to include statements from the header file iostream. 10/20/2015 ECE 264: Lecture 2 11
using Directive The using directive instructs the compiler to use files defined within a specific namespace Namespaces allow us to declare different scopes Example: using namespace std; std is the name of the Standard C++ namespace Including this line allows you to avoid specifying namespace for every identifier in your headers Otherwise, cout would have to be std::cout, etc. 10/20/2015 ECE 264: Lecture 2 12
Block of Code A block of code is defined by a set of curly braces {…}. Can contain comments and statements Statements can end in semicolon (;) or be enclosed in braces (e.g. if ) Example: int main() { //Block defines body of main function double x1(1), x2(4), side1; side1 = x2 – x1; cout << side1 << endl; return 0; // main()returns int value of 0 } //end definition of main Every C++ program must contain exactly one function named main() C++ program solutions always begin execution in main() 10/20/2015 ECE 264: Lecture 2 13
Constants and Variables Constants and variables represent memory locations that we reference in our program solutions. Constants are objects storing specific data that can not be modified. 10 is an integer constant 4.5 is a floating point constant "Side1" is a string constant 'a' is a character constant Variables are memory locations that store values that can be modified. double x1(1.0), x2(4.5), side1; side1 = x2-x1; x1, x2 and side1 are examples of variables that can be modified. 10/20/2015 ECE 264: Lecture 2 14
Memory Snapshot 10/20/2015 ECE 264: Lecture 2 15 #include using namespace std; int main() { double x1(1.0), x2(4.5), side1; double x1 double x2 double side1 side1 = x2-x1; double x1 double x2 double side1 cout << “side 1 has length: “ side1; ? Output: side 1 has length: 3.5
10/20/2015 ECE 264: Lecture 2 16 Common C++ Data Types KeywordExample of a constant booltrue char'5' int25 double25.0 string"hello" // #include
C++ Identifiers Identifiers are used to name objects in C++. Rules for selecting valid identifiers: Identifier must begin with a letter or underscore _ Identifiers consists of alphanumeric characters and underscore character only An identifier can not be a reserved word Only the first 31 characters of an identifier are used to distinguish it from other identifiers. C++ is case sensitive Good programming practice: choose descriptive identifiers 10/20/2015 ECE 264: Lecture 2 17
Declarations A declaration statement defines new identifiers and allocates memory Can assign initial value in declaration Syntax: [modifier] data_type identifier_list; Examples: double length(20.75), width(11.5), volume; int numberOfFeetInYard(3); const int MIN_SIZE = 0; Text uses: identifier(initial_value) (C++ specific) Could just as easily use: identifier = initial_value Good programming practices Grouping declarations together for similarly used variables or using 1 per line allows you to comment them meaningfully Separate declarations from rest of program using whitespace 10/20/2015 ECE 264: Lecture 2 18
Symbolic Constants A symbolic constant is defined in a declaration statement using the modifier const. A symbolic constant allocates memory for an object that can not be modified during program execution Attempt to modify constant syntax error A symbolic constant must be initialized in the declaration statement 10/20/2015 ECE 264: Lecture 2 19
Assignment Operator The assignment operator (=) is used in C++ to assign a value to a memory location. The assignment statement: x1 = 1.0; assigns the value 1.0 to the variable x1. Thus, the value 1.0 is stored in the memory location associated with the identifier x1. 10/20/2015 ECE 264: Lecture 2 20
10/20/2015 ECE 264: Lecture Example 1 - initialization double sum = 0; sum 4 Example 2 int x; x=5; x Assignment Operators - Examples 0 5 a 4 Example 3 char ch; ch = 'a'; ch
10/20/2015 ECE 264: Lecture 2 22 Assignment Statements - continued Example 4 int x, y, z; x=y=0; z=2; x y z How is the memory map affected by the following statement? y = z; 0 0 2
10/20/2015 ECE 264: Lecture 2 23 Arithmetic Operators Addition+ Subtraction- Multiplication* Division/ Modulus% Modulus returns remainder of division between two integers Example 5%2 returns a value of 1
10/20/2015 ECE 264: Lecture 2 24 Integer Division Division between two integers results in an integer. The result is truncated, not rounded Example: The expression 5/3 evaluates to 1 The expression 3/6 evaluates to 0
10/20/2015 ECE 264: Lecture 2 25 Priority of Operators 1.ParenthesesInner most first 2.Unary operatorsRight to left (+ -) 3.Binary operatorsLeft to right (* / %) 4.Binary operatorsLeft to right (+ -)
Increment/decrement operators Increment Operator ++ post incrementx++; pre increment++x; Decrement Operator - - post decrementx- -; pre decrement- -x; For examples assume k=5 prior to executing the statement. m= ++k;both m and k become 6 n = k- -;n becomes 5 and k becomes 4 10/20/2015 ECE 264: Lecture 2 26
10/20/2015 ECE 264: Lecture 2 27 Abbreviated Assignment Operators operatorexampleequivalent statement +=x+=2; x=x+2; -=x-=2;x=x-2; *=x*=y;x=x*y; /=x/=y;x=x/y; %=x%=y;x=x%y;
10/20/2015 Engineering Problem Solving with C++, Etter,Ingber Second Edition 28
Input/output streams C++ has three standard input/output streams cin is the standard input (e.g., keyboard) cout is the standard output cerr is the standard error Standard input Use the stream input operator >> to direct keyboard input to variables General Form: cin >> identifier >> identifier; Input value must be compatible with identifier type 10/20/2015 ECE 264: Lecture 2 29
Input/output streams (cont.) Standard output Use the stream output operator << to direct data to cout General Form: cout << expression << expression; Note: An expression is a C++ constant, identifier, formula, or function call. endl can be used to place an output character in the buffer and flush the buffer 10/20/2015 ECE 264: Lecture 2 30
10/20/2015 Engineering Problem Solving with C++, Etter,Ingber Second Edition 31 output 1,2 4.5 cm _ //Example1: Determine the output #include using namespace std; int main() { int i, j; double x; string units = " cm"; cin >> i >> j; cin >> x; cout << "output \n"; cout << i << ',' << j << endl << x << units << endl; return 0; } //Input stream:
10/20/2015 Engineering Problem Solving with C++, Etter,Ingber Second Edition 32 //Example 2: Determine the output #include using namespace std; int main() { int i, j; double x, y; cin >> i >> j >> x >> y; cout << "First output " << endl; cout << i << ',' << j << ',' << x << ',' << y << endl; cin >> x >> y >> i >> j; cout << "Second output" << endl; cout << i << ',' << j << ',' << x << ',' << y << endl; return 0; } //Input stream is: First output 1,2,3.4,5 Second output 3,2,2,3 _
10/20/2015 Engineering Problem Solving with C++, Etter,Ingber Second Edition 33 Characters and input >> discards leading whitespace get() method used to input whitespace characters Example: int x; char ch; cin >> x >> ch; cin >> x; cin.get(ch); xch xch Input stream: 45 c 39 b 45‘c’ 39‘\n ’
Final notes Next time Functions in C++--pass by value, reference Potentially cover pointers as well Acknowledgements: this lecture borrows heavily from lecture slides provided with the following texts: Etter & Ingber, Engineering Problem Solving with C++, 2 nd ed. Deitel & Deitel, C++ How to Program, 6 th ed. 10/20/2015 ECE 264: Lecture 2 34