Upload
bernard-lyons
View
217
Download
0
Tags:
Embed Size (px)
Citation preview
Chapter 2: Introduction to C++
Resource: Starting Out with C++, Third Edition, Tony Gaddis
The Parts of a C++ Program
• C++ programs have parts and components that serve specific purposes.
2-1 Program
//A simple C++ program Comment#include <iostream.h> - Header file
void main (void) Marks the beginning of a function{ beginning of the function main
cout << “Programming is great fun!”;} ending of the function main
Program Output:Programming is great fun!
Make sure you have a closing brace for every opening brace in your program!
String Constant
Resource: Starting Out with C++, Third Edition, Tony Gaddis
void main(void)
Although most C++ programs have more than one function, every C++ program must have a function called main.
It is the starting point of the program. If you are ever reading someone else’s C++ program and want to find where it starts, just look for the function called main.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
C++ is a Case Sensitive Language
C++ is a case sensitive language. That means it regards uppercase letters as being entirely different characters than their lowercase counterparts.
In C++, the name of the function main must be spelled out in all lowercase letters. It doesn’t see “Main” the same as “main,” or “VOID” the same as “void.” This is true for all the C++ key words.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
A Program
Remember, a program is a set of instructions for the computer.
If something is to be displayed on the screen, you MUST use a programming statement for that purpose.
Special Character TableCharacter Name Description / / double slash Marks the beginning of a comment. # Pound sign Marks the beginning of a preprocessor
directive < > Opening and
closing brackets Encloses a filename when used with the #include directive
( ) Opening and closing parenthesis
Used in naming a function, as in int main ()
{ } Opening and closing braces
Encloses a group of statements, such as the contents of a function.
" " Opening and closing quotation marks
Encloses a string of characters, such as a message that is to be printed on the screen
; Semicolon Marks the end of a complete programming statement
Resource: Starting Out with C++, Third Edition, Tony Gaddis
The cout Object
•Use the cout object to display information on the computer’s screen.
– The cout object is referred to as the standard output object.
– Its job is to output information using the standard output device i.e. monitor.
You can think of the word cout as console output.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-2 Program
// A simple C++ program
#include <iostream.h>
void main (void)
{
cout << “Programming is “ << “great fun!”;
}
Program Output:Programming is great fun!
This is another way to write the program
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-3 Program
// A simple C++ program#include <iostream.h>
void main (void){cout<< “Programming is “;cout << “ great fun!”;
}Program Output:Programming is great fun!
This is another way to write the program
Resource: Starting Out with C++, Third Edition, Tony Gaddis
<< Operator
• When the << symbol is used, it is called the stream-insertion operator.
• The information immediately to the right of the << operator is sent to cout and then displayed on the screen.
• This operator can be used to send more than one item to cout.
• Unless you specify otherwise, the information you send to cout is displayed in a continuous stream. Sometimes this can produce less-than-desirable results. -- Refer to program 2-4, page 35 on next slide.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-4 Program// An unruly printing program#include <iostream.h>
void main(void){
cout << "The following items were top sellers";
cout << "during the month of June:";cout << "Computer games";cout << "Coffee";cout << "Aspirin";
}Program OutputThe following items were top sellers during the month of June:Computer gamesCoffeeAspirin
Resource: Starting Out with C++, Third Edition, Tony Gaddis
New Lines
• cout does not produce a newline at the end of a statement, unless it is told to do so.
• To produce a newline, use either the stream manipulator endl.
• or the escape sequence \n.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-5 ProgramTake a Few Minutes to Type Program – page 35
// A well-adjusted printing program#include <iostream.h>
void main(void){cout << "The following items were top sellers" << endl;cout << "during the month of June:" << endl;cout << "Computer games" << endl;cout << "Coffee" << endl;cout << "Aspirin" << endl;
}
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-5 Program Output
The following items were top sellersduring the month of June:Computer gamesCoffeeAspirin
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-6 Program// Another well-adjusted printing program
#include <iostream.h>
void main(void)
{
cout << "The following items were top sellers" << endl;
cout << "during the month of June:" << endl;
cout << "Computer games" << endl << "Coffee";
cout << endl << "Aspirin" << endl;
}
This is another way to write the program
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-6 Program Output
The following items were top sellersduring the month of June:Computer gamesCoffeeAspirin
Resource: Starting Out with C++, Third Edition, Tony Gaddis
New Line
Another way to cause cout to go to a new line is to insert an escape sequence in the string itself. An escape sequence starts with the backslash character (\), and is followed by one or more control characters. The newline escape sequence is \n. When cout encounters \n in a string, it doesn’t print it on the screen, but interprets it as a special command to advance the output cursor to the next line.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Newline Escape Sequence \n
DO NOT confuse the backslash (\) with the forward slash (/).
An escape sequence will not work if you accidentally start it with a forward slash. Also, do not put a space between the backslash and the control character.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
// Yet another well-adjusted printing program
#include <iostream.h>
using namespace std;
void main(void)
{
cout << "The following items were top sellers\n";
cout << "during the month of June:\n";
cout << "Computer games\nCoffee";
cout << "\nAspirin\n";
}
2-7 ProgramTake a Few Minutes to Type Program – page 36
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-7 Program Output
The following items were top sellersduring the month of June:Computer gamesCoffeeAspirin
Common Escape Sequences TableAllows you the ability to exercise greater control over the way
information is output by your program. Escape Sequence
Name Description
\ n Newline Causes the cursor to go to the next line for subsequent printing
\ t Horizontal tab Causes the cursor to skip over to the next tab stop
\ a Alarm Causes the computer to beep \ b Backspace Causes the cursor to back up, or move
left one position \ r Return Causes the cursor to go to the
beginning of the current line, not the next line.
\ \ Backslash Causes a backslash to be printed \ ' Single quote Causes a single quotation mark to be
printed \ " Double quote Causes a double quotation mark to be
printed
Resource: Starting Out with C++, Third Edition, Tony Gaddis
The #include Directive
• The #include directive causes the contents of another file to be inserted into the program.
• Preprocessor directives are not C++ statements and do not require semicolons at the end.
• Preprocessor directives are signals to the preprocessor, which runs prior to the compiler (hence the name preprocessor). The preprocessor’s job is to set programs up in a way that makes life easier for the programmer.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
#include <iostream.h>
The header file iostream.h must be included in any program that uses the cout object. This is because cout is not part of the “core” of the C++ language.
iostream.h is part of the input-output stream library.
The header file, iostream.h, contains information describing iostream objects. Without it, the compiler will not know how to properly compile a program that uses cout.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
An #include Directive Continued
• An #include directive must always contain the name of the file.
• The preprocessor inserts the entire contents of the file into the program at the point it encounters the #include directive.
• The compiler doesn’t actually see the #include directive. Instead, it sees the information that was inserted by the preprocessor, just as if the programmer had typed it there.
• The information contained in the header files is C++ code.
Later you will learn to create your own header files
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Variables and Constants
• Variables represent storage locations in the computer’s memory.
• Constants are data items whose values do not change while the program is running.
• Every variable must have a declaration.
Part of a programmers job is to determine how many variables a program will need and what types of information they will hold.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
#include <iostream.h>
void main(void){ int value; value = 5; cout << “The value is “ << value << endl;
}Program Output:The value is 5
2-8 ProgramTake a Few Minutes to Type Program – page 40
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Int value; Variable Declaration
• It tells the compiler the variable’s name and type of data it will hold.
• This line indicates the variable’s name is value.
• The word int stands for integer, so value will only be used to hold integer numbers.
• You MUST have a declaration for every variable you intend to use in a program. In C++, variable declarations can appear at any point in the program.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Value = 5; Assignment Statement
• Variable declarations end with a semicolon.• This is called an assignment.• The assignment statement evaluates the
expression on the right of the equal sign then stores it into the variable named on the left of the equal sign.
• For example: The equal sign is an operator that copies the value on its right (5) into the variable named on its left(value).
• The data type of the variable was in integer, so the data type of the expression on the right should evaluate to an integer as well.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Constants
• A variable is called a variable because its value may be changed.
• A constant, on the other hand, is a data item whose value does not change during the program’s execution.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-10 Program#include <iostream.h>
void main (void)
{
int apples; variable
apples = 20;
cout<< “Today we sold “ << apples << “ bushels\n”;
cout << “of apples.\n”;
}
integer
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-10 Program Output
Today we sold 20 bushels
of apples.
Where are the constants in program 2.10?
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-10 Constants from Program
Constant Type of Constant 20 Integer constant "Today we sold " String constant " bushels\n" String constant "of apples.\n" String constant
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Checkpoint 2.5 - page 43
Examine the 2.8 program?
What are the variables and constants that appear in the program.
Variables: little and big
Constants: 2, 2000, “The Little number is”, “The big number is”
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-6 Identifiers
• An identifier is a programmer-defined name that represents some element of a program.
• Variables are examples of identifiers. • You may choose your own variable
names, as long as, you do not use key words.
See Next Slide for C++ Key Words
The C++ Key Words Table
asm auto break bool case catch char class const const_ cast continue default delete do double dynam ic_ cast else enum explicit extern false float for friend goto if inline int long m utable nam espace new operator private protected public register reinterpret_ cast return short signed sizeof static static_ cast struct sw itch tem plate this throw true try typedef typeid typenam e union unsigned using virtual void volatile w char_ t w hile
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Names for Variables
• Names of your variables should indicate what the variables are used for. You may be tempted to declare variables with names like this: int x;
• The rather nondescript name “x”, gives no clue as to the variable’s purpose. Here is a better example: int itemsOrdered;
• The name itemOrdered gives anyone reading the program an idea of the variable’s use.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Names for Variables Continued
• You may notice that there is uppercase and lowercase letters in itemsOrdered. You may use uppercase letters in variable names.
• You CAN NOT have spaces in a variable name.
• You can use the underscore character to separate words in a variable name i.e. int items_ordered.
• Be consistent and make your variable names as sensible as possible.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Self-Documenting Programs
• When you give your variables descriptive names, this helps produce self-documenting programs.
• This means you get an understanding of what the program is doing just be reading the code.
• Since real-world programs usually have thousands of lines, it is important that they be as self-documenting, as possible.
Some Variable Names Table
Variable Name Legal or Illegal?
dayOfWeek Legal
3dGraph Illegal. Cannot begin with a digit.
_employee_num Legal
june1997 Legal
Mixture#3 Illegal. Cannot use # symbol.
Legal Identifiers• The first character MUST be one of the letters a-z, A-Z,
or an underscore character (_).• After the first character you may use the letters a-z, A-
Z, the digits 0-9, or under-scores.• Uppercase and lowercase characters are distinct, this
means ItemsOrdered is not the same as itemsordered.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Different Types of Data
There are many different types of data. – Whole Numbers– Fractional Numbers– Negative Numbers– Positive Numbers– Large Numbers– Small Numbers– Textual Information
When you write a program you MUST determine what types of information it will be likely to encounter.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Data Types
• Variables are classified according to their data type, which determines the kind of information that may be stored in them.
• Numeric data types are broken into two additional categories: integer and floating point.
• Integers are whole numbers like 12, 157, -34 and 2.
• Floating point numbers have a decimal point, like 23.7, 189.0231, and 0.987.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Numeric Data Type
• Your primary considerations for selecting a numeric data type are:– the largest and smallest numbers
that may be stored in the variable.– how much memory the variable
uses.– whether the variable stores signed
or unsigned numbers.– the number of decimal places of
precision the variable has.
Integer Data Types, Sizes & Ranges Table
Data Type Size Range
short 2 Bytes -32,768 to +32.767 unsigned short 2 Bytes 0 to +65,535 int 4 Bytes -2,147,4833,648 to
+2,147,4833,647 unsigned int 4 Bytes 0 to 4,294,967,295 long 4 Bytes -2,147,4833,648 to
+2,147,4833,647 unsigned long 4 Bytes 0 to 4,294,967,295
The size of a variable is the number of bytes of memory it uses. Typically, the larger a variable is, the greater the range it can hold. The below shows the C++ integer data types with their typical sizes and ranges.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Variable Declarations
• Some examples of variable declarations:– int days;– unsigned speed;– short month;– unsigned short amount;– long deficit;– unsigned long insects;
Resource: Starting Out with C++, Third Edition, Tony Gaddis
unsigned Data Type
• Can ONLY store positive values. • They can be used when you know your
program will not encounter negative values.– For example, variables that hold age or
weights would rarely hold numbers less than 0.
• An unsigned int variable can also be declared using ONLY the word unsigned.– For example, unsigned int days; unsigned days;
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Size of Integers
• The size of integers is dependent on the type of machine you are using.
• You will learn to use the sizeof operator to determine how large all the data types are on your computer.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-11 ProgramLook at this program – page 48
// This program has variables of several of the integer types.
#include <iostream.h>
void main(void){
int checking;unsigned int miles;long days;
checking = -20;miles = 4276;days = 184086;cout << "We have made a long journey of " << miles;cout << " miles.\n";cout << "Our checking account balance is " << checking;cout << "\nExactly " << days << " days ago Columbus ";cout << "stood on this spot.\n";
}
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-11 Program Output
We have made a long journey of 4276 miles.
Our checking account balance is -20
Exactly 184086 days ago Columbus stood on this spot.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
More Than One Variable
• In most programs, you will need more than one variable of any given data type. If a program uses two integers, length and width, they could be declared separately, like this: int length;int width;
• It is easier, however, to combine both variable declarations on one line:int length, width;
• You can declare several variables of the same type like this, simply separating their names with commas.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-12 Program Look at this program – page 49
// This program shows three variables declared on the same
// line.
#include <iostream.h>
void main(void)
{
int floors,rooms,suites;
floors = 15;
rooms = 300;
suites = 30;
cout << "The Grande Hotel has " << floors << " floors\n";
cout << "with " << rooms << " rooms and " << suites;
cout << " suites.\n";
}
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-12 Program Output
The Grande Hotel has 15 floors
with 300 rooms and 30 suites.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Integer and Long Integer Constants
• Look at the following lines from Program 2-12:
floors = 15;
rooms = 300;
suites = 30;• Each of these lines contains an integer constant.
In C++, integer constants are stored in memory just as an int.
• On a system that use 2 byte integers and 4 byte longs, the constant is too large to be stored as an int, so it is stored as a long.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Hexadecimal & Octal Constants
• Hexadecimal numbers are preceded by 0x– Hexadecimal F4 would be expressed in
C++ as 0xF4• Octal numbers are preceded by a 0
– Octal 31 would be written as 031
You will not be writing programs for some time that require this type of manipulation.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
The char Data Type
• char is for character.• Usually 1 byte long.• Internally stored as an integer.• Primarily for storing characters.• American Standard Code for Information
Interchange (ASCII) character set shows integer representation for each character ‘A’ = 65, ‘B’ = 66, ‘C’ = 67, etc.
• Single quotes denote a character, double quotes denote a string
Refer to Appendix A, which shows the ASCII character set.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-13 Program// This program demonstrates the close // relationship between// characters and integers.#include <iostream.h>
void main(void){char letter;
letter = 65;cout << letter << endl;letter = 66;cout << letter << endl;
}
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-13 Program Output
A
B
Copy 2-13 program to the classroom computer and change the ASCII
characters using Appendix A and run the program.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-14 Program 2-14// This program uses character constants
#include <iostream.h>
void main(void)
{
char letter;
letter = 'A'; character constants (single quotes)
cout << letter << endl;
letter = 'B'; character constants (single quotes)
cout << letter << endl;
}
This is another way to write the program.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-14 Program Output
A
B
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Strings• Strings are a series of characters
stored in consecutive memory locations.
• Strings can be virtually any length.• In C++, an extra byte is appended to
the end of most strings.• C-Strings always have a null
terminator at the end. This marks the end of the string.
• Escape sequences are always stored internally as a single character.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-15 Program
// This program uses character constants#include <iostream.h>
void main(void){char letter;
letter = 'A';cout << letter << '\n';letter = 'B';cout << letter << '\n';
}
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-15 Program Output
A
B
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Review Key Points Regarding Characters, Strings, and C-Strings:
• Printable characters are internally represented by numeric codes. Most computers use ASCII codes for this purpose.
• Characters occupy a single byte of memory.• C-Strings are consecutive sequences of characters
and can occupy several bytes of memory.• C-Strings always have a null terminator at the end.
This marks the end of the C-string.• Character constants are always enclosed in single
quotation marks.• String constants are always enclosed in double
quotation marks.• Escape sequences are always stored internally as a
single character.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
The C++ string Class
• The string class is an abstract data type.
• It provides capabilities that make working with strings easy and intuitive.
• You must us the #include <string> statement.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Floating Point Data Types
• Floating point data types are used to declare variables that can hold real numbers.
• Whole numbers are not adequate for many jobs.
• Floating point numbers allows fractional values.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Floating Point Numbers• There are three data types that can represent
floating point numbers:floatdoublelong double
• float data type is considered a single precision.
• The double data type is usually twice as big as float, so it is considered double precision.
• The long double is intended to be larger than the double.
Floating Point Data Types on PCs Table
Data Type Key Word Description
Single Precision
float 4 bytes. Numbers between + 3.4E-38 and + 3.4E38
Double Precision
double 8 bytes. Numbers between +1.7E-308 and +1.7E308
Long Double Precision
long double 8 bytes. Numbers between +1.7E-308 and +1.7E308
You will notice there are no unsigned floating point data types. On all machines, floats, doubles, and long doubles can store positive or negative numbers.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-16 Program// This program uses floating point data types
#include <iostream.h>
void main(void)
{
float distance;
double mass;
distance = 1.495979E11;
mass = 1.989E30;
cout << "The Sun is " << distance << " kilometers away.\n";
cout << "The Sun\'s mass is " << mass << " kilograms.\n";
}
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-16 Program Output
The Sun is 1.4959e+11 kilometers away.
The Sun's mass is 1.989e+30 kilograms.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Floating Point Constants
• May be expressed in a variety of ways.• E notation is one method. Can be
expressed with an uppercase E or a lowercase e. The plus sign in front of the exponent is optional.– When you are writing numbers that
are extremely large or extremely small, this will probably be the easiest way.
• Can express floating point constants in decimal notation.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
The bool Data Type
• Expressions that have a true or false value are called boolean expressions.
• The bool data type allows you to create small integer variables that are suitable for holding true or false values.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-17 Program
#include <iostream.h>
void main (void){ bool boolValue; boolValue = true; cout << boolValue << endl; boolValue = false; cout << boolValue << endl;}
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-17 Program Output
1
0
Internally, true is represented as the number 1 and false is represented by the number 0.
Read Appendix F: Creating a Boolean Data Type
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Determining the Size of a Data Type
• The sizeof operator may be used to determine the size of a data type on any system.
• If you are not sure what the sizes of data types are on your computer, C++ provides a way to find out.
• The name of the data type or variable is placed inside the parentheses that follow the operator. The operator returns the number of bytes used by that item. This operator can be invoked anywhere you can use an unsigned integer, including a mathematical operations!
cout << “The size of an integer is “ << sizeof(int);
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-18 Program Look at this program – page 59
#include <iostream.h>
void main (void){
long double apple;cout << “The size of an integer is “ << sizeof(int);cout << “ bytes.\n”;cout << “The size of a long integer is “ << sizeof(long);cout << “ bytes.\n”;cout << “An apple can be eaten in “ << sizeof(apple);cout << “ bytes!\n”;
}
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-18 Program Output
The size of an integer is 4 bytes.
The size of a long integer is 4 bytes.
An apple can be eaten in 8 bytes!
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Variable Assignment and Initialization
• An assignment operation assigns, or copies, a value into a variable.
• When a value is assigned to a variable as part of the variable’s declaration, it is called an initialization.
• A value is stored in a variable with an assignment statement.
For example: unitsSold = 12;• The = symbol is called the assignment
operator.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Operators
• Operators perform operations on data.• The data that operators work with are called
operands.• The assignment operator I.e. = has two
operands. In the statement unitsSold = 12; the operands are unitsSold and 12.
• In an assignment statement, C++ requires the name of the variable receiving the assignment to appear on the left side of the operator.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-19 Program
//This program shows variable initialization#include <iostream.h>
void main (void){int month = 2, days = 28;cout << “Month “ << month << “ has “ << days << “ days.\n”;
}
Program Output:Month 2 has 28 days.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
A Variable’s ScopeIntroduced to Concept in this Chapter
• A variable’s scope is the part of the program that has access to the variable.
• Every variable has a scope.• The first rule of scope you should
learn is that a variable CAN NOT be used in any part of the program before the declaration.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-20 Program// This program can't find its variable
#include <iostream.h>
void main(void)
{
cout << Value;
int Value = 100;
}
The program will NOT work, because it attempts to send the contents of the variable value to cout before the variable is declared. The compiler reads your program from top to bottom. If it encounters a statement that uses a variable before the variable is declared, an error will result. To correct the program, the variable declaration MUST be placed before any statement that uses it.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Arithmetic Operators• There are many operators for
manipulating numeric values and performing arithmetic operations.
• Generally, there are 3 types of operators: unary, binary, and ternary.– Unary operators operate on one
operand.– Binary operators require two
operands.– Ternary operators need three
operands.
Fundamental Arithmetic Operators TableArithmetic operations are very common in programming
Operator Meaning Type Example
+ Addition Binary Total = Cost + Tax; - Subtraction Binary Cost = Total - Tax; * Multiplication Binary Tax = Cost * Rate; / Division Binary SalePrice = Original/2;
% Modulus Binary Remainder = Value%3;
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-21 Program// This program calculates hourly wages// The variables in function main are used as follows:// regWages: holds the calculated regular wages.// basePay: holds the base pay rate.// regHours: holds the number of hours worked less
overtime.// otWages: holds the calculated overtime wages.// otPay: holds the payrate for overtime hours.// otHours: holds the number of overtime hours worked.// totalWages: holds the total wages.#include <iostream.h>void main(void){
float regWages, basePay = 18.25, regHours = 40.0;float otWages, otPay = 27.78, otHours = 10;float totalWages;
regWages = basePay * regHours; otWages = otPay * otHours;totalWages = regWages + otWages;cout << "Wages for this week are $" << totalWages << endl;
}
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-21 Program Output
Wages for this week are $1007.8
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Comments
• Comments are notes of explanation that document lines or sections of a program.
• Comments are part of a program, but the compiler ignores them. They are intended for people who may be reading the source code.
• Commenting the C++ Way//
• Commenting the C Way/* */
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Comments for Class Assignments
The below is a sample of how your comments should appear in your submitted assignment programs
//PROGRAM: CHUECK2.CPP//Written by Carla Hueckstaedt//1/25/02//Chapter 2//The program calculates company payroll//Last modification: 1/27/02
Real-world programs are big and complex. Thoroughly documented programs will make your life easier, not to mention the other poor souls who may have to read your code in the future.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-22 Program// PROGRAM: PAYROLL.CPP
// Written by Herbert Dorfmann
// This program calculates company payroll
// Last modification: 3/30/96
#include <iostream.h>
void main(void)
{
float payRate; // holds the hourly pay rate
float hours; // holds the hours worked
int empNum; // holds the employee number
This shows that comments can be placed liberally throughout the program. (The remainder of this program is left out.)
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-23 Program// PROGRAM: PAYROLL.CPP// Written by Herbert Dorfmann// Also known as "The Dorfmiester"// Last modification: 3/30/96// This program calculates company payroll.// Payroll should be done every Friday no later than// 12:00 pm. To start the program type PAYROLL and // press the enter key. #include <iostream.h> // Need the iostream file because
// the program uses cout.void main(void) // This is the start of function main.{ // This is the opening brace for main.
float payRate; // payRate is a float variable.// It holds the hourly pay rate.
float hours; // hours is a float variable too.// It holds the hours worked.
int empNum; // empNum is an integer.// It holds the employee number.
This shows how commenting can be overdone. Comments should explain the aspects of your code that are not evident. (The remainder of this program is left out.)
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-24 Program/* PROGRAM: PAYROLL.CPP
Written by Herbert Dorfmann
This program calculates company payroll
Last modification: 3/30/96 */
#include <iostream.h>
void main(void)
{
float payRate; /* payRate holds hourly pay rate */
float hours; /* hours holds hours worked */
int empNum; /* empNum holds employee number */
This is another way to put comments into your program. Everything between these markers is ignored. (The remainder of this program is left out.)
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-25 Program/*
PROGRAM: PAYROLL.CPP
Written by Herbert Dorfmann
This program calculates company payroll
Last modification: 3/30/96
*/
#include <iostream.h>
void main(void)
{
float payRate; // payRate holds the hourly pay rate
float hours; // hours holds the hours worked
int empNum; // empNum holds the employee number
(The remainder of this program is left out.)
Use for multi-line comments
Use for single line comments
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Syntax
• Syntax rules govern the way a language may be used.
• The syntax rules of C++ dictate how and where to place key words, semicolons, commas, braces, and other components of the language.
• The compiler’s job is to check for syntax errors, and if there are none, generate object code.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-26 Program
#include <iostream.h>
void main(void){float shares=220.0;float avgPrice=14.67;cout <<"There were "<<shares<<" shares sold at $"<<avgPrice<<" per share.\n";}
Program OutputThere were 220 shares sold at $14.67 per share.
Although the program is syntactically correct (it doesn’t violate any rules of C++), it is very difficult to read.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
2-27 Program// This example is much more readable
#include <iostream.h>
void main(void)
{
float shares = 220.0;
float avgPrice = 14.67;
cout << "There were " << shares << " shares sold at $";
cout << avgPrice << " per share.\n";
}
Program OutputThere were 220.0 shares sold at $14.67 per share.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Programming Style• Program style refers to the way a
programmer uses identifiers, spaces, tabs, blank lines, and punctuation characters to visually arrange a program’s source code.– Generally, C++ ignores white space.– It is a common C++ style to indent all the
lines inside a set of braces.– Include a blank line after variable
declarations and cout statements.• Although you have the freedom to develop
your own style, you should adhere to common programming practices. By doing so, you will write programs that visually make sense to other programmers.