ITP 134 C++ Study Guide Chapter 2 C++ Fundamentals Instructions: Use this Study Guide to help you understand the important points of this chapter. See the book for lots of great programming examples. Important concepts, keywords, statements and functions are shown in emphasized font. Code syntax and examples are shown in code font. Games & Graphics in C++ 2nd edition by Tony Gaddis 2.1 The Parts of a C++ Program CONCEPT: Your first step in learning C++ is to learn to basic parts of a C++ program Basic structure of a C++ program #include <iostream> using namespace std; // include directive for the library for input/output // namespace organizes program entries for iostream int main() { return 0; // Main function. Starting point for the program // Return 0 means executed correctly. // Statements end with semicolons ; } Comments // single line comment /* block comment Used for several lines */ 2.2 Displaying Screen Output CONCEPT: You write cout statements to display output in a console window. Console – old computer term for simple screen and keyboard. (page 39) 2.3 More about the #include Directive CONCEPT: The #include directive causes the contents of another file to be inserted into the program. (page 45) 2.4 A First Look at Variables CONCEPT: A variable is a named storage location in memory. (pg 46) Using the endl Manipulator Use the endl to start a new line for cout Using the \n Escape Sequence Another way to start a new line is to use \n for cout. See Table 2-1 Common Escape Sequences (page 44) for other ways to control output. ITP 134 – Mrs. Eaton Data Types See Table 2-3 Some of C++ Data Types on page 48 for more details on data types. Numeric data types – you must choose the type of data you will store in a variable. (pg 48) int – stores integers (whole numbers) using 4 bytes, range from -2.1B to 2.1B Chapter 2 Study Guide – 2nd Edition Page 1 float – stores floating point numbers (real numbers with a decimal point) using 4 bytes double – stores larger integer or real numbers with 15 digits of precision using 8 bytes Non-Numeric Data Types bool – stores the Boolean values true or false using 1 byte char – stores a single character using 1 byte string – stores strings of text so size varies You can optionally initialize and declare a variable in a single statement. Part 1 of book: Use int for integers and double for real numbers. (pg 49) Part 2 of book: Use int for integers and float for real numbers. The App Game Kit uses float instead of double. (pg 54) You can name variables whatever you want as long as you follow these rules: (pg 47) Must begin with a letter a-z, A-Z, or an _ (underscore) Must contain only letters a-z, A-Z, or _. Cannot contain special characters like $, &, % etc. Cannot contain spaces. Are case sensitive. You must use uppercase, lowercase exactly each time you use the variable. Cannot use C++ reserved words. See Table 1-2 on page 16 for C++ reserved word list. Naming conventions (pg 48) Use camelCase with a lowercase starting letter, and then uppercase for each word. Such as centerPointX. We will be using camelCase in this book and in this class like many professionals. Not recommended to run words together using all lowercase. Really hard to read names such as centerpointx. For constant names use a _ (underscore) to represent a space. Such as MAX_VALUE Declaring Variables datatype variableName1, variableName2, variableName3; Variable declaration (pg 80) where datatype is int, float, or double. Declare more than one variable and separate with commas. Variable Initialization variableName = value; ITP 134 – Mrs. Eaton datatype variableName = value; Initialize a variable (pg 51) declare and assign in one statement. int speed = 60; double amount = 23.90; Declaring Multiple Variables with One Statement Variable Names Assignment statement (pg 51) Assign a value to a variable. Variable is always on the left and the assigned value always on the right. This is different from math class. int month, day, year; or int month=5, day = 4, year = 1865; Where to Declare Variables Local variable – declare a variable inside the main function. We’ll see more places to declare local variables later. Declare Variables Before Using Them An uninitialized variable is a variable that has been declared, but has not been assigned a value yet. You want to assign a value to a variable before you exactly use it, otherwise you will have unpredictable results. Numeric Literals CONCEPT: A numeric literal is an item of data that is typed into a program’s code. (actual number or string instead of using a variable). (pg 81) A numeric literal is a number typed directly into code. (pg 52) A string literal is a string typed directly into code surrounded by double quotes. Variables and Assignment Compatibility Warning: If you try to assign a real number to an integer data type, the numbers after the decimal point will be truncated. This may not be what you were expecting. (pg 52-53) Chapter 2 Study Guide – 2nd Edition Page 2 2.5 Reading Keyboard Input CONCEPT: You write cin statements to read input from the keyboard. (page 55) // declare age variable int age; // prompt user cout << “What is your age? “; // read value from keyboard cin >> age 2.6 Comments, Blank Lines and Indentation CONCEPT: Comments are brief notes that are placed in a program’s source code, explaining how parts of a program work. Programmers commonly use blank lines and indentation in program code to give the code visual organization and make it easier to read. (pg 58) // Use for single line comments Banner Comments for Program Submissions Example /************************************* *** Programmer: Carlotta Eaton Program: Program 2-11 SalePrice.cpp Purpose: Program calculates sales price ************************************** **/ 2.7 Performing Calculations and Working with Numbers CONCEPT: To perform calculations in a C++ program, you use math operators to create math expressions. (pg 60) + (add) – (subtract) * (multiply) / (divide) and % (modulus gives remainder of division) You will usually need to rewrite math equations using C++ operators. The Order of Operations Operation precedence – same as math classes (pg 62-63) 1. First perform operations inside ( ) 2. Perform * / and % in order from left to right ITP 134 – Mrs. Eaton 3. Perform + - in order from left to right Grouping with Parentheses Group expressions with () to change the order of operations above (pg 63) Integer Division In C++, when you divide an integer by an integer the result is a integer (truncates the fractional portion of the result). This may not be what you were expecting so be careful. (pg 63-64) Combined Assignment Operators C++ is one of the languages where you have shortcuts for some common assignment operations. (pg 66) “short cut operator” += -= *= /= %= Example x += 5; y -= 2; z *= 10; a /= b; c %= 3; Means x = x + 5; y = y – 2; z = z * 10; a = a / b; c = c % 3; Mixed-Type Expressions and Data Type Conversion C++ follows these rules when evaluating expressions with both int and double values: (pg 66-67) When operation on 2 int values, the result will be int (Integer). When operation on 2 double values, the result will be double (real). When operation on int and double, the int will be converted to a double and then result will be double. You can also explicitly change the data type of a variable: (pg 67-68) intValue = static_cast<int>(doubleValue) 2.8 Named Constants CONCEPT: A named constant is a name that represents a value that cannot change during the program’s execution. Use the const keyword to declare a constant. (page 71) const datatype CONSTANTNAME = value; // general use nd Chapter 2 Study Guide – 2 Edition Page 3 const double INTEREST_RATE = 0.129; //example Use all caps for constant names is a good programming practice. (pg 72) You must declare and initialize a constant in the same statement, otherwise you will get an error. 2.9 Math Functions in the Standard Library CONCEPT: The C++ standard library provides several functions for performing advanced mathematical operations. Include the <cmath> library to use these functions. pow(Base, Exponent) // returns base exponent (pg 74) sqrt(value) //returns the square root (float) of a value (pg 75) floor(value) // returns the smallest whole number less than or equal to a value (pg 75) Trigonometry Functions (pg 75) cos(angle) in radians (pg 75) sin(angle) tan(angle) //returns cosine (float) of angle //returns sine //returns tangent 2.11 The char Data Type CONCEPT: You use the char data type to store a single character in memory. (pg 79) Here is the syntax to declare and initialize a char variable. char letter; // declaration letter = ‘A’; // use single quotes You cannot assign strings to char variables. Chapter 2 Program Examples 2.10 Working with Strings CONCEPT: You use the standard library’s string class to create objects that can hold strings. (pg 76) #include <string> // include string library to use strings string movie; // declaration movie = “Wheels of Fury”; // use double quotes for strings Program 2-1 HelloWorld.cpp (page 40) Program 2-2 MultipleItems.cpp (page 41) Program 2-3 OneLine.cpp (page 42) Program 2-4 ThreeLines.cpp (page 42) Program 2-5 EscapeSquence.cpp (page 43) Program 2-6 VariableDemo.cpp (page 50) Program 2-7 VariableInit.cpp (page 51) Program 2-8 OneValue.cpp (page 53) Program 2-9 InputExample.cpp (page 56) Program 2-10 SimplePayroll.cpp (page 56) Program 2-11 SingleLineComment.cpp (page 58) Program 2-12 MultiLineComment.cpp (page 59) Program 2-11 SalePrice.cpp (Page 61-62) Program 2-12 SecondsConverter.cpp (page 6465) Program 2-13 TypeCast.cpp (page 67-68) In The SpotLight: Calculating Percentages and Discounts (page 68-69) In The SpotLight: Calculating an Average (page 69-71) Program 2-16 NamedConstant.cpp (page 73) Program 2-17 PowFunction.cpp (page 74-75) Program 2-18 StringExample.cpp (page 76) Program 2-19 StringInput1.cpp (page 77) Program 2-20 StringInput2.cpp (page 77-78) Program 2-21 CharLiterals.cpp (page 79) There is a limitation to using cin to read string input. A cin statement can read only one word. (pg 77) ITP 134 – Mrs. Eaton Chapter 2 Study Guide – 2nd Edition Page 4