Chapter 2 – Introduction to C++ Programming
Outline
2.2
First Program in C++: Printing a Line of Text
2.3
Modifying Our First C++ Program
2.4
Another C++ Program: Adding Two Integers
2.6
Arithmetic
2.7
Decision Making: Equality and Relational Operators
1
2.2 First Program in C++:
Printing a Line of Text
• Comments
–
–
–
–
Document programs
Improve program readability
Ignored by compiler
Single-line comment
Begin with //
• Preprocessor directives
– Processed by preprocessor before compiling
– Begin with #
Good Programming Practice 2.1
Every program should begin with a comment that describes the purpose of
the program, author, date and time.
2
2.2 First Program in C++:
Printing a Line of Text
• In <iostream> preprocessor file
cin
• Standard input stream
• Normally keyboard
cout
• Standard output stream
• Normally computer screen
cerr
• Standard error stream
• Display error messages
3
1
2
3
4
5
6
7
8
9
10
11
12
// Fig. 1.2: fig01_02.cpp
// A first program in C++.
#include <iostream>
// function main begins program execution
int main()
{
std::cout << "Welcome to C++!\n";
return 0;
// indicate that program ended successfully
} // end function main
Welcome to C++!
4
1
2
3
4
5
6
7
8
9
10
11
12
// Fig. 1.2: fig01_02.cpp
// A first program in C++.
#include <iostream>
5
Single-line comments.
// function main begins program execution
int main()
{
std::cout << "Welcome to C++!\n";
return 0;
// indicate that program ended successfully
} // end function main
Welcome to C++!
1
2
3
4
5
6
7
8
9
10
11
12
// Fig. 1.2: fig01_02.cpp
// A first program in C++.
#include <iostream>
6
Preprocessor directive to
include input/output stream
execution
header file <iostream>.
// function main begins program
int main()
{
std::cout << "Welcome to C++!\n";
return 0;
// indicate that program ended successfully
} // end function main
Welcome to C++!
#include<iostream> is a preprocessor directive that notifies the preprocessor
to include the contents of the input/output stream header file
•The file iostream must be included for any program that uses cin or cout
1
2
3
4
5
6
7
8
9
10
11
12
// Fig. 1.2: fig01_02.cpp
// A first program in C++.
Function main
#include <iostream>
7
returns an
integer value.
begins program
execution
Function
main appears
exactly once in every C++
program..
// function main
int main()
{
std::cout << "Welcome to C++!\n";
return 0;
// indicate that program ended successfully
} // end function main
Welcome to C++!
•Parenthesis after main indicate main is a program building block called a function.
•C++ programs contain one or more function, exactly one of which must be main.
•C++ programs begin executing at the function main.
•The function main returns an integer (int).
1
2
3
4
5
6
7
8
9
10
11
12
8
// Fig. 1.2: fig01_02.cpp
// A first program in C++.
#include <iostream>
// function main begins program execution
int main()
{
std::cout << "Welcome to C++!\n";
return 0;
Statements end with a
semicolon ;.
// indicate that program ended successfully
Stream insertion operator.
} // end function main
Welcome to C++!
Name cout belongs to
namespace std.
<< sends the stream of characters to the the standard output stream object,
std::cout (screen).
std::cout indicates we are using a “namespace” std.
Must include std:: before we use cout, cin, cerr, if we use <iostream>.
1
2
3
4
5
6
7
8
9
10
11
12
9
// Fig. 1.2: fig01_02.cpp
// A first program in C++.
#include <iostream>
// function main begins program execution
int main()
{
std::cout << "Welcome to C++!\n";
return 0;
// indicate that program ended successfully
} // end function main
Welcome to C++!
Keyword return is one of
several means to exit
function; value 0 indicates
program terminated
successfully.
return 0 is included at the end of every main function. It’s a way to
exit the function.
2.2 First Program in C++:
Printing a Line of Text
• Standard output stream object
– “Connected” to screen
std::cout
<<
• Stream insertion operator
• Value to right (right operand) inserted into output stream
• Namespace
std:: specifies using name that belongs to “namespace” std
std:: removed through use of using statements (shortcut)
• Escape characters
– \
– Indicates “special” character output
10
2.2 First Program in C++:
Printing a Line of Text
Escape Sequence
Description
\n
Newline. Position the screen cursor to the
beginning of the next line.
\t
Horizontal tab. Move the screen cursor to the next
tab stop.
\r
Carriage return. Position the screen cursor to the
beginning of the current line; do not advance to the
next line.
\a
Alert. Sound the system bell.
\\
Backslash. Used to print a backslash character.
\"
Double quote. Used to print a double quote
character.
11
1
2
3
4
5
6
7
8
9
10
11
12
13
12
// Fig. 1.4: fig01_04.cpp
// Printing a line with multiple statements.
#include <iostream>
// function main begins program execution
int main()
{
std::cout << "Welcome ";
std::cout << "to C++!\n";
return 0;
Multiple stream insertion
statements produce one line
of output.
// indicate that program ended successfully
} // end function main
Welcome to C++!
•Program does same thing as before
2.3
Modifying
Our First
C++
Program
1
2
3
4
5
6
7
8
9
10
11
12
13
// Fig. 1.5: fig01_05.cpp
// Printing multiple lines with a single statement
#include <iostream>
// function main begins program execution Using newline characters
print on multiple lines.
int main()
{
std::cout << "Welcome\nto\n\nC++!\n";
return 0;
to
// indicate that program ended successfully
} // end function main
Next line
Next line
Welcome
to
Next line (twice)
C++!
Good Programming Practice 2.3
Make the last character printed by a function a newline ( \n). This ensures
that the function will leave the screen cursor positioned at the beginning of
a new line.
#include <iostream>
using namespace std;
int main( )
{
char str[] = "Hello C++";
cout << "Value of str is : " << str << endl;
}
14
#include <iostream>
using namespace std;
int main( )
{
char str[] = "Unable to read....";
cerr << "Error message : " << str << endl;
}
When the above code is compiled and executed, it
produces the following result:
Error message : Unable to read....
15
2.4 Another C++ Program:
Adding Two Integers
• Variables (cannot begin with digit, case sensitive)
– Common data types
int - integer numbers
char - characters
double - floating point numbers
– Declare variables with name and data type before use
int integer1;
int integer2;
int sum;
The variable integer1 is an integer.
The variable integer2 is an integer.
The variable sum is an integer.
– Can declare several variables of same type in one declaration
• Comma-separated list
int integer1, integer2, sum;
Does the same as above.
16
2.4 Another C++ Program:
Adding Two Integers
• Input stream object
>> (stream extraction operator)
• Used with std::cin
• Waits for user to input value, then press Enter (Return) key
• Stores value in variable to right of operator
– Converts value to variable data type
=
(assignment operator)
• Assigns value to variable
• Binary operator (two operands)
• Example:
sum = variable1 + variable2;
17
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
18
// Fig. 1.6: fig01_06.cpp
// Addition program.
#include <iostream>
Single-line comments.
Preprocessor directive to
// function main begins program execution
include input/output stream
int main()
header file <iostream>.
{
int integer1; // first number to be input by user
main returns
an
int integer2; // Function
second number
to be input
by user
int sum;
// integer
variable
in which sum will be stored
value.
std::cout << "Enter first integer\n";
std::cin >> integer1;
// prompt
// read an integer
std::cout << "Enter second integer\n"; // prompt
std::cin >> integer2;
// read an integer
sum = integer1 + integer2;
// assign result to sum
std::cout << "Sum is " << sum << std::endl; // print sum
return 0;
// indicate that program ended successfully
} // end function main
These parts were common with the previous program.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
19
// Fig. 1.6: fig01_06.cpp
// Addition program.
#include <iostream>
// function main begins program execution
int main()
Declare integer variables.
{
int integer1; // first number to be input by user
int integer2; // second number to be input by user
int sum;
// variable in which sum will be stored
std::cout << "Enter first integer\n";
std::cin >> integer1;
// prompt
// read an integer
std::cout << "Enter second integer\n"; // prompt
std::cin >> integer2;
// read an integer
sum = integer1 + integer2;
// assign result to sum
std::cout << "Sum is " << sum << std::endl; // print sum
return 0;
// indicate that program ended successfully
} // end function main
Declaring variables (all integers).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
20
// Fig. 1.6: fig01_06.cpp
// Addition program.
#include <iostream>
// function main begins program execution
int main()
{
Use stream extraction
int integer1; // first number to be input by user
standard input
int integer2; // second number to operator
be inputwith
by user
to obtain
user input.
int sum;
// variable in whichstream
sum will
be stored
std::cout << "Enter first integer\n";
std::cin >> integer1;
// prompt
// read an integer
std::cout << "Enter second integer\n"; // prompt
std::cin >> integer2;
// read an integer
sum = integer1 + integer2;
// assign result to sum
std::cout << "Sum is " << sum << std::endl; // print sum
return 0;
// indicate that program ended successfully
} // end function main
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
21
// Fig. 1.6: fig01_06.cpp
// Addition program.
#include <iostream>
// function main begins program execution
int main()
{
int integer1; // first number to be input by user
int integer2; // second number to be input by user
int sum;
// variable in which sum will be stored
std::cout << "Enter first integer\n";
std::cin >> integer1;
// prompt
// read an integer
std::cout << "Enter second integer\n"; // prompt
Stream
std::cin >> integer2;
// read an integer
sum = integer1 + integer2;
// assign result to sum
manipulator
std::endl outputs a
newline, then “flushes output
buffer.”
std::cout << "Sum is " << sum << std::endl; // print sum
return 0;
// indicate that program ended successfully
} // end function main
Written as one line (or could have done in
three).
Concatenating, chaining or
cascading stream insertion
operations.
Enter first integer
45
Enter second integer
72
Sum is 117
22
2.6 Arithmetic
• Arithmetic calculations
+
addition
*
multiplication
/
division, integer division truncates remainder
7 / 5 evaluates to 1
%
modulus operator returns remainder
7 % 5 evaluates to 2
Common Programming Error 2.3
Attempting to use the modulus operator, % with non integer operands.
23
2.6 Arithmetic
• Rules of operator precedence
– Operators in parentheses evaluated first
• Nested/embedded parentheses
– Operators in innermost pair first
– Multiplication, division, modulus applied next
• Operators applied from left to right
– Addition, subtraction applied last
Operator(s)
Operation(s)
• Operators
applied fromOrder
leftoftoevaluation
right (precedence)
()
Parentheses
*, /, or %
Multiplication Division Evaluated second. If there are several, they re
Modulus
evaluated left to right.
+ or -
Addition
Subtraction
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If
there are several pairs of parentheses “on the same level”
(i.e., not nested), they are evaluated left to right.
Evaluated last. If there are several, they are
evaluated left to right.
24
2.6
Arithmetic
•
m=a+b+c/5
only c is divided by 5
•
m = (a + b + c) / 5
sum is divided by 5
•
y=m*x+b
Eq. for line, no parenthesis needed
•
y= 2 * 5 * 5 + 3 * 5+ 7
y = 72
Common Programming Error 2.4
Some programming languages use ** or ^ for exponentiation. C++ does not
support these operators.
Good Programming Practice 2.14
It’s acceptable to use unnecessary parenthesis to make an expression clearer.
Breaking a long expression into a sequence of smaller ones promotes clarity.
25
2.7 Decision Making: Equality and
Relational Operators
if structure
– Make decision based on truth or falsity of condition
• If condition met, body executed
• Else, body not executed
• Equality and relational operators
– Equality operators
• Same level of precedence
– Relational operators
• Same level of precedence
– Associate left to right
26
2.7 Decision Making: Equality and
Relational Operators
Sta nd a rd a lg eb ra ic
eq ua lity op era tor or
rela tiona l op era tor
C++ eq ua lity
or rela tiona l
op era tor
Exa m p le
of C++
c ond ition
Mea ning of
C++ c ond ition
>
>
x > y
x is greater than y
<
<
x < y
x is less than y
>=
x >= y
x is greater than or equal to y
<=
x <= y
x is less than or equal to y
=
==
x == y
x is equal to y
!=
x != y
x is not equal to y
Relational operators
Equality operators
27
2.7 Decision Making: Equality and
Relational Operators
Common Programming Error 2.5
Syntax error occurs when ==, >=, etc. appear with spaces between symbols.
Common Programming Error 2.6
Reversing the order of the pair of symbols, >=, <=, !=.
Common Programming Error 2.7
Confusing the equality operator == with the assignment operator =.
==
“is equal to”
=
“is assigned the value to”
28
2.7 Decision Making: Equality and
Relational Operators
using statement
– Eliminate use of std:: prefix
– Writing using std::cout allows the program to use cout
instead of std::cout
29
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
30
// Fig. 1.14: fig01_14.cpp
// Using if statements, relational
// operators, and equality operators.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
// program uses cout
// program uses cin
// program uses endl
using statements eliminate
need for std:: prefix.
// function main begins program execution
int main()
{
Can write
cout
cin
int num1; // first number
to be
readand
from
user
without
std::
prefix.
int num2; // second number to be read from user
cout << "Enter two integers, and I will tell you\n"
<< "the relationships they satisfy: ";
cin >> num1 >> num2;
// read two integers
if ( num1 == num2 )
cout << num1 << " is equal to " << num2 << endl;
if ( num1 != num2 )
cout << num1 << " is not equal to " << num2 << endl;
using statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Fig. 1.14: fig01_14.cpp
// Using if statements, relational
// operators, and equality operators.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
// program uses cout
// program uses cin
// program uses endl
variables.
// function main begins programDeclare
execution
int main()
{
int num1; // first number to be read from user
int num2; // second number to be read from user
cout << "Enter two integers, and I will tell you\n"
<< "the relationships they satisfy: ";
cin >> num1 >> num2;
// read two integers
if ( num1 == num2 )
cout << num1 << " is equal to " << num2 << endl;
if ( num1 != num2 )
cout << num1 << " is not equal to " << num2 << endl;
31
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
32
// Fig. 1.14: fig01_14.cpp
// Using if statements, relational
// operators, and equality operators.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
// program uses cout
// program uses cin
// program uses endl
// function main begins program execution
int main()
{
int num1; // first number to be read from user
if structure compares values
int num2; // second number to be read from user
of num1 and num2 to test for
equality.and I will tell you\n"
integers,
cout << "Enter two
<< "the relationships they satisfy: ";
If condition
cin >> num1 >> num2;
// read two integers
is true (i.e.,
values are equal), execute this
statement.
if ( num1 == num2 )
cout << num1 << " is equal to " << num2 << endl;
if ( num1 != num2 )
cout << num1 << " is not equal to " << num2 << endl;
if structure compares values
of num1 and num2 to test for
inequality.
If condition is true (i.e.,
values are not equal), execute
this statement.
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
33
if ( num1 < num2 )
cout << num1 << " is less than " << num2 << endl;
if ( num1 > num2 )
cout << num1 << " is greater than " << num2 << endl;
if ( num1 <= num2 )
cout << num1 << " is less than or equal to "
<< num2 << endl;
if ( num1 >= num2 )
cout << num1 << " is greater than or equal to "
<< num2 << endl;
return 0;
// indicate that program ended successfully
} // end function main
Enter two integers, and I will tell you
the relationships they satisfy: 22 12
22 is not equal to 12
22 is greater than 12
22 is greater than or equal to 12
Statements may be split over
several lines.
2.7 Decision Making: Equality and
Relational Operators
Good Programming Practice 2.16
Indent the statement in the body of an if statement to enhance readability.
Good Programming Practice 2.19
Check operator preference when writing expressions with many operators.
Common Programming Error 2.8
Placing a ; in an if statement. This is a logic error. It causes the body of an if structure
to be empty, giving incorrect results.
34
Summary
C++ statements
Arithmetic
Operators
Relational
Equality
Operators
<<
+
>
>>
-
<
if
*
>=
int
/
<=
main
%
==
//
#include<iostream>
std::cin
Writing clear and
understandable
programs
!=
std::cout
std::cerr
std::endl
using
35
© Copyright 2026 Paperzz