ch01_BasicElementCPlusPlus
ch01_BasicElementCPlusPlus
Chapter 1
Chapter 1 Course Outline Content
Basic Elements of C++ Program
• Getting Started in the C++ Programming
Environment
• The basic of a C++ program
• Data types and Expression
• Increment and Decrement Operators
• Program Style and Form
main menu
Objectives
In this chapter you will:
main menu
Objectives (continued)
• Become familiar with the use of increment and
decrement operators
• Examine ways to output results using output statements
• Learn how to use preprocessor directives and why they
are necessary
• Explore how to properly structure a program, including
using comments to document a program
• Learn how to write a C++ program
main menu
Introduction
• Computer program: sequence of statements
designed to accomplish some task
• Programming: planning/creating a program
• Syntax: rules that specify which statements
(instructions) are legal
• Programming language: a set of rules,
symbols, and special words
• Semantic rule: meaning of the instruction
main menu
C++ Programs
• A C++ program is a collection of one or
more subprograms, called functions
• A subprogram or a function is a collection
of statements that, when activated
(executed), accomplishes something
• Every C++ program has a function called
main
• The smallest individual unit of a program
written in any language is called a token
main menu
Symbols
• Special
Example:
symbols sum = a + b * c;
? result = result ++;
+ ,
- <=
* !=
/ ==
. >=
;
main menu
Symbols (continued)
• Word symbols
– Reserved words, or keywords
Example:
– Include: int sum, result;
• int void calculate();
return (sum);
• float
• double
• char
• void
• return
main menu
Identifiers
• Consist of letters, digits, and the
underscore character (_)
• Must begin with a letter or underscore
• C++ is case sensitive
• Some predefined identifiers are cout and
cin
• Unlike reserved words, predefined
identifiers may be redefined, but it is not a
good idea
main menu
Legal and Illegal Identifiers
main menu
Data Types
• set of values together with a set of
operations is called a data type
– Pointers
main menu
Simple Data Types
• Three categories of simple data
main menu
main menu
int Data Type
• Examples:
-6728
0
78
• Positive integers do not have to have a +
sign in front of them
• No commas are used within an integer
• Commas are used for separating items in
a list
main menu
bool Data Type
• bool type
main menu
char Data Type
• The smallest integral data type
• Used for characters: letters, digits, and
special symbols
• Each character is enclosed in single quotes
• Some of the values belonging to char data
type are: 'A', 'a', '0', '*', '+', '$', '&'
• A blank space is a character and is written '
', with a space left between the single
quotes
main menu
Floating-Point Data Types
• C++ uses scientific notation to represent
real numbers (floating-point notation)
main menu
Floating-Point Data Types
(continued)
• float: represents any real number
– Range: -3.4E+38 to 3.4E+38
• Memory allocated for the float type is 4
bytes
• double: represents any real number
– Range: -1.7E+308 to 1.7E+308
• Memory allocated for double type is 8
bytes
• On most newer compilers, data types
double and long double are same main menu
Arithmetic Operators
• C++ Operators
+ addition
- subtraction
* multiplication
/ division
% remainder (mod operator)
main menu
Type Conversion (Casting)
• Implicit type coercion: when value of one
type is automatically changed to another
type
main menu
main menu
string Data Type
• Programmer-defined type supplied in
standard library
• Sequence of zero or more characters
• Enclosed in double quotation marks
• Null: a string with no characters
• Each character has relative position in
string
• Position of first character is 0, the position
of the second is 1, and so on
• Length: number of characters in string
main menu
Input
• Data must be loaded into main memory
before it can be manipulated
main menu
main menu
Allocating Memory: Variable
memory location whose content may change
during execution
main menu
Assignment Statement
• The assignment statement takes the form:
variable = expression;
• Expression is evaluated and its value is assigned
to the variable on the left side
• In C++ = is called the assignment operator
• A C++ statement such as:
i = i + 2;
evaluates whatever is in i, adds two to it, and
assigns the new value to the memory location i
main menu
Declaring & Initializing Variables
• Variables can be initialized when declared:
int first=13, second=10;
char ch=' ';
double x=12.6, y=123.456;
• first and second are int variables with
the values 13 and 10, respectively
• ch is a char variable whose value is empty
• x and y are double variables with 12.6 and
123.456, respectively
main menu
Input (Read) Statement
• cin is used with >> to gather input
cin >> variable >> variable;
• The extraction operator is >>
• For example, if miles is a double variable
cin >> miles;
– Causes computer to get a value of type
double
– Places it in the memory cell miles
main menu
Input Statement (continued)
• Using more than one variable in cin
allows more than one value to be read at
a time
• For example, if feet and inches are
variables of type int a statement such as:
cin >> feet >> inches;
– Inputs two integers from the keyboard
– Places them in locations feet and inches
respectively
main menu
Example 2-17
#include <iostream>
#include <string>
using namespace std;
int main()
{
string firstName; //Line 1
string lastName; //Line 2
int age; //Line 3
double weight; //Line 4
cout << "Enter first name, last name, age, "
<< "and weight, separated by spaces."
<< endl; //Line 5
cin >> firstName >> lastName; //Line 6
cin >> age >> weight; //Line 7
cout << "Name: " << firstName << " "
<< lastName << endl; //Line 8
cout << "Age: " << age << endl; //Line 9
cout << "Weight: " << weight << endl; //Line 10
return 0; //Line 11
}
main menu
Sample Run:
Enter first name, last name, age, and weight, separated by spaces.
Sheila Mann 23 120.5
Name: Sheila Mann
Age: 23
Weight: 120.5
main menu
Increment & Decrement Operators
• Increment operator: increment variable by 1
• Decrement operator: decrement variable by 1
• Pre-increment: ++variable
• Post-increment: variable++
• Pre-decrement: --variable
• Post-decrement: variable--
main menu
Increment & Decrement Operators
(continued)
main menu
Output (continued)
• Manipulator: alters output
main menu
Output Example
cout << a;
produces an output of 45
main menu
The New Line Character
• The new line character is '\n'
• Without this character the output is printed
on one line
• Tells the output to go to the next line
• When \n is encountered in a string
– Cursor is positioned at the beginning of next
line
• A \n may appear anywhere in the string
main menu
Examples
• Without the new line character:
cout << "Hello there.";
cout << "My name is James.";
– Would output:
Hello there.My name is James.
• With the new line character:
cout << "Hello there.\n";
cout << "My name is James.";
– Would output
Hello there.
My name is James.
main menu
Preprocessor Directives
• C++ has a small number of operations
• Many functions and symbols needed to run
a C++ program are provided as collection of
libraries
• Every library has a name and is referred to
by a header file
• Preprocessor directives are commands
supplied to the preprocessor
• All preprocessor commands begin with #
• No semicolon at the end of these commands
main menu
Preprocessor Directive Syntax
• Syntax to include a header file
#include <headerFileName>
#include <iostream>
main menu
Using cin and cout in a
Program and namespace
• cin and cout are declared in the header
file iostream, but within a namespace
named std
#include <iostream>
#include <string>
main menu
Creating a C++ Program
main menu
• Declaration Statements
int a, b, c;
double x, y;
– Variables can be declared anywhere in the
program, but they must be declared before they
can be used
main menu
Example 2-28
main menu
Program Style and Form
• The Program Part
– Every C++ program has a function main
– Basic parts of function main are:
• The heading
• The body of the function
main menu
Syntax
• Errors in syntax are found in compilation
int x; //Line 1
int y //Line 2: syntax error
double z; //Line 3
y = w + x; //Line 4: syntax error
main menu
Use of Blanks
• Use of Blanks
– One or more blanks separate input numbers
– Blanks are also used to separate reserved words
and identifiers from each other and other
symbols
• Blanks between identifiers in the second statement
are meaningless:
int a,b,c;
int a, b, c;
• In the statement: inta,b,c;
no blank between the t and a changes the
reserved word int and the identifier a into a new
identifier, inta.
main menu
Semicolons, Brackets, &
Commas
• Commas separate items in a list
main menu
Semantics
• Possible to remove all syntax errors in a
program and still not have it run.
• Even if it runs, it may still not do what you
meant it to do.
• For example,
2 + 3 * 5 and (2 + 3) * 5
are both syntactically correct expressions,
but have different meanings.
main menu
Form and Style
• Consider two ways of declaring variables:
– Method 1
int feet, inch;
double x, y;
– Method 2
int a,b;double x,y;
• Example:
x *= y;
main menu
Programming Example
• Write a program that takes as input a
given length expressed in feet and inches
– Convert and output the length in centimeters
• Input: Length in feet and inches
• Output: Equivalent length in centimeters
• Lengths are given in feet and inches
• Program computes the equivalent length
in centimeters
• One inch is equal to 2.54 centimeters
main menu
Programming Example (continued)
• Convert the length in feet and inches to all
inches:
– Multiply the number of feet by 12
– Output centimeters
main menu
Variables and Constants
• Variables
int feet; //variable to hold given feet
int inches; //variable to hold given inches
int totalInches; //variable to hold total inches
double centimeters; //variable to hold length in
//centimeters
• Named Constant
const double conversion = 2.54;
const int inchesPerFoot = 12;
main menu
Main Algorithm
• Prompt user for input
• Get data
• Echo the input (output the input)
• Find length in inches
• Output length in inches
• Convert length to centimeters
• Output length in centimeters
main menu
Putting It Together
• Program begins with comments
• System resources will be used for I/O
• Use input statements to get data and
output statements to print results
• Data comes from keyboard and the output
will display on the screen
• The first statement of the program, after
comments, is preprocessor directive to
include header file iostream
main menu
Putting It Together (continued)
• Two types of memory locations for data
manipulation:
– Named constants
– Variables
• Named constants are usually put before main
so they can be used throughout program
• This program has only one function (main),
which will contain all the code
• The program needs variables to manipulate
data, which are declared in main
main menu
Body of the Function
• The body of the function main has the
following form:
int main ()
{
declare variables
statements
return 0;
}
main menu
Writing a Complete Program
• Begin the program with comments for
documentation
main menu
//********************************************************
// Program Convert Measurements: This program converts
// measurements in feet and inches into centimeters using
// the formula that 1 inch is equal to 2.54 centimeters.
//********************************************************
//header file
#include <iostream>
using namespace std;
//named constants
const double CENTIMETERS_PER_INCH = 2.54;
const int INCHES_PER_FOOT = 12;
int main ()
{
//declare variables
int feet, inches;
int totalInches;
double centimeter;
//Statements: Step 1 - Step 7
cout << "Enter two integers, one for feet and "
<< "one for inches: "; //Step 1
cin >> feet >> inches; //Step 2
cout << endl;
main menu
cout << endl;
cout << "The numbers you entered are " << feet
<< " for feet and " << inches
<< " for inches. " << endl; //Step 3
totalInches = INCHES_PER_FOOT * feet + inches; //Step 4
Sample Run
Enter two integers, one for feet, one for inches: 15 7
The numbers you entered are 15 for feet and 7 for inches.
The total number of inches = 187
The number of centimeters = 474.98
main menu
Summary
• C++ program: collection of functions
where each program has a function
called main
• Identifier consists of letters, digits, and
underscores, and begins with letter or
underscore
• The arithmetic operators in C++ are
addition (+), subtraction (-),multiplication
(*), division (/), and modulus (%)
• Arithmetic expressions are evaluated
using the precedence associativity rules
main menu
Summary (continued)
• All operands in an integral expression are
integers and all operands in a floating-point
expression are decimal numbers
• Mixed expression: contains both integers
and decimal numbers
• Use the cast operator to explicitly convert
values from one data type to another
• A named constant is initialized when
declared
• All variables must be declared before used
main menu
Summary (continued)
• Use cin and stream extraction operator
>> to input from the standard input device
• Use cout and stream insertion operator
<< to output to the standard output device
• Preprocessor commands are processed
before the program goes through the
compiler
• A file containing a C++ program usually
ends with the extension .cpp
main menu
Thank you
Exercise 1.3
Write a program that displays the result of
expression below:
main menu
Exercise 1.4
Consider the following program 1. Write C++ statements that include the
segment: header files iostream.
2. Write a C++ statements that allows you to
// include statement use cin, cout, and endl
// using namespace statement 3. Write C++ statements that declare the
following variables: num1, num2, num3,
and average of type int.
int main() {
4. Write C++ statements that store 125 into
// variable declaration num1, 28 into num2 and -25 into num3.
// executable statements 5. Write C++ statements that store the average
// return statement of num1, num2 and num3 into average
} 6. Write C++ statements that output the values
of num1. num2, num3 and average.
7. Compile and run your program.