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

Chapter 2

Chapter 2 introduces C++ programming, highlighting its practicality, portability, and ability to access low-level functions. It covers the structure of a C++ program, including functions, variables, and data types, as well as common issues like the splash screen problem and how to handle console output. The chapter also discusses operators, including arithmetic and comparison operators, and provides examples of variable declaration and initialization.

Uploaded by

nedmacuacua88
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Chapter 2

Chapter 2 introduces C++ programming, highlighting its practicality, portability, and ability to access low-level functions. It covers the structure of a C++ program, including functions, variables, and data types, as well as common issues like the splash screen problem and how to handle console output. The chapter also discusses operators, including arithmetic and comparison operators, and provides examples of variable declaration and initialization.

Uploaded by

nedmacuacua88
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

CHAPTER 2

Introduction to C++
Why do we learn C++ Programming?
• C has been used successfully for every type of programming
problem imaginable from operating systems to spreadsheets to
expert systems - and efficient compilers are available for machines
ranging in power from the Apple Macintosh to the Cray
supercomputers.

• The largest measure of C's success seems to be based on purely


practical considerations including but not limited to:
• The portability of the compiler;
• The standard library concept;
• a powerful and varied repertoire of operators;
• an elegant syntax;
Why do we learn C++ Programming?
• C is often called a "Middle Level" programming language. This is not
a reflection on its lack of programming power but more a reflection
on its capability to access the system's low level functions.

• Most high-level languages (e.g. Java, C#) provides everything the


programmer might want to do already built into the language. A low
level language (e.g. assembler) provides nothing other than access
to the machines basic instruction set. C stands just in the middle of
these and can handle both ends effectively.
2:1

The Parts of a C++ Program


C++ Program
• Always remember that, a C program is a combination of functions.

• A function is the combination of a set of instructions to perform a


specific task.

• Every C language program contains at least one function (e.g. the


main function as it is the entry to the console applications).
The Parts of a C++ Program
// sample C++ program Single line Comment

preprocessor directive
#include <iostream> Include the contents of a standard input/output
header

using namespace std; Inject all the names of entities that exist in the
std namespace into the global namespace. Like cout,
cin, endl input/output header.
int main() The main function of a program where the execution
will start, int means that main function "returns"
{ an integer value, void means that main function does
not take an input.
cout << "Hello, there!"; Entire line called a statement. All statements must
end with a semicolon (;).Prints the string of
return 0; characters within quotes (" ").

} Every C language program must end with a return 0 to


tell the Operating System that the program finished
(terminated) successfully. The value 0(zero)
represents successful termination.

Curly brackets, used to indicate a function body.


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
Following the
Correct Syntax
• C/C++ is a compiler language, which
needs to recognize every single statement,
library and command in order to run.

• The statements on the right are going to be


a scaffold for all of the programs you are
going to write within this course content

• You will modify and put extra bits in each


program you write but the pattern you see
on the right would exist in each program
you write
Splash Screen Problems
• During your C programming practices, you might encounter a
difficulty in viewing the console output screen as the generated
C++ program would run the command prompt so fast that the
entire program would be executed in the blink of an eye.
• This is a generic problem in Windows Environment and often
referred to as the Splash Screen problem. The splash screen
particularly happens outside of Borland compilers and can be
solved by pausing the output screen meaning that until you enter a
character or press any key - the screen would be frozen. There are
multiple ways to solve this problem.
• One easy way of addressing this issue is using System(“Pause”);
statement.
Splash Screen Problems
System(“Pause”); creates problems
• While System(“Pause”); solves the splash screen problem to some
extent, the code is incredibly nasty and a Windows Specific
command.
• System(“Pause”); could cause more problems than it actually
solves.
• Additionally, it creates a backdoor in the application which might
allow your applications to be violated.
Splash Screen Problems
• Hence, we do not recommend the use of System(“Pause”); To
solve the Splash Screen problem, you can use the following two
statements: cin.ignore(); cin.get();
• These two statements would freeze the screen in a relatively
efficient way until you press a key on your keyboard. More
importantly, the statements given above are platform independent
and would work in any Operating Systems (OS)
2:2

Standard Output:
The cout Object
The cout Object
• cout is our standard output function and the monitor of a computer
is the standard output device.

• It displays output on the computer screen

• You use the stream insertion operator << to send output to cout:

cout << "Programming is fun!";


The cout Object
• Can be used to send more than one item to cout:

cout << "Hello " << "there!";


Or:

cout << "Hello ";


cout << "there!";

• This produces one line of output:

cout << "Programming is ";


cout << "fun!";
The cout Object
• The backslash (\) is called an escape character. It indicates that
cout is supported to do something out of the ordinary.
• When encountering a backslash in a string, the compiler looks
ahead at the next character and combines it with the backslash to
form an escape sequence.
• Some common escape sequences are as follows
Escape Sequence Description
\n Newline. Position the cursor at the beginning of the next line
\t Horizontal tab. Move the cursor to the next tab stop.
\a Alert. Sound the system bell
\\ Backslash. Insert a backslash character in a string
\” Double quote. Insert a double quote character in a string.
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!";
• You do NOT put quotation marks around endl

PS: The last character in endl is a lowercase L, not the number 1.


Class Exercise
Try printing the text “Hello World” using the various escape
sequences and the endl manipulator that applies.
2:3

The #include Directive


The #include Directive
• Inserts the contents of another file into the program
• This is a preprocessor directive, not part of C++ language
• #include lines not seen by compiler
• Do not place a semicolon at end of #include line
2:4

Variables and Literals


Variables
• A variable is a storage location which contains some known or
unknown quantity or information, particularly a value generated
during the run-time of the program.
• Has a name and a type of data it can hold
• Must be defined before it can be used:
int num;
• A variable name should represent the purpose of the variable.
• A variable is usually a non-constant value that changes during the
program according to the actions of the users.
• If a variable is initialized to a value by default and this never
changes throughout the run-time, the variable is called a Constant.
• In C/C++, the constant values are defined with const keyword
Variable Definition
• In order to use a variable in C++, we must first declare it specifying
which data type we want it to be.
• Variables are just a position in the memory (RAM) to which you can
give a name. Rather than using the address #A234DE987211, we
give the variable a name such as num
• The syntax to declare a new variable is to write the specifier of the
desired data type (like int, char, float...) followed by a valid variable
identifier.
Data Type Storage Size Detail
Int 2 or 4 bytes Integer
Float 4 bytes Floating point
Double 8 bytes Floating point
char 1 byte character
Variable Definition
• 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;
unsigned int area;
• Variables of different types must be in different definitions
Literals
• Literal: a value that is written into a program’s code.

"hello, there" (string literal)


12 (integer literal)
Literals

String
20 is an integer literal literals
2:5

Variable Initialization
Variable Assignments and Initialization
• Variables can be initialized (assigned an initial value) in their
definition or after definition
• The assignment statement uses the = operator to store a value in a
variable.
num1 = 12;
int num1 = 12, num2 = 5, area;
• This statement assigns the value 12 to the num variable.
• The variable receiving the value must appear on the left side of the
= operator.
• This will NOT work:

// ERROR!
12 = num1;
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; int
• The auto key word tells the compiler to determine the variable’s
data type from the initialization value.

auto interestRate= 12.0; double


auto stockCode = 'D’; char
auto customerNum = 459L long
2:6

Identifiers
Identifiers
• An identifier is a programmer-defined name for some part of a
program: variables, functions, etc.

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

Valid and Invalid Identifiers

IDENTIFIER VALID? REASON IF INVALID


totalSales Yes
total_Sales Yes
total.Sales No Cannot contain .
4thQtrSales No Cannot begin with digit
totalSale$ No Cannot contain $
C++ Key Words
Class Exercise
Declare, initialize and print out the values assigned to the variables
2:7

Integer Data Types


Integer Data Types
• Integer variables can hold whole numbers such as 12, 7, and -99
Integer Types in Program 2-10
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: 1234L

• 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


2:8

The char Data Type


The char Data Type
• Used to hold characters or very small integer values
• Character literals must be enclosed in single quote marks.
• Usually 1 byte of memory
• Numeric value of character from the character set is stored in
memory, it is calculated using the ascii code:
CODE: MEMORY:
char letter; letter
letter = 'C'; 67
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 l o \0
2:9

The C++ string Class


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;
The string class in Program 2-15
2 : 10

Floating-Point Data Types


Floating-Point Data Types
• The floating-point data types are:
float
double
long double

• They can hold real numbers such as:


12.45 -3.8

• Stored in a form similar to scientific notation

• All floating-point numbers are signed


Floating-Point Data Types
Floating-Point Literals
• Can be represented in
• Fixed point (decimal) notation:
31.4159 0.0000625
• E notation:
3.14159E1 6.25e-5
• Are double by default
• Can be forced to be float (3.14159f) or long double
(0.0000625L)
Floating-Point Data Types in Program 2-16
2 : 11

The bool Data Type


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

bool finished = false; 0


Boolean Variables in Program 2-17
2 : 12

Determining the Size of a


Data Type
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";
2 : 13

Scope
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
Class Exercise
Practice the different data types discussed
2 : 14

Operators
Arithmetic Operators
• Used for performing numeric calculations
• C++ has unary, binary, and ternary operators:
• unary (1 operand) -5
• binary (2 operands) 13 - 7
• ternary (3 operands) exp1 ? exp2 : exp3
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
Arithmetic Operators in Program 2-21
Comparison Operators
• Expressions are combinations of operators and their operands
which are used to modify the values of variables
• Equality & relational operators

Operator Expression Explanation


== x==y x is equal to y
!= x!=y x is not equal to y
> x>y x is greater than y
< x<y x is less than y
>= x>=y x is greater or equal to y
<= x<=y x is less or equal to y
Operators
Assignment operators
Assume: int c = 3, d = 5, e = 4, f = 6, g = 12

Operator Expression Explanation Answer


+= c+=7 c = c+7 10
-= d-=4 d = d-4 1
*= e*=5 e =e*5 20
/= f/=3 f =f/3 2
%= g%=9 g =g%9 3
Operators
Increment & decrement operators

Operator Expression Explanation


++ x++ Increment a by 1 then use the new value of a in
the expression.
++ ++x Use the current value of a in the expression, then
increment a by 1
-- x-- Decrement b by 1 then use the new value of b in
the expression.
-- --x Use the current value of b in the expression, then
decrement b by 1
Operators
Increment & decrement operators
Assume: int x = 3, y = 3, a = 9, b = 9

Operator Expression Explanation First Second


assignment assignment
++ a = x++ + 7 a = (x++) + 7 10 to a 4 to x
++ a = ++y + 7 a = (++y) + 7 4 to y 11 to a
-- a = x-- + 7 a = (x--) + 7 16 to a 8 to x
-- a = --y + 7 a = (--y) + 7 8 to y 15 to a
Operators A Closer Look at the %
A Closer Look at the / Operator
Operator • % (modulus) operator
• / (division) operator computes the remainder
performs integer division if resulting from integer
both operands are integers division
cout << 13 / 5; cout << 13 % 5; //
// displays 2 displays 3
• If either operand is floating
• % requires integers for both
point, the result is floating
point operands
cout << 13 / 5.0; cout << 13 % 5.0; //
// displays 2.6 error
2 : 15

Comments
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
Comments
Single Line Comments
• Begin with // through to the end of line:
int length = 12; // length in inches
// calculate rectangle area
area = length * width;
Comments
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 */
2 : 16

Named Constants
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 = 0.0675;
const int NUM_STATES = 50;
• Often named in uppercase letters
Named Constants in Program 2-28
Exercise 1
What is the output
of the program?
Exercises
Exercise 2:
• Write a complete C program that calculates and displays the
average of two numbers.
Exercise 3:
• Write a complete C program that calculates and displays the
product (multiplication) of 3 numbers.
Exercise 4:
• Write a complete C program for that calculates and displays the
addition of the squares of that two numbers
Questions??
Thank you for your time.

You might also like