0% found this document useful (0 votes)
73 views64 pages

C++ Programming: From Problem Analysis To Program Design,: Fourth Edition

The document discusses the basic elements of C++ programs including functions, data types, operators, and program structure. It covers simple data types like int, float, bool and char. Arithmetic operators like +, -, *, /, and % are explained along with precedence rules. Comments, identifiers, and other syntax elements are defined. Program structure is demonstrated using keywords, blocks, and statements.

Uploaded by

has
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views64 pages

C++ Programming: From Problem Analysis To Program Design,: Fourth Edition

The document discusses the basic elements of C++ programs including functions, data types, operators, and program structure. It covers simple data types like int, float, bool and char. Arithmetic operators like +, -, *, /, and % are explained along with precedence rules. Comments, identifiers, and other syntax elements are defined. Program structure is demonstrated using keywords, blocks, and statements.

Uploaded by

has
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

C++ Programming:

From Problem Analysis


to Program Design, Fourth Edition

Chapter 2: Basic Elements of C++


Objectives

In this chapter, you will:


• Become familiar with the basic components of
a C++ program, including functions, special
symbols, and identifiers
• Explore simple data types
• Discover how to use arithmetic operators
• Examine how a program evaluates arithmetic
expressions

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


Objectives (continued)

• Learn what an assignment statement is and


what it does
• Become familiar with the string data type
• Become familiar with the use of increment
and decrement operators

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


What Is a Program Made Of?

• Common elements in programming languages:


− Keywords
− Programmer-Defined Identifiers
− Operators
− Punctuation
− Syntax

C++ Programming: From Problem Analysis to Program Design, Fourth Edition Slide 1- 44
The Basics of a C++ Program
• Function: collection of statements; when
executed, accomplishes something
− May be predefined or standard
• Syntax: The rules of grammar that must be
followed when writing a program (keywords,
operators, symbols, and punctuation)
• Programming language: a set of rules,
symbols, and special words
• Semantic rule: meaning of the instruction
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 5
Structure of a C program

Statement = Command or
instruction
Parts of a C++ Program
comment
// sample C++ program preprocessor
#include <iostream> directive
which namespace
using namespace std; to use
int main() beginning of
function named main
{ beginning of
block for main
cout << "Hello, there!"; statement output

return 0;
string
} end of block literal
for main send 0 to
operating system
Comments
• Comment is a statement that is not executed.
• This helps reader and also yourself to understand your codes and
document parts of the program.
• Two types:

− Single line
// This is a C++ program. It prints the sentence:
// Welcome to C++ Programming.

− Multiple line
/*
You can include comments that can
occupy several lines.
*/

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


Special Symbols

• Special symbols

+ ?
- ,
* <=
/ !=
. ==
; >=

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


Punctuation
• Characters that mark the end of a statement, or
that separate items in a list
• Example: , and ;

Slide 1- 10
Reserved Words (Keywords)

• Have a special meaning in C++


• Can not be used for any other purpose

− Include: int, float, double, char,


const, void, return, main, etc.

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


Identifiers

• Names made up by the programmer


• Not part of the C++ language
• Used to represent various things: variables
(memory locations), functions, etc.

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


Naming Identifiers

• Identifiers can be self-documenting:


− CENTIMETERS_PER_INCH
• Avoid run-together words :
− annualsale
− Solution:
• Capitalize 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, Fourth Edition 13


Identifiers (cont)

• Cannot duplicate a reserved word


• Consist only of letters, digits, or the
underscore character (_)
• First character must be alphabetic character
or underscore
• C++ is case sensitive
− NUMBER is not the same as number
• Two predefined identifiers are cout and cin

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


Identifiers (cont)

• The following are legal identifiers in C++:


− first
− conversion
− payRate

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


Identifiers (cont)

• Valid OR Invalid ?
− A
− $a
− Student8
− 3name
− student_name
− person name
− _person_name
− int
− TRUE
− what?
− FALSE
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 16
Whitespaces

• Every C++ program contains whitespaces


− Include blanks, tabs, and newline characters
• Used to separate special symbols, reserved
words, and identifiers
• Proper utilization of whitespaces is important
− Can be used to make the program readable

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


Data Types

• Data type: set of values together with a set of


operations
• C++ data types fall into three categories:

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


Simple Data Types

• Three categories of simple data


− Integral: integers (numbers without a decimal)
− Floating-point: decimal numbers
− Enumeration type: user-defined data type

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


Simple Data Types (continued)

• Integral data types are further classified into


nine categories:

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


int Data Type

• Examples:
-6728
0
78
+763
• Positive integers do not need a + sign
• No commas are used within an integer
− Commas are used for separating items in a list

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


int Data Type
• Integer variables can hold whole numbers such
as 12, 7, and -99.

1-22
bool Data Type

• bool type
− Two logical values: true and false
− Manipulate logical (Boolean) expressions
− bool variables are stored as small integers
− false is represented by 0, true by 1:
• bool, true, and false are reserved words
bool allDone = true;
bool finished = false;

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


char Data Type

• The smallest integral data type


• Used for characters: letters, digits, and special
symbols
• Usually 1 byte of memory
• Each character is enclosed in single quotes
− 'A', 'a', '0', '*', '+', '$', '&'
• A blank space is a character and is written ' ',
with a space left between the single quotes
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 24
Floating-Point Data Types

• C++ uses scientific notation to represent real


numbers (floating-point notation)

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


Floating-Point Data Types
(continued)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 26


Floating-Point Data Types
(continued)
• Maximum number of significant digits
(decimal places) for float values is 6 or 7
• Maximum number of significant digits for
double is 15
• Precision: maximum number of significant
digits
− Float values are called single precision
− Double values are called double precision

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


Arithmetic Operators and Operator
Precedence
• C++ arithmetic operators used for performing
numeric calculations :
− + addition
− - subtraction
− * multiplication
− / division
− % modulus operator
• +, -, *, and / can be used with integral and
floating-point data types
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 28
Binary Arithmetic Operators

• C++ has unary, binary, and ternary operators:


− unary (1 operand) -5
− binary (2 operands) 13 - 7
− ternary (3 operands) exp1 ? exp2 : exp3
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

1-29
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 29
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 defined

1-30
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

1-31
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

1-32
Order of Precedence

• All operations inside of () are evaluated first


• *, /, and % are at the same level of
precedence and are evaluated next
• + and – have the same level of precedence
and are evaluated last
• When operators are on the same level
− Performed from left to right (associativity)
• 3 * 7 - 6 + 2 * 5 / 4 + 6 means
(((3 * 7) – 6) + ((2 * 5) / 4 )) + 6

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


Expressions

• If all operands are integers


− Expression is called an integral expression
• Yields an integral result
• Example: 2 + 3 * 5
• If all operands are floating-point
− Expression is called a floating-point
expression
• Yields a floating-point result
• Example: 12.8 * 17.5 - 34.50

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


Mixed Expressions

• Mixed expression:
− Has operands of different data types
− Contains integers and floating-point
• Examples of mixed expressions:
2 + 3.5
6 / 4 + 3.9
5.4 * 2 – 13.6 + 18 / 2

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


Mixed Expressions (continued)

• Evaluation rules:
− If operator has same types of operands
• Evaluated according to the type of the operands
− If operator has both types of operands
• Integer is changed to floating-point
• Operator is evaluated
• Result is floating-point
− Entire expression is evaluated according to
precedence rules

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


Type Conversion (Casting)

• Implicit type coercion: when value of one type


is automatically changed to another type
• Cast operator: provides explicit type
conversion
static_cast<dataTypeName>(expression)

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


Type Conversion (continued)

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


string Type
• Programmer-defined type supplied in ANSI/ISO Standard
C++ library
• A series of zero or more characters in consecutive
memory locations:
"Hello"

• Stored with the null terminator, \0, at the end


• Enclosed in double quotation marks
• Null: a string with no characters
• Each character has relative position in string
− Position of first character is 0

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


Input

• Data must be loaded into main memory


before it can be manipulated
• Storing data in memory is a two-step process:
− Instruct computer to allocate memory
− Include statements to put data into memory

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


Allocating Memory with Constants
and Variables
• Named constant: memory location whose
content can’t change during execution
• The syntax to declare a named constant is:

• In C++, const is a reserved word

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


Allocating Memory with Constants
and Variables (continued)
Constant = named memory location that holds a non-changeable
value
− Must be declared
− A variable name should represent the purpose of the variable.
− Re-usable
− MUST be initialized
− Can not be modified after initialization
int main ()
{
const double pi = 3.14;
double area, radius;
radius = 12;
area = pi * radius * radius;
pi = 3.14159; /* but, this is wrong */
return 0;
}
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 42
Allocating Memory with Constants
and Variables
• Variable: memory named storage location in
the computer’s memory for holding a piece of
data whose content may change during
execution

• The syntax to declare a named constant is:

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


Allocating Memory with Constants
and Variables (continued)
• In order to use a variable in our program we must
first declare it.
• HOW?
− A declaration statement has the format:

type variable_name;

− type : what kind of data will be stored in that location (integer?


character? floating point?)
− variable_name : what is the name of the variable?
− semi-colon : indicates this is a statement!

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


Variable types

• There are four basic data types in C


Type C keyword to use:
Integer int
Floating point float
double
Character char
Variable types

• int
− Integer variables hold signed whole numbers (i.e.
with no fractional part), such as 10, – 4353, etc.

− Integers typically take up 4 bytes ( = 32 bits, 1


for the sign, 31 for the number).

− The range of integers is typically


• from – 231 (approx –109) to + 231 (approx. 109)
Variable types

• float and double


− floating point variables hold signed floating point numbers
(i.e. with a fractional part), such as 10.432, – 33.335, etc.
− double provides twice the precision of float.
− floats typically take up 4 bytes
− doubles take up 8 bytes
− The range of floats is approximately ±2127 (±1038)
− The range of doubles is approximately ±21023 (±10308)
Variable types

• char
− character variables hold single characters, such as 'a', '\n', '
', etc.

− characters usually take 1 byte (8 bits).

− IMPORTANT : Note that the value of a character is enclosed


in single quotes.
Variable types

• char (continued)
− ASCII (American Standard Code for Information
Exchange) is used to represent
• the characters A to Z (both upper and lower case)
• the digits 0 to 9
• special characters (e.g. @, <, etc)
• special control codes
− For example,
• the character 'A' is represented by the code 65
• the character '1' is represented by the code 49
• IMPORTANT: the integer 1, the character '1' and the ASCII
code 1 represent three different things!
Variable values

• After a variable has been declared, its memory location does


not contain valid data.
• Variables can be initialized when declared:
• All variables must be initialized before they are used in any
computations.
− But not necessarily during declaration
• There are two ways to initialize a variable:
− by assigning a value using an assignment statement
− by reading its value from the keyboard
Variable values
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;

1-51
Variable values

• The basic syntax of an assignment statement is

• variable = value;

- Assign the value on the right hand side to the variable on the left hand side
- Expression is evaluated and its value is assigned to the variable on the left side
In C++, = is called the assignment operator
• Example
int num_students; // declare
num_students = 22; // initialize
Variable values

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


Literals

• Literals are fixed values written into a program.


− Not declared, no memory location assigned
− Not re-usable; just written directly into each statement
• Example:
char keypressed;
keypressed = ‘y’; /* ‘y’ is a character literal */
• Example:
double pi;
pi = 3.14; /* 3.14 is a floating-point literal. */
• Example:
int index;
index = 17; /* 17 is an integer literal */
Example

/* sample program that demonstrates


variable declaration and
initialization. */

#include <stdio.h>

int main ()
{
int num_students;
num_students = 22;
return 0;
}
Example

/* sample program that demonstrates variable


declaration and initialization. */

#include <stdio.h>

int main ()
{
double rate, amount; /* declare two
double variables */
amount = 12.50;
rate = 0.05;
return 0;
}
Example

/* sample program that demonstrates how to


declare and initialize a variable at
the same time */

#include <stdio.h>

int main ()
{
char grade = ‘A’;
return 0;
}
Example

/* sample program that demonstrates how to


declare and initialize a variable at
the same time */

#include <stdio.h>

int main ()
{
char pass_grade = ‘A’, fail_grade = ‘F’;
return 0;
}
Increment & Decrement Operators

• Increment operator: increment variable by 1


− Pre-increment: ++variable
− Post-increment: variable++
• Decrement operator: decrement 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, Fourth Edition 59
Increment & Decrement Operators
(Continued)
• postincrement operator
• n++; can be used instead of n = n + 1;
• postdecrement operator
• n--; can be used instead of n = n - 1;
• preincrement operator
• ++n; can be used instead of n = n + 1;
• predecrement operator
• --n; can be used instead of n = n - 1;

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


Increment & Decrement Operators
(Continued)
• n++;++n and n--;--n are not equivalent in all
cases
• These operators as well as incrementing or
decrementing the variable also return a value.
i = n++;
• Value of i ? Is it the old value of n before it is
incremented or the new value after it is
incremented?

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


Increment & Decrement Operators
(Continued)
• Rule :
− postincrement or postdecrement operator
delivers the old value of the variable before
incrementing or decrementing the variable.
− A preincrement or predecrement operator
carries out the incrementation first and then
delivers the new value.
• n = 5 ; i = n++;  Give 5 to i and 6 to n
• n = 5 ; i = ++n; Give 6 to i and 6 to n.

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


Specialised Assignment Statements
• sum = sum + x;
can be represented in C++ by:
• sum += x;
• This notation can be used with the arithmetic
operators +, -, *, / and %.
• General form :
• variable op= expression
• which is interpreted as being equivalent to:
• variable = variable op ( expression )
C++ Programming: From Problem Analysis to Program Design, Fourth Edition 63
Specialised Assignment Statements
(Continued)

total += value; or total = total + value;

prod *= 10; or prod = prod * 10;


x /= y + 1; or x = x/(y + 1);
n %= 2; or n = n % 2;

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

You might also like