0% found this document useful (0 votes)
21 views64 pages

Unit 2 DSA

The document provides an overview of tokens in C++, including keywords, identifiers, constants, punctuators, and operators. It details the rules for defining identifiers, the types of constants, and the various categories of operators such as arithmetic, relational, logical, and bitwise. Additionally, it covers variable scope, naming conventions, and data types, along with their sizes and ranges.

Uploaded by

poojaagg257
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)
21 views64 pages

Unit 2 DSA

The document provides an overview of tokens in C++, including keywords, identifiers, constants, punctuators, and operators. It details the rules for defining identifiers, the types of constants, and the various categories of operators such as arithmetic, relational, logical, and bitwise. Additionally, it covers variable scope, naming conventions, and data types, along with their sizes and ranges.

Uploaded by

poojaagg257
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

UNIT - 2

Tokens
• Smallest unit in a C++ program that the compiler
understands.
• Types of Tokens:
1) Keywords
2) Identifiers
3) Constants
4) Punctuators
5) Operators
Keywords
• Keywords are reserved words that carry predefined meanings and
specific functionalities within a program.

• The total number of keywords in C++ are 95.

• Examples of common keywords:


→ int, float, if, else, for, while, class, public, private, return, try,
catch, virtual, namespace, etc.
Keywords
if else switch case default

break continue goto return for

while do auto register static

extern short int long signed

unsigned float double void bool

char const class struct union

enum typedef using namespace new

delete sizeof inline friend virtual

true false nullptr


Identifiers
• Identifiers are the unique names assigned to variables, functions,
classes, structs, or other entities within the program.
• Example:

int num = 10;

string first_name = “Ram”;


Rules to define the name of identifier:
• An identifier can only begin with a letter or an underscore(_).

• An identifier can consist of letters (A-Z or a-z), digits (0-9), and underscores
(_). White spaces and Special characters can not be used as the name of an
identifier.

• Keywords cannot be used as an identifier because they are reserved words to


do specific tasks. For example, string, int, class, struct, etc.

• Identifier must be unique in its namespace. As C++ is a case-sensitive


language so identifiers such as 'first_name' and 'First_name' are different
entities.
Valid Names Invalid Names

1) 12raju //Starts with digit


_ram ,
ram_shyam , 2) mohan sharma //contains space
ram23 ,
shyam_001 3) int, float, string // keywords
Constants
• Constants are fixed values in a program whose value cannot be
changed during execution.

Type Syntax / Example Explanation

int x = 10; Fixed values written


Literal Constants
char ch = 'A'; directly in code.
Declares a variable as
const Keyword const float pi = 3.14; constant → cannot be
modified.
Preprocessor constant
#define MAX 100
#define Macro (symbolic name for a
int arr[MAX];
value).
enum Colors { RED, Defines a group of named
Enumerated Constants
GREEN, BLUE }; integer constants.
Punctuators
• Punctuators are the token characters having specific meanings within
the syntax of the programming language. These symbols are used in a
variety of functions, including ending the statements, defining control
statements, separating items, and more.

• Punctuators in C++ are:


1) Semicolon (;): It is used to terminate the statement.
2) Square brackets []: They are used to store array elements.
3) Curly Braces {}: They are used to define blocks of code.
4) Double-quote ("): It is used to enclose string literals.
5) Single-quote ('): It is used to enclose character literals.
Operators
• C++ operators are special symbols that are used to perform operations
on operands such as variables, constants, or expressions.

• Types of Operators:
1) Arithmetic: +, -, *, %, /,++,--
2) Relational: ==, !=, <, >,<=,>=
3) Logical: &&, ||, !
4) Assignment: =, +=, -=
5) Ternary Operator:-?:
6) Bitwise Operator: &, |, ^, <<, >>,~
7) Miscellaneous Operator(sizeof(),comma(,),dot(.),arrow(->),::,&
Variables
• Variable is a name given to a memory location. It is the basic unit of storage in a
program. The value stored in a variable can be accessed or changed during
program execution.

• Syntax of variable definition:


--> type name;
where, type is the type of data that a variable can store, and name is the name
assigned to the variable

• Example: int value; //Declaration of variable


value = 5; // Intializing a variable
int a = 10; // Declaration and Intialization
Variable Naming Convention
The set of rules for naming a variable are same as identifier. These are suggestions for
naming variables for easier understanding.

• Start with lowercase alphabet.

• Use camelCase (first letter of word should be lowercase and then each word begin
with uppercase. Eg:(studentName, firstName)

• Constants usually in UPPERCASE → MAX_VALUE, MIN_VALUE

• Use descriptive, meaningful names.

• For example, first_name, frequencyCount.


Scope of Variable
When you declare a program element such as a class, function, or variable, its
name can only be "seen" and used in certain parts of your program. The
context in which a name is visible is called its scope.

Types of Variable Scope:

➢ Local Scope
➢ Global Scope
Local Scope
Variables defined within a function or block are said to be local to those functions or a
block and are called local variables. Local variables do not exist outside the block in
which they are declared, i.e. they cannot be accessed or used outside that block.

#include <iostream>

int main() {
{
int x = 10; // Local variable, Scope local to only this block
cout << x; // Works here
}
cout << x; // Error: x not visible here
}
Global Scope
Global scope refers to the region outside any function or a block. The variables
declared here are accessible throughout the entire program and are called Global
Variables.

#include <iostream>

int x = 20; // Global variable

int main() {
cout << x; // Accessible everywhere
}
Scope and Lifetime of Variables
Scope Lifetime Example

Local Scope Exists only within the void func(){ int x=5; }
block/function

Global Scope Exists throughout program int x=10; int main(){}


execution
Data Types in C++

Primitive Derived User Defined

int Array Class


float
function Structure
double

char pointer Union

boolean Enum
Data Type Keyword Example Size (approx.) Range

Boolean bool bool pass = true; 1 byte true / false

-128 to 127 (signed)0


Character char char grade = 'A'; 1 byte
to 255 (unsigned)

Short Integer short short age = 25; 2 bytes -32,768 to 32,767

-2,147,483,648 to
Integer int int marks = 90; 4 bytes
2,147,483,647

(4B) -2,147,483,648 to
2,147,483,647(8B) -
long population = 9,223,372,036,854,77
Long Integer long 4 or 8 bytes
100000; 5,808 to
9,223,372,036,854,77
5,807
Data Type Keyword Example Size (approx.) Range

-
9,223,372,036,854,77
long long stars =
Long Long Int long long 8 bytes 5,808 to
1000000000;
9,223,372,036,854,77
5,807

Float float float pi = 3.14; 4 bytes ~1.2E−38 to 3.4E+38

~2.3E−308 to
Double double double g = 9.81; 8 bytes
1.7E+308

long double val = ~3.4E−4932 to


Long Double long double 8–16 bytes
3.14159; 1.1E+4932

string name =
String string Depends Depends on length
"Apporva";
OPERATORS
Operators are special symbols that are used to perform operations on operands
such as variables, constants, or expressions.

For example: (A+B), in which 'A' and 'B' are operands, and '+' is an arithmetic operator
which is used to add two operands.
UNARY
OPERATOR

BINARY
OPERATOR
BASED ON
NO. OF ARITHMETIC
OPERANDS TERNARY
OPERATORS
OPERATOR
RELATIONAL
OPERATORS
CLASSIFICATION
OF OPERATORS
LOGICAL
OPERATORS

BASED ON BITWISE
ROLE OF OPERATORS
OPERATOR

ASSIGNMENT
OPERATORS

MISCELLANEOUS
OPERATORS
Unary Operators
• Unary operator operates on only one operand.
For example, in the expression -3,

• The operand can be present towards the right of unary operator, as in -3 or towards
the left of unary operator, as in the expression a++.

• Examples of unary operators are:


1. & (address-of operator)
2. sizeof operator
3. ! (logical negation)
4. ~ (bitwise negation)
5. ++ (increment operator)
6. -- (decrement operator) etc.
Binary Operators
Binary operator operates on two operands. It requires an operand towards its
left and right.

For example, in expression 2-3

Examples of binary operators are:


1. * (multiplication operator),
2. / (division operator),
3. << (left shift operator),
4. == (equality operator),
5. && (logical AND),
6. & (bitwise AND) etc.
Ternary Operators

Ternary operator operates on three operands.

Conditional operator (i.e. ?:) is the only ternary operator available in Cpp.

Expression1 ? Expression2 : Expression3;


If Expression1 became true then Expression2 will be executed otherwise Expression3 will be
executed.
Operator Precedence
Each operator in Cpp has a precedence associated with it.

In a compound expression, if the operators involved are of different precedence, the


operator of higher precedence is evaluated first. For example, in an expression
b=2+3*5, The precedence order is * > + > = .

To determine which of these operators will operate first, the associativity of these
operators is to be considered.
Associativity of Operators

An operator can be either left-to-right associative or right-to-left associative.

If operators are left-to-right associative, they are applied in left-to-right order i.e. the
operator which appears towards left will be evaluated first.

If they are right-to-left associative, they will be applied in the right-to-left order.

The multiplication and the division operators are left-to- right associative.
Hence, in expression 2*3/5, * evaluated first then / from left to right.
Arithmetic Operators
The arithmetic operations like addition, subtraction, multiplication, division
etc. can be performed by using arithmetic operators.
[Link] Operator Name of Operator Category ary of Precedence Associativiy
Operators

1. + Unary plus Unary Unary Level-I R→L


- Unary minus operators (Highest) (Right-to-
++ Increment left)
-- Decrement
2. * Multiplication Multiplicative Binary Level-II L→R
/ Division operators (Intermediate) (Left-to-
% Modulus right)

3. + Addition Additive Binary Level-III L→R


- Subtraction operators (Lowest)
Relational Operators
Relational operators are used to compare two quantities (i.e. their operands).

[Link] Operator Name of Category ary of Precedence Associativity


Operator Operators amongst
relational class

1. < Less than Relational Binary Level-I L→R


> Greater than operators
<= Less than or equal to
>= Greater than or
equal to

2. == Equal to Equality Binary Level-II L→R


!= Not equal to operators
Logical Operators
Logical operators are used to logically relate the expressions.

[Link] Operator Name of Category ary of Precede Associati


Operator Operator s nce amongst vity
logical class

1. ! Logical NOT Unary Unary Level-I R→L

2. && Logical AND Logical Binary Level-II L→R


operator

3. || Logical OR Logical Binary Level-III L→R


operator
Bitwise Operators
These operators do not consider operand as one entity and operate on the individual bits
of operands.
[Link] Operator Name of Category ary of Precedence Associativity
Operator Operators amongst
bitwise class
1. ~ Bitwise NOT Unary Unary Level-I R→L

2. << Left Shift Shift operators Binary Level-II L→R


>> Right Shift
3. & Bitwise AND Bitwise Binary Level-III L→R
operator
4. ^ Bitwise X-OR Bitwise Binary Level-IV L→R
operator
5. | Bitwise OR Bitwise Binary Level-V L→R
operator
Assignment Operators
A variable can be assigned a value by using assignment operator.

[Link] Operator Name of Operator Category ary of Precedence Associativity


Operators
1. = Simple assignment Assignment Binary Level-I R→L
*= Assign product Assign Shorthand
/= quotient Assign assignment
%= modulus Assign operators
+= sum Assign
-= differenceAssign
&= bitwise AND
|= Assign bitwise OR
^= Assign bitwise XOR
<<= Assign left shift
>>= Assign right shift
Conditional Operator
Conditional operator is the only ternary operator available in Cpp.

The general form of conditional operator is E1?E2:E3, where E1, E2 and E3 are
sub-expressions.
The sub-expression E1 must be of scalar type .
The sub-expression E1 is evaluated first. If it evaluates to a non-zero value (i.e. true), then
E2 is evaluated and E3 is ignored.
If E1 evaluates to zero (i.e. false), then E3 is evaluated and E2 is ignored.
Miscellaneous Operator
Other operators available in Cpp are:
Function call operator (i.e. ())
Array subscript operator (i.e. [])
Member select operator
⚫Direct member access operator (i.e. . (dot operator or
period))
⚫Indirect member access operator (i.e. -> (arrow operator))

Indirection operator (i.e. *)


Conditional operator (i.e. ?:)
Comma operator (i.e. ,)
sizeof operator
Address-of operator (i.e. &)
Sizeof Operator
The sizeof operator is used to determine the size in bytes that a value or a data
object will take in memory.

The general form of sizeof operator is:


sizeof expression or sizeof (expression)

For example: sizeof 2, sizeof(a), sizeof(2+3)

sizeof(type-name) For example: sizeof(int), sizeof(int*), sizeof(char)


The type of result of evaluation of sizeof operator is int.
Address-of Operator
The address-of operator is used to find address i.e. l-value of a data object.

The following are the important points about address-of operator:


1. The address-of operator must appear towards the left side of its operand.

2. The syntax of using address-of operator is & operand.


COMBINED PRECEDENCE OF ALL OPERATOR

S.N Operator Name of Operator Category ary of Precedence Associativity


o Operator
s
1. () Function call Level-I
[] Array subscript (Highest)
-> Indirect member access
. Direct member access

2. ! Logical NOT Unary Unary Level-II R→L


~ Bitwise NOT Unary
+ plus Unary minus
- Increment
++ Decrement Address-
-- of Indirection Sizeof
&
*
sizeof
3. * Multiplication Multiplicative Binary Level-III L→R
/ Division operators
% Modulus
[Link] Operator Name of Operator Category ary of Precedence Associativity
Operators
4. + Addition Additive Binary Level-IV L→R
- Subtraction operators
5. << Left Shift Shift Binary Level-V L→R
>> Right Shift operators
6. < Less than Relational Binary Level-VI L→R
> Greater than operators
<= Less than or equal to
>= Greater than or equal to

7. == Equal to Equality Binary Level-VII L→R


!= Not equal to operators
8. & Bitwise AND Bitwise Binary Level-VIII L→R
operator
9. ^ Bitwise X-OR Bitwise Binary Level-IX L→R
operator
10. | Bitwise OR Bitwise Binary Level-X L→R
operator
11. && Logical AND Logical Binary Level-XI L→R
operator
12. || Logical OR Logical Binary Level-XII L→R
operator
13. ?: Conditional operator Conditional Ternary Level-XIII R→L
[Link] Operator Name of Operator Category ary of Precedence Associativity
Operator
s
14. = Simple assignment Assignment Binary Level-XIV R→L
&
*= Assign product Shorthand
/= Assign quotient Assign assignment
%= modulus Assign operators
+= sum Assign
-= Difference Assign
&= bitwise AND Assign
|= bitwise OR Assign
^= bitwise XOR Assign
<<= left shift Assign
>>= right shift Assign

15. , Comma operator Comma Binary Level-XV L→R


(Least)
Usage of Math Library
Header: #include<cmath>
Namespace: std
Provides mathematical functions for operations in Cpp.

Constants (C++20 in ):
- std::numbers::pi = 3.141592653589793...
- std::numbers::e = 2.718281828459045…

Type Variants:
- float → sinf, cosf, powf
- long double → sinl, cosl, powl
USAGE OF MATH LIBRARY
FUNCTION
USAGE OF MATH LIBRARY FUNCTION

Example Code:

#include<cmath>
#include using namespace std;
int main()
{
double x = 9.0;
cout << "Square root: " << sqrt(x) << endl;
cout << "Power: " << pow(2, 3) << endl;
return 0;
}
Typecasting
Typecasting in C++ is the process of converting one data type into another. It allows us to
perform operations between incompatible data types by explicitly or implicitly converting
them.

• Implicit Typecasting:
→ Done automatically by the compiler.

→ Converts smaller data type → larger data type

→ Example: int x = 10;

double y = x;

• Explicit Typecasting:
→ Done manually by the programmer.

→ Example: double pi = 3.14159;

int value = (int) pi;


Taking Inputs on Coding Platforms
Single value in a single line:

#include <iostream>

int main() {
int n;
cin >> n; // Input: 5
cout << "You entered: " << n;
return 0;
}
Taking Inputs on Coding Platforms
Multiple known values in a single line:

#include <iostream>

int main() {
int a, b, c;
cin >> a >> b >> c; // Input: 10 20 30
cout << "Sum = " << a + b + c;
return 0;
}
Taking Inputs on Coding Platforms
Multiple known values in multiple lines.

#include <iostream>

int main() {
int x, y;
cin >> x; // Input: 7
cin >> y; // Input: 8
cout << "Product = " << x * y;
return 0;
}
Program Flow Control
Conditional Statements

 Conditional statements help you to make a decision based on certain


conditions. These conditions are specified by an expression which are
evaluated to a boolean value of true or false.

 C++ has the following conditional statements:


❑ if
❑ else
❑ else if
❑ switch
‘IF’ STATEMENT
To specify a block of code to be executed, if a specified condition is true.

The general form of if statement is:

if(expression) //if header


statement //if body
‘IF’ STATEMENT (CONT..)
‘IF ELSE’ STATEMENT
Most of the problems require one set of actions to be performed
if a particular condition is true and another set of actions to be
performed, if the condition is false.

To implement such a decision, C + + language provides if-else


statement.

The general form of if-else statement is:

if(expression) //if-else header


statement1 //if body
else //else clause
statement2 //else body
Flow chart of if else statement
‘IF ELSE’ STATEMENT (CONT…)
Program to input a number and display the same if it is positive or negative.
#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (num > 0) {
cout << "Number " << num << " is positive." << endl;
}
else {
cout << "Number " << num << " is negative." << endl;
}
return 0;
}

OUTPUT –
Enter a number: -9
Number -9 is negative.
‘NESTED IF ELSE’ STATEMENT
If the body of if statement is another if statement

if( expression1 ){
if( expression1 ) if( expression2 ){
{ statement-block1;
if( expression2 ) }
{ else {
statement-block1; statement-block
} 2;
else }
{ }
statement-block 2; else
} {
} if( expression3 ){
else statement-block3;
{ }
statement-block 3; else {
} statement-block
4;} }
Flow chart of nested if else statement
‘IF ELSE LADDER’
if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
}
else {
// statement(s)
}
Flow chart of if else ladder statement
Switch Statement
switch(expression)
The switch statement is used to {
control complex branching case value_1:
operations. /* Statement/s */
When there are many conditions, it break;
becomes too difficult and
case value_2:
complicated to use if and if-else /* Statement/s */
constructs. break;

case value_n:
/* Statement/s */
break;

default:
/* Statement/s */
}
Flow chart of Switch statement
C++ PROGRAM TO PRINT NAME OF THE DAY OF WEEK.
#include <iostream>
using namespace std;
int main() {
int day;
cout << "Enter a number (1-7): ";
cin >> day;
switch (day) {
case 1: cout << "Sunday"; break;
case 2: cout << "Monday"; break;
case 3: cout << "Tuesday"; break;
case 4: cout << "Wednesday"; break;
case 5: cout << "Thursday"; break;
case 6: cout << "Friday"; break;
case 7: cout << "Saturday"; break;
default: cout << "Invalid input! Please enter
number between 1 and 7.";
}
return 0;
}
C++ PROGRAM TO CHECK VOWEL OR CONSONANT USING SWITCH CASE (break
statement using in each case)
#include <iostream>
using namespace std;
int main() {
char ch;
cout << "Enter any alphabet: ";
cin >> ch;
switch(ch) {
case 'a': cout << "Vowel"; break;
case 'e': cout << "Vowel"; break;
case 'i': cout << "Vowel"; break;
case 'o': cout << "Vowel"; break;
case 'u': cout << "Vowel"; break;
case 'A': cout << "Vowel"; break;
case 'E': cout << "Vowel"; break;
case 'I': cout << "Vowel"; break;
case 'O': cout << "Vowel"; break;
case 'U': cout << "Vowel"; break;
default: cout << "Consonant";
}
return 0;
}
Switch Vs Else-If Ladder

S. No. Switch Else-If Ladder


It executes the different
It executes the different
cases on the basis of the
1 blocks based on the condition
value of the switch
specified.
variable.

It can only evaluate the int It can evaluate any type of


2 or char type expressions. expression.

Faster and easier to read


3 It can get messy when there
for the large number of
are lots of conditions.
conditions.
Reference

1. Geeksforgeeks [Link]
examples/

2. W3Schools [Link]

3. [Link]
[Link]
H OW B R EA K STATEMEN T WORKS ?

You might also like