Unit-1_PPS_H6nS4p8J1kalgorithm and flowchart

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 82

Unit-1

BY PROF.AVANI BHUVA
Program Development Steps
In order to solve a problem using a computer it is necessary
to evolve a detailed and precise step by step method of
solution.
1. Algorithm
2. Flowchart
3. Program

BY PROF.AVANI BHUVA
Definition of Algorithm
Finite sequence of instructions (to solve a problem).
The development of a proper procedure to get the required results.
An ALGORITHM is a finite set of statements, each of which has a clear meaning and can be executed in a
finite amount of time and with a finite amount of efforts.
Its an English language representation of the sequence of steps to be executed to perform a given task.
Its description of the steps necessary to solve a problem,
It should define the procedure to perform the given task
Hence its also called as STEP-FORM ALGORITHM
Graphical representation of an algorithm can be done by using FLOWCHART or PSEUDO CODE
ALGORITHM

Algorithm is a step – by – step procedure which is helpful in solving a problem. If, it is written in English like
sentences then, it is called as ‘PSEUDO CODE’.

BY PROF.AVANI BHUVA
What are the Characteristics of an Algorithm?

As one would not follow any written instructions to cook the recipe, but only the standard one. Similarly, not all written instructions for programming is an
algorithms. In order for some instructions to be an algorithm, it must have the following characteristics:
•Clear and Unambiguous: The algorithm should be clear and unambiguous. Each of its steps should be clear in all aspects and must lead to only one
meaning.
•Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined inputs.
•Well-Defined Outputs: The algorithm must clearly define what output will be yielded and it should be well-defined as well.
•Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time.
•Feasible: The algorithm must be simple, generic, and practical, such that it can be executed with the available resources. It must not contain some future
technology or anything.
•Language Independent: The Algorithm designed must be language-independent, i.e. it must be just plain instructions that can be implemented in any
BY PROF.AVANI BHUVA
language, and yet the output will be the same, as expected.
Properties of Algorithm

1. Non ambiguity: Algorithm must be clear and precise. No ambiguity in algorithm.


2. Range of Input: Range should be mentioned in the algorithm. There should be clear indication for range
3. Multiplicity: Algorithm can be represented in multiple way i.e. by writing in English language or graphical
representation called as flowchart or Pseudo code Algorithm
4. Speed: It should produce fast result or efficiently
5. Finiteness: It should be finite i.e. no infinite condition.

It should terminate after a finite time.


It should produce at least one output.
It should take zero or more input.
It should be deterministic means giving the same output for the same input case.
Every step in the algorithm must be effective i.e. every step should do some work.
BY PROF.AVANI BHUVA
Algorithm to add 3 numbers and print their sum:
1. START
2. Declare 3 integer variables num1, num2 and num3.
3. Take the three numbers, to be added, as inputs in variables num1, num2, and num3 respectively.
4. Declare an integer variable sum to store the resultant sum of the 3 numbers.
5. Add the 3 numbers and store the result in the variable sum.
6. Print the value of the variable sum
7. END

BY PROF.AVANI BHUVA
Terminology used for algorithm are:
1. START, END /STOP
2. INPUT / READ ( TO ACCPET THE VALUES IN THE VARIABLES)
3. PRINT (“HELLO”)
4. Arithmetic Operations : C=A+B or C=A*B or C=A-B
5. Logical Operations: AND , OR ,NOT (aANDb)
6. IF ,ELSE ,THEN
7. GOTO
Pseudo code for display Hello word
Step:1 START
Step:2 PRINT “HELLO”
STEP:3 STOP

BY PROF.AVANI BHUVA
Defined as: “A sequence of activities to be processed for getting desired output from a given input.”

+ Addition
- Subtraction
* Multiplication
/ Division
-> Assignment. For example B -> Y*7 means B will have the
value of Y*7
Read For taking input
Print For displaying output
Start For beginning the algorithm steps
End For stopping the algorithm steps to make it a finite
algorithm
if <condition> then <statement> else For conditional statement
<statement>
Go to step n For moving to step n
Repeat For repeating a set of statements/instructions

BY PROF.AVANI BHUVA
1. Write an algorithm to add two numbers entered by user.
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: sum←num1+num2
Step 5: Display sum
Step 6: Stop
2. Square of a number Pseudo code
Step:1 START
Step:2 PRINT “Enter a no”
Step:3 INPUT n
Step:4 a=n*n
Step:5 PRINT a
Step:6 STOP
BY PROF.AVANI BHUVA
3. WAA TO CALCULATE AND DISPLAY THE AREA AND PERIMETER OF A RECTANGLE

STEP:1 START
STEP:2 PRINT “ENTER THE LENGTH AND BREADTH OF THE RECTANGLE”
STEP:3 INPUT L,B
STEP:4 A=L*B
STEP:5 P=2(L+B)
STEP: 6 PRINT A,P
STEP:7 STOP

4. Write an algorithm to find the largest among three different numbers entered by user.
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number. BY PROF.AVANI BHUVA
Step 5: Stop
5. Print computer 5 times

Step:1 START
STEP:2 i=1
Step:3 IF i>5 THEN GOTO 7
STEP:4 PRINT “COMPUTER”
STEP:5 i=i+1
STEP:6 GOTO 3
STEP: 7 STOP

6. WAA TO DISPLAY THE FIRST n NATURAL NUMBERS , WHERE THE VALUE OF n SHOLD BE TAKEN FROM THE USER.
STEP:1 START
STEP:2 PRINT “ENTER n”
STEP:3 READ n
STEP: 4 i=1
STEP:5 IF i>n THEN GOTO STEP 8
STEP:6 PRINT i
STEP:7 i=i+1 GOTO STEP 4
STEP:8 STOP
BY PROF.AVANI BHUVA
Flowchart
A detailed graph which represents steps to be performed within the machine to produce the needed output.
Algorithm represented in pictorial form.
Requires only a few symbols in program charting to indicate the necessary operations.
Diagrammatic representation of an algorithm is called flow chart.
Characteristics of FCs:
1. An aid in formulating and understanding algorithms.
2. Easy visual recognition, a standard convention is used in drawing flow charts.
3. Sequencing & repetition instructions easily visible.
4. Helps in detecting, locating, and removing mistakes if the program fails to run to completion.
5. The program FC acts as a guide or blueprint during the program preparation phase.
6. It becomes a model of a program or system that can be broken down into detailed parts for study.
7. Can be used as working models in the design of new programs and systems.
8. Program Documentation.

BY PROF.AVANI BHUVA
BY PROF.AVANI BHUVA
BY PROF.AVANI BHUVA
1. Write an algorithm to add two numbers entered by user.
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: sum←num1+num2
Step 5: Display sum
Step 6: Stop

BY PROF.AVANI BHUVA
BY PROF.AVANI BHUVA
BY PROF.AVANI BHUVA
2. Calculate the Interest of a Bank Deposit
Algorithm:
Step 1: Read amount,
Step 2: Read years,
Step 3: Read rate,
Step 4: Calculate the interest with formula
Interest=Amount*Years*Rate/100
Step 5: Print interest,

BY PROF.AVANI BHUVA
if statement in C++ Programs
The if statement facilitates to check a particular condition. If that condition is true, then a specific block (enclosed
under the if) of code gets executed.
This flowchart will help you.

if(boolean_expression)
{
// Body of if
// If expression is true then execute this
}
else
{
// Body of else
// If expression is false then execute this
}

BY PROF.AVANI BHUVA
3. Determine Whether a Temperature is Below or Above the Freezing Point
Algorithm:
Step 1: Input temperature,
Step 2: If(temp<32)
then print "below freezing point",
otherwise print "above freezing point“
Step:3 stop

BY PROF.AVANI BHUVA
4.

BY PROF.AVANI BHUVA
5. Program to find whether a number is odd or even.
Flowchart:

Algorithm:
Step 1: Start.
Step 2: Input a
Step 3: if(a%2==0)
then print “a is even”
otherwise
print “a is odd”
Step 4: Stop

BY PROF.AVANI BHUVA
Ladder if...else...if statement syntax
if (boolean_expression_1)
{
// If expression 1 is true then execute
// this and skip other if
}
else if (boolean_expression_2)
{
// If expression 1 is false and
// expression 2 is true then execute
// this and skip other if
}
else if (boolean_expression_n)
{
// If expression 1 is false,
// expression 2 is also false,
// expression n-1 is also false,
// and expression n is true then execute
// this and skip else.
}
else
{
// If no expressions are true then
// execute this skipping all other.
}
BY PROF.AVANI BHUVA
Example 1: Check whether a number is positive, neg

Algorithm:
1. Start
2. Print”Enter a number”.
3. Read n.
4. If n>0 then print “The number is positive”
Else if n<0 print “The number is negative”
Else “The number is zero”.
5. Stop

BY PROF.AVANI BHUVA
Switch-Case Statement
When you have to execute multiple statements under one operation, Switch-case comes into play.
There are several cases under one switch statement.
Syntax:
switch(variable)
{
case n1:
//Statement block;
break;
case n2:
//Statement block;
break;
.
.
.
case n:
//Statement block;
break;
}
BY PROF.AVANI BHUVA
BY PROF.AVANI BHUVA
6. Program to calculate the area of a rectangle or circle or triangle by taking the
user’s choice.

Algorithm:
Step 1: Start
Step 2: Initialize variables
Step 3: Take input for choice and then for area variables from
the user
Step 4: Case 1: Circle: 3.14*3.14*r
Case 2: Rectangle: ar=a*b
Case 3: Triangle: at=0.5*a*b
Step 5: Display output according to case
Step 6: Stop

BY PROF.AVANI BHUVA
Algorithm of factorial of a number
Step 1: Start
Step 2: Read a number n
Step 2: Initialize variables:
i = 1, fact = 1
Step 3: if i <= n go to step 4 otherwise go to step 7
Step 4: Calculate
fact = fact * i
Step 5: Increment the i by 1 (i=i+1) and go to step 3
Step 6: Print fact
Step 7: Stop

BY PROF.AVANI BHUVA
1. Character set of C++

Whenever we write any C program then it consists of different statements.


Character set includes all the alphabets, digits and special symbols supported by the processors.
 Each C Program is set of statements and each statement is set of different c programming lexims.
 In C Programming each and every character is considered as single lexim. i.e. [ Basic Lexical Element ]

Types Character Set

Lowercase Letters a-z

Uppercase Letters A to Z

Digits 0-9

Special Characters !@#$%^&*{} [] () , : ; “ etc.

White Spaces Tab Or New line Or Space

BY PROF.AVANI BHUVA
2. Keywords in C++ Programming Language

auto double int struct

These are some special words that have break else long switch
a predefined meaning for the C compiler
case enum register typedef
These are the keywords reserved for the
certain operations and hence sometimes
also referred as RESERVED WORDS char extern return union

All keywords are in LOWER CASE const float short unsigned


Cannot be used as Variable Name
continue for signed void
These keywords are used in different
place of programming default goto sizeof volatile

do if static while

BY PROF.AVANI BHUVA
3. Identifiers
Identifiers are names given to different user defined things like variables, constants, functions,
classes, objects, structures, unions etc.
While making the identifier follow the below rules:
1. The identifier can consist of alphabets, digit and special symbol underscore ( _ )
2. An identifier cannot start with a digit. It can start either with an alphabet or underscore
3. It cannot contain any special symbol except underscore, blank spaces are also not allowed.
4. It cannot be a keyword
5. It’s a case sensitive. That is, word and WORD is recognized as a separate identifier.
6. Earlier limit was 32 character but now this limit is removed.

BY PROF.AVANI BHUVA
Valid or Invalid Identifiers
1. simple_interest VALID
2. char INVALID
3. 3friends INVALID
4. _3friends VALID

1. Void
2. void
3. #3friends
4. Simple interest

BY PROF.AVANI BHUVA
The ASCII value for ‘A’ is 65, ‘B’ is 66 , ‘C’ is 67 and so on
The ASCII value of ‘a’ is 97 and so on
The user defined data types are structure, union , class. The derived data types are array , function, pointer
and reference.

NOTE: The arithmetic operations can be done even or char


type of data. This is because the processor stores ASCII

BY PROF.AVANI BHUVA
4. Constants and Variable

A constant is an entity that doesn’t change during the execution of a program. whereas a variable is
an entity that may change.
Constants can be defined either by writing the keywords constant before the data type or by using #
define
Constants are used to declare the values that remain constant for e.g. value of pi
The use of constants in program will be discussed later wherever required
Variables are values given to identifier that can change their values during the execution of the
program.

BY PROF.AVANI BHUVA
Defining Constants
There are two simple ways in C++ to define constants −
1. Using #define preprocessor.
2. Using const keyword.
The #define Preprocessor
Following is the form to use #define preprocessor to define a constant −
#define identifier value
Following example explains it in detail −
#include <iostream>
using namespace std;
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
When the above code is compiled and executed, it produces the following result −
50

BY: PROF.AVANI B
The const Keyword
You can use const prefix to declare constants with a specific type as follows −

const type variable = value;


Following example explains it in detail −
#include <iostream>
using namespace std;
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
When the above code is compiled and executed, it produces the following result −

50

BY: PROF.AVANI B
Directives
preprocessor directive : is an instruction to the compiler. A part of the compiler called the preprocessor deals with these
directives before it begins the real compilation process.
#include <iostream>
Is not a program statement
It starts with a # sign.
Program statements are instructions to the computer to do something
The preprocessor directive #include tells the compiler to insert another file into source file.
In effect, the #include directive is replaced by the contents of the file indicated.
Using an #include directive to insert another file into source file is similar to pasting a block of text into a document
with your word processor.
The type file usually included by #include is called a header file.
The preprocessor directive #include tells the compiler to add the header file iostream to source file before compiling.
 iostream is an example of a header file (sometimes called an include file). It’s concerned with basic input/output
operations, and contains declarations that are needed by the cout identifier and the << operator.
Without these declarations, the compiler won’t recognize cout and will think << is being used incorrectly.
The newer Standard C++ header files don’t have a file extension, but some older header files, left over from the days of
the C language, have the extension .h.

BY: PROF.AVANI B
Directives
using directive:

A C++ program can be divided into different namespaces.


A namespace is a part of the program in which certain names are recognized; outside of the namespace
they’re unknown.
The directive
using namespace std;
says that all the program statements that follow are within the std namespace.
 Various program components such as cout are declared within std namespace. If we didn’t use the using
directive, we would need to add the std name to many program elements. For example, std::cout <<
“Hello World \n”;
To avoid adding std:: dozens of times in programs we use the using directive instead.

BY: PROF.AVANI B
Main function section
int main() {}
•The starting point of all C++ programs is the main function.
•This function is called by the operating system when your program is executed by the computer.
•{ signifies the start of a block of code, ​and } signifies the end.

Function body section

cout << "Hello World" << endl;


return 0;

•The name cout is short for character output and displays whatever is between the << brackets.
•Symbols such as << can also behave like functions and are used with the keyword cout.
•The return keyword tells the program to return a value to the function int main
•After the return statement, execution control returns to the operating system component that launched this
program.
•Execution of the code terminates here.

BY PROF.AVANI BHUVA
Output Operator
cout is a predefined object that represents the standard output
stream in C++.
Standard output stream represents the screen.
The operator << is called the insertion or put to operator. It
inserts (or sends) the contents of the variable on its right to the
object on its left.
<< is the bit-wise left shit operator and still can be used for this
purpose. This is an example of how one operator can be used
different purposes, depending on the context. This concept is
known as operator overloading, an important aspect of
polymorphism.
printf() can be used for displaying in C programming.

BY: PROF.AVANI B
Input operator
cin is a predefined object that represents the standard input stream in C++.
Standard input stream represents the keyboard.
The operator >> is called the extraction or get from operator. It extracts (or takes) the value
from the keyboard and assigns it to the variable on its right.
Like <<, the operator >> can be overloaded.

BY: PROF.AVANI B
Basic Program Structure
A C++ program is structured in a specific and particular manner. In C++, a program is divided into the following three
sections:
1. Standard Libraries Section
2. Main Function Section
3. Function Body Section
For example, let’s look at the implementation of the Hello World program:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
return 0;
}
•#include is a specific preprocessor command that effectively copies and pastes the entire text of the file, specified
between the angle brackets, into the source code.
•The file <iostream>, which is a standard file that should come with the C++ compiler, is short for input-output
streams. This command contains code for displaying and getting an input from the user.
•namespace is a prefix that is applied to all the names in a certain set. iostream file defines two names used in this
program - cout and endl.

BY PROF.AVANI BHUVA
BY: PROF.AVANI B
Average of two numbers

BY: PROF.AVANI B
C++ Data Types
In C++, data types are declarations for
variables. This determines the type and Data Type Meaning Size (in Bytes)
size of data associated with variables.
int Integer 2 or 4
For example, int age = 13;
Here, age is a variable of type int. float Floating-point 4
Meaning, the variable can only store
Double Floating-
integers of either 2 or 4 bytes. double 8
point
C++ Fundamental Data Types
char Character 1
The table below shows the fundamental
data types, their meaning, and their sizes wchar_t Wide Character 2
(in bytes):
bool Boolean 1

void Empty 0

BY PROF.AVANI BHUVA
1. C++ int
The int keyword is used to indicate integers.
Its size is usually 4 bytes. Meaning, it can store values from -2147483648 to 2147483647.
For example,int salary = 85000;
2. C++ float and double
float and double are used to store floating-point numbers (decimals and exponentials).
The size of float is 4 bytes and the size of double is 8 bytes. Hence, double has two times the precision of float. To learn more, visit C++ float
and double.
For example,float area = 64.74;
double volume = 134.64534;
As mentioned above, these two data types are also used for exponentials. For example,
double distance = 45E12 // 45E12 is equal to 45*10^12
3. C++ char
Keyword char is used for characters.
Its size is 1 byte.
Characters in C++ are enclosed inside single quotes ' '.
For example,
char test = 'h';
BY PROF.AVANI BHUVA
Note: In C++, an integer value is stored in a char variable rather than the character itself. To learn more, visit C++ characters.
4. C++ bool
The bool data type has one of two possible values: true or false.
Booleans are used in conditional statements and loops (which we will learn in later
chapters).
For example,
bool cond = false;
5. C++ void
The void keyword indicates an absence of data. It means "nothing" or "no value".
We will use void when we learn about functions and pointers.
Note: We cannot declare variables of the void type.

BY PROF.AVANI BHUVA
C++ Type Modifiers
We can further modify some of the fundamental data types by using type modifiers. There are 4 type
modifiers in C++. They are:
1. signed
2. unsigned
3. short
4. long
We can modify the following data types with the above modifiers:
1. int
2. double
3. char

BY PROF.AVANI BHUVA
C++ Modified Data Types List

Data Type Size (in Bytes) Meaning


signed int 4 used for integers (equivalent to int)
unsigned int 4 can only store positive integers
used for small integers (range -32768
short 2
to 32767)
used for small positive integers (range
unsigned short 2
0 to 65,535)
used for large integers (equivalent to
long at least 4
long int)
used for large positive integers or 0
unsigned long 4
(equivalent to unsigned long int)
used for very large integers (equivalent
long long 8
to long long int).
used for very large positive integers or
unsigned long long 8 0 (equivalent to unsigned long long
int)
long double 12 used for large floating-point numbers
used for characters (guaranteed range -
signed char 1
127 to 127)
unsigned char 1 used for characters (range 0 to 255)
BY PROF.AVANI BHUVA
Let's see a few examples.
long b = 4523232;
long int c = 2345342;
long double d = 233434.56343;
short d = 3434233; // Error! out of range
unsigned int a = -5; // Error! can only store positive numbers or 0
Derived Data Types
Data types that are derived from fundamental data types are derived types. For example: arrays,
pointers, function types, structures, etc.

BY PROF.AVANI BHUVA
Examples:
1. Age in years: int data type should be used
2. Rate of interest: Float data type must be used
3. Alphabet: Char type of data is to be used, as a character is to be used
4. Principal amount: float type data must be used, as principal is in rupee and paisa
5. Runs made by a batsman:
6.Factorial of a number:
7. Radius of a circle:
8. User input ‘Y’ or ‘N’:

BY PROF.AVANI BHUVA
C++ Comments
C++ comments are hints that a programmer can add to
make their code easier to read and understand. They
are completely ignored by C++ compilers.
There are two ways to add comments to code:
1. // - Single Line Comments
2. /* */ -Multi-line Comments

1. Single Line Comments 2. Multi-line comments


In C++, any line that starts with // is a comment. For In C++, any line between /* and */ is also a comment. For
example, example,
// declaring a variable /* declaring a variable
int a;
// initializing the variable 'a' with the value 2 to store salary to employees
a = 2; */
Here, we have used two single-line comments: int salary = 2000;
// declaring a variable This syntax can be used to write both single-line and multi-line
// initializing the variable 'a' with the value 2 comments.
We can also use single line comment like this:
int a; // declaring a variable

BY PROF.AVANI BHUVA
Exchange of two no’s without
using third variable.
#include <iostream>
using namespace std;
int main()
{
int a,b;
cout<<"enter the value of a,b";
cin>>a>>b;
a=a+b;
b=a-b;
a=a-b;
cout<<"the value of a"<<a<<endl<<"the value of b"<<b<<endl;
return 0;
}

BY PROF.AVANI BHUVA
C++ Operators
In programming, an operator is a symbol that operates on a value or a variable.
The data on which the operation is performed are called as OPERANDS.
If an operator requires one operand, it is called as UNARY OPERATOR, two operands called binary
Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while -
is an operator used for subtraction.
Operators in C++ can be classified into 6 types:
1. Unary Operators
2. Arithmetic Operators
3. Relational Operators
4. Assignment Operators
5. Logical Operators
6. Bitwise Operators
7. Conditional operator
8. Special Operator
BY PROF.AVANI BHUVA
+ + C rin erato p o ary n .U 1

BY PROF.AVANI BHUVA
BY PROF.AVANI BHUVA
1. Unary minus(-) :
The symbol shown in bracket is unary minus.
It returns the negative value of the variable to which it is preceded.
Eg. If x=3 then y=-x;
Will make the value of y as -3
2.Casting operator(()) or type conversion:
It is many a times required to convert one data type to another.
The casting operator is used for type conversion. i.e. it can be used to convert one data to one type to another type
Eg. If int x=3;
Float y=5.6
Then the statement, x=(int)y;
Will result in the value of x as 5.
3. Logical Not operator (!) :
It is used to check certain conditions in a statement. It performs the logical not of the result obtained from the expression
Eg. If x=1 then y=!x;
Will result with y having value 0.
BY PROF.AVANI BHUVA
4. Address of operator (&) :
This operator returns the address of the variable associated with it.
Eg. If we write y=&x;
Then the memory address allocated to the variable x will be copied into the variable y. (will see in pointer)
5. indirection operator or value of operator(*):
It returns the value of the data at the given address. (see in pointer)
Eg.
Z=*y;
Will give the value of the data stored at the address given by y.

BY PROF.AVANI BHUVA
6. size of operator:
It is used to know the size of a variable as required to store its value in memory. It can also be used to find the size of a data
type
The space required to store different data type is different ranging from 1 byte to 10 bytes.
Eg: sizeof(int);
Will returns the value as 2 , as int requires 2 bytes.
eg. int x,y;
char a;
X=sizeof(a);
Y=sizeof(float);
Then x will have 1 (because a is char) and y will have 4 (y is float)
7. Bitwise not operator (~):
It is used to perform bitwise NOT operation. This operation can be performed by using the operator given in brackets i.e. ~
Eg. If x=3,
Then y=~x;
Will result in y having a value of -4

BY PROF.AVANI BHUVA
8. Increment and Decrement Operator(Unary operators)
++ and - -
The operator ++ adds 1 to the operand , while – subtracts 1.Both are unary operators and takes following form:
++m; is equivalent to m=m+1
or m++;
--m; is equivalent to m=m-1
or m--;
While ++m and m++ mean the same thing when they from statements independently, they behave differently
whey they are used in expression on the right hand side of an assignment statement
Consider the following:
m=5;
y=++m;
In this case value of y and m would be 6.(prefix operator first adds 1 to the operand and then result is assigned to
the variable on left)
m=5;
y=m++;
Then the value of y would be 5and value of m would be 6 (postfix operator first assign the value to the variable
on left and then increments the operand)

BY PROF.AVANI BHUVA
#include <iostream>
using namespace std;
int main()
{
int a;
float b;
char g;
cout << "No of Bytes taken up by a is " << sizeof(a) << endl;
cout << "No of Bytes taken up by b is " << sizeof(b) << endl;
cout << "No of Bytes taken up by g is " << sizeof(g) << endl;
return 0;
}

Output
No of Bytes taken up by a is 4
No of Bytes taken up by b is 4
No of Bytes taken up by g is 1

BY PROF.AVANI BHUVA
2. C++ Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on variables and data. For example,
a + b;
Here, the + operator is used to add two variables a and b. Similarly there are various other arithmetic
operators in C++.

Operator Description Example

+ Adds two operands A + B will give 30


- Subtracts second operand from the A - B will give -10
first
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of B % A will give 0


after an integer division

BY PROF.AVANI BHUVA
#include <iostream> Here, the operators +, - and * compute addition, subtraction,
and multiplication respectively as we might have expected.
using namespace std; / Division Operator
int main() Note the operation (a / b) in our program. The / operator is the
division operator.
{ As we can see from the above example, if an integer is divided
int a,b,c; by another integer, we will get the quotient. However, if either
divisor or dividend is a floating-point number, we will get the
cout<<"enter value of a and b"; result in decimals.
In C++,
cin>>a>>b;
7/2 is 3
b = 2; 7.0 / 2 is 3.5
7 / 2.0 is 3.5
c=a+b;
7.0 / 2.0 is 3.5
// printing the sum of a and b % Modulo Operator
The modulo operator % computes the remainder. When a = 9 is
cout << "a + b = " <<c<< endl; divided by b = 4, the remainder is 1.
return 0; Note: The % operator can only be used with integers.
Output:
}
enter value of a and b34
3
a + b = 36
BY PROF.AVANI BHUVA
3. Relational Operators
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then −
Operator Description Example
== Checks if the values of two operands are equal or not, (A == B) is not true.
if yes then condition becomes true.
!= Checks if the values of two operands are equal or not, (A != B) is true.
if values are not equal then condition becomes true.

> Checks if the value of left operand is greater than the (A > B) is not true.
value of right operand, if yes then condition becomes
true.
< Checks if the value of left operand is less than the (A < B) is true.
value of right operand, if yes then condition becomes
true.
>= Checks if the value of left operand is greater than or (A >= B) is not true.
equal to the value of right operand, if yes then
condition becomes true.
<= Checks if the value of left operand is less than or (A <= B) is true.
equal to the value of right operand, if yes then
condition becomes true.

BY PROF.AVANI BHUVA
4. Assignment Operators:
These operators are used to assign the value of the expression or variable on the right of the assignment operator to the variable
on its left.
Operator Description Example
= Simple assignment operator. Assigns values from right side operands to left side C = A + B will assign the value of A + B to C
operand

+= Add AND assignment operator. It adds the right operand to the left operand and C += A is equivalent to C = C + A
assign the result to the left operand.

-= Subtract AND assignment operator. It subtracts the right operand from the left C -= A is equivalent to C = C - A
operand and assigns the result to the left operand.

*= Multiply AND assignment operator. It multiplies the right operand with the left C *= A is equivalent to C = C * A
operand and assigns the result to the left operand.

/= Divide AND assignment operator. It divides the left operand with the right operand C /= A is equivalent to C = C / A
and assigns the result to the left operand.

%= Modulus AND assignment operator. It takes modulus using two operands and C %= A is equivalent to C = C % A
assigns the result to the left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2


^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2


BY PROF.AVANI BHUVA
5 Logical Operators:
Following table shows all the logical operators supported by C language. Assume variable A holds 1
and variable B holds 0, then

Operator Description Example

&& Called Logical AND operator. If both the operands (A && B) is false.
are non-zero, then the condition becomes true.

|| Called Logical OR Operator. If any of the two (A || B) is true.


operands is non-zero, then the condition becomes
true.
! Called Logical NOT Operator. It is used to reverse !(A && B) is true
the logical state of its operand. If a condition is true,
then Logical NOT operator will make it false.

BY PROF.AVANI BHUVA
Example:
Y>5&&y<10
It will result in “true” i.e. 1 if the value of y is greater than 5 AND less than else it will return “false”
i.e. 0
Y>5||y==2
It will result in “true” i.e. 1 if the value of y is greater than 5 OR equal to 2, else it will return “false”
i.e. 0

BY PROF.AVANI BHUVA
6 Bitwise Operators:
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as
follows −

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

BY PROF.AVANI BHUVA
Bitwise
The Operators:
following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and variable 'B' holds 13, then −

Operator Description Example


& Binary AND Operator copies a bit to the result if it exists in both (A & B) = 12, i.e., 0000 1100
operands.
| Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, i.e., 0011 1101

^ Binary XOR Operator copies the bit if it is set in one operand (A ^ B) = 49, i.e., 0011 0001
but not both.
~ Binary Ones Complement Operator is unary and has the effect (~A ) = -61, i.e,. 1100 0011 in 2's
of 'flipping' bits. complement form.
<< Binary Left Shift Operator. The left operands value is moved left A << 2 = 240 i.e., 1111 0000
by the number of bits specified by the right operand.

>> Binary Right Shift Operator. The left operands value is moved A >> 2 = 15 i.e., 0000 1111
right by the number of bits specified by the right operand.

BY PROF.AVANI BHUVA
Bitwise Operators:
1. 5 & 3=1

(5)10=(0101)2

(3)10=(0011)2

Ans =(0001)2 =(1)10 A B A&B A|B A^ B


2. 12|9=13
0 0 0 0 0
(12)10=(1100)2

(9)10 =(1001)2
0 1 0 1 1
Ans =(1101)2=(13)10

3. 8^10=2 1 1 1 1 0

(8)10 =(1000)2
1 0 0 1 1
(10)10=(1010)2

Ans =(0010)2 =(2)10

4.~7=-8

(7)10=(0111)2

Ans =(1000)2 =(-8)10

BY PROF.AVANI BHUVA
1. 10<<2=40
Assuming the data to be char i.e. 8 bit data
(10)10 =(00001010)2
After shifting left once =(00010100)2
After shifting left for the second time =(00101000)2 =(40)10
Note: when shifting to left, each of the bit is shifted left. The first bit is lost and the last bit is inserted as 0
2. 13>>3=1
Assuming the data to be char i.e. 8 bit data
(13)10 =(00001011)2
After shifting right once =(00000101)2
After shifting right for the second time =(00000010)2
After shifting right for the third time =(00000001)2 =(1)10
Note: when shifting to right, each of the bit is shifted right. The first inserted as 0 and the last bit is lost

BY PROF.AVANI BHUVA
7. Conditional Operator (Ternary operator)

An operator that requires three operand is called as ternary operator


A ternary operator pair “?:”
Syntax is given below:
(condition) ? <value if condition is true>:<value if condition is false>;
Example:
z=(x>y)?x:y;
This statement will put the value of x into z if x>y satisfy
Else; the value of y will put into z
exp1?exp2:exp3
Exp1 evaluated first. If it is nonzero(true), then the exp2 is evaluated and becomes the value of the expression. If exp1 is
false, exp3 is evaluated and its value becomes the value of the expression. Note only one of the expression is evaluated.
Example:
a=10;
b=15;
x=(a>b)?a:b;
A slightly complicated use of this operator is to find the greatest of three number as shown below:
G=(x>y)?((x>z)?x:z)):(y>z)?y:z);

BY PROF.AVANI BHUVA
The ? is called a ternary operator because it requires three operands and can be used to replace if-else
statements, which have the following form −
if(condition) {
var = X;
} else {
var = Y;
}
For example, consider the following code −
if(y < 10) {
var = 30;
} else {
var = 40;
}
Above code can be rewritten like this −
var = (y < 10) ? 30 : 40;
BY PROF.AVANI BHUVA
8. Special operators
These operators are used to select certain elements of a set of elements.
1. [] : This operator is used to select an element of ARRAY.
2. . : This is called as period operator and used to select an element of structure or union.
3. -> : this is used to select an element of a structure or union pointed by a pointer.
4. () : this is called as a function call operator and is used to call or select a function.
5. , : the comma (,) operator is used to separate the different values etc.
6. The size of operator: sizeof is a compile time operator and , when used with an operand, it returns the no of
bytes the operand occupies
M=sizeof(sum);
N=sizeof(int);
They used to determine the size of array and structure when the size is unknown

BY PROF.AVANI BHUVA
\' single quote
Escape Sequences \" double quote
Escape sequence is a
character followed by \? question mark
backslash (\) \\ backslash
They are used especially \a audible bell(cause a beep sound,when char enter)
to perform some special \b backspace
operations like going to form feed - new page (breaking ASCII control
new line, providing a \f character. It forces the printer to eject the current page
horizontal tab, vertical tab and continue printing at the top of another)
etc. \n
line feed - new line (moves cursor down to the next
line without returning to the beginning of the line.
carriage return (helps to move the cursor head to the
\r
beginning of current line
\t horizontal tab
\v vertical tab
\nnn arbitrary octal value

BY PROF.AVANI BHUVA
Precedence in C++

Operator precedence determines the grouping of terms in an expression and decides


how an expression is evaluated. Certain operators have higher precedence than others;
for example, the multiplication operator has a higher precedence than the addition
operator.
High priority * / %
Low priority + -
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a
higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here,operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

BY PROF.AVANI BHUVA
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= Right to left
|=
Comma , Left to right
BY PROF.AVANI BHUVA
Expression in C++: Arithmetic and
Boolean Expression

BY PROF.AVANI BHUVA
If A=7,B=3 and C=4
1 A%B
=7%3 =1(since the remainder after dividing 7 by 3 is 1)
2. A/C
=7/4 =1 (since the quotient after dividing 7 by 4 is 1)
3. A*B/C
=7*3/4 =21/4 (since the associativity of arithmetic operations is left to right first operation is *)
4. A*(C%B)
=7*(4%3) =7*1 =7 (since the bracket opening is to be done first, and remainder of 4 div by 3 is 1)
5. A*C%B
7*4%3 =28%3 =1
6. 2*B+3*(A-C)
=2*3+3*(7-4) =6+3*(3) =6+9 (since the precedence of multiply is more than add, first multiplication is done) =15
7 A+B-C
=7+3-4 =6

BY PROF.AVANI BHUVA
int i=9,j=6;
float x=0.5,y=0.1
char a=‘a’, b=‘b’;
find the values of the following expression

1. (3*i-2*j)%(2*a-b)
=(27-12)%(2*97-98) (since the ASCII values stored in char type variables is 97 for a &98 for b)
=(15) % (96) =15
2. 2*(j/5)+(4*(j-3))%(i+j-2)
3. (x>y)&&(i>0)&&(j>5)
=1&&1&&1 (if condition is true then it results is 1 else 0)
=1
4. ((x<y)&&(i<0))||(j>3)
=(0&&1)||(1) =(0)||(1) =1
5. a==99
=0 (since given condition is false, the value is 97 hence return to 0)
5. ++i
6. i++
7. !(b==98)
BY PROF.AVANI BHUVA
Write a program to initialize Write a program to exchange values of two
your details like age, name, variables without using 3rd variable
gender, city, height etc and
display it. (for name & city
use character array)

#include <iostream> #include <iostream>


using namespace std; using namespace std;
int main() int main()
{ {
char name[100] ; int a, b;
int age; cout<<"enter value of and b";
cout << "Enter name of the person: "; cin>>a>>b;
cin.getline(name, 100); cout<<"Before swap a= "<<a<<" b= "<<b<<endl;
cout << "Enter age: "; a=a+b; //a=15 (5+10)
cin >> age; b=a-b; //b=5 (15-10)
cout << "Name: " << name << endl; a=a-b; //a=10 (15-5)
cout << "Age: " << age << endl; cout<<"After swap a= "<<a<<" b= "<<b<<endl;
return 0; return 0;
} }

BY PROF.AVANI BHUVA
Given the value of x, y, and z. Write a program to rotate their values such that x has value of y, y has value of z and z has value
of x.

#include <iostream>
using namespace std;
int main()
{
int x,y,z,c;
cout<<"enter the value of x,y,z";
cin>>x>>y>>z;
c=x+y+z;
z=c-(z+y);
y=c-(y+x);
x=c-(z+y);
cout<<"the value of c"<<c<<endl<<"the value of x"<<x<<endl<<"the value of y"<<y<<endl<<"the value of z"<<z;
}

BY PROF.AVANI BHUVA

You might also like