Download presentation
Presentation is loading. Please wait.
1
Chapter 2: Introduction to C++
2
The Parts of a C++ Program
2.1 The Parts of a C++ Program
3
The Parts of a C++ Program
// sample C++ program #include <iostream> using namespace std; int main() { cout << "Hello, there!"; return 0; } comment preprocessor directive which namespace to use beginning of function named main beginning of block for main output statement string literal Send 0 to operating system end of block for main
4
Special Characters Character Name Meaning // Double slash
Beginning of a comment # Pound sign Beginning of preprocessor directive < > Open/close brackets Enclose filename in #include ( ) Open/close parentheses Used when naming a function { } Open/close brace Encloses a group of statements " " Open/close quotation marks Encloses string of characters ; Semicolon End of a programming statement
5
The #include Directive
2.3 The #include Directive
6
The #include Directive
Inserts the contents of another file into the program This is a preprocessor directive, not part of C++ language #include is preprocessed before compilation. Do not place a semicolon at end of #include line
7
2.2 The cout Object
8
The cout Object Displays output on the computer screen
You use the stream insertion operator << to send output to cout: cout << "Programming is fun!";
9
The cout Object Can be used to send more than one item to cout:
cout << "Hello " << "there!"; Or: cout << "Hello "; cout << "there!";
10
The cout Object This produces one line of output: cout << "Programming is "; cout << "fun!";
11
The endl Manipulator You can use the endl manipulator to start a new line of output. This will produce two lines of output: cout << "Programming is" << endl; cout << "fun!";
12
The endl Manipulator cout << "Programming is" << endl; cout << "fun!"; Programming is fun!
13
The endl Manipulator You do NOT put quotation marks around endl
The last character in endl is a lowercase L, not the number 1. endl This is a lowercase L
14
Notice that the \n is INSIDE
The \n Escape Sequence You can also use the \n escape sequence to start a new line of output. This will produce two lines of output: cout << "Programming is\n"; cout << "fun!"; Notice that the \n is INSIDE the string.
15
The \n Escape Sequence cout << "Programming is\n"; cout << "fun!"; Programming is fun!
16
User input: “Hello !” > ./myProgram What is your name? Alice >
// include library of standard input and output commands #include <iostream> #include <string> using namespace std; int main() { // Begin main function string name; // create variable called name cout << "What is your name?"; cin >> name; // get name from user cout << "Hello "; // output "Hello " cout << name << "!\n"; // output "<name>!" return 0; // end program } // End main function > ./myProgram What is your name? Alice > > ./myProgram What is your name? Alice Hello Alice! > > ./myProgram What is your name? >
17
Variable declaration // include library of standard input and output commands #include <iostream> using namespace std; #include <string> int main() { // Begin main function string name; // create variable called name cout << "What is your name?"; cin >> name; // get name from user cout << "Hello "; // output "Hello " cout << name << "!\n"; // output "<name>!" return 0; // end program } // End main function “Declare” new variable by writing type followed by variable name. More examples: int age, weight; // multiple declarations
18
Input command // include library of standard input and output commands #include <iostream> using namespace std; int main() { // Begin main function string name; // create variable called name cout << "What is your name?"; cin >> name; // get name from user cout << "Hello "; // output "Hello " cout << name << "!\n"; // output "<name>!" return 0; // end program } // End main function cin >> varName; receives input from keyboard saves into the varName
19
Variables and Literals
2.4 Variables and Literals
20
Variables and Literals
Variable: a storage location in memory Has a name and a type of data it can hold Must be defined before it can be used: int item;
21
Declaration, Initialization
Terminology: Declare: creates space in memory. 'Labels the mailbox with the variable name'. Does NOT store anything. Just puts up the box. Example: int age; Initialize: the initial time a value is put in that memory location. The first assignment. Example: age = 21;
22
Variable Definition in Program 2-7
23
Variables A variable is a place (or location) in program memory that is used to hold a value. All variables have a type that determines what can values it can hold. The type tells how much space (memory) a variable has and how values are represented. Remember, computers only have 0’s and 1’s to represent any value.
24
Variable Storage 1010 age Variable Name, like your name on the box. Example: integer called age Memory Address: like your street address, but just a number with no street) Example:
25
Variable Storage 1010 21 age age
Variable Name, like your name on the box. Example: integer called age Memory Address: like your street address, but just a number with no street) Example: Can store a value in there - of the proper type Example: 21
26
Literals Literal: a value that is written into a program’s code.
"hello, there" (string literal) 12 (integer literal)
27
Integer Literal in Program 2-9
20 is an integer literal
28
String Literals in Program 2-9
These are string literals
29
2.5 Identifiers
30
Identifiers An identifier is a programmer-defined name for some part of a program: variables, functions, etc.
31
C++ Key Words You cannot use any of the C++ key words as an identifier. These words have reserved meaning.
32
Variable Names A variable name should represent the purpose of the variable. For example: itemsOrdered The purpose of this variable is to hold the number of items ordered.
33
Identifier Rules The first character of an identifier must be an alphabetic character or and underscore ( _ ), After the first character you may use alphabetic characters, numbers, or underscore characters. Upper- and lowercase characters are distinct
34
Valid and Invalid Identifiers
REASON IF INVALID totalSales Yes total_Sales total.Sales No Cannot contain . 4thQtrSales Cannot begin with digit totalSale$ Cannot contain $
35
Variables – locations in memory
Each variable has a location (address) in memory Each location holds a value Value can change as program progresses Address Value grade A P Different variable types take up different amounts of memory weight 140
36
2.6 Integer Data Types
37
Integer Data Types Integer variables can hold whole numbers such as 12, 7, and -99.
38
Defining Variables Variables of the same type can be defined
- On separate lines: int length; int width; unsigned int area; - On the same line: int length, width; Variables of different types must be in different declarations
39
Integer Types in Program 2-10
This program has three variables: checking, miles, and diameter
40
Integer Literals An integer literal is an integer value that is typed into a program’s code. For example: itemsOrdered = 15; In this code, 15 is an integer literal.
41
Integer Literals in Program 2-10
42
Integer Literals Integer literals are stored in memory as ints by default To store an integer constant in a long memory location, put ‘L’ at the end of the number: L To store an integer constant in a long long memory location, put ‘LL’ at the end of the number: 324LL Constants that begin with ‘0’ (zero) are base 8: 075 Constants that begin with ‘0x’ are base 16: 0x75A
43
2.7 The char Data Type
44
The char Data Type Used to hold characters or very small integer values Usually 1 byte of memory Numeric value of character from the character set is stored in memory: CODE: char letter; letter = 'C'; MEMORY: letter 67
45
Character Literals Character literals must be enclosed in single quote marks. Example: 'A'
46
Character Literals in Program 2-14
47
Character Strings A series of characters in consecutive memory locations: "Hello" Stored with the null terminator, \0, at the end: Comprised of the characters between the " " H e l o \0
48
2.8 The C++ string Class
49
The C++ string Class Special data type supports working with strings
#include <string> Can define string variables in programs: string firstName, lastName; Can receive values with assignment operator: firstName = "George"; lastName = "Washington"; Can be displayed via cout cout << firstName << " " << lastName;
50
The string class in Program 2-15
51
Floating-Point Data Types
2.9 Floating-Point Data Types
52
Floating-Point Data Types
The floating-point data types are: float double long double They can hold real numbers such as: Stored in a form similar to scientific notation All floating-point numbers are signed
53
Floating-Point Data Types
54
Floating-Point Literals
Can be represented in Fixed point (decimal) notation: E notation: (2en is 2x10 raised to the n power) E e-5 Are double by default Can be forced to be float ( f) or long double ( L)
55
These two are different
More complex output float degrees; degrees = 39.6; cout << "The temperature today is "; cout << degrees << " degrees" << endl; These two are different cout << "which is " << degrees – 32 ; cout << " degrees above freezing " << endl;
56
Variable assignment Result: The temperature today is 39.6 degrees
which is 7.6 degrees above freezing
57
Example program Let’s say we want to print the Earth’s distance from the Sun that is stored in a variable named distance billion meters Let’s say we want to print the mass of the Sun that is stored in a variable named mass 1.989 × 10^30 kg
58
Floating-Point Data Types in Program 2-16
59
So far Programs can have…
preprocessing directives (e.g. #include), comments, a main function with {} enclosing statements. The main function is required; it must have a return statement. Input and output using cin and cout respectively. cin >> variable; // reads input with “extraction” operator cout << expression; // writes expression with “insertion” operator. variables that are named memory locations A variable name is an identifier. Identifiers can start with a _ or letter, but cannot be a keyword. Variables have a type that tells the computer how to represent values: int, short, char, float, double, string and bool.
60
2.10 The bool Data Type
61
The bool Data Type Represents values that are true or false
bool variables are stored as small integers false is represented by 0, true by 1: bool allDone = true; bool finished = false; allDone finished 1
62
Boolean Variables in Program 2-17
63
Variable Assignments and Initialization
2.12 Variable Assignments and Initialization
64
Variable Assignments and Initialization
An assignment statement uses the = operator to store a value in a variable. item = 12; This statement assigns the value 12 to the item variable.
65
Assignment The variable receiving the value must appear on the left side of the = operator. This will NOT work: // ERROR! 12 = item;
66
Variable Initialization
To initialize a variable means to assign it a value when it is defined: int length = 12; Can initialize some or all variables: int length = 12, width = 5, area;
67
Variable Initialization in Program 2-19
68
Declaring Variables With the auto Key Word
C++ 11 introduces an alternative way to define variables, using the auto key word and an initialization value. Here is an example: auto amount = 100; The auto key word tells the compiler to determine the variable’s data type from the initialization value. auto interestRate= 12.0; auto stockCode = 'D'; auto customerNum = 459L; int double char long
69
2.14 Arithmetic Operators
70
Arithmetic Operators Used for performing numeric calculations
C++ has unary, binary, and ternary operators: unary (1 operand) binary (2 operands) ternary (3 operands) exp1 ? exp2 : exp3
71
Binary Arithmetic Operators
SYMBOL OPERATION EXAMPLE VALUE OF ans + addition ans = 7 + 3; 10 - subtraction ans = 7 - 3; 4 * multiplication ans = 7 * 3; 21 / division ans = 7 / 3; 2 % modulus ans = 7 % 3; 1
72
A Closer Look at the / Operator
/ (division) operator performs integer division if both operands are integers cout << 13 / 5; // displays 2 cout << 91 / 7; // displays 13 If either operand is floating point, the result is floating point cout << 13 / 5.0; // displays 2.6 cout << 91.0 / 7; // displays 13.0
73
A Closer Look at the % Operator
% (modulus) operator computes the remainder resulting from integer division cout << 13 % 5; // displays 3 % requires integers for both operands cout << 13 % 5.0; // error
74
What does this program do?
Exercise: Build & Make it better! #include <iostream> using namespace std; int main() { int dollars, coins; cout << "How many dollars do you have? "; cin >> dollars; coins = dollars*4; cout << "I will give you " << coins; cout << " coins.\n"; return 0; }
75
Let’s look at a bigger example
Our program helps us with Buying cookies. We need to calculate the total cost of the cookies using this program. What variables do we need? How much does one cookie cost? How may cookies did we buy? Where can we put the total amount?
76
Variable declaration and initialization
All variables must be declared before they are used double cookieCost; // cost of 1 cookie int numCookiesPurchased; double totalCost; Variables are initialized with the first assignment statement cookieCost = .50; // initialize variable Declaration and initialization can also be performed in one line float cookieCost = .50;
77
Buying Cookies #include <iostream>// include io library using namespace std; int main() { // Begin main function int cookieCost = 1; // cost of 1 cookie int numCookiesPurchased; double totalCost; numCookiesPurchased = 3; totalCost = numCookiesPurchased * cookieCost; cout << "Cookies: "; cout << numCookiesPurchased << " at $"; cout << cookieCost << " each " << endl; cout << "Total cost = $" << totalCost << endl; return 0; // end program } // End main function
78
Buying Cookies #include <iostream>// include io library using namespace std; int main() { // Begin main function int cookieCost = 1; // cost of 1 cookie int numCookiesPurchased; double subtotal; numCookiesPurchased = 3; subtotal = numCookiesPurchased * cookieCost; cout << "Cookies: "; cout << numCookiesPurchased << " at $"; cout << cookieCost << " each " << endl; cout << "Subtotal = $" << subtotal << endl; return 0; // end program } // End main function But we don't always want to buy 3 cookies!
79
Buying Cookies with input
#include <iostream>// include io library using namespace std; int main() { // Begin main function int cookieCost = 1; // cost of 1 cookie int numCookiesPurchased; double subtotal; cout << "Number of Cookies? "; // prompt cin >> numCookiesPurchased; // read from keyboard subtotal = numCookiesPurchased * cookieCost; cout << "Cookies: "; cout << numCookiesPurchased << " at $"; cout << cookieCost << " each " << endl; cout << "Subtotal = $" << subtotal << endl; return 0; // end program } // End main function
80
Lab2: Cookies + Tax Using the above example:
Create a tax rate variable if tax is: .05 (not 5%) What type should it be? What is a good name? Read in the tax rate Calculate & print the tax Print the total
81
Lab 2: Cookies Sample Output
Number of Cookies? 3 Cookies: 3 at $1 each Subtotal = $3 Tax Rate? .05 Tax = $0.15 Total = $3.15
82
Tax Basics Given: Subtotal of all the items taxRate
Tax = subtotal * taxRate; Total is subtotal + subtotal * taxRate
83
Fancy Shorthand Operators
Extra stuff Fancy Shorthand Operators
84
Shorthand Assignment Operators
int a = 6; Standard assignment: a = 4; Other assignments: a += 3; // a = a + 3; a -= 3; // a = a - 3; a *= 3; // a = a * 3; a /= 3; // a = a / 3; a %= 3; // a = a % 3;
85
Increment and decrement
int c = 12; Increment by 1: c++ evaluates to c=c + 1 Decrement by 1: c-- evaluates to c=c - 1
86
Determining the Size of a Data Type
2.11 Determining the Size of a Data Type
87
Determining the Size of a Data Type
The sizeof operator gives the size of any data type or variable: double amount; cout << "A double is stored in " << sizeof(double) << "bytes\n"; cout << "Variable amount is stored in " << sizeof(amount) << "bytes\n";
88
Assigning between types
int vs float floats will be rounded to nearest integer and ints will be expanded to a precision float int vs char char will be converted to integer ASCII code and int will be converted to corresponding ASCII character int vs bool bool will be converted to 0 (if false) or 1 (if true) and int will be converted to false (of 0) or 1 (if not 0)
89
Type safety Ideally, every variable will be used only according to its type A variable will only be used after it has been initialized Only operations defined for the variable’s declared type will be applied Every operation defined for a variable leaves the variable with a valid value
90
2.13 Scope
91
Scope The scope of a variable: the part of the program in which the variable can be accessed A variable cannot be used before it is declared.
92
Variable Out of Scope in Program 2-20
93
2.15 Comments
94
Comments Used to document parts of the program
Intended for persons reading the source code of the program: Indicate the purpose of the program Describe the use of variables Explain complex sections of code Are ignored by the compiler
95
Single-Line Comments Begin with // through to the end of line:
int length = 12; // length in inches int width = 15; // width in inches int area; // calculated area // calculate rectangle area area = length * width;
96
Multi-Line Comments Begin with /*, end with */
Can span multiple lines: /* this is a multi-line comment */ Can begin and end on the same line: int area; /* calculated area */
97
2.16 Named Constants
98
Named Constants Named constant (constant variable): variable whose content cannot be changed during program execution Used for representing constant values with descriptive names: const double TAX_RATE = ; const int NUM_STATES = 50; Often named in uppercase letters
99
Named Constants in Program 2-28
100
2.17 Programming Style
101
Programming Style The visual organization of the source code
Includes the use of spaces, tabs, and blank lines Does not affect the syntax of the program Affects the readability of the source code
102
Variable names
103
Variable names, part 2 Choose meaningful names
Avoid acronyms (first letter of several words) Avoid lengthy names Good: age, size, address, count, sumData x, y, i – single letters as counting variables Bad: rbi, lda, xZ25, tla,sase neuron_response_magnitude
104
More about binary
105
The binary representation
int age = 65; assigns a binary code to memory: char grade = 'A'; assigns a binary code to memory: Every variable value is a number in binary, C++ interprets the binary number based on the variable type
106
Binary Machine code (binary) is made only of 0s and 1s? Why? 1 Binary Digit is a Bit 8 Binary Digits is a Byte
107
Analogy from Base 10 Notation: N10 also called Decimal
Digits we use are: 0,1,2, Remember: Maximum digit = Base -1 Each Place value is 10 times the previous (start at the right) Place value 10000 1000 100 10 1 2 4 310 Mult place value by digit +0 + 1000 +200 +40 +3 Sum =
108
Base 2 Notation: N2 also called Binary
Binary Digits (bits) we use are: 0, 1 Maximum digit = Base -1 Each Place value is 2 times the previous (start at the right) Place value 16 8 4 2 1 02 Mult place value by digit +16 + 0 +4 +2 +0 Sum = 2210
109
#1. Convert this binary value to decimal
Place value 16 8 4 2 1 02
110
#2. Convert this binary value to decimal
Place value 16 8 4 2 1 02
111
#2. Convert this binary value to decimal
Place value 16 8 4 2 1 02 = 2610
112
#3. Convert this binary value to decimal
1 02 = 2810
113
#3. Convert this binary value to decimal
1 02
114
#4. Convert this binary value to decimal
1 12 Note that, just like in the decimal system, if you put 0s in front of the number, it does not change its value. So, is the same as
115
#4. Convert this binary value to decimal
1 12 = 510
116
Convert Decimal (base 10) to Binary (base 2)
16 8 4 2 1 22 ? Sum: + Similar to making change – How do you hand someone 68 cents? Anyone? Answer: Pick from high value coins to low 2 Quarters, (subtract 50, leaving 18 cents) 1 dime, leaving 8 cents 1 nickel, leaving 3 cents then pick 3 pennies
117
Give the Binary Value for: 510
16 8 4 2 1 Sum: + 1 Sum: +0 +4 +1
118
Give the Binary Value for: 1210
16 8 4 2 1 Sum: + 1 Sum: +0 +8 +4
119
Give the Binary Value for: 2610
16 8 4 2 1 Sum: + 1 Sum: +16 +8 +0 +2
120
From ThinkGeek.com
121
From numbers to symbols: the ASCII table
American Standard Code for Information Interchange
122
Example Program Let’s think about a program to calculate hourly wages
Let’s consider that there may be overtime wages Calculate both the regular wages and overtime wages What do we need to know? Remember gross pay?
123
Arithmetic Operators in Program 2-21
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.