0% found this document useful (0 votes)
31 views

Basic Elements of C++

This document provides an overview of basic C++ concepts including increment and decrement operators, output statements, preprocessor directives, namespaces, data types like string, program structure, syntax errors, semantics, naming conventions, documentation, and formatting. It also summarizes key points about C++ programs, arithmetic expressions, data types, input/output, and control structures.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Basic Elements of C++

This document provides an overview of basic C++ concepts including increment and decrement operators, output statements, preprocessor directives, namespaces, data types like string, program structure, syntax errors, semantics, naming conventions, documentation, and formatting. It also summarizes key points about C++ programs, arithmetic expressions, data types, input/output, and control structures.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 67

Lecture 3:

Basic Elements of C++


Increment and Decrement
Operators
• Increment operator: increase variable by 1
– Pre-increment: ++variable
– Post-increment: variable++
• Decrement operator: decrease variable by 1
– Pre-decrement: --variable
– Post-decrement: variable—
• What is the difference between the following?
x = 5; x = 5;
y = ++x; y = x++;

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 2


Output
• The syntax of cout and << is:

– Called an output statement


• The stream insertion operator is <<
• Expression evaluated and its value is printed at the
current cursor position on the screen

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 3


Output (cont’d.)
• A manipulator is used to format the output
– Example: endl causes insertion point to move to
beginning of next line

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 4


Output (cont’d.)
• The new line character is '\n'
– May appear anywhere in the string
cout << "Hello there.";
cout << "My name is James.";
Output:
Hello there.My name is James.
cout << "Hello there.\n";
cout << "My name is James.";
Output :
Hello there.
My name is James.

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 5


Output (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 6


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 program
• All preprocessor commands begin with #
• No semicolon at the end of these commands

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 7


Preprocessor Directives (cont’d.)
• Syntax to include a header file:

• For example:
#include <iostream>
– Causes the preprocessor to include the header file
iostream in the program
• Preprocessor commands are processed before the
program goes through the compiler

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 8


namespace and Using cin and
cout in a Program
• cin and cout are declared in the header file
iostream, but within std namespace
• To use cin and cout in a program, use the
following two statements:
#include <iostream>
using namespace std;

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 9


Using the string Data Type in a
Program
• To use the string type, you need to access its
definition from the header file string
• Include the following preprocessor directive:
#include <string>

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 10


Creating a C++ Program
• A C++ program is a collection of functions, one of
which is the function main
• The first line of the function main is called the
heading of the function:
– int main()
• The statements enclosed between the curly braces
({ and }) form the body of the function

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 11


Creating a C++ Program (cont’d.)
• A C++ program contains two types of statements:
– Declaration statements: declare things, such as variables
– Executable statements: perform calculations, manipulate
data, create output, accept input, etc.

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 12


Creating a C++ Program (cont’d.)
• C++ program has two parts:
– Preprocessor directives
– The program
• Preprocessor directives and program statements
constitute C++ source code (.cpp)
• Compiler generates object code (.obj)
• Executable code is produced and saved in a file with
the file extension .exe

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 13


Debugging: Understanding and Fixing
Syntax Errors
• Compile a program
– Compiler will identify the syntax errors
– Specifies the line numbers where the errors occur
Example2_Syntax_Errors.cpp
c:\chapter 2 source code\example2_syntax_errors.cpp(9) : error
C2146: syntax error :
missing ';' before identifier 'num'
c:\chapter 2 source code\example2_syntax_errors.cpp(11) :
error C2065: 'tempNum' :
undeclared identifier

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 14


Syntax
• Syntax rules: indicate what is legal and what is not
legal
• Errors in syntax are found in compilation
int x; //Line 1
int y //Line 2: error
double z; //Line 3

y = w + x; //Line 4: error

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 15


Use of Blanks
• In C++, you use one or more blanks to separate
numbers when data is input
• Blanks are also used to separate reserved words and
identifiers from each other and from other symbols
• Blanks must never appear within a reserved word or
identifier

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 16


Use of Semicolons, Brackets, and
Commas
• All C++ statements end with a semicolon
– Also called a statement terminator
• { and } are not C++ statements
– Can be regarded as delimiters
• Commas separate items in a list

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 17


Semantics
• Semantics: set of rules that gives meaning to a
language
– 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
• Ex: 2 + 3 * 5 and (2 + 3) * 5
are both syntactically correct expressions, but have
different meanings

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 18


Naming Identifiers
• Identifiers can be self-documenting:
– CENTIMETERS_PER_INCH
• Avoid run-together words :
– annualsale
– Solution:
• Capitalizing the beginning of each new word: annualSale
• Inserting an underscore just before a new word: annual_sale

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 19


Prompt Lines
• Prompt lines: executable statements that inform the
user what to do
cout << "Please enter a number between 1 and 10 and "
<< "press the return key" << endl;
cin >> num;

• Always include prompt lines when input is needed


from users

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 20


Documentation
• A well-documented program is easier to understand
and modify
• You use comments to document programs
• Comments should appear in a program to:
– Explain the purpose of the program
– Identify who wrote it
– Explain the purpose of particular statements

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 21


Form and Style
• Consider two ways of declaring variables:
– Method 1
int feet, inch;
double x, y;
– Method 2
int feet,inch;double x,y;
• Both are correct; however, the second is hard to read

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 22


Summary
• C++ program: collection of functions, one of which is
always called main
• Identifiers consist 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

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 23


Summary (cont’d.)
• All operands in an integral expression are integers
• 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

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 24


Summary (cont’d.)
• 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

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 25


Input/output and Control
Structures-I
I/O Streams and Standard I/O
Devices
• I/O: sequence of bytes (stream of bytes) from source
to destination
– Bytes are usually characters, unless program requires
other types of information
– Stream: sequence of characters from source to destination
– Input stream: sequence of characters from an input device
to the computer
– Output stream: sequence of characters from the computer
to an output device

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 27


I/O Streams and Standard I/O Devices
(cont’d.)
• Use iostream header file to receive data from
keyboard and send output to the screen
– Contains definitions of two data types:
• istream: input stream
• ostream: output stream
– Has two variables:
• cin: stands for common input
• cout: stands for common output

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 28


I/O Streams and Standard I/O Devices
(cont’d.)
• Variable declaration is similar to:
– istream cin;
– ostream cout;
• To use cin and cout, the preprocessor directive
#include <iostream> must be used
• Input stream variables: type istream
• Output stream variables: type ostream

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 29


cin and the Extraction Operator
>>
• The syntax of an input statement using cin and the
extraction operator >> is:

• The extraction operator >> is binary


– Left-side operand is an input stream variable
• Example: cin
– Right-side operand is a variable

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 30


cin and the Extraction Operator >>
(cont’d.)
• No difference between a single cin with multiple
variables and multiple cin statements with one
variable
• When scanning, >> skips all whitespace
– Blanks and certain nonprintable characters
• >> distinguishes between character 2 and number 2
by the right-side operand of >>
– If type char or int (or double), the 2 is treated as a
character or as a number 2

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 31


cin and the Extraction Operator >>
(cont’d.)

• Entering a char value into an int or double


variable causes serious errors, called input failure

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 32


cin and the Extraction Operator >>
(cont’d.)
• When reading data into a char variable
– >> skips leading whitespace, finds and stores only the next
character
– Reading stops after a single character
• To read data into an int or double variable
– >> skips leading whitespace, reads + or - sign (if any),
reads the digits (including decimal)
– Reading stops on whitespace non-digit character

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 33


cin and the Extraction Operator >>
(cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 34


cin and the Extraction Operator >>
(cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 35


cin and the Extraction Operator >>
(cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 36


Using Predefined Functions in a
Program
• Function (subprogram): set of instructions
– When activated, it accomplishes a task
• main executes when a program is run
• Other functions execute only when called
• C++ includes a wealth of functions
– Predefined functions are organized as a collection of
libraries called header files

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 37


Using Predefined Functions in a
Program (cont’d.)
• Header file may contain several functions
• To use a predefined function, you need the name of
the appropriate header file
– You also need to know:
• Function name
• Number of parameters required
• Type of each parameter
• What the function is going to do

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 38


Using Predefined Functions in a
Program (cont’d.)
• To use pow (power), include cmath
– Two numeric parameters
– Syntax: pow(x,y) = xy
• x and y are the arguments or parameters
– In pow(2,3), the parameters are 2 and 3

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 39


Input Failure
• Things can go wrong during execution
• If input data does not match corresponding variables,
program may run into problems
• Trying to read a letter into an int or double variable
will result in an input failure
• If an error occurs when reading data
– Input stream enters the fail state

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 40


Output and Formatting Output
• Syntax of cout when used with <<

• expression is evaluated
• value is printed
• manipulator is used to format the output
– Example: endl

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 41


setprecision Manipulator
• Syntax:

• Outputs decimal numbers with up to n decimal


places
• Must include the header file iomanip:
– #include <iomanip>

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 42


setw
• Outputs the value of an expression in a specified
number of columns
– cout << setw(5) << x << endl;
• If number of columns exceeds the number of
columns required by the expression
– Output of the expression is right-justified
– Unused columns to the left are filled with spaces
• Must include the header file iomanip

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 43


setfill Manipulator
• Output stream variables can use setfill to fill
unused columns with a character

• Example:
– cout << setfill('#');

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 44


Types of Manipulators
• Two types of manipulators:
– With parameters
– Without parameters
• Parameterized: require iomanip header
– setprecision, setw, and setfill
• Nonparameterized: require iostream header
– endl, fixed, showpoint, left, and flush

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 45


Control Structures I (Selection)
Control Structures
• A computer can proceed:
– In sequence
– Selectively (branch): making a choice
– Repetitively (iteratively): looping
– By calling a function
• Two most common control structures:
– Selection
– Repetition

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 47


Control Structures (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 48


Relational Operators
• Conditional statements: only executed if certain
conditions are met
• Condition: represented by a logical (Boolean)
expression that evaluates to a logical (Boolean) value
of true or false
• Relational operators:
– Allow comparisons
– Require two operands (binary)
– Evaluate to true or false

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 49


Relational Operators (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 50


Relational Operators and Simple
Data Types
• Relational operators can be used with all three
simple data types:
 8 < 15 evaluates to true
 6 != 6 evaluates to false
 2.5 > 5.8 evaluates to false
 5.9 <= 7.5 evaluates to true

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 51


Relational Operators and the
string Type
• Relational operators can be applied to strings
– Strings are compared character by character, starting with
the first character
– Comparison continues until either a mismatch is found or
all characters are found equal
– If two strings of different lengths are compared and the
comparison is equal to the last character of the shorter
string
• The shorter string is less than the larger string

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 52


Relational Operators and the
string Type (cont’d.)
• Suppose we have the following declarations:
string str1 = "Hello";
string str2 = "Hi";
string str3 = "Air";
string str4 = "Bill";
string str5 = "Big";

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 53


Relational Operators and the
string Type (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 54


Relational Operators and the
string Type (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 55


Relational Operators and the
string Type (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 56


Logical (Boolean) Operators and
Logical Expressions
• Logical (Boolean) operators: enable you to combine
logical expressions

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 57


Logical (Boolean) Operators and
Logical Expressions (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 58


Logical (Boolean) Operators and
Logical Expressions (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 59


Logical (Boolean) Operators and
Logical Expressions (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 60


Order of Precedence
• Relational and logical operators are evaluated from
left to right
– The associativity is left to right
• Parentheses can override precedence

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 61


Order of Precedence (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 62


Order of Precedence (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 63


Order of Precedence (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 64


Order of Precedence (cont’d.)

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 65


The int Data Type and Logical
(Boolean) Expressions
• Earlier versions of C++ did not provide built-in data
types that had Boolean values
• Logical expressions evaluate to either 1 or 0
– Logical expression value was stored in a variable of the
data type int
• Can use the int data type to manipulate logical
(Boolean) expressions

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 66


The bool Data Type and Logical
(Boolean) Expressions
• The data type bool has logical (Boolean) values
true and false
• bool, true, and false are reserved words
• The identifier true has the value 1
• The identifier false has the value 0

C++ Programming: From Problem Analysis to Program Design, Sixth Edition 67

You might also like