PF Notes - I
PF Notes - I
ADD 6 , 3
mnemonic code 110 11
It is relatively easy for writing programs in assembly language, but it will
be slow in execution, because the program needs to be converted into
machine language for execution.
COMPILER VS INTERPRETER:
ROLE OF COMPILER:
During the process of translation, the compiler reads the source program (High-Level
Language Program) statement-wise and checks for syntax errors in the whole program
at once.
If there is a syntax error/s in the program, it generates the error and compilation of
program stops.
The programmer fixes the errors and compiles the program again.
If there is no syntax error in the program, the compiler converts the whole program into
machine language program (object program) also called as executable code. That object
program (machine code) is directly understandable by the computer/processor. So, the
processor executes that program.
The process of compilation is relatively complicated. It spends a lot of time analyzing and
processing the program.
The executable result is some form of machine-specific binary code.
ROLE OF INTERPRETER:
The interpreter converts and executes the source code line-by-line when the program is
running.
If there is an error in a line, interpreter stops further error checking of source code and
displays the error/s.
The programmer fixes the errors and the process of translation starts again.
Interpreter then translates a program written in a high-level language and also executes
it line-by-line. Interpreter does not generate the executable code.
Interpreter allows evaluation and modification of the program while it is executing.
Relatively less time spent for analyzing and processing the program.
Program execution is relatively slow compared to compiler.
INTERPRETER VS COMPILER
NOTE:
Ctrl+Click on the link below:
https://www.youtube.com/watch?v=e4ax90XmUBc
OVERVIEW OF PROGRAMMING:
SOURCE CODE, OBJECT CODE, AND EXECUTABLE CODE:
When a C++ program is written, it must be typed into the computer and saved to a file. A
text editor, which is similar to a word processing program, is used for this task. The statements
written by the programmer are called source code, and the file they are saved in is called the
source file (.cpp file). After the source code is saved to a file, the process of translating it to
machine language can begin.
During the first phase of this process, a program called the preprocessor reads the source
code. The preprocessor searches for special lines that begin with the # symbol. These lines
contain commands that cause the preprocessor to modify the source code in some way.
During the next phase the compiler steps through the preprocessed source code,
translating each source code instruction into the appropriate machine language instruction. This
process will uncover any syntax errors that may be in the program. Syntax errors are illegal uses
of key words, operators, punctuation, and other language elements. If the program is free of
syntax errors, the compiler stores the translated machine language instructions, which are called
object code, in an object file (.obj file).
Although an object file contains machine language instructions, it is not a complete
program. Here is why: C++ is conveniently equipped with a library of pre-written code for
performing common operations or sometimes-difficult tasks. For example, the library contains
hardware-specific code for displaying messages on the screen and reading input from the
keyboard. It also provides routines for mathematical functions, such as calculating the square
root of a number. This collection of code, called the run-time library, is extensive. Programs
almost always use some part of it. When the compiler generates an object file, however, it does
not include machine code for any run-time library routines the programmer might have used.
During the last phase of the translation process, another program called the linker
combines the object file with the necessary library routines. Once the linker has finished with this
step, an executable file (.exe file) is created. The executable file contains machine language
instructions, or executable code, and is ready to run on the computer.
The executable file (.exe) is saved in memory (Hard Disk). A program called Loader loads
that .exe file into the RAM. The Processor then executes the file and gives the output.
STRUCTURE OF C++ PROGRAM:
1. Comments – You can see two types of comments in the above program
// This is a single line comment
return 0;
}
Now if someone reads my comment he or she can understand what I did there just by
reading my comment. This improves readability of your code and when you are working on a
project with your team mates, this becomes essential aspect.
2. #include<iostream> – This statements tells the compiler to include iostream file. This file
contains pre-defined input/output functions that we can use in our program.
3. using namespace std; – A namespace is like a region, where we have functions, variables etc
and their scope is limited to that particular region. Here std is a namespace name, this tells the
compiler to look into that particular region for all the variables, functions, etc.
4. int main() – As the name suggests this is the main function of our program and the execution
of program begins with this function, the int here is the return type which indicates to the
compiler that this function will return a integer value. That is the main reason we have a return
0 statement at the end of main function.
5. cout << “Hello World!”; – The cout object belongs to the iostream file and the purpose of this
object is to display the content between double quotes as it is on the screen. This object can also
display the value of variables on screen.
6. return 0; – This statement returns value 0 from the main() function which indicates that the
execution of main function is successful. The value 1 represents failed execution.
int main()
{
cout<<"Hello World!";
return 0;
}
STYLE-2:
#include<iostream>
using namespace std;
2. Escape sequences: An escape sequence starts with the backslash character (\) and is
followed by one or more control characters. It allows you to control the way output is
displayed by embedding commands within the string itself.
In old days, computer operators interacted with computer system by typing on a terminal.
The terminal which consisted of a keyboard and a screen was known as the console (the black
screen in CODE BLOCKS that shows us output).
In C++ input and output is performed in the form of a sequence of bytes or more
commonly known as streams.
Input Operation: If bytes flow from a device like a keyboard, a disk drive, or a network
connection etc. to main memory, this is called input operation.
Output Operation: If bytes flow from main memory to a device like a display screen, a
printer, a disk drive, or a network connection, etc., this is called output operation.
Header files available in C++ for Input/Output operations are:
1. iostream: iostream (i-o-stream) stands for standard input-output stream. This header file
contains definitions to objects like cin, cout, cerr and clog, which are used for input and
output operations in C++ programs.
2. iomanip: iomanip (i-o-manip) stands for input-output manipulators. This file contains
some functions that are used to manipulate/work with streams. This file contains
definitions of setw, setprecision etc. We can simply say that this file is used for designing
input and output streams of data.
3. fstream: fstream (f-stream) header file mainly describes the file stream. This header file is
used to work with files to save (output) and get (input) data from files. The data being read
from a file is known as input and data being written into the file is known as output.
The cout And cin Objects:
The two keywords cout (c-out = console output) in C++ and cin (c-in = console input) in C++ are
used very often for printing outputs and taking inputs respectively. These two are the most basic
methods of taking input and printing output in C++.
To use cin and cout in C++ one must include the header file iostream in the program. Cout is
an object of ostream class, while cin is an object of istream class.
THE cout OBJECT:
cout is classified as a stream object, which means it works with streams of data. To print a
message on the screen, you send a stream of characters to cout. Let’s look at line:
cout << "Programming is great fun!";
Notice that the << operator is used to send the string “Programming is great fun!” to
cout. When the << symbol is used this way, it is called the stream insertion operator. The item
immediately to the right of the operator is sent to cout and then displayed on the screen.
The stream insertion operator (<<) is always written as two less-than signs with no space
between them. Because you are using it to send a stream of data to the cout object, you can
think of the stream insertion operator as an arrow that must point toward cout.
Example-1: Let’s take a simple example where we want the user to enter his age and we
display his age on the screen.
#include <iostream>
using namespace std;
int main()
{
int age;
cout << "Enter your age: ";
cin >> age; // Taking input
cout << "Your age is: " << age;
return 0;
}
Output
The above program asks the user to input the age. The object cin is connected to the input
device. The age entered by the user is extracted from cin using the stream extraction operator
(>>) and the extracted data is then stored in the variable age present on the right side of the
extraction operator.
#include <iostream>
using namespace std;
int main() {
char a;
int num;
return 0;
}
Output
Programming errors often remain undetected until the program is compiled or executed.
Some of the errors inhibit the program from getting compiled or executed. Thus errors should be
removed before compiling and executing.
The most common errors can be broadly classified as follows.
TYPE OF ERRORS:
1) Syntax errors: Errors that occur when you violate the rules of writing C/C++ syntax
are known as syntax errors. This compiler error indicates something that must be
fixed before the code can be compiled. All these errors are detected by compiler
and thus are known as compile-time errors.
Most frequent syntax errors are:
Missing Parenthesis { }.
Printing the value of variable without declaring it.
Missing semicolon ;
2) Run-time Errors: Errors which occur during program execution (run-time) after
successful compilation are called run-time errors.
Example: One of the most common run-time error is division by zero also known
as Division error. These types of error are hard to find as the compiler doesn’t point
to the line at which the error occurs.
For more understanding run the example given below.
In the
given example, there is Division by zero error. This is an example of run-time error i.e.
errors occurring while running the program.
3) Logical Errors: On compilation and execution of a program, desired output is not
obtained when certain input values are given. These types of errors which provide
incorrect output but appears to be error free are called logical errors.
These are one of the most common errors done by beginners of programming.
These errors solely depend on the logical thinking of the programmer and are easy to
detect if we follow the line of execution and determine why the program takes that
path of execution
4) Linker Errors: These error occurs when after compilation we link the different object
files with main’s object using RUN key. These are errors generated when the
executable of the program cannot be generated. This may be due to wrong function
prototyping, incorrect header files. One of the most common linker error is
writing Main() instead of main().
5) Semantic errors: This error occurs when the statements written in the program are
not meaningful to the compiler (i.e. they don’t follow the writing rules of C++).
COMMON ERRORS:
We will discuss them while writing programs. Point to note here is, you will do these
while writing programs for first time.
LANGUAGE KEYWORDS:
Following are some rules that are followed while naming identifiers in C++:
Names can contain letters (a…z, A…Z), digits (0…9) and underscores (_).
Names must begin with a letter or an underscore (_).
Names are case sensitive (e.g. myVar and myvar are different variables).
Names cannot contain whitespaces (space) or special characters like !, #, %, etc.
Reserved words/keywords (such as int, float, char etc.) cannot be used as identifier
names.
TYPES OF IDENTIFIERS:
User-Defined Identifiers: these are defined by the programmers where they can give
their own names to variables, constants, labels, functions, arrays, classes etc. in the
programs.
VARIABLES:
In our daily life we deal with data all the time. That data can be in the form of
numbers/digits/integers (0…9), characters/text/strings (a…z, A…Z, !,@,#,$,%,+,-,/,x etc) and
decimal/floating point values (3.45 etc).
For Example, in banks, the staff deal with customers’ data all the time, in educational
institutions data for students is processed throughout the year. Similarly, hospitals, airports,
NADRA, WAPDA etc. deal with data all the time. Similarly, applications like gmail, google,
youtube, facebook, whatsapp, twitter etc deal with a lot of data all the time.
While writing programs, programmers also deal with a lot of data and they need to save
that data in their programs. In almost all programming languages, variables are used to save
data in a program.
Syntax:
// declaring single variable…
data_type variable_name;
Example:
To save the age of a person in a program, we can declare a variable named age
as:
int age; // an integer variable
Similarly,
float temperature; // a decimal/floating point variable
char grade; // a character variable
Take another example where we declare three integer variables named as num1,
num2, sum. Below is the memory (RAM) diagram.
DATA TYPE:
Data Type: A Data Type of a variable defines what type of data will be stored in that
variable.
For Example, in the statements below:
int age;
float temperature;
char grade;
int age; means that we want to tell the compiler/computer that we will use a variable
named as age and it will hold integer data. Similarly, the statement float temperature; tells the
compiler that temperature is a floating point (decimal) variable and it will hold floating point
data. Likewise, char grade; tells the compiler that grade is a character variable and it will hold
character data.
2. Derived Data Types: The data-types that are derived from (built-from) the primitive or
built-in datatypes are referred to as Derived Data Types.
These can be of four types namely:
Function
Array
Pointer
Reference
3. Abstract or User-Defined Data Types: These data types are defined by the
programmer/user and are composed of both built-in and derived data types. For Example,
defining a class in C++ or a structure.
C++ provides the following user-defined datatypes:
Class
Structure
Union
Enumeration
Typedef defined DataType
Below is the table to show different data types with their size in memory and their ranges.
TYPES OF VARIABLES:
As discussed above, variables can categorized based on their data types. So, according to
basic data types, types of variables are:
1 Bool
Stores either value true or false.
2 Char
Typically a single octet (one byte). This is an integer type.
3 Int
The most natural size of integer for the machine.
4 Float
A single-precision floating point value.
5 Double
A double-precision floating point value.
6 Void
Represents the absence of type.
7 wchar_t
A wide character type.
There are other types of variables as well:
1) Variables based on their scope. These are of two types: 1) Local Variables. 2) Global
Variables.
2) Static variables.
3) Reference variables.
4) Pointer variables.
SOME IMPORTANT CONCEPTS:
VARIABLE DECLARATION, DEFINITION, INITIALIZATION AND ASSIGNMENT:
1) VARIABLE DECLARATION:
The process of specifying (i) the data-type, and (ii) the name of a variable, in a
program is called variable declaration. It is a process of introducing a variable to the
program.
Syntax:
2) VARIABLE DEFINITION:
In variable definition, the compiler reads the variable declaration statement and also
allocates memory/space to variables in RAM according to the data type of the variable.
The syntax of both variable declaration and variable definition is the same. The only
difference is in the allocation of memory. In C++, both variable declaration and variable
definition processes are done at the same time.
Example,
int age; // both declaration and definition processes
Compiler will read the above line and will allocate memory to ‘age’ variable in RAM,
according to its data type which is ‘int’ in our case.
Take another example where we declare three integer variables named as num1,
num2 and sum. Below is the memory (RAM) diagram for the process of variable
declaration and variable definition.
3) VARIABLE INITIALIZATION:
The process of giving/assigning value to variable at the time of ‘variable
declaration’ is called variable initialization.
Syntax:
// variable initialization for single variable…
data_type variable_name = value;
// variable initialization for multiple variables…
data_type variable1_name = value1 , variable2_name = value2 ;
Example:
Literals: Literals are the fixed values that we use in C++ programs.
Example:
In the statement:
cout << “Hello World!” << endl;
here, “Hello World!” is a fixed value, that is why it is a literal.
TYPES OF LITERALS:
In every data type in C++, we use literals which are just values. So, according to
five basic data types, literals are also of five basic types:
1. Integer literals
2. Floating-point literals
3. Boolean literals
4. Character literals
5. String literals
1) INTEGER LITERALS:
These are used to represent and store the integer values. Integer literals are
expressed in two types, i.e.
I. Prefixes: The Prefix of the integer literal indicates the base in which it is to be read.
For example:
0x10 = 16
Because 0x prefix represents a HexaDecimal base.
So 10 in HexaDecimal is 16 in Decimal.
Hence the value 16.
There are basically represent in four types.
i. Decimal-literal(base 10): A non-zero decimal digit followed by zero or more
decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9).
For example:
56, 78
ii. Octal-literal(base 8): a 0 followed by zero or more octal digits(0, 1, 2, 3, 4, 5, 6, 7).
For example:
045, 076, 06210
iii. Hex-literal(base 16): 0x or 0X followed by one or more hexadecimal digits(0, 1, 2,
3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F).
For example:
0x23A, 0Xb4C, 0xFEA
iv. Binary-literal(base 2): 0b or 0B followed by one or more binary digits(0, 1).
For example:
0b101, 0B111
II. Suffixes: The Prefix of the integer literal indicates the type in which it is to be read.
For example:
12345678901234LL
indicates a long long integer value 12345678901234
because of the suffix LL
These are represented in many ways according to their data types.
i. int: No suffix is required because integer constant is by default assigned as an
int data type.
ii. unsigned int: character u or U at the end of an integer constant.
iii. long int: character l or L at the end of an integer constant.
iv. unsigned long int: character ul or UL at the end of an integer constant.
v. long long int: character ll or LL at the end of an integer constant.
vi. unsigned long long int: character ull or ULL at the end of integer constant.
2) FLOATING-POINT LITERALS:
These are used to represent and store real numbers. The real number has an integer
part, real part, fractional part and an exponential part. The floating-point literals can be
stored either in decimal form or exponential form. While representing the floating-point
decimals one must keep two things in mind to produce valid literals:
In the decimal form, one must include the decimal point, exponent part or both,
otherwise, it will lead to an error.
In the exponential form, one must include the integer part, fractional part or both,
otherwise, it will lead to an error.
Few floating-point literal representations are shown below:
Valid Floating Literals:
10.125
1.215-10L
10.5E-3
Invalid Floating Literals:
123E
1250f
0.e879
3) CHARACTER LITERAL:
This refers to the literals that are used to store a single character within a single
quote. To store multiple characters, one needs to use a character array. Storing more than
one character within a single quote will throw a warning and displays just the last character
of the literal.
char type: This used to store normal character literal or the narrow-character literals.
Example:
char ch = 'G';
Escape Sequences: There are various special characters that we can use to perform
various operations regarding program output.
4) STRING LITERALS:
String literals are similar to that of the character literals, except that it can store
multiple characters and uses a double quote to store the same. It can also accommodate
the special characters and escape sequences.
Example:
string stringVal = "Hello World!";
5) BOOLEAN LITERALS:
They are used to represent the boolean datatypes. These can carry two values:
true: To represent True value. This must not be considered equal to int 1.
false: To represent False value. This must not be considered equal to int 0.
CONSTANTS/NAMED CONSTANTS:
As we know that literals are fixed (constant) values that we use in our programs.
Sometimes, it is helpful to give names to these literals, so that we may use them easily in our
programs.
Let’s take an example, that we are writing a program to find the circumference of a circle.
The program is:
#include <iostream>
}
The value 3.14158 is the value of PI. There are two problems here.
a. Except the programmer, no one knows what is 3.14158.
b. Assume that a programmer has written a program to find the circumference of 10 circles.
Also assume that the programmer wants to change the value of PI from 3.14158 to
3.14159. The programmer will have to search through the source code for every
occurrence of 3.14158.
Both of these problems can be addressed by using constants/named constants (because
we give names to literals).
Constants/Named Constants: A constant/named constant is like a variable, but its
content is read-only and cannot be changed while the program is running.
There are two simple ways in C++ to define constants/named constants −
return 0;
}
2) Using const Keyword:
We can use const keyword to do the same job as discussed earlier.
Syntax:
const data-type variable-name = value;
NOTE: Note here that we must initialize constants as soon as they are defined.
The above example can be written using const keyword as:
Example:
#include <iostream>
using namespace std;
int main()
{
}
Note that it is a good programming practice to define constants in CAPITALS.
Sizeof Operator:
The sizeof is a keyword, but it is a compile-time operator that determines the size, in bytes, of a
variable or data type or even a value.
The sizeof operator can be used to get the size of classes, structures, unions and any other
user defined data type.
The syntax of using sizeof is as follows −
int main()
{
cout << "Size of char :" << sizeof(char) << endl;
cout << "Size of wchar_t :" << sizeof(wchar_t) << endl << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of int :" << sizeof(int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of long long int : " << sizeof(long long int) << endl << endl;
return 0;
}
TYPE CONVERSION:
Type Conversion: The process of converting value of one data type to another data type,
is known as type conversion.
The main idea behind type conversion is to make variable of one type compatible with
variable of another type to perform an operation. For example, to find the sum of two variables,
one of int type & other of float type. So, there is a need to use a technique that will convert all
the values to a same data type to solve this problem.
There are two types of type conversion in C++:
1) Implicit Type Conversion (Automatic Type Conversion / Coercion).
2) Explicit Type Conversion (Type Casting).
1) Implicit Type Conversion: Implicit Type Conversion is a type conversion that is done
automatically by the compiler. Also known as automatic type conversion / coercion.
Done by the compiler on its own, without any external trigger from the user.
Generally takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid loss of data.
All the data types of the variables are upgraded to the data type of the variable with
largest data type.
bool -> char -> short int -> int -> unsigned int -> long int -> unsigned long-> long long int->
float -> double -> long double
It is possible for implicit conversions to lose information, signs can be lost (when signed
is implicitly converted to unsigned), and overflow can occur (when long long is implicitly
converted to float).
TYPE CONVERSION RULES:
Rule-2: chars, shorts, and unsigned shorts are automatically promoted to int.
Rule-3: When an operator works with two or more values of different data types, the
lower-ranking value is promoted to the type of the higher-ranking value.
Rule-4: When the final value of an expression is assigned to a variable, it will be converted
to the data type of that variable.
EXAMPLES:
char -> int && int -> char:
char c = 'a';
int i = c;
cout << "Int = " << i << endl;
c = i;
cout << "Char = " << c << endl;
char, int && float:
char c = 'A'; // ASCII A = 65
int i = 110;
float f = 100.50;
char char_sum;
int int_sum;
float float_sum;
char_sum = c + i + f;
cout << "CharSum = " << char_sum << endl;
int_sum = c + i + f;
cout << "IntSum = " << int_sum << endl;
float_sum = c + i + f;
cout << "FloatSum = " << float_sum << endl;
int -> long && long -> int:
int i = 100;
long l = i;
cout << "Long = " << l << endl;
i = l;
cout << "Int = " << i << endl;
i=f;
cout << "Int = " << i << endl;
i = 103.876;
cout << "Int = " << i << endl;
f = i;
cout << "Float = " << f << endl;
int, float and double:
int i = 100;
float f = 123.45;
double d = 343.78;
int int_sum;
float float_sum;
double double_sum;
int_sum = i + f + d;
cout << "IntSum = " << int_sum << endl;
float_sum = i + f + d;
cout << "FloatSum = " << float_sum << endl;
double_sum = i + f + d;
cout << "DoubleSum = " << double_sum << endl;
2) Explicit Type Conversion: When the user manually changes data from one type to
another, this is known as explicit type conversion. This type of conversion is also known
as type casting.
There are three major ways in which we can use explicit conversion in C++. They
are:
1. C-style type casting (also known as cast notation)
2. Function notation (also known as old C++ style type casting)
3. Type conversion operators
C-Style Type Casting:
double d = 1.2;
int sum = (int)d + 1;
cout << "Sum = " << sum << endl;
d = (double)sum + 23.7;
cout << "Again Double = " << d << endl;
Function Style Casting:
We can also use the function like notation to cast data from one type to another.
The syntax for this style is:
data_type (expression);
For example,
int i = 125;
double d = double(i);
cout << "Double = " << d << endl;
Another example,
double d = 1.2;
A Cast operator / Type Conversion Operator is an unary operator which forces one data
type to be converted into another data type. C++ supports four types of casting:
1. Static Cast
2. Dynamic Cast
3. Const Cast
4. Reinterpret Cast
We will only use static cast operator here.
Static Cast: The static cast is the simplest among all type-casting using the cast
operator. The static cast is able to perform all the conversions that are carried out
implicitly.
Syntax:
static_cast <new_type> (expression)
Example:
char c = 'A';
int i = 100;
float f = 3.5;
Here, ‘+’ is the operator known as addition operator and ‘a’ and ‘b’ are operands. The
addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.
Unary operators: these operators require only one operand. Example in diagram
below.
Binary operators: these operators require two operands. Example in diagram below.
Ternary operators: these operators require three operands. Example in diagram below.
1) ARITHMETIC OPERATOTRS:
Arithmetic Operators: These are used to perform arithmetic/mathematical operations on
operands. Basic arithmetic operators are:
Addition: The ‘+’ operator adds two operands. For example, x+y.
Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y.
Multiplication: The ‘*’ asterisk operator multiplies two operands. For example, x*y.
Division: The ‘/’ operator divides the first operand by the second. For example, x/y.
Modulus: The ‘%’ operator returns the remainder when first operand is divided by the
second. For example, x%y.
Example-1:
#include <iostream>
using namespace std;
int main()
{
int a = 7, b = 2;
x++;
And similarly −
x = x-1;
is the same as:
x--;
Both the increment and decrement operators can either precede (prefix) or follow
(postfix) the operand. For example −
x = x+1; x = x-1;
can be written as:
++x; // prefix form --x; // prefix form
or as −
x++; // postfix form x--; // postfix form
When an increment or decrement is used as part of an expression, there is an important
difference in prefix and postfix forms.
If you are using prefix form then increment or decrement will be done before rest of the
expression, and if you are using postfix form, then increment or decrement will be done after
the complete expression is evaluated.
Following is the example to understand this difference −
Example-2:
#include <iostream>
return 0;
}
Example-3:
#include <iostream>
using namespace std;
int main()
{
int x = 2, y = 0;
cout << "x = " << x << ", y = " << y << endl;
y = ++x;
cout << "After y = ++x ==> x = " << x << ", y = " << y << endl;
y = x++;
cout << "After y = x++ ==> x = " << x << ", y = " << y << endl;
cout << "x = " << x << ", y = " << y << endl;
return 0;
}
Pre-decrement (--x;) and post-decrement (x--;) YOURSELF.
2) ASSIGNMENT OPERATORS:
Assignment operators are used to assign values to variables. The left side operand of
the assignment operator is a variable and right side operand of the assignment operator can be
a value or an expression. The value on the right side must be cast able of the variable on the left
side otherwise the compiler will raise an error.
Assignment Operators are also known as combined assignment operators, compound
operators and arithmetic assignment operators.
Different types of assignment operators are shown below:
“=”: This is the simplest assignment operator. This operator is used to assign the value on
the right to the variable on the left.
For example:
a = 10;
b = 20;
ch = 'y';
“+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the
current value of the variable on left to the value on the right and then assigns the result
to the variable on the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
“-=”: This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the
current value of the variable on left from the value on the right and then assigns the result
to the variable on the left.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
“*=”: This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies
the current value of the variable on left to the value on the right and then assigns the
result to the variable on the left.
Example:
(a *= b) can be written as (a = a * b)
If initially value stored in a is 5. Then (a *= 6) = 30.
“/=”: This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the
current value of the variable on left by the value on the right and then assigns the result
to the variable on the left.
Example:
(a /= b) can be written as (a = a / b)
If initially value stored in a is 6. Then (a /= 2) = 3.
Example-4:
#include <iostream>
using namespace std;
int main()
{
int a = 10;
cout << "a = "<< a << "\n";
a += 10;
cout << "a += 10; ==> "<< a << "\n";
a -= 5;
cout << "a -= 5; ==> "<< a << "\n";
a *= 7;
cout << "a *= 7; ==> "<< a << "\n";
a /= 3;
cout << "a /= 3; ==> "<< a << "\n";
a %= 5;
cout << "a %= 5; ==> "<< a << "\n";
return 0;
}
Below tables explain their working:
Multiple assignment operator: multiple assignment means to assign the same value to
several variables with one statement.
C++ allows you to assign a value to multiple variables at once. If a program has
several variables, such as a, b, c, and d, and each variable needs to be assigned a value,
such as 12, the following statement may be constructed:
int a = b = c = d = 12;
The value 12 will be assigned to each variable listed in the statement. The assignment
operator works from right to left. 12 is first assigned to d, then to c, then to b, then to a.
3) RELATIONAL OPERATORS:
Relational operators are used for comparison of two values to understand the type of
relationship a pair of number shares. For example, less than, greater than, equal to etc. Let’s see
them one by one:
1. Equal to operator (==): Represented as ‘==’, the equal to operator checks whether the
two given operands are equal or not. If so, it returns true. Otherwise it returns false. For
example, 5==5 will return true.
2. Not equal to operator (!=): Represented as ‘!=’, the not equal to operator checks whether
the two given operands are equal or not. If not, it returns true. Otherwise it returns false.
It is the exact boolean complement of the ‘==’ operator. For example, 5!=5 will return
false.
3. Greater than operator (>): Represented as ‘>’, the greater than operator checks whether
the first operand is greater than the second operand or not. If so, it returns true.
Otherwise it returns false. For example, 6>5 will return true.
4. Less than operator (<): Represented as ‘<‘, the less than operator checks whether the first
operand is lesser than the second operand. If so, it returns true. Otherwise it returns false.
For example, 6<5 will return false.
5. Greater than or equal to operator (>=): Represented as ‘>=’, the greater than or equal to
operator checks whether the first operand is greater than or equal to the second operand.
If so, it returns true else it returns false. For example, 5>=5 will return true.
6. Less than or equal to operator (<=): Represented as ‘<=’, the less than or equal to
operator checks whether the first operand is less than or equal to the second operand. If
so, it returns true else false. For example, 5<=5 will also return true.
Example-5:
#include <iostream>
using namespace std;
int main()
{
int a = 10, b = 4;
cout << "a > b :: " << (a > b) << endl;
cout << "a < b :: " << (a < b) << endl;
return 0;
}
4) LOGICAL OPERATORS:
They are used to combine two or more conditions/constraints or to complement the
evaluation of the original condition under consideration. They are described below:
1. Logical AND operator: The ‘&&’ ampersand operator returns true when both the
conditions under consideration are satisfied. Otherwise it returns false. For example, a
&& b returns true when both a and b are true (i.e. non-zero).
2. Logical OR operator: The ‘||’ operator returns true even if one (or both) of the conditions
under consideration is satisfied. Otherwise it returns false. For example, a || b returns
true if one of a or b or both are true (i.e. non-zero). Of course, it returns true when both
a and b are true.
3. Logical NOT operator: The ‘!’ operator returns true the condition in consideration is not
satisfied. Otherwise it returns false. For example, !a returns true if a is false, i.e. when
a=0.
Example-6:
#include <iostream>
using namespace std;
int main()
{
int a = 1, b = 0;
return 0;
}
PRECEDENCE AND ASSOCIATIVITY OF OERATORS:
PUNCTUATIONS: