[go: up one dir, main page]

0% found this document useful (0 votes)
9 views40 pages

PF Notes - I

The document provides an introduction to programming, covering the definition of computer programs, types of programming languages (high-level and low-level), and the roles of compilers and interpreters in translating code. It explains the structure of a C++ program, including comments, input/output operations, and syntax rules, while emphasizing the importance of coding conventions for readability. Additionally, it discusses the process of compiling and executing a program, along with examples of taking user input in C++.

Uploaded by

nidashahzadi2468
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views40 pages

PF Notes - I

The document provides an introduction to programming, covering the definition of computer programs, types of programming languages (high-level and low-level), and the roles of compilers and interpreters in translating code. It explains the structure of a C++ program, including comments, input/output operations, and syntax rules, while emphasizing the importance of coding conventions for readability. Additionally, it discusses the process of compiling and executing a program, along with examples of taking user input in C++.

Uploaded by

nidashahzadi2468
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

INTRODUCTION TO PROGRAMMING:

PROGRAM AND PROGRAMMING LANGUAGES:


A computer program (also commonly called an application) is a set of instructions that
the computer can perform in order to perform some task. The process of creating a program is
called programming. A person who writes computer programs is called a programmer.
Programming Languages: In programming, languages which are used for writing
computer programs are called programming languages.
Programmers use programming languages to write computer programs.

TYPES OF PROGRAMMING LANGUAGES:


There are basically two types of programming languages:
1) High-Level Languages.
2) Low-Level Languages.
1) High-Level Languages: Languages which are close to human language (easily
understandable by humans) are called High-Level Languages.
Computer cannot directly understand programs written in High-Level Languages.
These programs must be converted into machine language by a process called
language translation (which is the process of converting High-Level Programs into
Machine Language Program). That is why, programs written in High-Level Languages
are slower in execution (run slowly).
Language Translators are used for carrying out the process of Language Translation.
These are Compiler, Interpreter and Assembler.
Examples: C++, Java, C#, Swift, Python, Ruby, Dart etc.
2) Low-Level Languages: Languages which are far from human language (not easily
understandable by humans) are called Low-Level Languages.
Examples: Machine Language, Assembly Language etc.

 Machine Language: Machine Language is the only language that a computer


can directly understand. It is also called native language of a computer.
In Machine Language, program instructions are written in the form of
binary digits (0 and 1). Programs written in machine language do not need
any translation. That is why, programs written in machine language are faster
in execution (run faster).
Let’s say we have to add two numbers 3 (binary = 11) and 6 (binary = 110).
Let’s say code for addition in machine language is 1011 1001. So, we can write
a machine language instruction as:

The problem here is that programmers had to remember these


instructions, which was very difficult for them. That is why High-Level
Languages were developed.

 Assembly Language: Assembly Language is one-level higher than machine


language. In assembly language, programmers use Simple English Codes for
writing programs. These codes are called (mnemonics).
The above machine language example can be re-written in assembly
language as:

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:

Compiler: A compiler is a computer program that transforms code written in a high-level


programming language into the machine code. It is a program which translates the human-
readable code to a language (machine language) a computer processor understands (binary 1
and 0 bits). The computer processes the machine code to perform the corresponding tasks.
Interpreter: An interpreter is a computer program, which coverts high-level program
statements one-by-one into the machine code when the program is running.
Both compiler and interpreters do the same job which is converting higher level
programming language code to machine code. However, a compiler will convert the code into
machine code (creates an executable file i.e. exe file) before the program runs. Interpreters
convert source code into machine code when the program is running.

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:

Let’s discuss each and every part of the above program.

1. Comments – You can see two types of comments in the above program
// This is a single line comment

/* This is a multiple line comment


suitable for long comments
*/
Comments as used to write some notes about a program written by programmer during
code development. Comment doesn’t affect your program logic in any way, you can write
whatever you want in comments but it should be related to the code and have some meaning so
that when someone else look into your code, the person should understand what you did in the
code by just reading your comment.
For example:

/* This is a simple C++ program


That displays Hello World on the screen
*/
#include<iostream>

//Single line comment


using namespace std;

//This is where the execution of program begins


int main()
{
// displays Hello World! on screen
cout<<"Hello World!";

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.

INDENTATION AND CODING CONVENTIONS:


Indentation Convention: Indentation Convention means to write a program in a way that
it is more readable (easy to read) not only for the programmer, but also for anyone who sees
that program.
Coding Conventions: Coding Convention means to give proper/meaningful names to
variables, functions and other user-defined identifiers.
Programmers strictly follow indentation and coding conventions because there are many
benefits for following them.
Let’s take a simple example:
Q = Which Style is more readable (easy to read)?
STYLE-1:
#include<iostream>

using namespace std;

int main()
{
cout<<"Hello World!";

return 0;
}
STYLE-2:
#include<iostream>
using namespace std;

int main(){ cout<<"Hello World!"; return 0;


}

Style-1? Why? Because Program in Style-1 is more readable (easy to read)?


This is what indentation and coding conventions are all about, in short words.
PROGRAM OUTPUT:
1. In program output, we will discuss about, the following when we will be practicing the
programs:
 setw(), left, right with setw()
 setprecision(), fixed, showpoint
SEE TOPIC: Formatting Output.

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.

NOTES: Programs will be shared in separate file.

THE cin OBJECT:


So far we have seen that we use variables, assign value to them and after performing
some calculations and we give the output. However, these programs have a limitation that user
cannot enter his or her own data. If you decide to change the initial value of any variable, the
program must be modified and recompiled. Almost in all real-life applications like facebook,
WhatsApp, Twitter, Messages, ATM programs etc., user enters data and the application work
with the data entered by the user. In C++, user can enter data using cin object.
Usually the input device in a computer is the keyboard. C++ cin statement is the instance
of the class istream and is used to read input from the standard input device which is usually a
keyboard.
The stream extraction operator (>>) is used along with the object cin for reading inputs.
The stream extraction operator extracts the data from the object cin which is entered using the
keyboard.

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

Enter your age: 18


Your age is: 18

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.

Example-2: We want the user to enter the length of a rectangle.


C++ TAKING MULTIPLE INPUTS:
In C++, we can take multiple inputs in a single cin statement.

#include <iostream>
using namespace std;

int main() {
char a;
int num;

cout << "Enter a character and an integer: ";


cin >> a >> num;

cout << "Character: " << a << endl;


cout << "Number: " << num;

return 0;
}

Output

Enter a character and an integer: F


23
Character: F
Number: 23

cin >> a >> num;

can also be written as:


cin >> a;
cin >> num;
NOTES: Programs will be shared in separate file.
SYNTAX RULES:
Syntax Rules: these are the rules programmers must follow while writing C++ programs.
We will discuss them while we will be practicing the programs.
ERRORS/ TYPES OF ERRORS:
Error: Error is an illegal operation performed by the user which results in abnormal
working of the program.

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 ;

 Syntax of conditional (if-else, switch)/ iterative structures (while, do-while, for)


is wrong.

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:

Keyword: A Keyword is a special word in a programming language that has a pre-defined


(already mentioned) meaning and pre-defined use. Keywords are also called Reserved Words.
In C++, there are more than 64 keywords. Keywords in C++ are always written in small
letters. Below is a list of C++ Keywords.
DATA TYPES:
IDENTIFIERS:
Identifiers: Identifiers are used as general names given to different parts of the program
namely variables, constants, labels, functions, arrays, classes etc. by the programmers.
As the name suggests, they are used to identify certain parts of a program. Identifiers are
the building blocks of a program.

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:

 Standard/Predefined Identifiers: Like Keywords, Standard/Pre-defined Identifiers have


special meaning in C++, but they can be re-defined in the program for other purposes,
but this practice is not-recommended.
Example: cin/cout are standard identifiers in C++ which are the names of
input/output functions defined in iostream library.

 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.

Variable: A Variable is a location in computer’s memory (RAM) where the data of a


program can be stored by the programmer for performing different calculations and for later
use in the program. A variable is the basic unit of storing data in a program. Variable means “a
quantity that can change”.
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
 In C++, all the variables must be declared before use.
Q = How to declare variables?
Variable Declaration: Variable declaration means to give it:
1) a data type.
2) and a name.
In other words, we can say that variable declaration statement introduces that
variable to the computer before it can be used in the program.

Syntax:
// declaring single variable…
data_type variable_name;

// declaring multiple variables…


data_type variable1_name, variable2_name, variable3_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.

TYPES OF DATA TYPES:


Whenever a variable is defined in C++, the compiler allocates some memory for that
variable based on the data-type with which it is declared. Every data type requires a different
amount of memory.

Data types in C++ is mainly divided into three types:


1. Primitive/Built-In/Pre-defined Data Types: These data types are built-in or predefined in
C++ and can be used directly by the programmers to work with variables. Example: int,
char, float, bool etc.
Primitive data types available in C++ are:
 Integer
 Character
 Boolean
 Floating Point
 Double Floating Point
 Valueless or Void
 Wide Character

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

DATA TYPE MODIFIERS:


As the name implies, datatype modifiers are used with the built-in data types to modify
the length of data that a particular data type can hold.
Data type modifiers available in C++ are:
 Signed
 Unsigned
 Short
 Long

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:

Sr.# Type & Description

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:

// declaring single variable…


data_type variable_name;

// declaring multiple variables…


data_type variable1_name, variable2_name, variable3_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
In variable declaration, the compiler just reads the variable data type and
variable name, but it does not allocate (assign) any space/memory to the variable in RAM.

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:

I. int age = 5; // single variable initialization


As ‘5’ it is the first value (initial value) given to ‘age’ variable, it is therefore called
variable initialization.
II. int num1 = 5, num2 = 10, sum = 0; // multiple variables initialization
The compiler will store binary of the values in RAM, because data is stored in RAM as
binary values.
4) VARIABLE ASSIGNMENT:
The process of assigning (giving) a value to a variable is called, variable
assignment.
Syntax:
Variable assignment has 2 different syntaxes, i.e. the syntax of variable
declaration and variable initialization.
Example:
// syntax of variable declaration
int age;
age = 50; // variable assignment
age = 60; // variable assignment
// syntax of variable initialization
int age = 50; // both variable assignment and initialization
age = 60; // variable assignment
NOTE:
Variable initialization is a type of variable assignment, but because it is the first value
assigned to a variable at the time of declaration, that is why it has a special name i.e. variable
initialization.

LVALUES AND RVALUES:

There are two kinds of expressions in C++ −


 lvalue − Expressions that is to the left side of variable assignment statement and refer
to a memory location is called "lvalue" expression. An lvalue may appear as either the
left-hand or right-hand side of a compound assignment.
 rvalue − The term rvalue refers to a data value that is at the right side of a variable
assignment statement and stored at some address in memory. An rvalue is an
expression that cannot have a value assigned to it which means an rvalue may appear
on the right- but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric
literals are rvalues and so may not be assigned and can not appear on the left-hand side.
Following is a valid statement −
int age = 20;
But the following are not valid statements and would generate compile-time error −
10 = 20;
int 20 = age;
LITERALS:

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>

using namespace std;


int main()
{
float radius = 3.456, circumference;
circumference = 2 * 3.14158 * radius;
cout << "Circumference = " << circumference << endl;
return 0;

}
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 −

 Using #define preprocessor directive.


 Using const keyword.
1) THE #define Preprocessor Directive:
Following is the form to use #define preprocessor directive to define a constant −
Syntax:
#define identifier value

Following is an example program:


Example:
#include <iostream>
#define PI 3.14159
using namespace std;
int main()
{
float radius = 3.456, circumference;
circumference = 2 * PI * radius;
cout << "Circumference = " << circumference << endl;

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()
{

const float PI = 3.14159;


float radius = 3.456, circumference;
circumference = 2 * PI * radius;
cout << "Circumference = " << circumference << endl;
return 0;

}
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 −

sizeof (data type/variable/value)


sizeof (int);  sizeof(5); sizeof(age);
Where data type is the desired data type including classes, structures, unions and any
other user defined data type.
Example:
#include <iostream>
using namespace std;

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;

cout << "Size of float :" << sizeof(float) << endl;


cout << "Size of double :" << sizeof(double) << endl;
cout << "Size of long double : " << sizeof(long double) << 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-1: When a value is converted to a higher data type, it is said to be promoted. To


demote a value means to convert it to a lower data type.

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;

 int -> float && float -> int:


int i = 100;
float f = i;
cout << "Float = " << f << 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:

As the name suggests, this type of casting is favored by the C programming


language. It is also known as cast notation / conversion by assignment.
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;
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;

int sum = int(d) + 1;


cout << "Sum = " << sum << endl;
d = (double)sum + 23.7;
cout << "Again Double = " << d << endl;
NOTE: We used both the C style type conversion and the function-style casting for type
conversion and displayed the results. Since they perform the same task, both give us the same
output.
Type Conversion Operators / Cast Operators:

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;

// using cast operator


i = static_cast<int>(f);  int(f);  (int)f;
cout << "Int = " << i << endl << "Float = " << f << endl;
i = static_cast<int>(c);
cout << "Char --> Int = " << i << endl;
OPERATORS:
Operator: Operators are symbols that help us to perform specific mathematical and
logical computations on operands. In other words, we can say that an operator operates the
operands.
For example, consider the below statement:
c = a + b;

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’.

TYPES OF OPERATORS WITH RESPECT TO OPERANDS:


There are three types of operators in C++ with respect to operands:

 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;

// printing the sum of a and b


cout << "a + b = " << (a + b) << endl;
// printing the difference of a and b
cout << "a - b = " << (a - b) << endl;

// printing the product of a and b


cout << "a * b = " << (a * b) << endl;

// printing the division of a by b


cout << "a / b = " << (a / b) << endl;

// printing the modulo of a by b


cout << "a % b = " << (a % b) << endl;
return 0;
}
NOTES:
 C++ does not allow integer division by ZERO, but with floats, it allows.
 Modulo operator (%) only works with integers.

1.1) INCREMENT (++) AND DECREMENT (--) OPERATORS:


The increment operator (++) adds 1 to its operand, and the decrement operator (--)
subtracts 1 from its operand. Thus −
x = x+1;
is the same as:

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>

using namespace std;


int main()
{
int x = 2;

cout << "x = " << x << endl;


cout << "++x = " << ++x << endl;
cout << "x++ = " << x++ << endl;
cout << "x = " << x << endl;

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;

cout << "a >= b :: " << (a >= b) << endl;

cout << "a <= b :: " << (a <= b) << endl;

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;

cout << "a && b :: " << (a && b) << endl;

cout << "a || b :: " << (a || b) << endl;

cout << "!a :: " << !a << endl;


cout << "!b :: " << !b << endl;

return 0;
}
PRECEDENCE AND ASSOCIATIVITY OF OERATORS:
PUNCTUATIONS:

You might also like