0% found this document useful (0 votes)
6 views31 pages

Lecture 21 & 22

The document discusses key programming concepts, including selection statements, iterative statements, and the fundamentals of subprograms. It outlines the characteristics of selection and iterative statements, as well as the design issues and types of parameters in subprograms. Additionally, it explains parameter passing methods and provides examples in various programming languages such as Ruby and C#.

Uploaded by

Hanzala Shafique
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)
6 views31 pages

Lecture 21 & 22

The document discusses key programming concepts, including selection statements, iterative statements, and the fundamentals of subprograms. It outlines the characteristics of selection and iterative statements, as well as the design issues and types of parameters in subprograms. Additionally, it explains parameter passing methods and provides examples in various programming languages such as Ruby and C#.

Uploaded by

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

COMSATS University Islamabad,

Wah Campus

Lecture No. 21 & 22


Statement- Level Control Structures: Selection Statements, Iterative Statements Fundamentals
of Sub-Programs, Design Issues for Subprograms: • General Subprogram Characteristics

Basic Definitions • Parameters • Procedures and Functions

Theory Of Programming Languages


Fall 2024 1
~~~ Dr. Khalid Iqbal Khattak ~~~
Selection Statements
A selection statement
provides the means of
Selection statements fall
choosing between two or
into two general categories
more execution paths in a
program

Two-way
• if control_expression
then clause
else clause

n-way, or multiple selection.


• The multiple-selection statement
allows the selection of one of any
number of statements or
statement groups.

Fall 2024
Theory Of Programming Languages 2
~~~ Dr. Khalid Iqbal Khattak ~~~
Iterative Statements

An iterative statement is one that


causes a statement or collection
of statements to be executed zero,
one, or more times. An iterative
statement is often called a loop

Statements in programming used


to execute part of code repeatedly
based on condition or set of
conditions

Theory Of Programming Languages


Fall 2024 3
~~~ Dr. Khalid Iqbal Khattak ~~~
Iterative Statements (generic)
>> list = [2, 4, 6, 8]
The most common Ruby iterator is each
>> list.each {|value| puts value}

C# code

List<String> names = new


List<String>();

names.Add("Bob");
names.Add("Carol");
names.Add("Alice"); . . .

foreach (String name in names)

Console.WriteLine(name); 4.times
{puts
In Ruby
"Hey!"}
Theory Of Programming Languages
Fall 2024 4
~~~ Dr. Khalid Iqbal Khattak ~~~
Fundamentals of Sub-Programs
A subprogram is defined as a set of statements that can be reused at
multiple places in a program when convenient. This reuse results in
multiple types of savings, from memory space to coding time.

A subprogram is a sequence of instructions whose execution is


invoked from one or more remote locations in a program.

A formal parameter is a dummy variable listed in the subprogram


header and used in the subprogram

Types of Parameters:
Subprograms can be saved separately as modules and used again in
other programs (time saving, tested and debugged) Value parameters
reference parameters
• Procedures: A procedure is used to do an action output parameters
• Functions: A function is used for calculating value.
parameter arrays

Theory Of Programming Languages


Fall 2024 5
~~~ Dr. Khalid Iqbal Khattak ~~~
Fundamentals of Sub-Programs

Theory Of Programming Languages


Fall 2024 6
~~~ Dr. Khalid Iqbal Khattak ~~~
Design Issues for Subprograms
Subprograms are complex structures having a lengthy list of
issues:
• choice of one or more parameter-passing methods (the types of actual
parameters will be type checked against the types of the corresponding
formal parameters.)
• The nature of the local environment of a subprogram (local variables are
statically or dynamically allocated.)?
• Subprogram definitions can be nested?
• Subprogram names can be passed as parameters?
• Question of the correct referencing environment of a subprogram?
• Side effects of functions can cause problems
• Subprograms can be overloaded or generic.

An overloaded subprogram is one that has the same name as


another subprogram in the same referencing environment
Theory Of Programming Languages
Fall 2024 7
~~~ Dr. Khalid Iqbal Khattak ~~~
Design Issues for Subprograms

A generic subprogram is one whose computation can be done on data of


different types in different calls.

A closure is a nested subprogram and its referencing environment, which


together allow the subprogram to be called from anywhere in a program.
• Are local variables statically or dynamically allocated? Can subprogram definitions appear in
other subprogram definitions? What parameter-passing method or methods are used?
• Are the types of the actual parameters checked against the types of the formal parameters?
• If subprograms can be passed as parameters and subprograms can be nested, what is the
referencing environment of a passed subprogram?
• Are functional side effects allowed?
• What types of values can be returned from functions? How many values can be returned
from functions? Can subprograms be overloaded?
• Can subprograms be generic?
• If the language allows nested subprograms, are closures supported?

Theory Of Programming Languages


Fall 2024 8
~~~ Dr. Khalid Iqbal Khattak ~~~
Design Issues for Subprograms

A Subprogram is implemented using the Call & Return


instructions in Assembly Language.

The Call Instruction is present in the Main Program and the


Return(Ret) Instruction is present in the subprogram itself.

It is important to note that the Main Program is suspended


during the execution of any subprogram.

Control always returns to the caller when the subprogram


execution terminates

Theory Of Programming Languages


Fall 2024 9
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Basic Definitions

A subprogram header, first


A part of the definition, serves
several purposes
subprogram
A subprogram • Subprogram header specifies
definition that the following syntactic unit
call is the
describes A subprogram is said to is a subprogram definition of
explicit be active if, after having some particular kind.
the interface been called, it has begun
request that a • In languages that have more
to and the execution but has not than one kind of subprogram,
specific yet completed that the kind of the subprogram is
actions of execution.
subprogram usually specified with a special
the word.
be executed. • If the subprogram is not
subprogram anonymous, the header
abstraction. provides a name for the
subprogram.
• It may specify a list of
parameters.

Theory Of Programming Languages


Fall 2024 10
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Basic Definitions
• Python subprogram and Ruby subprogram header can
be defined with def.
• The header of a JavaScript subprogram begins with
function
– def adder parameters
• In C, the header of a function named adder
– void adder (parameters)
• The reserved word void in this header indicates that
the subprogram does not return a value.
• C-based languages and few others like JavaScript uses
{} to end the body of subprogram. End (in Ruby) and
indentation (in Python) must be indicated to the end
of the body by the first statement.

Theory Of Programming Languages


Fall 2024 11
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Basic Definitions
• Consider the following skeletal example:

• If the then clause of this selection construct is


executed
– function fun can be called, but not the version in the
else clause
• if the else clause is chosen
– function can be called but the one in the then clause
cannot.
Theory Of Programming Languages
Fall 2024 12
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Basic Definitions
# Ruby program to illustrate the passing
# parameters to new method Vehicle is the class name. def is a keyword which is used
#!/usr/bin/ruby to define “initialize” method in Ruby. It is called
# defining class Vehicle whenever a new object is created.
class Vehicle Parameters in initialize method and @veh_id
# initialize method @veh_color, @veh_name are the local
def initialize(id, color, name) variables
# variables Output
@veh_id = id
@veh_color = color ID is: 1
@veh_name = name
# displaying values Color is: Red
puts "ID is: #@veh_id"
puts "Color is: #@veh_color" Name is: Sunny
puts "Name is: #@veh_name"
puts "\n" ID is: 2
end
end
Color is: Black
# Creating objects and passing parameters
# to new method
xveh = Vehicle. new("1", "Red", Theory
“Sunny")
Name is: City
Of Programming Languages
Fall 2024 13
yveh = Vehicle. new("2", "Black",~~~
“City")
Dr. Khalid Iqbal Khattak ~~~
Subprograms: Basic definitions
• The parameter profile of a subprogram contains the number,
order, and types of its formal parameters
• The protocol of a subprogram is its parameter profile plus, if it
is a function, its return type.
• Prototypes: A prototype is an early version of a product from
which future versions are developed
– Prototype-based programming uses the process generalized objects,
which can then be cloned and extended. Using fruit as an example, a
"fruit" object would represent the properties and functionality of fruit
in general

Theory Of Programming Languages


Fall 2024 14
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Basic definitions
• Prototypes: A prototype is an early version of a product from
which future versions are developed
– Prototype-based programming uses the process generalized objects,
which can then be cloned and extended. Using fruit as an example, a
"fruit" object would represent the properties and functionality of fruit in
general

Theory Of Programming Languages


Fall 2024 15
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Parameters
A parameter is a special kind of variable used in a function to
refer to one of the pieces of data provided as input to the
function.
These pieces of data are the values of the arguments with which the function is going
to be called/invoked.

Theory Of Programming Languages


Fall 2024 16
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Parameters
Types of parameters
Parameters appear in
• By value procedure definitions;
• By reference arguments appear in
• By output procedure calls.
• Parameter array OR

In the function definition


f(x) = x*x the variable x is a Loosely, a parameter is a
parameter; in the function type, and an argument is
Parameter modes call f(2) the value 2 is the an instance.
argument of the function.
• Input parameters
• Output parameters
• input/output Input parameters are used when dynamic content is passed to
parameters the external data source
Output parameters are the parameters that are fetched from
the response of a service call

Theory Of Programming Languages


Fall 2024 17
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Parameters
Formal parameters are The subprogram must
characterized by one of add list1 to list2 and
three distinct return the result as a
semantics models: revised version of list2

can receive data


from the Consider a subprogram list1 should be in
corresponding that takes two arrays of mode
actual parameter int values as
parameters—list1 and
can transmit data to list2.
the actual list2 must be inout
mode
parameter; or

can do both.
• Models called in mode,
The third array
out mode, and inout should be out mode
mode Theory Of Programming Languages
Fall 2024 18
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Parameters
Formal parameters are Consider a subprogram The subprogram must add
characterized by one of that takes two arrays of int list1 to list2 and return
three distinct semantics values as parameters— the result as a revised
models: list1 and list2. version of list2

can receive data


from the list1 should be in
corresponding mode
actual parameter

can transmit data


list2 must be
to the actual
inout mode
parameter; or

can do both.
The third array
• Models called in
mode, out mode, and
should be out
inout mode mode
Theory Of Programming Languages
Fall 2024 19
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Parameters Passing
In Python, functions can take inputs, known as parameters or
arguments, to perform specific tasks based on those inputs.

A function can be defined with parameters by placing the


parameter names inside the parentheses of the function definition.

def greet(name):

print(f"Hello, {name}!")

greet("Alice") # Outputs: Hello, Alice!

Arguments passed to a function in the exact order in which they are defined are called positional
arguments

It is the position that the arguments are placed in the brackets that is inherited, not the variable
name. Theory Of Programming Languages
Fall 2024 20
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Parameters Passing
• POSITIONAL ARGUMENTS
def display_info(name, age):
print(f"My name is {name} and I am {age} years old.")
display_info("Bob", 25) # Outputs: My name is Bob and I am 25 years old.

• PASS BY REFERENCE
– pass a mutable object(list, dictionary, set) to a function and modify its
value within the function, it will affect the original object.

def modify_list(lst):
lst.append(100)
numbers = [1, 2, 3]
modify_list(numbers)
print(numbers) # Outputs: [1, 2, 3, 100]

Theory Of Programming Languages


Fall 2024 21
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Parameters Passing
Pass-by-Value
• A parameter is passed by value, the value of the actual parameter is used to initialize
the corresponding formal parameter, which then acts as a local variable in the
subprogram, thus implementing in-mode semantics

Pass-by-Result is an implementation model for out-mode parameters.


• When a parameter is passed by result, no value is transmitted to the subprogram.
• The corresponding formal parameter acts as a local variable, but just before control is
transferred back to the caller, its value is transmitted back to the caller’s actual
parameter, which obviously must be a variable.

void Fixer(out int x, out int y) {

The formal parameter x is assigned to its corresponding x = 17; y = 35;


actual parameter first, then the value of the actual parameter }.
a in the caller will be 35. If y is assigned first, then the value
of the actual parameter a in the caller will be 17. ..
f.Fixer(out a, out a);

Theory Of Programming Languages


Fall 2024 22
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Parameters Passing
• Another problem that can occur with pass-by-result is that
the implementer may be able to choose between two
different times to evaluate the addresses of the actual
parameters: at the time of the call or at the time of the
return.
• Ex. consider the following C# method and following code:

void DoIt(out int x, int index){


x = 17; index = 42;
}.
. . sub = 21;
f.DoIt(list[sub], sub);

Theory Of Programming Languages


Fall 2024 23
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Parameters Passing
Pass-by-Value-Result
• Pass-by-value-result is an implementation model for inout-mode
parameters in which actual values are copied.
• It is in effect a combination of pass-by value and pass-by-result
Pass-by-Reference
• Pass-by-reference means to pass the reference of an argument in
the calling function to the corresponding formal parameter of the
called function.
• The called function can modify the value of the argument by using
its reference passed in.
• The following example shows how arguments are passed by
reference.

Theory Of Programming Languages


Fall 2024 24
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Parameters Passing
• Pass-by-Reference
– Pass-by-reference means to pass the reference of an argument in the
calling function to the corresponding formal parameter of the called
function.
– The called function can modify the value of the argument by using its
reference passed in.
– The following example shows how arguments are passed by reference.
#include <stdio.h>
void swapnum(int &i, int &j) { int temp = i;
i = j;
j = temp;}
int main(void) { int a = 10; int b = 20;
swapnum(a, b);
printf("A is %d and B is %d\n", a, b);
return 0;}

Theory Of Programming Languages


Fall 2024 25
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Parameters Passing
• Pass-by-Name
– Pass by name refers to a mechanism, for passing parameters where
the actual argument (the expression or variable) is directly
substituted into the body of the function or procedure at each point
where the parameter is used.
– In terms of the parameter is not evaluated until it is used within the
function or procedure def swap(a, b):
temp = a
a=b
b = temp
Output
def main():
('After swapping, x =', 5)
x=5
('After swapping, y =', 10) y = 10
swap(x, y)
print("After swapping, x =", x)
print("After swapping, y =", y)
Theory Of Programming Languages
Fall 2024 main() 26
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Procedures and Functions

A procedure performs a task and does


not necessarily return any values
• Example: A procedure might be to draw a
square

A function return values for elsewhere


in the program to use
• Example: A function may ask the user
shape_name and return the result in a string.
Theory Of Programming Languages
Fall 2024 27
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Procedures and Functions

A procedure allows you to produce a block of


code that can be used many times to repeat an
action or operation.
• Example: Look at the block of code below drawing a text cat

print (" ^___^ ")


print (" / o o \ ")
print ("=\ ' /=")
print (" \ - / ")
def myCat (): myCat()
Theory Of Programming Languages
Fall 2024 28
~~~ Dr. Khalid Iqbal Khattak ~~~
Subprograms: Procedures and Functions
Functions use the same principles as procedures however
functions return values to back outside the function.

Functions are discrete entities of code and variable inside the


function are not the same as the variables outside the function.

def get_info():

name = "Alice"

age = 30
def myNum(): return name, age
num1 = (5) person_name, person_age = get_info()
myNum()
#This line both calls the functions and receives #the return value
print (num1) in to the two variables

print(person_name) # Outputs: Alice

print(person_age) # Outputs: 30
error: NameError: name 'num1' is not defined
Theory Of Programming Languages
Fall 2024 29
~~~ Dr. Khalid Iqbal Khattak ~~~
General Subprograms Characteristics
• A subprogram has a single entry point
• The caller is suspended during execution of the called
subprogram
• Control always returns to the caller when the called
subprogram's execution terminates
It is important to note that the
Main Program is suspended
during the execution of any
subprogram. Moreover, after the
completion of the subprogram,
the main program executes from
the next sequential address
present in the Program Counter.

Theory Of Programming Languages


Fall 2024 30
~~~ Dr. Khalid Iqbal Khattak ~~~
_______________________________

END

_______________________________

You might also like