[go: up one dir, main page]

0% found this document useful (0 votes)
7 views82 pages

PF Lecture 2

The document serves as an introduction to C++ programming, covering fundamental concepts such as input/output, operators, and data types. It explains the structure of a C++ program, including functions, variables, and the use of comments and whitespace for readability. Additionally, it discusses arithmetic operations, variable declarations, and provides examples of simple C++ programs.

Uploaded by

graved250
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)
7 views82 pages

PF Lecture 2

The document serves as an introduction to C++ programming, covering fundamental concepts such as input/output, operators, and data types. It explains the structure of a C++ program, including functions, variables, and the use of comments and whitespace for readability. Additionally, it discusses arithmetic operations, variable declarations, and provides examples of simple C++ programs.

Uploaded by

graved250
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/ 82

Introduction to C++

Programming, Input/Output
and Operators
C++ How to Program, 10/e

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.1 Introduction
We now introduce C++ programming, which
facilitates a disciplined approach to program
development.
Most of the C++ programs you’ll study in this book
process data and display results.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.2 First Program in C++: Printing a Line
of Text
Simple program that prints a line of text (Fig. 2.1).

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.2 First Program in C++: Printing a Line
of Text (cont.)
// indicates that the remainder of each line is a
comment.
◦ You insert comments to document your programs and to
help other people read and understand them.
◦ Comments are ignored by the C++ compiler and do not
cause any machine-language object code to be generated.
A comment beginning with // is called a single-line
comment because it terminates at the end of the
current line.
You also may use comments containing one or more
lines enclosed in /* and */.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.2 First Program in C++: Printing a Line
of Text (cont.)
A preprocessing directive is a message to the C++
preprocessor.
Lines that begin with # are processed by the
preprocessor before the program is compiled.
#include <iostream> notifies the preprocessor to
include in the program the contents of the
input/output stream header file <iostream>.
◦ This header is a file containing information used by the
compiler when compiling any program that outputs data to
the screen or inputs data from the keyboard using
C++-style stream input/output.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.2 First Program in C++: Printing a Line
of Text (cont.)
You use blank lines, space characters and tab
characters (i.e., “tabs”) to make programs easier to
read.
◦ Together, these characters are known as white space.
◦ White-space characters are normally ignored by the
compiler.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.2 First Program in C++: Printing a Line
of Text (cont.)
main is a part of every C++ program.
The parentheses after main indicate that main is a program
building block called a function.
C++ programs typically consist of one or more functions and
classes.
Exactly one function in every program must be named main.
C++ programs begin executing at function main, even if main
is not the first function defined in the program.
The keyword int to the left of main indicates that main
“returns” an integer (whole number) value.
◦ A keyword is a word in code that is reserved by C++ for a specific
use.
◦ For now, simply include the keyword int to the left of main in each
of your programs.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.2 First Program in C++: Printing a Line
of Text (cont.)
A left brace, {, must begin the body of every function.
A corresponding right brace, }, must end each function’s
body.
A statement instructs the computer to perform an
action.
Together, the quotation marks and the characters
between them are called a string, a character string or a
string literal.
We refer to characters between double quotation marks
simply as strings.
◦ White-space characters in strings are not ignored by the
compiler.
Most C++ statements end with a semicolon (;), also
known as the statement terminator.
◦ Preprocessing directives (like #include) do not end with a
semicolon.
©1992-2017 by Pearson Education, Inc. All Rights Reserved.
2.2 First Program in C++: Printing a Line
of Text (cont.)
Typically, output and input in C++ are accomplished with
streams of data.
When a cout statement executes, it sends a stream of
characters to the standard output stream
object—std::cout—which is normally “connected” to the
screen.
The std:: before cout is required when we use names that
we’ve brought into the program by the preprocessing
directive #include <iostream>.
◦ The notation std::cout specifies that we are using a name, in this
case cout, that belongs to “namespace” std.
◦ The names cin (the standard input stream) and cerr (the standard
error stream) also belong to namespace std.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.2 First Program in C++: Printing a Line
of Text (cont.)
In the context of an output statement, the <<
operator is referred to as the stream insertion
operator.
◦ The value to the operator’s right, the right
operand, is inserted in the output stream.
The characters \n are not printed on the screen.
The backslash (\) is called an escape character.
◦ It indicates that a “special” character is to be output.
When a backslash is encountered in a string of
characters, the next character is combined with
the backslash to form an escape sequence.
The escape sequence \n means newline.
◦ Causes the cursor to move to the beginning of the next
line on the screen.
©1992-2017 by Pearson Education, Inc. All Rights Reserved.
2.2 First Program in C++: Printing a Line
of Text (cont.)
When the return statement is used at the end of
main the value 0 indicates that the program has
terminated successfully.
According to the C++ standard, if program
execution reaches the end of main without
encountering a return statement, it’s assumed
that the program terminated successfully—exactly
as when the last statement in main is a return
statement with the value 0.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.3 Modifying Our First C++ Program

Welcome to C++! can be printed several ways.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.3 Modifying Our First C++ Program
(cont.)
A single statement can print multiple lines by using
newline characters.
Each time the \n (newline) escape sequence is
encountered in the output stream, the screen cursor
is positioned to the beginning of the next line.
To get a blank line in your output, place two newline
characters back to back.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.4 Another C++ Program: Adding
Integers
The next program obtains two integers typed by a
user at the keyboard, computes their sum and
outputs the result using std::cout.
Figure 2.5 shows the program and sample inputs
and outputs.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.4 Another C++ Program: Adding
Integers (cont.)
Declarations introduce identifiers into programs.
The identifiers number1, number2 and sum are the
names of variables.
A variable is a location in the computer’s memory where
a value can be stored for use by a program.
Variables number1, number2 and sum are data of type
int, meaning that these variables will hold integers
(whole numbers such as 7, –11, 0 and 31914).

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.4 Another C++ Program: Adding
Integers (cont.)
Lines 8–10 initialize each variable to 0 by placing a value
in braces ({ and }) immediately following the variable’s
name
◦ Known as list initialization
◦ Introduced in C++11
Previously, these declarations would have been written
as:
◦ int number1 = 0;
◦ int number2 = 0;
◦ int sum = 0;

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.4 Another C++ Program: Adding
Integers (cont.)
All variables must be declared with a name and a data
type before they can be used in a program.
If more than one name is declared in a declaration (as
shown here), the names are separated by commas (,);
this is referred to as a comma-separated list.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.4 Another C++ Program: Adding
Integers (cont.)
Data type double is for specifying real numbers, and
data type char for specifying character data.
Real numbers are numbers with decimal points, such as
3.4, 0.0 and –11.19.
A char variable may hold only a single lowercase letter,
a single uppercase letter, a single digit or a single special
character (e.g., $ or *).
Types such as int, double and char are called
fundamental types.
Fundamental-type names are keywords and therefore
must appear in all lowercase letters.
Appendix C contains the complete list of fundamental
types.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.4 Another C++ Program: Adding
Integers (cont.)
A variable name is any valid identifier that is not a
keyword.
An identifier is a series of characters consisting of
letters, digits and underscores ( _ ) that does not
begin with a digit.
C++ is case sensitive—uppercase and lowercase
letters are different, so a1 and A1 are different
identifiers.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.4 Another C++ Program: Adding
Integers (cont.)
Declarations of variables can be placed almost
anywhere in a program, but they must appear before
their corresponding variables are used in the
program.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.4 Another C++ Program: Adding
Integers (cont.)
A prompt it directs the user to take a specific action.
A cin statement uses the input stream object cin
(of namespace std) and the stream extraction
operator, >>, to obtain a value from the keyboard.
Using the stream extraction operator with
std::cin takes character input from the standard
input stream, which is usually the keyboard.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.4 Another C++ Program: Adding
Integers (cont.)
When the computer executes an input statement that
places a value in an int variable, it waits for the user to
enter a value for variable number1.
The user responds by typing the number (as characters)
then pressing the Enter key (sometimes called the Return
key) to send the characters to the computer.
The computer converts the character representation of the
number to an integer and assigns (i.e., copies) this number
(or value) to the variable number1.
Any subsequent references to number1 in this program
will use this same value.
Pressing Enter also causes the cursor to move to the
beginning of the next line on the screen.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.4 Another C++ Program: Adding
Integers (cont.)
In this program, an assignment statement adds the
values of variables number1 and number2 and
assigns the result to variable sum using the
assignment operator =.
◦ Most calculations are performed in assignment
statements.
The = operator and the + operator are called binary
operators because each has two operands.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.4 Another C++ Program: Adding
Integers (cont.)
std::endl is a so-called stream manipulator.
The name endl is an abbreviation for “end line” and
belongs to namespace std.
The std::endl stream manipulator outputs a
newline, then “flushes the output buffer.”
◦ This simply means that, on some systems where outputs
accumulate in the machine until there are enough to “make
it worthwhile” to display them on the screen, std::endl
forces any accumulated outputs to be displayed at that
moment.
◦ This can be important when the outputs are prompting the
user for an action, such as entering data.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.4 Another C++ Program: Adding
Integers (cont.)
Using multiple stream insertion operators (<<) in a
single statement is referred to as concatenating,
chaining or cascading stream insertion operations.
Calculations can also be performed in output
statements.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.5 Memory Concepts
Variable names such as number1, number2 and sum
actually correspond to locations in the computer’s
memory.
Every variable has a name, a type, a size and a value.
When a value is placed in a memory location, the
value overwrites the previous value in that location;
thus, placing a new value into a memory location is
said to be destructive.
When a value is read out of a memory loca-tion, the
process is nondestructive.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.6 Arithmetic
Most programs perform arithmetic calculations.
Figure 2.9 summarizes the C++ arithmetic operators.
The asterisk (*) indicates multiplication.
The percent sign (%) is the remainder operator.
◦ Yields the remainder after integer division.
◦ Can be used only with integer operands.
The arithmetic operators are all binary operators.
Integer division (i.e., where both the numerator and the
denominator are integers) yields an integer quotient.
◦ Any fractional part in integer division is discarded (i.e.,
truncated)—no rounding occurs.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.6 Arithmetic (cont.)
Arithmetic expressions in C++ must be entered into
the computer in straight-line form.
Expressions such as “a divided by b” must be
written as a / b, so that all constants, variables and
operators appear in a straight line.
Parentheses are used in C++ expressions in the
same manner as in algebraic expressions.
For example, to multiply a times the quantity b + c
we write
◦a * ( b + c )

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.6 Arithmetic (cont.)
C++ applies the operators in arithmetic expressions
in a precise sequence determined by the following
rules of operator precedence, which are generally
the same as those followed in algebra.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.6 Arithmetic (cont.)
There is no arithmetic operator for exponentiation
in C++, so x2 is represented as x * x.
Figure 2.11 illustrates the order in which the
operators in a second-degree polynomial are
applied.
As in algebra, it’s acceptable to place redundant
parentheses in an expression to make the
expression clearer.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


Example: Quadratic Equation

#include<iostream> g++ quadratic.cpp


#include<cmath>
int main() {
double b, c;
a
std::cin >> b >> c; // input coefficients -3.0 2.0
// Calculate roots of x*x + b*x + c. 2 1
double discriminant = b*b - 4.0*c;
double d = sqrt(discriminant);
a
double root1 = (-b + d) / 2.0;
double root2 = (-b - d) / 2.0;
-1.0 -1.0
// Print them out. 1.61803 -0.618034
std::cout << root1 << " " << root2 << std::endl;
}
Data types

A data type is set of values and set of operations on


those values.
type set of values examples of values examples of operations
17
int integers add, subtract, divide, multiply
12345
3.14159
double floating-point numbers add, subtract, divide, multiply
7.034e23
'a'
char characters compare
'$'
"Hello World!"
std::string sequence of characters concatenate
"C++ is fun"
true
bool truth values and, or, not
false
Other built-in numeric types
Group Type names* Notes on size / precision Usual size (in bytes)

char Exactly one byte in size. At least 8 bits. 1

char16_t Not smaller than char. At least 16 bits. 2


Character types
char32_t Not smaller than char16_t. At least 32 bits. 4

wchar_t Can represent the largest supported character set. 2 / 4

signed char Same size as char. At least 8 bits. 1

signed short int Not smaller than char. At least 16 bits. 2

Integer types (signed) signed int Not smaller than short. At least 16 bits. 4

signed long int Not smaller than int. At least 32 bits. 4 / 8

signed long long int Not smaller than long. At least 64 bits. 8

unsigned char
unsigned short int
Integer types (unsigned) unsigned int (same size as their signed counterparts)
unsigned long int
unsigned long long int
float 4
Floating-point types double Precision not less than float 8
long double Precision not less than double 16
Signed Numbers
signed numbers as two's complement integer
▪ One’s Complement
● Invert all bits from 1 to 0 and 0 to 1
e.g. Number = 01100101
1’s Complement 10011010
▪ Add 1 in one’s complement
10011010
1
------------------
10011011
Signed Numbers
signed numbers as two's complement integer
C++ standard library
#include <cmath>

double fabs(double a) absolute value of a


double fmax(double a, double b) maximum of a and b

double fmin(double, double) minimum of a and b


double sin(double theta) sine function
double cos(double theta) cosine function
double tan(double theta) tangent function
double exp(double a)
double log(double a)
double pow(double a, double b)
long lround(double a) round to the nearest integer
double sqrt(double a) square root of a
2.7 Decision Making: Equality and
Relational Operators
The if statement allows a program to take alternative
action based on whether a condition is true or false.
◦ If the condition is true, the statement in the body of the if
statement is executed.
◦ If the condition is false, the body statement is not executed.
Conditions in if statements can be formed by using the
equality operators and relational operators (Fig. 2.12).
The relational operators all have the same level of
precedence and associate left to right.
The equality operators both have the same level of
precedence, which is lower than that of the relational
operators, and associate left to right.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.7 Decision Making: Equality and
Relational Operators (cont.)
Fig. 2.12 uses six if statements to compare two
numbers input by the user.
If the condition in any of these if statements is
satisfied, the output statement associated with that
if statement executes.
Figure 2.13 shows the program and the
input/output dialogs of three sample executions.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.7 Decision Making: Equality and
Relational Operators (cont.)
using declarations eliminate the need to repeat the
std:: prefix.
◦ Can write cout instead of std::cout, cin instead of std::cin
and endl instead of std::endl, respectively, in the remainder of
the program.
Many programmers prefer to use the declaration
using namespace std;
which enables a program to use all the names in any
standard C++ header file (such as <iostream>) that a
program might include.
From this point forward in the book, we’ll use the
preceding declaration in our programs.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.7 Decision Making: Equality and
Relational Operators (cont.)
Each if statement in Fig. 2.13 has a single statement
in its body and each body statement is indented.
Each if statement’s body is enclosed in a pair of
braces, { }, creating what’s called a compound
statement or a block that may contain multiple
statements.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.7 Decision Making: Equality and
Relational Operators (cont.)
Statements may be split over several lines and may
be spaced according to your preferences.
It’s a syntax error to split identifiers, strings (such as
"hello") and constants (such as the number 1000)
over several lines.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


2.7 Decision Making: Equality and
Relational Operators (cont.)
Figure 2.14 shows the precedence and associativity
of the operators introduced in this chapter.
The operators are shown top to bottom in
decreasing order of precedence.
All these operators, with the exception of the
assignment operator =, associate from left to right.

©1992-2017 by Pearson Education, Inc. All Rights Reserved.


Example of computing with bool: leap year test
Q. Is a given year a leap year?
A. Yes if either (i) divisible by 400 or (ii) divisible by 4 but not 100.
#include<iostream>

int main() {
int year;
std::cin >> year;
bool isLeapYear;

// divisible by 4 but not 100


isLeapYear = (year % 4 == 0) && (year % 100 != 0);

// or divisible by 400
isLeapYear = isLeapYear || (year % 400 == 0); enable printing of bool
values as true/false
instead on 1/0
std::cout << std::boolalpha << isLeapYear;
}
Data type for computing with strings: std::string

values sequence of characters1


character interpretation depends
typical literals2 "Hello, " "1 " " * " on the context
operations concatenation std::string s; // create
operators + empty string
1
infinite many possible values
2
std::string can be constructed
from these literals

Examples of std::string operations


(concatenation)

std::string s1 { "Hello, " };


std::string s2 { s1 + "ITP class" };
std::string s3 = s2 + '\n';
std::cout << s3;

You might also like