0% found this document useful (0 votes)
3 views120 pages

Principles of Programming

The document outlines the principles of programming, focusing on algorithms and flowcharts. It covers definitions, characteristics, and functions of algorithms, as well as the process of translating algorithms into flowcharts. Additionally, it introduces programming languages, their types, and the evolution of programming languages over time.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views120 pages

Principles of Programming

The document outlines the principles of programming, focusing on algorithms and flowcharts. It covers definitions, characteristics, and functions of algorithms, as well as the process of translating algorithms into flowcharts. Additionally, it introduces programming languages, their types, and the evolution of programming languages over time.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 120

COMP 151

PRINCIPLES OF
PROGRAMMING

PROF. PATRICK KWABENA MENSAH


Algorithms &
Flowcharts
Learning Outcomes

At the end of the lesson, I should be able to:


a. -Define algorithm, Pseudo codes and flowchart
b. -State characteristics of Algorithms
c. -Outline functions of Algorithm
d. -Write algorithm for solving a given problem
e. -Flowchart symbols and their uses
f. -Translating algorithms to flowchart programs
g. -Draw flowcharts for solving given problems
What is a COMPUTER?
ALGORITHMS AND
FLOWCHARTS

A typical programming task can be divided into


two phases:

 Problem solving phase


 produce an ordered sequence of steps that describe
solution of problem
 this sequence of steps is called an algorithm

 Implementation phase
 implement the program in some programming
language
Steps in Problem Solving

1. First produce a general algorithm: (one


can use pseudo code)

2. Refine the algorithm successively to get


step by step detailed algorithm that is
very close to a computer language.

3. Pseudo code is an artificial and informal


language that helps programmers
develop algorithms. Pseudo code is very
similar to everyday English.
Pseudocode & Algorithm

1. Example 1: Write an algorithm to determine a student’s


final grade and indicate whether it is passing or failing.
The final grade is calculated as the average of four
marks.
Pseudocode & Algorithm

Pseudo code:

1. Input a set of 4 marks


2. Calculate their average by
summing and dividing by 4
3. if average is below 50
Print “FAIL”
else
Print “PASS”
Pseudocode & Algorithm

Detailed Algorithm:

Step 1: Input M1,M2,M3,M4


Step 2: GRADE = (M1+M2+M3+M4)/4
Step 3: if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
endif
The Flowchart
A Flowchart is a graphical representation of the sequence of
operations in an information system or program.

Flowchart Characteristics:
1. shows the sequence of instructions in a single
program or subroutine
2. shows logic of an algorithm from start to finish
3. emphasizes individual steps and their
interconnections
4. control flow from one action to the next
5. Different symbols are used to draw each type of
flowchart
6. The start symbol indicates the beginning of a
program
7. The end symbol indicate the end of a program.
Flowchart Symbols

The Flowchart

Name Symbol Use in Flowchart

Oval Denotes the beginning or end of the program

Parallelogram Denotes an input operation

Rectangle Denotes a process to be carried out


e.g. addition, subtraction, division etc.

Diamond Denotes a decision (or branch) to be made.


The program should continue along one of
two routes. (e.g. IF/THEN/ELSE)

Hybrid Denotes an output operation

Flow line Denotes the direction of logic flow in the program


Flowchart solution to Example1

START

Algorithm:
Input
M1,M2,M3,M4
Step 1: Input M1,M2,M3,M4
Step 2: GRADE  (M1+M2+M3+M4)/4
GRADE(M1+M2+M3+M4)/4 Step 3: if (GRADE <50) then
Print “FAIL”
else
N Y
IS Print “PASS”
GRADE<50
endif

PRINT PRINT
“PASS” “FAIL”

STOP
Example 2

Write an algorithm and draw a flowchart to convert the


length in feet to centimeter.

Pseudo code:
1. Input the length in feet (Lft)
2. Calculate the length in cm (Lcm) by multiplying LFT
with 30
3. Print length in cm (LCM)
Flowchart
Algorithm
START
Step 1: Input Lft
Step 2: Lcm  Lft x 30 Input
Lft
Step 3: Print Lcm

Lcm  Lft x 30

Print
Lcm

STOP
Example 3

Write an algorithm and draw a


flowchart that will read the two sides of
a rectangle and calculate its area.

Pseudocode
1. Input the width (W) and Length (L) of
a rectangle
2. Calculate the area (A) by multiplying
L with W
3. Print A
START

Algorithm
Step 1: Input W,L Input
W, L
Step 2: A  L x W
Step 3: Print A
ALxW

Print
A

STOP
Example 4

Write an algorithm and draw a flowchart


that will calculate the roots of a quadratic
equation ax 2 + bx + c = 0

Hint: d = sqrt ( b − 4ac ), and the roots are:


2

x1 = (–b + d)/2a and x2 = (–b – d)/2a


Pseudo code:

1. Input the coefficients (a, b, c) of the quadratic


equation
2. Calculate d
3. Calculate x1
4. Calculate x2
5. Print x1 and x2
START

Algorithm:
Input
Step 1: Input a, b, c a, b, c

Step 2: d  sqrt ( b  b − 4  a  c )
d  sqrt(b x b – 4 x a x c)
Step 3: x1  (–b + d) / (2 x a)
Step 4: x2  (–b – d) / (2 x a) x1 (–b + d) / (2 x a)

Step 5: Print x1, x2 X2  (–b – d) / (2 x a)

Print
x1 ,x2

STOP
Terminologies

An algorithm is a step-by-step procedure in solving a


problem

Pseudo code is an artificial and informal language that


helps programmers develop algorithms. Pseudo code is
very similar to everyday English.

Flowchart is a graphical representation of


the sequence of operations in an
information system or program.
DECISION STRUCTURES
If - else
DECISION STRUCTURES

 The expression A>B is a logical expression

 it describes a condition we want to test

 if A>B is true (if A is greater than B) we take the


action on left

 print the value of A

 if A>B is false (if A is not greater than B) we take


the action on right

 print the value of B


DECISION STRUCTURES

Y N
is
A>B

Print A Print B
IF–THEN–ELSE STRUCTURE

 The structure is as follows:

If condition then
true alternative
else
false alternative
endif
IF–THEN–ELSE STRUCTURE

 The algorithm for the flowchart is as follows:

If A>B then
print A Y N
is
else A>B
print B
endif Print A Print B
Relational Operators

Relational Operators
Operator Description
> Greater than
< Less than
= Equal to
 Greater than or equal to
 Less than or equal to
 Not equal to
Example 5

 Write an algorithm that reads two values,


determines the largest value and prints the
largest value with an identifying message.
ALGORITHM
Step 1: Input VALUE1, VALUE2
Step 2: if (VALUE1 > VALUE2) then
MAX  VALUE1
else
MAX  VALUE2
endif
Step 3: Print “The largest value is”, MAX
START

Input
VALUE1,VALUE2

Y is
N
VALUE1>VALUE2

MAX  VALUE1 MAX  VALUE2

Print
“The largest value is”, MAX

STOP
NESTED IFS

 One of the alternatives within an IF–THEN–ELSE


statement
 may involve further IF–THEN–ELSE statement
Example 6

 Write an algorithm that reads three numbers and


prints the value of the largest number.
Step 1: Input N1, N2, N3
Step 2: if (N1>N2) then
if (N1>N3) then
MAX  N1 [N1>N2, N1>N3]
else
MAX  N3 [N3>N1>N2]
endif
else
if (N2>N3) then
MAX  N2 [N2>N1, N2>N3]
else
MAX  N3 [N3>N2>N1]
endif
endif
Step 3: Print “The largest number is”, MAX
Example 7

 Write and algorithm and draw a flowchart to


a) read an employee name (NAME), overtime hours
worked (OVERTIME), hours absent (ABSENT) and
b) determine the bonus payment (PAYMENT).
Step 1: Input NAME,OVERTIME,ABSENT
Step 2: if (OVERTIME–(2/3)*ABSENT > 40) then
PAYMENT  50
else if (OVERTIME–(2/3)*ABSENT > 30) then
PAYMENT  40
else if (OVERTIME–(2/3)*ABSENT > 20) then
PAYMENT  30
else if (OVERTIME–(2/3)*ABSENT > 10) then
PAYMENT 20
else
PAYMENT  10
endif
Step 3: Print “Bonus for”, NAME “is $”, PAYMENT
Bonus Schedule

OVERTIME – (2/3)*ABSENT Bonus Paid

>40 hours $50


>30 but  40 hours $40
>20 but  30 hours $30
>10 but  20 hours $20
 10 hours $10
Introduction of
Programming Languages
What is Computer?

 A computer is a programmable machine. This


means it can execute a programmed list of
instructions and respond to new instructions that it is
given.
Computer Program

 Computer program are instructions for a computer


 Computer executes the program in CPU
 Program has an executable form
 Computer program gets input from the user
 Computer program can generate information to
the user, this information is called output
Input and Output

input output
Computer Program
Programming Language Concepts

 What is a programming language?


 Why are there so many programming languages?
 What are the types of programming languages?
 Does the world need new languages?
What is a Programming
Languages

 A programming language is a set of rules that provides a way


of telling a computer what operations to perform.
 A programming language is a set of rules for communicating an
algorithm
What is a Programming
Language?
A programming language is a notational system for describing computation
in a machine-readable and human-readable form.
What is a Programming Language

 English is a natural language. It has words, symbols and


grammatical rules.
 A programming language also has words, symbols and rules of
grammar.
 The grammatical rules are called syntax.
 Each programming language has a different set of syntax rules.
Why Are There So Many
Programming Languages

 Why does some people speak French?


 Programming languages have evolved
over time as better ways have been
developed to design them.
 First programming languages were developed
in the 1950s
 Since then, thousands of languages have
been developed
 Different programming languages are
designed for different types of programs.
Levels of Programming Languages
class Triangle {
...
float surface()
High-level program return b*h/2;
}

LOAD r1,b
LOAD r2,h
Low-level program MUL r1,r2
DIV r1,#2
RET

Executable Machine code


0001001001000101001001
001110110010101101001.
..
What Are the Types of
Programming Languages

 First Generation Languages


 Second Generation Languages
 Third Generation Languages
 Fourth Generation Languages
 Fifth Generation Languages
First Generation Languages

 Machine language
 Operation code – such as addition or subtraction.
 Operands – that identify the data to be processed.
 Machine language is machine dependent as it is the only language the
computer can understand.
 Very efficient code but very difficult to write.
Second Generation
Languages
 Assembly languages
 Symbolic operation codes replaced binary operation codes.
 Assembly language programs needed to be “assembled” for execution
by the computer. Each assembly language instruction is translated into
one machine language instruction.
 Very efficient code and easier to write.
Third Generation Languages

 Closer to English but included simple mathematical notation.


 Programs written in source code which must be translated into machine
language programs called object code.
 The translation of source code to object code is accomplished by a
machine language system program called a compiler.
Third Generation Languages
(cont’d.)

 Alternative to compilation is interpretation which is accomplished by


a system program called an interpreter.
 Common third generation languages
 FORTRAN
 COBOL
 C and C++
 Visual Basic
Fourth Generation Languages

 A high-level language (4GL) that requires fewer


instructions to accomplish a task than a third-
generation language.
 Used with databases
 Query languages
 Report generators
 Forms designers
 Application generators
Fifth Generation Languages

 Declarative languages
 Functional(?): Lisp, Scheme, SML
 Also called applicative
 Everything is a function
 Logic: Prolog
 Based on mathematical logic
 Rule- or Constraint-based
The principal paradigms

 Imperative Programming (C)


 Object-Oriented Programming (C++)
 Logic/Declarative Programming (Prolog)
 Functional/Applicative Programming (Lisp)
Programming Languages

 Two broad groups


 Traditional programming languages
 Sequences of instructions
 First, second and some third-generation languages

 Object-oriented languages
 Objects are created rather than sequences of instructions
 Some third generation, and fourth and fifth generation
languages
Traditional Programming
Languages

 FORTRAN
 FORmula TRANslation.
 Developed at IBM in the mid-1950s.
 Designed for scientific and mathematical applications
by scientists and engineers.
Traditional Programming
Languages (cont’d.)

 COBOL
 COmmon Business Oriented Language.
 Developed in 1959.
 Designed to be common to many different computers.
 Typically used for business applications.
Traditional Programming
Languages (cont’d.)

 BASIC
 Beginner’s All-purpose Symbolic Instruction Code.
 Developed at Dartmouth College in mid 1960s.
 Developed as a simple language for students to write
programs with which they could interact through
terminals.
Traditional Programming
Languages (cont’d.)

 C
 Developed by Bell Laboratories in the early 1970s.
 Provides control and efficiency of assembly language
while having third generation language features.
 Often used for system programs.
 UNIX is written in C.
Object-Oriented Programming
Languages

 Simula
 First object-oriented language
 Developed by Ole Johan Dahl in the 1960s.
 Smalltalk
 First purely object-oriented language.
 Developed by Xerox in mid-1970s.
 Still in use on some computers.
Object-Oriented Programming
Languages (cont’d.)

 C++
 It is C language with additional features.
 Widely used for developing system and application
software.
 Graphical user interfaces can be developed easily with
visual programming tools.
Object-Oriented Programming
Languages (cont’d.)

 JAVA
 An object-oriented language similar to C++ that
eliminates lots of C++’s problematic features
 Allows a web page developer to create programs for
applications, called applets that can be used through
a browser.
 Objective of JAVA developers is that it be machine,
platform and operating system independent.
Special Programming Languages

 Scripting Languages
 JavaScript and VBScript
 Php and ASP
 Perl and Python
 Command Languages
 sh, csh, bash
 Text processing Languages
 LaTex, PostScript
Special Programming
Languages
(cont’d.)
 HTML
 HyperText Markup Language.
 Used on the Internet and the World Wide Web (WWW).
 Web page developer puts brief codes called tags in
the page to indicate how the page should be
formatted.
Special Programming Languages
(cont’d.)

 XML
 Extensible Markup Language.
 A language for defining other languages.
A language is a language is a
language

 Programming languages are languages


 When it comes to mechanics of the task,
learning to speak and use a programming
language is in many ways like learning to
speak a human language
 In both kind of languages, you have to
learn new vocabulary, syntax and
semantics (new words, sentence structure
and meaning)
 And both kind of language require
considerable practice to make perfect.
What determines a “good” language

 Formerly: Run-time performance


 (Computers were more expensive than
programmers)
 Now: Life cycle (human) cost is
more important
 Ease of designing, coding
 Debugging
 Maintenance
 Reusability
Criteria in a good
language design
 Writability: The quality of a language that enables a
programmer to use it to express a computation
clearly, correctly, concisely, and quickly.
 Readability: The quality of a language that enables
a programmer to understand and comprehend the
nature of a computation easily and accurately.
 Orthogonality: The quality of a language that
features provided have as few restrictions as possible
and be combinable in any meaningful way.
 Reliability: The quality of a language that assures a
program will not behave in unexpected or disastrous
ways during execution.
 Maintainability: The quality of a language that eases
errors can be found and corrected and new
features added.
Criteria (Continued)

 Generality: The quality of a language that avoids special


cases in the availability or use of constructs and by
combining closely related constructs into a single more
general one.
 Uniformity: The quality of a language that similar features
should look similar and behave similar.
 Extensibility: The quality of a language that provides
some general mechanism for the user to add new
constructs to a language.
 Standardability: The quality of a language that allows
programs written to be transported from one computer to
another without significant change in language structure.
 Implementability: The quality of a language that provides
a translator or interpreter can be written. This can address
to complexity of the language definition.
Compiler?

➢ A compiler is a piece of code that translates the high-level


language into machine language.
➢ When a user writes a code in a high-level language such as
Java and wants it to execute, a specific compiler which is
designed for Java is used before it will be executed.
➢ The compiler scans the entire program first and then translates it
into machine code which will be executed by the computer
processor and the corresponding tasks will be performed.
Compiler

 Shown in the figure is basic outline of the compilation process, here


program written in higher level language is known as source program
and the converted one is called object program.
Compiler working Process
Compiler code

➢ Here is a compiler code


example that run “HELLO
WORD”
➢ If you create any error in code
then out not found or get error
message.
Interpreter?

➢ Interpreters are not much different than compilers. They also


convert the high-level language into machine readable binary
equivalents.
➢ Each time when an interpreter gets a high-level language code
to be executed, it converts the code into an intermediate code
before converting it into the machine code.
➢ Each part of the code is interpreted and then execute
separately in a sequence and an error is found in a part of the
code it will stop the interpretation of the code without translating
the next set of the codes.
Interpreter

 Outlining the basic working of the interpreter the above figure shows that first a
source code is converted to an intermediate form and then that is executed by
the interpreter.
Interpreter Code Example
COMPILER vs INTERPRETER

 A Compiler and Interpreter both carry out the same purpose –


convert a high-level language (like C, Java) instructions into the
binary form which is understandable by computer hardware.
 They are the software used to execute the high-level programs
and codes to perform various tasks.
 Specific compilers/interpreters are designed for different high-
level languages. However, both compiler and interpreter have
the same objective but they differ in the way they accomplish
their task i.e. convert high level language into machine
language.
No. COMPILER INTERPRETER
1. Based on language translation Based on Interpretation Method.
linking-loading model.

2. Generate a target output program Do not generate any output program ,


as an output which can be run they evaluate the source program at
independently from the source each time for execution.
program.
3. Program execution is separate Program Execution is a part of
from compilation and performed Interpretation and is performed on a
only after the entire output statement-by-statement basis.
program is produced.
4. Target program execute The interpreter exist in the memory
independently and does not need during interpretation.
the presence of compiler in the
memory.
N COMPILER INTERPRETER
o.
5. Do not generate output program , If It can evaluate & execute program
any is occurred. statement until an error is found.

6. Need recompilation for generating Interpreter is independent of program


output program in target language modification issues as it processes
after each modification in the the source program each time during
source program. execution.
7. Suitable for Production Environment. Suitable for program development
environment.

8. Bounded to specific target machine Can be made portable by carefully


and cannot be ported. coding them in a higher level
language.
9. C and C++ are example of Visual Basic , LISP and MATLAB use
programming language that use Interpreter.
compilation model.
keywords

Keywords are words that :

➢ Are reserved for use.


➢ May not be used to name applications or objects ,such as
classes ,methods or variables.
➢ Are case-sensitive and in lowercase
Identifiers

An identifier is a name that:


➢ Identifies a variable, class or method
➢ Identifiers must start with either an uppercase or lowercase letter,
an underscore (_), or a dollar sign ($).
➢ Identifiers cannot contain punctuation, spaces, dashes,
or any of the Java technology keywords.
➢ Most importantly identifiers are case sensitive.
➢ Identifiers cannot begin with a digit (0-9)
➢ White space is not permitted.

❑ Examples of legal identifiers: age, $salary, _value, __1_value


❑ Examples of illegal identifiers : 123abc, -salary , max value
Variables

Variables are named memory locations that are used for storing data
items of a value of a particular data type or a reference to an object.

▪ Variable lives confined to the scope of their definition, which cab be :

➢ At the local evlevel inside a method or block of code , they are called
local variables
➢ At the object instance lel when defined as a Non-static attribute
, also called instance variables
➢ At the class level when defined as a static attribute , also called
class variables
➢Variables in method declarations—these are called parameters.
Data Types

➢ Value Types (Built in data types – Primitive data types Like: int ,
float , ..)

➢ Reference Types (any other type Like: objects , Interface ,


array, Enum ..)
stack heap
x
Data 5

int x =5;
ref

Memory
Primitive Data Types

❑ There are different primitive data types supported in programming,


and they enable you to define variables for storing data that
fall into one of three categories:

1. Numeric values
✓ integer (byte, short, int, and long)
✓ floating-point (float and double)

2. A single Unicode character (char)

3. Logical values (boolean) that can be true or false


Variables

Variable Declaration
▪ To declare a variable, you use the syntax :
datatype varableName;

▪ To Declare multiple variables using A single statement :


datatype variable1,variable2 ,variable3 ,..... variableN;

Variable Naming Conventions


The variable naming conversions are the same as those of identifiers
Java developers must not use the dollar symbol in a variable. Also, variable
names must not start with an underscore
Variables

 Initializing Variables
 You can assign values to variables in your program during variable
declaration.

 datatype variableName = initvalue;

 datatype variable1 = initvalue , variable2= initvalue2 , .... , variableN= initvalueN;

Uninitialized Variables
Attributes (instance or static) are always initialized to a default value
local variable must be initialized otherwise the Program does not compile
Integer Data Types

Data Type Size Range Default


Value
byte 1 byte (8 bits) -27 to 27-1 (-128 to +127 or 256 possible 0
values)
short 2 bytes (16 bits) -215 to 215-1 (-32,768 to 32,767 or 65,535 0
possible values )
int 4 bytes (32 bits) -231 to 231-1 (-2,147,483,648 to 0
2,147,483,647 or 4,294,967,296 possible
Values )
long 8 bytes (64 bits) -263 to 263-1 (-9,223,372,036854,775,808 to 0L
9,223,372,036854,775,807, or
18,446,744,073,709,551,616
possible values)
Floating-Point Data Types

Data Type Size Default Value

float 32-bit 0.0f

double 64-bit 0.0d

➢ Float is mainly used to save memory in large arrays of floating-point


numbers.
➢ Float data type is never used for precise values such as currency.

➢ Double data type is generally used as the default data type for
decimal values.
➢ Double data type should never be used for precise values such as
currency.
Character Type

✓ Char data type is used to store any character.

✓ Java uses Unicode to represent characters

✓ char data type is a single 16-bit Unicode character.

✓ Minimum value is '\u0000' (or 0).

✓ Maximum value is '\uffff' (or 65,535 inclusive).

✓ Default value : '\u0000'

✓ Example : char letterA ='A'


Boolean Type

✓ boolean data type represents one bit of information.

✓ There are only two possible values : true and false.

✓ This data type is used for simple flags that track true/false
conditions.

✓ Used to hold the result of an expression that evaluates


to either true or false.

✓ Default value : false

✓ The size of boolean is not defined in the Java specification, but


requires at least one bit.

✓ Example : boolean one = true


Declaring Constants

❑ A Constant is a variable type in java whose value does not


change .

❑ Constants are defined using the final keyword followed by the


variable declaration. By convention ,constant variable names
are in uppercase .If the name is composed of more than one
word, the words are separated by an underscore (_).

❑ Constants defined in this way cannot be reassigned, and it is


a compile - time error if your program tries to do so.

EX: final double PI=3.141592653589793;


EX: final int FEET_PER_YARD = 3;
Expressions

An expression is a combination of operators (such as


addition '+', subtraction '-', multiplication '*', division '/') and
operands (variables or literals), that can be evaluated to
yield a single value of a certain type

1 + 2 * 3 // evaluated to int 7
int sum, number; sum + number // evaluated to an int value
// Evaluated to a double value
double principal, interestRate; principal * (1 + interestRate)
Operators

✓ Arithmetic Operators
✓ Assignment Operators
✓ Relational Operators
✓ Logical Operators
✓ Increment and Decrement Operators
✓ Bitwise Operators
✓ Operator Precedence
Arithmetic Operators

Arithmetic operators are used in mathematical expressions

Operator Meaning Syntax


+ Addition X+y
‫ــ‬ Subtraction X-y
* Multiplication X*y
/ Division X/y
% Modulus X%y
The reminder from a division
operation
String Concatenation
The + operator may used to concatenate the strings together

print("Account Balance is"+ balance);


Compound Arithmetic Assignment Operators

Simple assignment operator, Assigns values from right side


operands to left side operand

Operator Expression Meaning


+= X += y X=X + y
‫=ــ‬ X -= y X=X – y
*= X *= y X=X * y
/= X /= y X=X / y
%= X %= y X=X % y
Relational Operators

Relational Operators are symbols user for determining relational


comparisons between operands. all expressions created using
relational operators will return a boolean value , depending on
whether the comparison is true

Operator Meaning Syntax


== equal to X == y
!= not equal to X != y
> greater than X>y
< less than X<y
>= greater than or equal to X >= y
<= less than or equal to X <= y
Logical Operators

Logical Operators evaluate expressions that carry boolean values .


The result returned by logical operators is also a boolean value.

Operator Meaning
& logical AND
&& conditional AND
| logical OR
|| Conditional OR
^ exclusive OR (XOR)
! logical (NOT)
Logical Operators - The truth tables
Increment and Decrement Operators

Operator Meaning
++ Increment operator; increase the value of
a numeric variable or array element by 1
-- Decrement operator; reduce the value of
a numeric variable or array element by 1

Prefix and Postfix


➢ Prefix :
Placing the operator before the operand causes increment or decrement to
occur before the value of the operand is used to evaluate an expression
For example : int a=5;
int x =++a;
both x and a will have the value 6
➢ Postfix :
Placing the operator after the operand causes increment or decrement to
occur after the value of the operand is used in an expression
For example : int a=5;
int x =a++;
x will have the value of 5 and a will have the value 6
Bitwise Operators

Operator Description
Binary bitwise AND (&) Returns a 1 if both bits are 1
Binary bitwise OR (|) Returns a 1 if either bit is 1
Binary bitwise XOR (^) Returns a 1 if both bits have different values
Unary bitwise complement (~) Changes each bit in its operand to the
opposite value
Binary left shift (<<) Shifts bits on the left to the left by a distance
denoted by the right operand .Fills in zeros
Binary right shift (>>) Shifts bits on the left to the right by a distance
denoted by the right operand .Fills in the
highest bit on the left side.
Binary arithmetic and logical shift Shifts bits on the left to the right by a distance
(>>>) denoted by the right operand .Fills in zeros
Operator Precedence

Operator precedence is the order in which operators are


evaluated in an expression containing two or more operators

Operators with same


precedence are calculated
from left to right

Parentheses alter the


order of calculations
Operator Precedence

precedence Operator
1 (..) [..] . (dot operator)
2 ++ -- ! ~ instanceof
3 new (type) expression
4 * / %
5 + -
6 << >> >>>
7 < > <= >=
8 = !=
9 &
10 ^
11 |
12 &&
13 ||
Functions

● Define functions
● Passing arguments to Function
● Return a value from function
● Scope of Objects
● Default arguments
● Positional and keyword arguments
● Variable length arguments
Functions

 Piece of reusable code


 Solves particular task
 Call function instead of writing code yourself
Built-in Functions
106
Syntax of Function
Function Call

 Once we have defined a function, we can


call it from another function, program or
even the Python prompt.
 To call a function we simply type the
function name with appropriate
parameters.

Calling the
Function
my_function()
Square function: Take one
arguments and prints its square
Function returning multiple value
Scope and Lifetime of variables

 Scope of a variable is the portion of a program where the


variable is recognized.
 Parameters and variables defined inside a function is not
visible from outside. Hence, they have a local scope.
 Lifetime of a variable is the period throughout which the
variable exits in the memory. The lifetime of variables inside
a function is as long as the function executes.
 They are destroyed once we return from the function.
Hence, a function does not remember the value of a
variable from its previous calls.
Default Arguments

 Function arguments can have default


values in Python.
 We can provide a default value to an
argument by using the assignment
operator (=).
Default Arguments

 In this function, the


parameter amount does not have a
default value and is required (mandatory)
during a call.
 On the other hand, the parameter
discountPercentage has a default value
of 0. So, it is optional during a call.
 If a value is provided, it will overwrite the
default value.
 Any number of arguments in a function
can have a default value.
Default Arguments

 Once we have a default argument, all the


arguments to its right must also have default values.

 SyntaxError: non-default argument follows default


argument
Keyword Arguments
 Positional argument cannot follow keyword
argument
Functions as Objects

● Although functions are created differently from normal


variables, functions are just like any other kind of value.
● They can be assigned and reassigned to variables, and later
referenced by those names.
Thank You.

You might also like