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

Fundamental Principles of Programming and Linear Structures

This document provides an overview of fundamental principles of programming in C++, focusing on concepts such as program structure, data types, and linear programming. It covers the evolution of programming languages, the basics of C++ syntax, and the importance of functions and tokens in programming. Additionally, it discusses common programming errors and the process of writing algorithms and pseudocode for problem-solving.

Uploaded by

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

Fundamental Principles of Programming and Linear Structures

This document provides an overview of fundamental principles of programming in C++, focusing on concepts such as program structure, data types, and linear programming. It covers the evolution of programming languages, the basics of C++ syntax, and the importance of functions and tokens in programming. Additionally, it discusses common programming errors and the process of writing algorithms and pseudocode for problem-solving.

Uploaded by

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

Compiled by:

Mamapule, Siyabonga

Topic 1: Fundamental Principles of


Programming and Linear Structures
Competencies
• Demonstrate an informed understanding of the basic principles of
programming in C++ using Code Blocks

• Key topics include an understanding of the program structure, concepts of


variables and data types, data input and output, arithmetic, relational, and
logic operators, and linear programs
Learning Outcomes
• Demonstrate an informed understanding of C++ programming

• Problem-solving using linear structures


Platform/IDE – Code Blocks
Overview of a Computer
➢ An electronic device capable of performing command. The basic commands that a
Computer computer performs are input (get data), output (display result), storage, and performance
of arithmetic and logical operations.
Two main computer components: Hardware and Software.

❑Major Hardware components include the central processing unit (CPU); main memory
(MM), also called random access memory (RAM); I/O devices; and secondary.

❑CPU is the “brain” of a computer and the most important piece of hardware in a computer.

❑Software are programs written to perform specific tasks. There are two types of programs:
system programs and application programs.

❑->> System programs control the computer. The system program that loads first when you
turn on your computer is called the operating system.

❑->> Application programs perform a specific task. Word processors, spreadsheets, and
games are examples of application programs.
The Language of a Computer
• Well, what is the language of the computer?
How does it store whatever you type on the
keyboard?
Computers use digital signals
❑ Digital signals represent information with a sequence of 0s and 1s. A 0
represents a low voltage, and a 1 represents a high voltage.
❑ Because digital signals are processed inside a computer, the language of a
computer, called Machine Language, is a sequence of 0s and 1s.
❑ The digit 0 or 1 is called a binary digit, or bit. Sometimes a sequence of 0s and
1s is referred to as a binary code or a binary number.
The Language of a Computer
❑A sequence of eight bits is called a byte. Moreover, 210 bytes 1024 bytes is called a kilobyte (KB).
❑The Table below summarises the terms used to describe various numbers of bytes.

Unit Symbol Bits/Byte


Byte - 8 bits
Kilobyte KB 210 bytes = 1024 bytes
Megabyte MB 1024 KB = 210 KB = 220 bytes = 1,048,576 bytes
Gigabyte GB 1024 MB = 210 MB = 230 bytes = 1,073,741,824 bytes
Terabyte TB 1024 GB = 210 GB = 240 bytes = 1,099,511,627,776 bytes
Petabyte PB 1024 TB = 210 TB = 250 bytes = 1,125,899,906,842,624 bytes
Exabyte EB 1024 PB = 210 PB = 260 bytes = 1,152,921,504,606,846,976 bytes
Zettabyte ZB 1024 EB = 210 EB = 270 bytes = 1,180,591,620,717,411,303,424 bytes
The Language of a Computer
Every letter, number, or special symbol (such as * or { ) on your keyboard is encoded as a sequence of bits, each
having a unique representation. The most commonly used encoding scheme on personal computers is the seven-
bit American Standard Code for Information Interchange (ASCII). ASCII data set consists of 128 characters
numbered 0 through 127.
In the ASCII data set, the position of the first character is 0, the position of the second character is 1, and so on.
Following this scheme, A is encoded as the binary number 1000001 and the character 3 is encoded as 0110011.
Given that ASCII is a seven-bit code. Therefore, to represent each ASCII character inside the computer, you must
convert the seven-bit binary representation of an ASCII character to an eight-bit binary representation. This is
accomplished by adding 0 to the left of the seven-bit ASCII encoding of a character. Hence, inside the computer,
the character A is represented as 01000001, and the character 3 is represented as 00110011.
Character ASCII Inside Computer
A 1000001 01000001
3 0110011 00110011
The Evolution of Programming Languages
Early computers were programmed in machine language. To write instructions in machine language, the
programmer had to remember the machine language codes for various operations. This need to remember
specific codes made programming not only very difficult but also error prone.
Assembly languages were developed to make the programmer’s job easier. In assembly language, an instruction
is an easy-to-remember form called a mnemonic. it is much easier to write instructions in assembly language.
However, a computer cannot execute assembly language instructions directly. The instructions first have to be
translated into machine language. A program called an assembler translates the assembly language instructions
into machine language.
Assembler: A program that translates a program written in assembly language into an equivalent program in
machine language.
The Evolution of Programming Languages
Moving from machine language to assembly language made programming easier, but a
programmer was still forced to think in terms of individual machine instructions. The next step
toward making programming easier was to devise high-level languages that were closer to
natural languages, such as English, French, German, and Spanish. Basic, FORTRAN, COBOL, C++,
C#, Java, and Python are all high-level languages.
In this course, you will learn the high-level language C++. C++ is an object-oriented language,
based on C. C combines the power of an assembly language with the ease of use and portability
of a high-level language.
To execute on a computer, these C++ instructions first need to be translated into machine
language. A program called a compiler translates instructions written in high-level languages into
machine code.
Compiler: A program that translates instructions written in a high-level language into the
equivalent machine language.
A Fundamental C++ program
• Consider the following C++ program:
1 #include <iostream> The following simple C++ program that
2 using namespace std; displays the message My first C++
3 program. on the console.
4 int main()
5 {
(The word console is an old computer
6 // Display Welcome to C++ to the console
7 cout << "My first C++ program." << endl; term. It refers to a computer’s text entry
8 and display device.
9 return 0;
10 } Console input means to receive input
from the keyboard and console output
means to display output to the monitor.)
A Fundamental C++ program
A C++ program is a collection of functions, one of which is the Console of the previous C++ program:
function main. A function is a set of statements whose
objective is to accomplish something. The preceding program
consists of only the function main; all C++ programs require the
function main.
The first line in the program: #include <iostream> is a compiler
preprocessor directive that tells the compiler to include the
iostream library in this program, which is needed to support
console input and output. C++ library contains predefined code
for developing C++ programs.
The statement in line 2 using namespace std; tells the compiler
to use the standard namespace. std is an abbreviation of
standard. Namespace is a mechanism to avoid naming conflicts
in a large program. The names cout and endl in line 7 are
defined in the iostream library in the standard namespace.
A Fundamental C++ program
❑ Every C++ program is executed from a main function. A function is a construct that contains statements. The main
function defined in lines 4–10 contains two statements. They are enclosed in a block that starts with a left brace, {,
(line 5) and ends with a right brace, } (line 10).
❑ The statement in line 7 displays a message to the console. cout (pronounced see-out) stands for console output. The
<< operator, referred to as the stream insertion operator, sends a string to the console. A string must be enclosed in
quotation marks. The statement in line 7 first outputs the string "My first C++ program.” to the console, then outputs
endl.
❑ Note that endl stands for end line. Sending endl to the console ends a line and flushes the output buffer to ensure
that the output is displayed immediately.
❑ The statement (line 9) return 0; is placed at the end of every main function to exit the program. The value 0 indicates
that the program has terminated with a successful exit.
❑ Line 6 is a comment that documents what the program is and how it is constructed. Comments help programmers to
communicate and understand the program. In C++, a comment is preceded by two slashes (//) on a line, called a line
comment, or enclosed between /* and */ on one or several lines, called a block comment or paragraph comment.
Special Characters (tokens)
The smallest individual unit of a program written in any language is called a token. C++’s
tokens are divided into special symbols, word symbols, and identifiers.
Character Name Description
# Pound sign Used in #include to denote a preprocessor directive.
<> Opening and closing angle brackets Encloses a library name when used with #include.
() Opening and closing parentheses Used with functions such as main().
{} Opening and closing braces Denotes a block to enclose statements.
// Double slashes Precedes a comment line.
<< Stream insertion operator Outputs to the console.
“” Opening and closing quotation marks Wraps a string (i.e., sequence of characters).
; Semicolon Marks the end of a statement.
Programming
Definition The term programming means to create (or develop) software,
which is also called a program.

In basic terms, software contains the instructions that tell a


computer—or a computerised device—what to do

These programs are examples of software. Software developers


create software with the help of powerful tools called programming
languages.
Programming
❑ A C++ program is a collection of one or more subprograms, called
functions. A subprogram (function) is a collection of statements, and
when it is activated, or executed, it accomplishes something.
❑ Some functions, called predefined or standard functions, are already
written and are provided as part of the system. However, programmers
must learn to write their own functions to accomplish most tasks.
❑ C++ programming may look like a foreign language. So, to make
meaningful sentences you must learn its alphabet, words, and syntax
rules.
❑ Syntax rules tell you which statements (instructions) are legal or valid, that is, which are accepted by the
programming language and which are not. Semantic rules are also important, these determine the meaning of the
instructions. The programming language’s rules, symbols, and special words enable you to write programs to solve
problems.
❑ Programming language: A set of rules, symbols, and special words.
Programming
WelcomeWithThreeMessages.cpp ComputeExpression.cpp

1 #include <iostream> 1 #include <iostream>


2 using namespace std; 2 using namespace std;
3 3
4 int main() 4 int main()
5{ 5{
6 cout << "Programming is fun!" << endl; 6 cout << "(10.5 + 2 * 3) / (45 - 3.5) = ";
7 cout << "Fundamentals First" << endl; 7 cout << (10.5 + 2 * 3) / (45 - 3.5) << endl;
8 cout << "Problem Driven" << endl; 8
9 9 return 0;
10 return 0; 10 }
11 }
Programming is fun! (10.5 + 2 * 3) / (45 – 3.5) = 0.39759036144578314
Fundamentals First
Problem Driven
Reserved Words and Identifiers
Reserved Words (Keywords)
❑A second category of tokens is reserved word symbols. Reserved words are also called
Keywords. Some of the reserved word symbols include the following
❑int, float, double, char, const, void, return

Identifiers
A third category of tokens is Identifiers. Identifies are names of things that appear in programs,
such as variables, constants, and functions
❑A C++ identifier consists of letters, digits, and the underscore character (_) and must begin
with a letter or underscore.
Following are legal identifiers in C++: First, Conversion, payrate, counter1
Legal Identifiers
Illegal Identifier Reason A Correct Identifier
Employee Salary There can be no space between employeeSalary
employee and Salary

Hello! The exclamation mark cannot be used in Hello


an identifier.
One + two The symbol + cannot be used in an onePlusTwo
identifier
2nd An identifier cannot begin with a digit second
Programming Errors
Programming Errors:
Programming errors can be categorised into three types: syntax errors, runtime errors, and logic errors.

Syntax Errors ShowSyntaxErrors.cpp


1 #include <iostream>
❑Errors that are detected by the compiler 2 using namespace std
are called syntax errors or compile 3
errors. Syntax errors result from errors in 4 int main()
5{
code construction, such as mistyping a 6 cout << "Programming is fun << endl;
keyword, omitting necessary 7
punctuation, or using an opening brace 8 return 0;
without a corresponding closing brace. 9}
Programming Errors
ShowRuntimeErrors.cpp
Runtime Errors:
❑Runtime errors cause a program to 1 #include <iostream>
terminate abnormally. They occur while an 2 using namespace std;
application is running if the environment 3
4 int main()
detects an operation that is impossible to 5{
carry out. Input mistakes typically cause 6 int i = 4;
runtime errors. An input error occurs when 7 int j = 0;
the program is waiting for the user to enter a 8 cout << i / j << endl;
value, but the user enters a value that the 9
10 return 0;
program cannot handle. 11 }
Programming Errors
Logic Errors: ShowLogicErrors.cpp
❑Logic errors occur when a program does
not perform the way it was intended.
1 #include <iostream>
Errors of this kind occur for many 2 using namespace std;
different reasons. 3
4 int main()
❑For example, suppose you wrote the 5{
following program to convert a Celsius 35 6 cout << "Celsius 35 is Fahrenheit degree " << endl;
degree to a Fahrenheit degree. 7 cout << (9 / 5) * 35 + 32 << endl;
8
❑Using this program, you will get 9 return 0;
Fahrenheit 67 degree, which is wrong. It 10 }

should be 95
Writing a Program
Writing a program involves designing a strategy for solving a problem
and then using a programming language to implement that strategy.
Consider the simple problem Writing a program involves designing algorithms and
of computing the area of a
translating them into programming instructions, or code.
circle. How do we write a
program for solving this?
An algorithm describes how a problem is solved by
listing the actions that must be taken and the order of
their execution. Algorithms can help the programmer
plan a program before writing it in a programming
language. Algorithms can be described in natural
languages or in pseudocode (natural language mixed
with some programming code).
Pseudocode and Algorithm
The algorithm for calculating the area of a circle can be described as follows
1. Read in the circle’s radius.
2. Compute the area using the following formula:
area = radius * radius * p
3. Display the result.
When you code—that is, when you write a program—you translate an algorithm into a program. The main
function would look like this
int main()
{
// Step 1: Read in radius
// Step 2: Compute area
// Step 3: Display the area
}
Variables and Data types
The program needs to read the radius entered by the user from the keyboard. This raises two
important issues:
❑Reading the radius
❑Storing the radius in the program
To store the radius, the program needs to declare a symbol called a variable. A variable
represents a value stored in the computer’s memory.
Rather than using x and y as variable names, choose descriptive names: in this case, radius for
radius, and area for area. To let the compiler know what radius and area are, specify their data
types. That is the kind of the data stored in a variable, whether integer, floating-point number,
or something else. This is known as declaring variables. C++ provides simple data types for
representing integers, floating-point numbers (i.e., numbers with a decimal point), characters,
and Boolean types. These types are known as primitive data types or fundamental types.
Data Types
Data Type: A set of values together with a set of allowed operations
C++ data types fall into the following three categories:
❑Simple data type
❑Structured data type
❑Pointers
Simple data types: The simple data type is the fundamental data type in C++ because it
becomes a building block for the structured data type.
Integral, which is a data type that deals with integers, or number without a decimal part.
Floating point, which is data type that deals with decimal numbers
Enumeration, which is user-defined data type.
Data Types
Integral data types are further classified into the following categories: char, short, int, long, bool,
unsigned char, unsigned short, unsigned int, unsigned long, long long, and unsigned long long

To deal with decimal numbers, C++ provides the floating-point data type, which we discuss in this section. To
facilitate the discussion, let us review a concept from a high school or college algebra course. You may be familiar
with scientific notation. For example:
❑ 43872918 = 4.3872918 * 107 { 10 to the power of seven}
❑ .0000265 = 2.65 * 10−5 { 10 to the power of minus five}
❑ 47.9832 = 4.79832 * 101 { 10 to the power of one}
To represent decimal numbers, C++ uses a form of scientific notation called floating-point notation.
An enumeration in C++ is a user-defined data type that consists of a set of named integer constants. It
is used to assign meaningful names to integral values, improving code readability and maintainability.
Declaring Variables
Declare radius and area as double-precision floating-point numbers. The program can
be expanded as follows:

❑ The program declares radius and area as int main()


variables. The reserved word double indicates {
that radius and area are double-precision double radius;
floating-point values stored in the computer. double area;
// Step 1: Read in radius
❑ For now, to learn how variables work, you can // Step 2: Compute area
assign a fixed value to radius in the program as
// Step 3: Display the area
you write the code; later, you will modify the
program to prompt the user for this value.
}
ComputeArea.cpp
1 #include <iostream>
Computing Area 2 using namespace std;
3
4 int main()
❑The second step is to compute area by 5{
assigning the result of the expression radius * 6 double radius;
radius * 3.14159 to area. 7 double area;
8
❑In the final step, the program will display the 9 // Step 1: Read in radius
value of area on the console by using cout << 10 radius = 20;
area. 11
12 // Step 2: Compute area
13 area = radius * radius * 3.14159;
14
The area is 1256.64 15 // Step 3: Display the area
16 cout << "The area is " << area << endl;
17
18 return 0;
19 }
Computing Area
❑Variables such as radius and area correspond to memory locations. Every variable
has a name, type, size, and value. Line 6 declares that radius can store a double value.
The value is not defined until you assign a value. Line 10 assigns 20 into radius.
❑Similarly, line 7 declares variable area and line 13 assigns a value into area. If you
comment out line 10, the program will compile and run, but the result is
unpredictable, because radius is not assigned a proper value.
Show the output of the following
❑Line 16 sends a string "The area is " to the console. It
code:
also sends the value in variable area to the console.
Note that quotation marks are not placed around
double area = 5.2;
area. If they were, the string "area" would be sent to
cout << "area";
the console.
cout << area;
Reading Input from ComputeAreaWithConsoleInp
the Keyboard ut.cpp
1 #include <iostream>
2 using namespace std;
❑Reading input from the keyboard 3
enables the program to accept input 4 int main()
from the user. 5{
6 // Step 1: Read in radius
❑Granted the radius is fixed in the source 7 double radius;
code. To use a different radius, you have 8 cout << "Enter a radius: ";
to modify the source code and 9 cin >> radius;
recompile it. You can use the cin object 10
to read input from the keyboard 11 // Step 2: Compute area
12 double area = radius * radius * 3.14159;
Enter a radius: 2.5 13
The area is 19.6349 14 // Step 3: Display the area
15 cout << "The area is " << area << endl;
Enter a radius: 23 16
The area is 1661.9 17 return 0;
18 }
Reading Input from the Keyboard
Line 8 displays a string "Enter a radius: " to the console. This is known as a prompt because it
directs the user to input something. Your program should always tell the user what to enter
when expecting input from the keyboard. Line 9 uses the cin object to read a value from the
keyboard.

Note that cin (pronounced see-in) stands for console input. The >> symbol, referred to as the stream
extraction operator, assigns an input to a variable. As shown in the sample run, the program displays
the prompting message "Enter a radius: "; the user then enters number 2, which is assigned to
variable radius. The cin object causes a program to wait until data is entered at the keyboard and the
Enter key is pressed. C++ automatically converts the data read from the keyboard to the data type of
the variable.
Reading Input from ComputeAverage.cpp
1 #include <iostream>
the Keyboard 2 using namespace std;
3
Different techniques to read in input. 4 int main()
5{
❑You can use a single statement to 6 // Prompt the user to enter three numbers
read multiple input. For example, 7 double number1, number2, number3;
the following statement reads three 8 cout << "Enter three numbers: ";
9 cin >> number1 >> number2 >> number3;
values into variable x1, x2, and x3: 10
11 // Compute average
12 double average = (number1 + number2 + number3) / 3;
Note! 13
We say, “declare a variable,” but not “define a 14 // Display result
variable.” We are making a subtle distinction 15 cout << "The average of " << number1 << " " << number2
16 << " " << number3 << " is " << average << endl;
here. A definition defines what the defined item
17
is, but a declaration usually involves allocating 18 return 0;
memory to store data for the declared item. 19 }
Initialize Variables
Variables often have initial values. You can declare a variable and initialize it in one step.
❑Consider, for instance, the following code:
int count = 1;
❑This is equivalent to the next two statements:
int count;
count = 1;
You can also use shorthand to declare and initialize variables of the same type together.
❑For example:
int i = 1, j = 2;
Assignment Statements and Assignment
Expressions
After a variable is declared, you can assign a value to it by using an assignment statement.
In C++, the equal sign (=) is used as the assignment operator. The syntax for assignment
statements is as follows:
variable = expression;
An expression represents a computation involving values, variables, and operators that,
taking them together, evaluates to a value. For example, consider the following code:
int y = 1; // Assign 1 to variable y
double radius = 1.0; // Assign 1.0 to variable radius
int x = 5 * (3 / 2); // Assign the value of the expression to x
x = y + 1; // Assign the addition of y and 1 to x
area = radius * radius * 3.14159; // Compute area
You can use a variable in an expression. A variable can also be used in both sides of the = operator. For example,
x = x + 1;
Assignment Statements and Assignment
Expressions
In C++, an assignment statement is essentially an expression that evaluates to the value to be assigned to
the variable on the left side of the assignment operator. For this reason, an assignment statement is also
known as an assignment expression. For example, the following statement is correct:

cout << x = 1;

x = 1;
…which is equivalent to
cout << x;
i = j = k = 1;
which is equivalent to
If a value is assigned to multiple variables, you k = 1;
can use this syntax: j = k;
i = j;
Named Constants
A named constant is an identifier that represents a permanent value.
❑ Every variable has a scope. The scope of a variable is the part of the program where the variable can
be referenced.
The value of a variable may change during the execution of a program, but a named constant, or
simply constant, represents permanent data that never changes. In our ComputeArea program, 𝝅 is a
constant. If you use it frequently, you don’t want to keep typing 3.14159; instead, you can declare a
constant for 𝝅. Here is the syntax for declaring a constant:

const datatype CONSTANTNAME = value;


A constant must be declared and initialized in the same statement. The word const is a C++
keyword for declaring a constant.
ComputeAreaWithConstant.cpp
Named Constants 1 #include <iostream>
2 using namespace std;
3
4 int main()
For example, you may declare 𝝅 as 5{
a constant and rewrite. 6 const double PI = 3.14159;
7
8 // Step 1: Read in radius
❑ Caution 9 double radius;
10 cout << "Enter a radius: ";
By convention, constants are named in 11 cin >> radius;
uppercase: PI, not pi or Pi. 12
13 // Step 2: Compute area
14 double area = radius * radius * PI;
15
16 // Step 3: Display the area
17 cout << "The area is ";
18 cout << area << endl;
19
20 return 0;
Numeric Operators
The operators for numeric data types include the standard arithmetic operators: addition (+),
subtraction (–), multiplication (*), division (/), and remainder (%), as shown in Table below. The
operands are the values operated by an operator.

❑ Remember Numeric data types


include: int, double, long etc.
Operator Name Example Result
+ Addition 34 + 1 35
- Subtraction 34.0 – 1.0 33.9
* Multiplication 300 * 30 9000
/ Division 1.0/2.0 0.5
% Modulus 20 % 3 2
Numeric Operators
The % operator, known as modulo or remainder operator, works only with integer operands and
yields the remainder after division. The left-hand operand is the dividend and the righthand
operand the divisor. Therefore, 7 % 3 yields 1, 3 % 7 yields 3, 12 % 4 yields 0, 26 % 8 yields 2, and 20
% 13 yields 7.

❑ See the following


Example:
Numeric Operators
Activity

❑Show the result of the following remainders:


• 56 % 6
• 78 % 4
• 34 % 5
• 34 % 15
• 5%1
• 1%5
Augmented Assignment Operators
❑The operators +, -, *, /, and % can be combined with the assignment operator to form augmented
operators.
❑ Often, the current value of a variable is used, modified, and then reassigned back to the
same variable. For example, the following statement increases the variable count by 1:

count = count + 1;
❑ C++ allows you to combine assignment and addition operators using an augmented
assignment operator. For example, the preceding statement can be written as follows:
count += 8;

❑ The += is called the addition assignment operator


Augmented Assignment Operators
❑Other augmented operators are shown in Table below:
Operator Name Example Equivalent
+= Addition assignment i += 8 i=i+8

-= Subtraction i -= 8 i=i–8
assignment

*= Multiplication i *= 8 i=i*8
assignment

/= Division assignment i /= 8 i=i/8


%= Modulus assignment i %= 8 i=i%8
Order of Precedence
❑When more than one arithmetic operator is used in an expression, C++ uses the operator
precedence rules to evaluate the expression. According to the order of precedence rules for
arithmetic operators, *, /, and % are at a higher level of precedence than + and -
❑Note that the operators *, /, and % have the same level of precedence. Similarly, the
operators + and - have the same level of precedence.

❑ When operators have the same level of precedence, the operations are performed
from left to right. To avoid confusion, you can use parentheses to group arithmetic
expressions.
Relational and Logical Operators in C++
❑In C++, relational and logical operators are used for decision-making by comparing values
and forming complex conditions.
❑ The bool data type declares a variable with the value either true or false. How do you compare two
values, such as whether a radius is greater than 0, equal to 0, or less than 0? C++ provides six relational
operators, shown in Table below, which can be used to compare two values (assume radius is 5 in the
table).
Relational and Logical Operators in C++
Logical Operators !, &&, and || can be used to create a compound Boolean expression.
❑ Sometimes, a combination of several conditions determines whether a statement is executed.
❑ You can use logical operators to combine these conditions. Logical operators, also known as Boolean
operators, operate on Boolean values to create a new Boolean value. The table below gives a list of
Boolean operators.

❑ Table 3.4 defines the not (!) operator. The not (!) operator negates true to false and false to true. Table
3.5 defines the and (&&) operator. The and (&&) of two Boolean operands is true if and only if both
operands are true. Table 3.6 defines the or (||) operator. The or (||) of two Boolean operands is true if
at least one of the operands is true.
Relational and Logical Operators in C++
Increment and Decrement Operators
The increment (++) and decrement (--) operators are for incrementing and Decrementing a
variable by 1.
❑ The ++ and -- are two shorthand operators for incrementing and decrementing a variable by 1.
These are handy, because that’s often how much the value needs to be changed in many
programming tasks. For example, the following code increments i by 1 and decrements j by 1.
int i = 3, j = 3;
i++; // i becomes 4
j--; // j becomes 2

❑ i++ is pronounced as i plus plus and i-- as i minus minus. These operators are known as
postfix increment (postincrement) and postfix decrement (postdecrement), because the
operators ++ and -- are placed after the variable
Increment and Decrement Operators
These operators can also be placed before the variable. For example,

int i = 3, j = 3;
++i; // i becomes 4
--j; // j becomes 2

❑ ++i increments i by 1 and --j decrements j by 1. These operators are known as prefix increment
(preincrement) and prefix decrement (predecrement).
Increment and Decrement Operators
❑The Table below shows Increment and Decrement Operators
Logo, company name

Description automatically generated

www.spu.ac.za

www.spu.ac.za

Private Bag X5008


North Campus
Chapel Street
Kimberley A picture containing text, clipart

Description automatically generated


Icon

Description automatically generated


A picture containing text, clipart, vector graphics

Description automatically generated


Icon

Description automatically generated

8300

You might also like