E-Book
C++Introduction to
Programming
WAN ANISHA WAN MOHAMMAD AZLINA MOHD MYDIN
INTRODUCTION TO C++ FOR BEGINNERS PAGE
1
TABLE OF CONTENT 17
CHAPTER 1 46
Introduction to Computer Programs
CHAPTER 2 61
Basic Elements of a Computer Program
74
CHAPTER 3 91
Selection Control Structure 102
128
CHAPTER 4 138
Repetition Control Structure
CHAPTER 5
Functions
CHAPTER 6
Arrays
EXERCISES
LAB EXERCISES
DISCUSSIONS
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 1
CHAPTER 1
INTRODUCTION TO COMPUTER PROGRAMS
Chapter Outline
1. Overview of Computers
- A brief overview of the history of computers
- Definition of Computer
- Categories of computer
- The basic operations of a computer
- Computer systems
2. Computers and Programming Languages
- The language of a computer
- Types of programming languages
3. Introduction to Programming
- Differences between software, programs and programmin
- The importance of computer programming
- The importance of writing a good program
- C++ relationship between programs, compiler, interpreter and assembler
4. Program Development Life Cycle
› Analysis, design, implementation and coding, testing and debugging, maintenance
At the end of this chapter, student should be able to:
i. Understand the concept and importance of program and programming
ii. Differentiate between compiler, program, interpreter and assembler
iii. Apply the steps in program development life cycle.
1. Overview of Computers
1.1 A Brief Overview Of The History Of Computers
› The history of computers started in the 19th century with the invention of the first general
purpose computing device.
› In the 20th century, early analogue computers were invented while computers for the
average consumer emerged in 1985.
› The first personal computer with a graphical user interface was introduced in 1983.
1|Page
INTRODUCTION TO C++ FOR BEGINNERS
1.2 Definition of Computer
› A computer is an electronic device, with its own memory, capable of performing
computations and making logical decisions at speeds faster than human beings.
› An electronic machine, operating under the control of instructions stored in its own memory
1.3 Categories of Computers
› Many types of computers are available in the market.
› Several types of computers can be found such as huge computers (supercomputers and
mainframes), table-sized computers (desktop PCs), small computers which can fit on a
person’s lap (laptops) or palm of one’s hand (palmtop), and also mobile computers such as
tablets and smartphones.
› Embedded computers are built with computer chips and software into household equipment
such as washing machines, televisions and microwaves.
1.4 The Basic Operations of a Computer
INPUT • Accepting data from user
PROCESS • Manipulating data
OUTPUT • Producing results
STORAGE • Storing results
› These operations are under the control of instructions stored in the computer’s memory
1.5 Computer Systems
COMPUTER
HARDWARE SOFTWARE CHAPTER 1
The electric, electronic The series of instructions that
and mechanical equipment tells the computer hardware
that makes up a computer how to perform task
2|Page
INTRODUCTION TO C++ FOR BEGINNERS
2. Computers and Programming Languages
2.1 The Language of a Computer
› Digital signals are sequences of 0s and 1s
› Machine language: language of a computer
• Binary code: A sequence of 0s and 1s
• Bits: also knowns as binary digits which are 0 and 1
• Byte: A sequence of eight bits
2.2 Types of Programming Language
2.2.1 Low-level Language
› Low level Languages are the languages that are machine dependent are known as
low level languages.
› Example: Machine Language, Assembly language.
a) Machine Language
› Early computers were programmed in machine language
› To calculate area = length * width in machine language:
100100 010001 // Load
100110 010010 // Multiply
100010 010011 // Store
b)Assembly Language
› Assembly language instruction are mnemonic (use code, easier to remember)
› Assembler: translates a program written in assembly language into machine
language
ASSEMBLY LANGUAGE MACHINE LANGUAGE
•LOAD •100100
•STOR •100010
•MULT •100110
•ADD •100101
•SUB •100011
CHAPTER 1
2|Page
INTRODUCTION TO C++ FOR BEGINNERS
2.2.2 High –level Language
› High level languages are the languages that are machine independent.
› In this level, instructions are quite English-like and a single instruction can be
written to correspond to many operations at the machine level.
› High-level languages include Basic, FORTRAN, COBOL, Pascal, C++, C, and Java
› Compiler: translates a program written in a high-level language machine language
› The equation area = length x width can be written in C++ as:
area = length * width;
3. Introduction to Programming
3.1 Differences between Software, Programs and Programming
› A program is a set of instructions that tells the computer how to solve a problem or perform
a task.
› A program is like a recipe. It contains a list of ingredients (variables) and a list of directions
(statements) that tell the computer what to do with the variables.
› A program can be as short as one line of code, or as long as several millions lines of code.
› Computer process data under the control of sets of instructions called computer program.
› A computer program is a set of detailed directions telling the computer exactly what to do,
one step at a time. Computer programs guide the computer through orderly sets of actions
specified by computer programmers.
What is programming?
› A programming is designing and writing a computer program.
› The programmer must decide what the program needs to do, develop the logic of how to do
it, and write instructions for the computer in a programming language that the computer can
translate into its own language and execute.
Software System Program
Collection of programs to Application or collections of Set of instructions to solve
perform operations programs to solve problems problems
Example: DEV C++ is used to Example: A student registration Example: Program to
write programs using the C++ ststem consists of programs to calculate the area of a room CHAPTER 1
programming language register subjects, groups, etc.
3|Page
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 1
3.2 The Importance of Computer Programming
› More design freedom, easier to modify and duplicate; able to debug, re-boot, backup and try
various types of designs.
› The ability to perform difficult tasks without making human-type errors (lack of focus, energy,
attention or memory)
› The capability in performing extended tasks at greater serial speeds than conscious human
thought.
› The human brain cannot be duplicated or "re-booted," and has already achieved
"optimization" through design by evolution, making it difficult to further improve.
› The human brain does not physically integrate well, externally or internally, with current
hardware and software.
› The non-existence of "boredom" when performing repetitive tasks.
3.3 The Importance of Writing a Good Program
› Some people consider Computer Programming as an Art which must follow certain standards
in order to promote program clarity, readability, and comprehension so as to produce
programs that are easier to read, test, debug, modify, and maintain.
› Standards that have been emphasize by most of the programmers are:
i. Names for variables, types and functions.
ii. Indent style and spacing.
3.3.1 Names For Variables, Types and Functions
› Choosing an appropriate variable names is seen as the basis for good style
programming
› The following are some rules that can be used when naming variables, types and
functions:
i. Function names will start with a lower case letter.
• Example: double averageMark (double, double);
ii. Variable names start with a lower case letter and the length must not be more
than 40 characters.
iii. Constant names can be all capital letters.
• Example: const int MAX_SIZE = 10.
4|Page
INTRODUCTION TO C++ FOR BEGINNERS
3.3.2 Indent Style And Spacing
› In order to improve its readability in programming, indentation is used to format
program source code.
› Adding spaces in between sentence makes your program much more readable.
› A new level of indentation should be used at every level of statement nesting in
your program.
› The minimum number of spaces at each indentation should be at least 3, and many
programmers use a tab mark (typically 8 spaces).
Style 1Comparison
Style 2
if (marks > 50)
{ if(marks>50){return PASS;}
else{return FAIL;}
return PASS;
}
else
{
return FAIL;
}
* Style 1 is much easier to read because they are indented well, and logical blocks of
code are grouped and displayed together more clearly.
3.4 C++ Relationship between Programs, Compiler, Interpreter and Assembler
› All programs have to be translated into machine code (0s and 1s) before the computer can
actually run them.
› This is because computer are not able to read program which is written in human language.
Program •Both compiler and interpreter are used to
translate high level language to machine code
Compiler •translate instructions all at one time
Interpreter •translate instructions one at a time
Assembler •translate assembly language to machine code
CHAPTER 1
5|Page
INTRODUCTION TO C++ FOR BEGINNERS
3.4.1 Interpreter
› A computer program that translates and executes a program written in a high- level
language
› Translates the source program, instruction by instruction, each time that program
is run.
› An interpreter translates program statements one at a time.
› Interpreters are helpful during the debugging stage, but are slower during
execution of the finished program.
3.4.2 Compiler
› A computer program that translates programs written in a high-level language into
machine code.
› Translates each high-level instruction into several machine-code instructions all at
once time.
› Compiler runs much faster than an interpreted program.
3.4.3 Assembler
› An assembler consists of little more than a table look up routine, where each word
of the source language (assembly language ) is looked up in a table for its numerical
equivalent, which is then output as part of the target language program.
› Assembly language generally gives the programmer precise and direct access to
every capability of the computer hardware.
4. Program Development Life Cycle
4.1 Problem Solving Phases
To be a good programmer, you must be a good problem solver. CHAPTER 1
To be a good problem solver, you must understand a problem in a methodical way,
from initial inspection and definition to final solution.
› Creating new program is called program development
› The process associated with creating successful applications programs is called the Program
Development Life Cycle (PDLC).
6|Page
INTRODUCTION TO C++ FOR BEGINNERS
› There are 5 steps to Program Development Life Cycle:
Analysis Design Implementation/ Testing/ Program
Coding Debugging Maintenance
4.2 Analysis CHAPTER 1
› Done by reviewing the program specifications
• Eliminate ambiguities in the problem statement.
• Other criteria must be identified especially the data that will be used as input, process
involve and output that will be produced.
› Indicating what the new system should do
› In this step, the objectives, outputs, inputs, and processing requirements are determined.
› The program objectives are the problems that you are trying to solve.
Example: Calculate the area of a room
o Output: area
o Input: length, width
o Process: area=length*width
4.3 Design
› Develop a series of steps with a logical order which, when applied would produce the output
of the problem.
› Good program design is very important in order to make the development process run
smoothly, as well as to make future revisions easier.
› In program design step, a solution is created using structured programming techniques such
as algorithm which consist of pseudocode and flowchart.
4.3.1 Algorithm
Programmer’s Algorithm is a systematic method that will make you a good
problem solver and therefore a good programmer.
7|Page
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 1
› A step-by-step problem solving process in which a solution is arrived at a finite
amount of time.
› Algorithm is a procedure or formula for solving a problem.
› A computer program can be viewed as an elaborate algorithm. In mathematics and
computer science, an algorithm usually means a small procedure that solves a
repeated problem. (Source: Whatis.com)
› An algorithm must satisfy some requirements which are:
• Unambiguousness (clear)
• Generality (unspecific)
• Correctness
• Finiteness (limitation)
Pseudocode
Types of Algorithm
Flow Chart
a) Pseudocode
› Is a semiformal, English like language with a limited vocabulary that can be used to
design and describe algorithms.
› Each pseudo code statement includes keywords that describe operations and some
appropriate English like description of operands.
› Each pseudo code statement should be written on a separate line.
› The statements that make up a sequence control structure should begin with clear
words such as compute, set and initialize.
› For the selection control structure use an if-else/ switch statement.
› For repetition control structure use the for/ while/ do..while statement
and indent the loop body.
› All words in a pseudo code statement must be clear and as easy as possible for
nonprogrammers to understand.
8|Page
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 1
Example: Sequential Control Structure
› Calculate the area of a room
BEGIN
DECLARE int length,width; double area
READ length, width
CALCULATE area = length * width
DISPLAY area
END
Example: Selection Control Structure
› Find the maximum of three numbers
BEGIN
DECLARE int num1,num2,num3,maximum
GET num1,num2,num3
IF (num1>=num2 && num1>=num3)
maximum=num1
ELSE IF (num2>=num1 && num2>=num3)
maximum=num2
ELSE IF (num3>=num1 && num3>=num2)
maximum=num3
DISPLAY maximum
END
Example: Repetition Control Structure
› Get and display 10 students marks
BEGIN
DECLARE int stu; double marks
INITIALIZE stu=1
WHILE (stu<=10)
GET marks
stu++
DISPLAY marks
END
9|Page
INTRODUCTION TO C++ FOR BEGINNERS
b) Flow Chart
› A graphic presentation of the detailed logical sequence of steps needed to solve
programming problems.
› Uses geometric symbols and familiar relational operators to provide a graphic
display of the sequence of steps involved in a program.
› The steps in a flowchart follow each other in the same logical sequence as their
corresponding program statements will follow in a program.
› Different symbols are used to represent different actions, such as start/stop,
decision, input/output, processing, and looping symbols.
Symbol Name Description
Flowline To connect symbols and indicate the flow of logic
Terminal Used to represent the beginning (Start) or the end
Input/Output (End) of a program
Used for input and output operations, such as reading
Processing and printing.
Decision Used for arithmetic and data manipulation
operations.
Connector Used for any logic or comparisons operations.
Offpage This symbol has one entry and two exit paths.
Connector The path chosen depend on whether the answer to
question is “yes” or “no”
Used to join different flowlines
Used to indicate that the flowchart continues to next
page
CHAPTER 1
10 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS
Example: Sequential Control Structure
› Calculate the area of a room
Start
DECLARE double area; int length; width
GET length,width
CALCULATE
area=length*width
DISPLAY area
End
Example: Selection Control Structure
› Find the maximum of three numbers
Start
DECLARE int num1,num2,num3,maximum
GET num1,num2,num3
if (num1>=num2 YES
&& num1>=num3) maximum=num1
NO YES
maximum=num2
if (num2>=num1
&& num2>=num3)
NO YES
maximum=num3
if (num3>=num2
&& num3<=num1)
DISPLAY maximum CHAPTER 1
End
11 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS
Example: Repetition Control Structure
› Get and display 10 students marks
Start
DECLARE int stu=1,double marks
while
FALSE GET marks TRUE
stu++
DISPLAY marks
End
Example: Function
› Calculate the area of a room by using 2 functions: getInput()and
calculate()
CHAPTER 1
12 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 1
Example: using off page connector
4.4 Implementation/Coding
› Solve the problem
› The pseudo code or flow diagram will be converted to a program by using a certain
programming language (eg.: BASIC, Java, C++).
› Coding is the actual process of creating the program in a programming language.
› The coded program is referred to as source code.
› To be executed, the program is converted by the computer to object code using a special
program (compiler or interpreter)
4.5 Testing/Debugging
› Check and verify for the correctness of the result.
› Debugging is the process of making sure a program is free of errors, or “bugs.”
› Preliminary debugging begins after the program has been entered into the computer system.
› The process whereby we will correct the error and run the program successfully.
4.6 Maintenance
› Virtually every program, if it is to last a long time, requires ongoing maintenance.
› Maintenance is a process of updating software for any changes, correction, additions, moves
to a different computing platform and more so that it continues to be useful.
› A costly process, but can be used to extend the life of a program.
13 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 2
CHAPTER 2
BASIC ELEMENTS OF A COMPUTER PROGRAM
Chapter Outline
1. C++ Program Structure
- Comments
- Preprocessor directives
- Functions
- Statements
2. Variable, Identifier, onstants and reserved words
3. Data type in C++
- Numeric data type
- Character data type
- String data type
- Logical Value data type
4. Variable and Constant Declaration
- Variable declaration
- Constant declaration
5. Arithmetic Expressions
- Arithmetic operators
- Mixed Type expressions
- Assignment statement
- Precedence & Associativity
- Increment and Decrement Operators (Postfix and Prefix Operators)
- Unary and Binary Operators
6. Mathematical library functions
7. Input and output Statement
- Input statement for numeric and character variable
- Input statement for string
- Output statements
8. Formatting Output Statement
- Escape Sequences
- Predefined Formatting Functions
9. Errors in C++ Programming
10. Program Debugging and Error Handling
14 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS
At the end of this chapter, student should be able to:
i. Identify the basic elements needed in writing a program
ii. Understand and apply the input/output statement
iii. Justify the process of writing a program and error handling
iv. Write a simple program
1. C++ Program Structure
Here is the basic steps usually applied during writing a program.
Write all the headers files needed to program
Write main functions
Write statement between start ({) and end
program (})
Declare all variables and constants
Write executable statements:
• cin statements
• cout statements
• Arithmetic expressions
// Introductory comments CHAPTER 2
// file name, programmer, when written or modified
// what program does
#include <iostream>
using namespace std;
int main()
{
constant declarations ;
variable declarations;
executable statements ;
}
15 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS
Example of C++ program:
braces #include <iostream> → compiler directive/header file
using namespace std;
int main()→ main function
{
//display greeting message comment
cout<<”Welcome to CSC 128 class”; statement
}
OUTPUT
Welcome to CSC 128 class
Comments /* : average.cpp
File Name : aiddamirah
Preprocessor directives Programmer : 2014253684
Function Matrix No : Exercise 1
Begin block Topic : To calculate BMI of a user
Program purpose : 25 November 2014
Function body Date
*/
End block
eEd #include <iostream>
using namespace std;
int main()
{ int num1, num2, num3, sum;
double average;
cout << "\nEnter first number: ";
cin >> num1;
cout << "\nEnter second number: ";
cin >> num2;
cout << "\nEnter third number: ";
cin >> num3;
sum = num1 + num2 + num3;
average = sum / 3;
cout << "The average of ”<<num1<<","<<num2<<" and "<<num3
<<" is "<<average;
}
1.1. Comments CHAPTER 2
› Important part of a program's documentation.
› Explain the purpose, parts of program and keep note regarding changes to the source code
› Describe about the reason of the program and understand the program more clearly.
› Increased the user understanding of the program.
› Store the names of programmers for future reference
› Used to make program documentation.
16 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 2
› Can be used in 2 ways:
i. Using /* */ symbol
• Used for one or more than one line of comments in group
• Example:
/*This is the example of comment in C++ program.
This is the second line */
ii. Using // symbol
• Used only for one line
• Example:
// This is example of comments
// This is the second line
1.2 Preprocessor Directive
› A line of code that begins with the # symbol.
› Are processed by preprocessor (which is usually bundled into the compiler) before
compilation.
› Are not executable code lines but instructions to the compiler.
› Each header file stores functions that are related to a particular application.
› The directive #include <iostream> tells the preprocessor to include the contents of the file
<iostream>, which includes input-output operations (such as printing to the screen).
17 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 2
1.3 Main Function
› Every C++ program contains one or more functions, one of which must be named main.
› A function is a block of code that carries out a specific task.
› The word main is followed in the code by a pair of parentheses ( ).
1.4 Braces
› Right after these parentheses we can find the body of the main function enclosed in braces
{ }.
› What is contained within these braces is what the function does when it is executed.
› Braces used to mark the beginning and end of blocks of code.
› The open braces ({ ) are place in the beginning of code after the main functions and close
braces ( }) are used to show closing of code.
› The code after the ( }) will not be read/evaluate by compiler
1.5 Statement
› A function consists of a sequence of statements that perform the work of the function.
› It consists of instructions or command which make the program work.
› Each statement in C++ ends with a semicolon (;).
› There are 3 type of statement :
2. Identifier, variable, constants and reserved words
› Identifier are names created by the programmer to variables, constants etc.
› Use meaningful and descriptive identifiers to make a program easier to understand.
› An identifier in C++ is case sensitive.
› For example, the identifier Area is not the same identifier as area or AREA.
18 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS
Rules for naming identifiers
Special Symbol/ Syntax Rules
› To write a meaningful program, you must learn the programming language’s special symbol
& words and syntax rules.
› The syntax rules tells you which statements (instructions) are legal, or accepted by the
programming language, and which are not.
› Like in any language (spoken or artificial) some words in C++ have a fixed meaning.
› In programming languages these words are called special / reserved words
› Special words & symbol state by C++ have their own special meaning which refers to
appropriate instruction.
› This word that cannot be used as a variable name.
Example:
Special Symbol Special Word (Keyword)
+ - * / ; <= void, include, int
Sample of Keyword
asm default goto register throw
auto delete try
break do if return typedef
case double inline short union
catch else unsigned
char enum int signed virtual
class extern void
const float long sizeof volatile
continue for while
friend new static
operator struct CHAPTER 2
private switch
protected template
public this
19 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS
› Example for legal dan illegal Variable.
Legal Variables Illegal Variables
total3 num age
ABC35 2small
_result $dollar
value123all dollar4
Valid variable name/identifier Invalid variable name/identifiers
constage total#
All_sum 10days
big13 %rate
profit12all good day
Exercise 1
Identifiers Valid/Not valid
courseFile
reg#
1stprize
tot_hour
Main
play-again
_amount
switch
321go
AveRageNum
3. Data Types in C++
CHAPTER 2
20 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 2
3.1 Numeric Data Type
i. Integer/Whole Numbers
› Whole number – positive, zero or negative
› C++ keyword
• int, long
› Example:
• int area; area=25;
ii. Floating/Decimal Numbers
› Numbers with decimal points
› C++ keyword
• float, double ,long double
› Example:
• float area; area=25.5;
3.2 Character Data Type
i. Single character
› Store one character value
› C++ keyword
• char
› Example:
• char gender; gender=’F’;
› Sometimes, char can also be used for holding more than individual letters.
› The statement shows that the variable gender will hold seven letters. The
following is an example for this kind of char data type:
› Example
• char gender[7] ={'m', 'a', 'l', 'e'}
21 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 2
3.3 String Data Type
› A string, also known as a sequence of characters, is used for variables such as name,
address, object code, telephone numbers, car plate numbers and other variables that are
made up of a combination of numbers, words and symbols.
› String variables are enclosed in double quotation marks.
› This string data type has a large storage size to hold the combination of values.
› The following are some examples showing the values of the string data type:
"Eric Soh"
"AGP103"
"C++ IS INTERESTING"
"AP100"
"012-123125"
3.4 Bool Data Type
› A variable that has a value of true or false is known as a logical value data type.
› The data type for a logical value is bool.
› The bool data type is usually used in a looping structure.
Table below show the description of all data type
22 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 2
4 Variable and Contsant Declaration
4.1 Variable Declaration
› The process of clarifying the variable name and data type of a variable is known as variable
declaration.
› The declaration is a C++ statement, so it should end with a semicolon (;).
› In the declaration statement, we should write the data type, followed by the variable name.
› The general way to write a variable declaration is as follows:
• Data type variable_name;
› Examples:
• int age;
• double totalPrice;
• char gender;
• char code [6];
• bool status;
• string name;
› Examples:
4.2 Constant Declaration
› Provide a way to define a variable which cannot be modified by any other part in the program
code.
› Can be defined by placing the keyword const in front of any variable declaration.
› May not have its value changed while the programming is running.
23 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS
› Constants are usually define in capital letter.
› Example to define a constant:
const int DAY_PER_WEEK= 7;
› Constant is a value that never changes -> fixed value.
› Example:
= 3.142
› Replaced with:
const double PI=3.142;
› All constant and variables to be used in a C++ program must be defined prior their use in the
program.
› The reason that we must defined:
i. First, the compiler must know the value of a constant before it is used and must reserve
memory location to store variables.
ii. Second, the compiler must know the data type of the constant and variables so that it
knows their attributes and behavior.
5. Arithmetic Expression
› Variables and constants of integral and floating point types can be combined into expressions
using arithmetic operators.
› In C++, we have to represent the algebraic expression by using the valid syntax.
› At a low level, a computer is not able to perform an arithmetic operation on two different
data types of data.
› In general, only variables and constants of the same type should be combined in an
expression. The compiler has strict type checking rules to check for this.
› In cases where mixed numeric types appear in an expression, the compiler replaces all
variables with copies of the highest precision type.
› Just as there is a need for a hierarchy of operations, there is also a need for a hierarchy of
types.
› The hierarchy of data types in C++ is:
highest
double
float CHAPTER 2
integer lowest
24 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 2
5.1 Arithmetic Operators
› The way of writing an arithmetic expression in C++ is also different compared to normal
mathematical expressions, where the formula will be in the right side. The following example
shows an arithmetic expression to add variable X to variable Y and store the answer in
variable ANS:
ANS = X + Y;
› Table below shows the operators available in C++ programming
5.2 Mixed-type Expression
› In a mixed-type expression like (2 / 4.0), the operand lower in hierarchy gets promoted to
the higher type before the operation is carried out.
› So, the expression (2 / 4.0) is converted to (2.0 / 4.0) before the division is performed.
› The division is, therefore, float division which results in the float value of 0.5. If one operand
has a long, double, or signed modifier, the other is promoted as well.
› Type changes can be made explicit by placing the value to be changed in parentheses and
placing the name of the new type before it.
› This is called type casting or type conversion.
25 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS
› Syntax:
(type) expression;
type (expression);
› Given:
int X; double Y;
Y = 3.4; X = 12;
int (Y) + X = Y
So, answer is Y = 15
X+Y=Y
So, answer is Y = 15.4
5.3 Assignment statement
› It is essential that every variable in a program is given a value explicitly before any attempt is
made to use it. It is also very important that the value assigned is of the correct type.
› The most common form of statement in a program uses the assignment operator, =, and
either an expression or a constant to assign a value to a variable:
variable = expression; (eg: int num=5)
variable = constant; (eg: const double PI=3.142)
› The assignment statement may be used to give a variable its first value in a program. This first
value assignment is called initialization, and in C++ all variables must be explicitly initialized.
In C++ here is how it is done:
double price; // price is declared to be of type double
price = 37.99; /*Now the memory cell named price
contains the value 37.99 */
› The declaration statement and initialization can be combined into one statement as
follow:
double price = 37.99;
› A variable can store only one value at a time. Suppose score, a variable of type float, CHAPTER 2
the following statements executed in sequence
score = 5.3;
score = 2.7;
26 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS
› First, the value 5.3 will be assigned to score and then assign the value 2.7 to score. The value
5.3 would be lost and score would retain the value 2.7.
› Two variables can also store the same value. Suppose num1 and num2 are of type int.
› Then the following statements cause the number stored in the location reserved for num1
to be fetched from memory and stored in the location reserved for num2. The contents of
num1 are unchanged. //the value of num1 is 45
num1 = 45;
num2 = num1; //the value of num2 takes the value of num1=45
› Besides simple assignment (=), we also have a situation of (= =) whereby this assignment is
used to do comparison between the right and left side of assignments (= =). For example:
if (ans = = ‘y’)
{
True statements;
}
else
{
False statements;
}
CHAPTER 2
27 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 2
5.4 Precedence & Associativity
› Precedence means the sequence of arrangements or the order of operations. It determine a
which operation should performed first.
› Associativity specifies the order of operations if the operators have equal precedence.
› Example
5.5 Increment and Decrement Operators (Postfix & Prefix)
28 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS
› Example :
CHAPTER 2
29 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 2
Output:
45
66
66
5.6 Unary or Binary Operators
› Unary operators are operators that operate on a single operand while binary operators
are operators that operate on two operands.
30 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS
6. Mathematical library functions
› Mathematical function perform an arithmetic operation
› All the arithmetical function from math.h header file are listed in the following table:
Function name Operation
sqrt() Return the square root of the argument
pow(x,y) Return x raised to the power of y
pow10(y) Return 10 raised to the power of y
sin() Return the sine of argument (radiant)
hypot(a,b) Return the hypotenuse of a right triangle whose sides are a and b
tan() Return the tangent of the argument (radians)
log() Return the natural log of the argument
log10() Return the base 10 log of the argument
abs() Return the absolute value of argument
Example:
CHAPTER 2
31 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 2
7. Input And Output statement
7.1 Input Statement for Numeric and Character Variables
› Provides fundamental input and output capability
› Getting data into the system is called (input) reading.
› Besides getting data from users, data from problems can be done in 3 ways:
1. initialize the value (changes can be done to the value) OR
2. declare the value as constant (changes cannot be done to the value) OR
3. assign the value directly into the formula
› The cin statement is used to get input from the user using keyboard.
› The stream extraction operator >> is capable of handling all of the basic data types in a way
that is transparent to the programmer.
› The general syntax for numeric and character variable :
cin >>variable name;//read data
› If wants to read more than one data in one statement, the general syntax as below:
cin>>variable name1>>variable name2;//read more than 1 data
32 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS
› Below is example of program that shown a program to read numeric data
7.2 Input Statement for String
› Input statement for char and string are different compared to numeric and single character.
› These reading process used getline keyword which inform the compiler to accept a string
value.
› Syntax: used for group
cin.getline(variable, length); of characters
getline(cin,name);
used for
string
› Below is example of program that shown a program to read char data type.
› Synopsis of CHAPTER 2
Example of
33 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 2
input statement based on different data type:
7.3 Output Statement
› The cout statement is used to display output.
› The general format for cout statement is as follow:
cout<<item1<<item2<<…<<itemn; (the value of the item will be displayed)
cout<<“statement”; (the word “statement” will be displayed)
› cout is followed by the list of item to be written, which are separated by the << (stream
insertion operator)
› The best way to understand how cout works is to look at the output generated by several
different cout statement.
› Example of displaying cout statement
//Program to display instruction and output
#include <iostream>
using namespace std;
int main()
{
//declare and assign value to variable
int age;
age =42;
string name = “Alan”;
// display string and values
cout<<”Hi, my name is ”<<name<< “.”<< endl;
cout<<”I am ”<<age<<”years old.”<<endl
return0;
}// program ends
10.2.2 Numbers, Characters and String
34 | P a g e
}
INTRODUCTION TO C++ FOR BEGINNERS
Synopsis of example of output statement:
8. Formatting output
› C++ allow output formatting using escape sequence and predefine functions.
8.1 Excape Sequence
› Escape sequences symbol also can be used to format the output.
› To use these escape sequence, simply include them as part of a string or insert as single
character.
› Table below shows the escape sequence usage
Escape Sequence Meaning
\n newline - go to the next line
\t horizontal tab
\a Alert/ beep
\\ print a backslash character
\? print a question mark character
\" print a double quote character
\' print a single quote character
› Example of Escape Sequence syntax:
cout<< “Simon says.\”Pull your ears.\””<<endl.
Output: Simon says. “Pull your ears.”
CHAPTER 2
35 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS
› Below are example of program for esacape sequence:
8.2 Predefine Formatting Functions
› To format the field of output screen, we must use setw( ) I/O manipulator contained in the
iomanip.h header file.
› This header file allows you to manipulate the output stream to obtain some desired effect.
› Below are some list of predefine function used in formatting:
Manipulator Action CHAPTER 2
setw(n) Set field width to n
setprecision(n) Sets floating-point precision to n
setfill(n) Sets fill character to n
36 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS
› Most system divides a page of text output into twenty five rows and eighty columns.
Example:
Suppose you want to create three column of output: person’s name, person’s address and
person’s phone number.
cout<<“\n\n // skip 2 lines
<<setw(15)<<“NAME” // display heading
<<setw(22)<<“ADDRESS”
<<setw(23)<<“PHONE”<<endl
cout<<setw(15)<<“----” // display underline
<<setw(22)<<“-------”
<<setw(23)<<“-----”<<endl;
OUTPUT SCREEN: 22 column 23 column
15 column ADRE PHON
NAME SS E
› Specifies character for blank space in field CHAPTER 2
› Single quotes required around character enclosed in parentheses
› Example:
num = 2.55;
cout<<setw(10)<<setfill(‘*’)<<num;
› Output:
******2.55
› Statement below are used to fixed deal palaces:
cout.setf(ios::fixed);
cout.precision(n);
› Statement cout.setf(ios::fixed) forces the compiler to generate a fixed
decimal output without exponential, or e, notation.
› Meanwhile cout.precision(n) dictates the number of decimal places to the
right of decimal point to be generated.
› Specifies character for blank space in field
cout.setf(ios::left);
37 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 2
› By default, when we use setw(n) to print values or information, the values are right
justified.
› Below are the example for formatting output using predefine functions.
38 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 2
9. Errors in C++ Programming
› After writting a program, the next step is to complie and test the program.
› Syntax errors is an error related with violations of syntax rules.
› Logical errors is an errors in the logic of a program like output produced is wrong
› Run time errors is an errors caused program instructions that require the computer to do
something illegal such as an attempt to divide a number by 0 and in this case, the
implementation of program will stop automatically and display a certain messages.
› Example:
10. Programming process, debugging and error handling
› The process of tracing, identifying and correcting errors in the programs is called debugging.
› Before debugging, users need to compile their program first.
› Compile is done once users have finished writing a program.
› Use the steps below to compile a program:
› After writing the program, click the compile button as shown in the next figure:
› After compile, if there is an error in the program , it will appear in the bottom part.
› To identify the location of the error, double click on the error statement.
› An arrow will appear on the left side of the program statement which contains error.
› After correcting (process called debugging) the errors, we have to compile again the program
until the message shown there is no errors in the program
39 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3
CHAPTER 3
SELECTION CONTROL STRUCTURE
Chapter Outline
1. Boolean values
- Relational operators
- Logical operators
- Compound Boolean Expressions
2. Types of selection control structure
- if statements
• One-way selection
• Two-way selection
• Multiple -way selection
- switch statement
• break statement usage
3. Nested Selection (Multi-way selection)
At the end of this chapter, student should be able to:
i. Understand the concept of relational and logical operators
ii. Understand the concept of selection control structure
iii. Differentiate between two types of selection control structure
iv. Understand the concept of nested if selection structure
v. Produce programs that use the selection control structure
1. Boolean Expression
› Allow flow of program to be altered, depending on one or more Boolean condition.
› The real intelligence of a computer comes from its ability to make decisions.
› No matter how complex a digital computer system seems to be, it’s only making simple
Boolean decisions: on or off, 1 or 0 or TRUE or FALSE.
› Decision in a computer program is made by testing one condition against another.
Example: if x<y
› Here, the condition of x is tested against the condition of y. If x is in fact less than y, the test
result is true.
40 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3
› However, if the value of x is greater than or equal to the value of y, the test is false.
› To test condition within a program, you will use relational or logical operators to produce
Boolean decision (TRUE or FALSE).
› When decisions are made in a computer program, they are simply the result of a computation
in which the final result is either TRUE or FALSE.
› The value zero (0) is considered to be FALSE by C++. Any positive or negative value is
considered to be TRUE.
› C++ evaluates any non-zero value to be TRUE.
› Boolean expressions can be written using a combination of operands, relational operators
and logical operators
› used to evaluate a Boolean expression.
› Based on the ANSI-C++ standard, the result of a relational operation can only be the Boolean
value of true or false.
1.1 Relational Operators
› In order to evaluate a comparison between two expressions we can use the Relational
operators. As specified by the ANSI-C++ standard, the result of a relational operation is a
boolean value that can only be true or false, according to the result of the comparison.
› When complex decisions must be coded into an algorithm, it may be necessary to “chain
together” a few relational expression that use relational operators. This is done with logical
operators (also known as Boolean Operators).
› Allow two quantities to be compared.
› Normally when the expression have 2 operands or identifiers, either same as, not same,
smaller than, bigger than etc
› Relational operators test the relation between two quantities, including the normal equalities
and inequalities.
41 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3
• Equalities mean relation between two quantities that has a same value.
For example, A = B means A and B have the same value.
• Inequalities are where two quantities have different values.
› Table below lists the common relational operators used to evaluate normal equalities and
inequalities in C++.
› Example below displays some simple Boolean expressions involving integers and floating
numbers
› In the American Standard Code for Information Interchange (ASCII) , characters or letters are
stored in alphabetical order.
› The value of character 'A' is lower than value of character 'B'.
› The uppercase character sequence is followed by lowercase character sequence. Table below
shows example of a few comparisons of data type char.
42 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3
› Below are the example programs performing the evaluation of Boolean expression.
1.2 Logical Operators
› Logical operators are used to combine two or more conditions in an expression.
› In order to evaluate a comparison between two logical expressions, we can use the Logical
Operators. (order of precedence: && must be evaluated first followed with || and !)
› If you need to test more than one relational expression at a time, it is possible to combine
the relational expressions using the logical operators.
› If an expression involves arithmetic, relational and logical operators, the arithmetic
operators are evaluated first, followed by the relational operators, followed by the logical
operators.
› The three logical operators in C++ are shown in Table below.
43 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3
› Table below shows results of evaluating two expressions with &&
› Table below shows results of evaluating two expressions with ||
› Table shows the results of evaluating an expression with !
1.3 Compound Boolean Expressions
› We can combine the relational and the logical operators while creating a Boolean expression.
For example, we want to write a program that can evaluate numbers between 0 to 10. This
condition can be written using the relational and logical operator as follows:
• (num >= 0) && (num <= 10)
› Combining two or more expressions creates a compound Boolean expression.
› The combination of relational and logical operators has to be evaluated based on the
operator’s precedence.
› Figure below shows the precedence of operators, from highest to lowest and
44 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3
› Example below shows some sample of the evaluation
2. Types of Selection Control Structures
› A program is usually not limited to a linear sequence of instructions. During its process it may
take decisions or repeat code.
› A condition is an expression which consists of relational operator and/or combines with
logical operator to produce results whether TRUE or FALSE.
› The program will proceed with an action (instructions given by the programmer) based on
the conditions result (TRUE or FALSE)
› There are two types of selection control structures, the if statement and the switch
statement.
› In an if selection, relational and logical operators are used in the decision-making process.
› Meanwhile, the switch statement is used when the condition does not involve relational and
logical operators.
45 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3
2.1 if statement
› The if statement is commonly used to write conditional statements.
› Usually, in if statements, we use logical and relational operators to evaluate expressions to
either true or false.
› In an if selection, the immediate statement after the if expression is executed if the if
expression returns true.
› If the if statement has braces containing a block of statements, the statements are executed
only if the if expression evaluates to true. If the expression is false, statements outside the
block are executed.
› The if statement selection can be performed in three ways:
• one-way selection
• two-way selection
• multiple-way selection.
2.1.1 One -way selection
› In a one-way selection, the if statement only executes the next statements if the condition
is true.
› Compare just a selection which is written in a statement of the form:
if (boolean-expression)
statement;
Example :
cin>>marks;
if (marks>=50)
cout<<”PASS”;
› The example below follows a fragment of a program which tests if the denominator is not
zero before attempting to calculate fraction.
Example :
if (total!=0)
fraction=counter/total;
statement;
› If the value of total is 0, the boolean expression above is false and the statement assigning
the value of fraction is ignored.
46 | P a g e
INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3
› If a sequence of statements is to be executed, this can be done by making a compound
statement or block by enclosing the group of statements in braces.
if (boolean-expression)
{
statements;
}
Example :
if (total!=0)
{
fraction = counter/total;
cout<<”Proportion is = ”<<fraction<<endl;
}
› Flowchart below show the general syntax of if one-way selection.
› Below is an example of program for if statement.
› The program below prompts the user to enter a number and then identifies whether the
number is positive.
47 | P a g e