SlideShare a Scribd company logo
1 of 7
AUTHOR: MOHAMMED ABDEL KHALEQ DWIKAT EMAIL: dwikatmo@gmail.com
TOPIC: VISUAL BASIC II / FUNCTIONS/SUBS DATE: 1/31/2020 PAGE: 1 OF 7
VVIISSUUAALL BBAASSIICC ((IIII))
AANN NNAAJJAAHH NNAATTIIOONNAALL UUNNIIVVEERRSSIITTYY
MMAANNAAGGEEMMEENNTT IINNFFOORRMMAATTIIOONN SSYYSSTTEEMMSS
PPRREEPPAARREEDD BBYY::
MMOOHHAAMMMMEEDD AABBDDEELL KKHHAALLEEQQ DDWWIIKKAATT
dwikatmo@najah.edu
:facebook.com/dwikatmo
: dwikatmo@gmail.com
3311//0011//22002200
UUSSIINNGG AADDVVAANNCCEEDD FFUUNNCCTTIIOONNSS//SSUUBBSS
Iteration vs. Recursion
Passing Parameters by reference
Passing Arrays as parameters
Optional Parameters
Overloading
AUTHOR: MOHAMMED ABDEL KHALEQ DWIKAT EMAIL: dwikatmo@gmail.com
TOPIC: VISUAL BASIC II / FUNCTIONS/SUBS DATE: 1/31/2020 PAGE: 2 OF 7
IITTEERRAATTIIOONN VVSS.. RREECCUURRSSIIOONN
Iteration is done by using loops, while recursion means the
function call itself.
Principle in recursion, if we can find or calculate process
N times, we can decompose it in N + (N-1) + (N-2) till the
stopping rule.
For example, instead of using the loop to sum from 1 to 5,
we can use recursion to sum it as follows
Sum (5) is
5 + Sum (4)
5 + 4 + Sum (3)
5 + 4 + 3 + Sum (2)
5 + 4 + 3 + 2 + Sum (1)
5 + 4 + 3 + 2 + 1
It works using a stack exactly like the following steps
Stack Rule: Last in First Out (LIFO) ‫الواصل‬‫ي‬ ‫أخيرا‬‫خد‬‫أوال‬ ‫م‬ . Last
number is 1, it is removed first, and so on
done
Sum(1) 1
+ + +
Sum(2) 2 2 2
+ + + + +
Sum(3) 3 3 3 3 3
+ + + + + +
Sum(4) 4 4 4 4 4 4 4
+ + + + + + + + +
Sum(5) 5 5 5 5 5 5 5 5 5
Ans. 1 3 6 10 15
start Step1 Step2 Step3 Step4 Step5 Step6 Step7 Step8 Step9 stop
AUTHOR: MOHAMMED ABDEL KHALEQ DWIKAT EMAIL: dwikatmo@gmail.com
TOPIC: VISUAL BASIC II / FUNCTIONS/SUBS DATE: 1/31/2020 PAGE: 3 OF 7
Write a function using iteration to sun from N to 1
Function Sum (ByVal N as Integer) As Long
Dim S As Long
For i = N To 1 Step -1
S += i
Next
Return s
End Function
For recursion, there should be a stopping rule (here we stop
at 1), the above is written in VB.net as
Function Sum (ByVal N as Integer) As Long
If N = 1 Then Return 1 'Stopping Rule
Return N + Sum (N - 1)
End Function
Write a VB.net functions using recursion to calculate the followings
1. Factorial of a number
Function Factorial (ByVal N As Integer) As Long
If N = 1 or N = 0 Then Return 1 'Stopping Rule
Return N * Factorial (N - 1)
End Function
A fractal is a geometrical figure, but unlike triangles, circles, and
rectangles, fractals can be divided into parts, each of which is a
reduced-size copy of the whole. There are many interesting examples of
fractals. A Sierpinski triangle is a pattern of recursive triangles.
Write a function using recursion to
Calculate M(i) = 1 +
1
2
+
1
3
+
1
4
+
1
5
+ ⋯
1
𝑖
Function M(ByVal i As Integer) As Double
If i = 1 Then Return 1
Return (1 / N) + M(i - 1)
End Function
AUTHOR: MOHAMMED ABDEL KHALEQ DWIKAT EMAIL: dwikatmo@gmail.com
TOPIC: VISUAL BASIC II / FUNCTIONS/SUBS DATE: 1/31/2020 PAGE: 4 OF 7
Calculate M(i) =
1
3
+
2
5
+
3
7
+
4
9
+ ⋯
𝑖
2𝑖+1
Function M(ByVal i As Integer) As Double
If i = 1 Then Return 1 / 3
Return (i / (2 * i + 1)) + M(i - 1)
End Function
Calculate M(i) =
1
2
+
2
3
+
3
4
+
4
5
+ ⋯
𝑖
𝑖+1
Function M(ByVal i As Integer) As Double
If i = 1 Then Return 1 / 2
Return (i / (i + 1)) + M(i - 1)
End Function
Print the characters in a string reversely
Print the digits in an integer reversely
Function P(ByVal S As String) As String
If S.Length = 1 Then Return S
Return S.Substring(S.Length - 1, 1) & P(S.Substring(0, S.Length - 1))
End Function
Occurrences of a specified character in a string) Write a recursive method that
Finds the number of occurrences of a specified letter in a string using the
following
method header:
Sum the digits in an integer using recursion
Function SumDigits(ByVal N As Integer) As Long
If N < 10 Then Return N
Return (N Mod 10) + Sum((N - N Mod 10) / 10)
End Function
Fibonacci series
Public Function Fib(ByVal N As Integer) As Integer
If N <= 2 Then Return 1
Return Fib(N - 1) + Fib(N - 2)
End Function
Call it, explore the Golden Ratio
For i = 1 To 25
T1.Text = T1.Text & i & vbTab & Fib(i) & vbTab & (Fib(i) / Fib(i - 1)).ToString("#.#00") & vbCrLf
Next
AUTHOR: MOHAMMED ABDEL KHALEQ DWIKAT EMAIL: dwikatmo@gmail.com
TOPIC: VISUAL BASIC II / FUNCTIONS/SUBS DATE: 1/31/2020 PAGE: 5 OF 7
PPAASSSSIINNGG PPAARRAAMMEETTEERRSS BBYY RREEFFEERREENNCCEE
1. Write a sub Swap that accept 2 variables x and y as
parameters, then swap them, test it. Print values of x,y
before swap and after swap.
Hint: you should pass parameters by reference
Sub Swap(ByRef x As Integer, ByRef y As Integer)
Dim Temp As Integer
Temp = x
x = y
y = Temp
End Sub
Dim A As Integer = 10, b As Integer = 7
T1.text = "before Swap " & vbcrlf
T1.text = T1.text & "a = " & A & " b = " & b & vbcrlf
Swap (A, b)
T1.text = T1.text & "After Swap " & vbcrlf
T1.text = T1.text & "a = " & A & " b = " & b
OOPPTTIIOONNAALL PPAARRAAMMEETTEERRSS
Write a function that calculate salary tax for an employee, if the
employee is Married, tax is 10% of the salary, if the employee is
single, then tax is 15% of the salary, by default, consider employee
as being Married
Function CalcTax(ByVal salary As Double, Optional ByVal Status As String =
"Married") As Double
If Status = "Married" Then
Return salary * 0.1
Else
Return salary * 0.15
End If
End Function
How to call it?
Dim Tax as double
Tax = CalcTax(100, "Single") tax will be 15
Tax = CalcTax(100, "Married") tax will be 10
You can call it without the second parameter, because if you didn’t specify it, it
is considered by default as Married.
Tax = CalcTax(100) same as Tax = CalcTax(100, "Married") tax will be 10
AUTHOR: MOHAMMED ABDEL KHALEQ DWIKAT EMAIL: dwikatmo@gmail.com
TOPIC: VISUAL BASIC II / FUNCTIONS/SUBS DATE: 1/31/2020 PAGE: 6 OF 7
A nother example with 2 optional parameters
Function CalcTax2(ByVal salary As Double, Optional ByVal Gender As String =
"Male", Optional ByVal Status As String = "Married") As Double
If Status = "Married" Then
If Gender = "Male" Then
Return salary * 0.10
Else
Return salary * 0.12
End If
Else
If Gender = "Male" Then
Return salary * 0.15
Else
Return salary * 0.18
End If
End If
End Function
'here we have 3 parameters which are salary, Gender, Status
'How to call it
txtTax.Text = CalcTax2(100) 'use salary only
txtTax.Text = CalcTax2(100, "Male")'use salary and Gender
'use salary, gender and status
txtTax.Text = CalcTax2(100, "Male", "Single")
txtTax.Text = CalcTax2(100, , "Male")'use salary, And status only
OOVVEERRLLOOAADDIINNGG
Overloading means: defining multiple functions with the same name
but with different parameters.
WWHHYY DDOO WWEE NNEEEEDD TTOO UUSSEE OOVVEERRLLOOAADDIINNGG??
it is useful, when the data type of a passed parameter is not the
same, and we need to call the function with different data types,
instead of defining different functions with different names, we use
one function name, but with different parameter data types. For
example, if we have a function
Function abs(ByVal x As Integer) As Integer
Return IIf(x < 0, -x, x)
End Function
If we call is to find the absolute value of -6.254, it will return
6 only, for that, we continue to define the same name for double data
types and other data types
Function abs(ByVal x As Double) As Double
Return IIf(x < 0, -x, x)
End Function
Function abs(ByVal x As SByte) As SByte
Return IIf(x < 0, -x, x)
End Function
AUTHOR: MOHAMMED ABDEL KHALEQ DWIKAT EMAIL: dwikatmo@gmail.com
TOPIC: VISUAL BASIC II / FUNCTIONS/SUBS DATE: 1/31/2020 PAGE: 7 OF 7
CCAALLLLIINNGG AA FFUUNNCCTTIIOONN FFRROOMM AANNOOTTHHEERR FFUUNNCCTTIIOONN
Write the correct code to calculate the following formula,
use functions only
Sum the digits in an integer. Write a function that computes the sum
of the digits in an integer.
For example, SumDigits(234) returns 9 (2 + 3 + 4). (Hint: Use the %
operator to extract digits, and the / operator to remove the extracted
digit. For instance, to extract 4 from 234, use 234 % 10 (= 4). To
remove 4 from 234, use 234 / 10 (= 23). Use a loop to repeatedly
extract and remove the digit until all the digits are extracted. Write
a test program that prompts the user to enter an integer and displays
the sum of all its digits.
Function SumDigits(N As Integer) As Integer
Dim Temp As Integer, Remainder As Integer
Temp = N Mod 10
Remainder = (N - Temp) / 10
If Remainder = 0 Then Return Temp
Return Temp + SumDigits(Remainder)
End Function
Another simpler example for any number of digits
Function SumDigits(N As String) As Integer
Dim sum As Integer
For i = 0 To N.Length - 1
sum = sum + Val(N(i))
Next
Return sum
End Function
Call it from click on command button as
T2.Text = SumDigits(T1.Text)

More Related Content

What's hot

Expanding Exponent Products
Expanding Exponent ProductsExpanding Exponent Products
Expanding Exponent Products
Passy World
 

What's hot (20)

Quantitative Analysis For Decision Making
Quantitative Analysis For Decision MakingQuantitative Analysis For Decision Making
Quantitative Analysis For Decision Making
 
Churn Prediction on customer data
Churn Prediction on customer dataChurn Prediction on customer data
Churn Prediction on customer data
 
Operations research : Assignment problem (One's method) presentation
Operations research : Assignment problem (One's method) presentationOperations research : Assignment problem (One's method) presentation
Operations research : Assignment problem (One's method) presentation
 
Assignment method
Assignment methodAssignment method
Assignment method
 
Assignment model
Assignment modelAssignment model
Assignment model
 
Mb 106 quantitative techniques 1
Mb 106 quantitative techniques 1Mb 106 quantitative techniques 1
Mb 106 quantitative techniques 1
 
Assignment1 solution
Assignment1 solutionAssignment1 solution
Assignment1 solution
 
Assignment Problem
Assignment ProblemAssignment Problem
Assignment Problem
 
Operations Research
Operations ResearchOperations Research
Operations Research
 
Mb 106 quantitative techniques 2
Mb 106 quantitative techniques 2Mb 106 quantitative techniques 2
Mb 106 quantitative techniques 2
 
Calculating garbage value in case of overflow
Calculating garbage value in case of overflowCalculating garbage value in case of overflow
Calculating garbage value in case of overflow
 
Lesson 33: The Assignment Problem
Lesson 33: The Assignment  ProblemLesson 33: The Assignment  Problem
Lesson 33: The Assignment Problem
 
Regression Study: Boston Housing
Regression Study: Boston HousingRegression Study: Boston Housing
Regression Study: Boston Housing
 
Python PCEP Logic Bit Operations
Python PCEP Logic Bit OperationsPython PCEP Logic Bit Operations
Python PCEP Logic Bit Operations
 
Expanding Exponent Products
Expanding Exponent ProductsExpanding Exponent Products
Expanding Exponent Products
 
c++ programming Unit 4 operators
c++ programming Unit 4 operatorsc++ programming Unit 4 operators
c++ programming Unit 4 operators
 
Ap for b.tech. (mechanical) Assignment Problem
Ap for b.tech. (mechanical) Assignment Problem Ap for b.tech. (mechanical) Assignment Problem
Ap for b.tech. (mechanical) Assignment Problem
 
Master slave control in gridview
Master   slave control in gridviewMaster   slave control in gridview
Master slave control in gridview
 
Image Processing using Matlab ( using a built in Highboost filtering,averagin...
Image Processing using Matlab ( using a built in Highboost filtering,averagin...Image Processing using Matlab ( using a built in Highboost filtering,averagin...
Image Processing using Matlab ( using a built in Highboost filtering,averagin...
 
Operation reasearch
Operation reasearchOperation reasearch
Operation reasearch
 

Similar to Advanced functions visual Basic .net

C programming session 02
C programming session 02C programming session 02
C programming session 02
Dushmanta Nath
 
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Task4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docxTask4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docx
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
josies1
 

Similar to Advanced functions visual Basic .net (20)

Chapter 16-spreadsheet1 questions and answer
Chapter 16-spreadsheet1  questions and answerChapter 16-spreadsheet1  questions and answer
Chapter 16-spreadsheet1 questions and answer
 
COMPUTER SCIENCE INVESTIGATORY PROJECT 2017-18
COMPUTER SCIENCE INVESTIGATORY PROJECT 2017-18COMPUTER SCIENCE INVESTIGATORY PROJECT 2017-18
COMPUTER SCIENCE INVESTIGATORY PROJECT 2017-18
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
Excel Function Training
Excel Function TrainingExcel Function Training
Excel Function Training
 
Writer Monad for logging execution of functions
Writer Monad for logging execution of functionsWriter Monad for logging execution of functions
Writer Monad for logging execution of functions
 
IRJET- Switch Case Statements in C
IRJET-  	  Switch Case Statements in CIRJET-  	  Switch Case Statements in C
IRJET- Switch Case Statements in C
 
Answers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And EngineersAnswers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
 
C- Programming Assignment practice set 2 solutions
C- Programming Assignment practice set 2 solutionsC- Programming Assignment practice set 2 solutions
C- Programming Assignment practice set 2 solutions
 
IRJET-Design and Implementation of LNS based Approximate Multiplier using Mit...
IRJET-Design and Implementation of LNS based Approximate Multiplier using Mit...IRJET-Design and Implementation of LNS based Approximate Multiplier using Mit...
IRJET-Design and Implementation of LNS based Approximate Multiplier using Mit...
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentation
 
5. R basics
5. R basics5. R basics
5. R basics
 
Pseudocode algorithim flowchart
Pseudocode algorithim flowchartPseudocode algorithim flowchart
Pseudocode algorithim flowchart
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Visual Basic(Vb) practical
Visual Basic(Vb) practicalVisual Basic(Vb) practical
Visual Basic(Vb) practical
 
Bcsl 033 solve assignment
Bcsl 033 solve assignmentBcsl 033 solve assignment
Bcsl 033 solve assignment
 
Vb scripting
Vb scriptingVb scripting
Vb scripting
 
Programming
ProgrammingProgramming
Programming
 
C Programing Arithmetic Operators.ppt
C Programing Arithmetic Operators.pptC Programing Arithmetic Operators.ppt
C Programing Arithmetic Operators.ppt
 
Functions Practice Sheet.docx
Functions Practice Sheet.docxFunctions Practice Sheet.docx
Functions Practice Sheet.docx
 
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Task4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docxTask4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docx
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
 

More from Mohammad Dwikat (7)

Multimedia digital images
 Multimedia  digital images Multimedia  digital images
Multimedia digital images
 
Digital audio
Digital audioDigital audio
Digital audio
 
Vb.net string class visual Basic .net
Vb.net string class visual Basic .netVb.net string class visual Basic .net
Vb.net string class visual Basic .net
 
Forms visual Basic .net
Forms visual Basic .netForms visual Basic .net
Forms visual Basic .net
 
1 main spss all test summary (a3)
1 main spss all test summary (a3)1 main spss all test summary (a3)
1 main spss all test summary (a3)
 
1 main spss test summary 2020 ultimate
1 main spss test  summary 2020 ultimate1 main spss test  summary 2020 ultimate
1 main spss test summary 2020 ultimate
 
0 intro to multimegia
0 intro to multimegia0 intro to multimegia
0 intro to multimegia
 

Recently uploaded

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 

Advanced functions visual Basic .net

  • 1. AUTHOR: MOHAMMED ABDEL KHALEQ DWIKAT EMAIL: dwikatmo@gmail.com TOPIC: VISUAL BASIC II / FUNCTIONS/SUBS DATE: 1/31/2020 PAGE: 1 OF 7 VVIISSUUAALL BBAASSIICC ((IIII)) AANN NNAAJJAAHH NNAATTIIOONNAALL UUNNIIVVEERRSSIITTYY MMAANNAAGGEEMMEENNTT IINNFFOORRMMAATTIIOONN SSYYSSTTEEMMSS PPRREEPPAARREEDD BBYY:: MMOOHHAAMMMMEEDD AABBDDEELL KKHHAALLEEQQ DDWWIIKKAATT dwikatmo@najah.edu :facebook.com/dwikatmo : dwikatmo@gmail.com 3311//0011//22002200 UUSSIINNGG AADDVVAANNCCEEDD FFUUNNCCTTIIOONNSS//SSUUBBSS Iteration vs. Recursion Passing Parameters by reference Passing Arrays as parameters Optional Parameters Overloading
  • 2. AUTHOR: MOHAMMED ABDEL KHALEQ DWIKAT EMAIL: dwikatmo@gmail.com TOPIC: VISUAL BASIC II / FUNCTIONS/SUBS DATE: 1/31/2020 PAGE: 2 OF 7 IITTEERRAATTIIOONN VVSS.. RREECCUURRSSIIOONN Iteration is done by using loops, while recursion means the function call itself. Principle in recursion, if we can find or calculate process N times, we can decompose it in N + (N-1) + (N-2) till the stopping rule. For example, instead of using the loop to sum from 1 to 5, we can use recursion to sum it as follows Sum (5) is 5 + Sum (4) 5 + 4 + Sum (3) 5 + 4 + 3 + Sum (2) 5 + 4 + 3 + 2 + Sum (1) 5 + 4 + 3 + 2 + 1 It works using a stack exactly like the following steps Stack Rule: Last in First Out (LIFO) ‫الواصل‬‫ي‬ ‫أخيرا‬‫خد‬‫أوال‬ ‫م‬ . Last number is 1, it is removed first, and so on done Sum(1) 1 + + + Sum(2) 2 2 2 + + + + + Sum(3) 3 3 3 3 3 + + + + + + Sum(4) 4 4 4 4 4 4 4 + + + + + + + + + Sum(5) 5 5 5 5 5 5 5 5 5 Ans. 1 3 6 10 15 start Step1 Step2 Step3 Step4 Step5 Step6 Step7 Step8 Step9 stop
  • 3. AUTHOR: MOHAMMED ABDEL KHALEQ DWIKAT EMAIL: dwikatmo@gmail.com TOPIC: VISUAL BASIC II / FUNCTIONS/SUBS DATE: 1/31/2020 PAGE: 3 OF 7 Write a function using iteration to sun from N to 1 Function Sum (ByVal N as Integer) As Long Dim S As Long For i = N To 1 Step -1 S += i Next Return s End Function For recursion, there should be a stopping rule (here we stop at 1), the above is written in VB.net as Function Sum (ByVal N as Integer) As Long If N = 1 Then Return 1 'Stopping Rule Return N + Sum (N - 1) End Function Write a VB.net functions using recursion to calculate the followings 1. Factorial of a number Function Factorial (ByVal N As Integer) As Long If N = 1 or N = 0 Then Return 1 'Stopping Rule Return N * Factorial (N - 1) End Function A fractal is a geometrical figure, but unlike triangles, circles, and rectangles, fractals can be divided into parts, each of which is a reduced-size copy of the whole. There are many interesting examples of fractals. A Sierpinski triangle is a pattern of recursive triangles. Write a function using recursion to Calculate M(i) = 1 + 1 2 + 1 3 + 1 4 + 1 5 + ⋯ 1 𝑖 Function M(ByVal i As Integer) As Double If i = 1 Then Return 1 Return (1 / N) + M(i - 1) End Function
  • 4. AUTHOR: MOHAMMED ABDEL KHALEQ DWIKAT EMAIL: dwikatmo@gmail.com TOPIC: VISUAL BASIC II / FUNCTIONS/SUBS DATE: 1/31/2020 PAGE: 4 OF 7 Calculate M(i) = 1 3 + 2 5 + 3 7 + 4 9 + ⋯ 𝑖 2𝑖+1 Function M(ByVal i As Integer) As Double If i = 1 Then Return 1 / 3 Return (i / (2 * i + 1)) + M(i - 1) End Function Calculate M(i) = 1 2 + 2 3 + 3 4 + 4 5 + ⋯ 𝑖 𝑖+1 Function M(ByVal i As Integer) As Double If i = 1 Then Return 1 / 2 Return (i / (i + 1)) + M(i - 1) End Function Print the characters in a string reversely Print the digits in an integer reversely Function P(ByVal S As String) As String If S.Length = 1 Then Return S Return S.Substring(S.Length - 1, 1) & P(S.Substring(0, S.Length - 1)) End Function Occurrences of a specified character in a string) Write a recursive method that Finds the number of occurrences of a specified letter in a string using the following method header: Sum the digits in an integer using recursion Function SumDigits(ByVal N As Integer) As Long If N < 10 Then Return N Return (N Mod 10) + Sum((N - N Mod 10) / 10) End Function Fibonacci series Public Function Fib(ByVal N As Integer) As Integer If N <= 2 Then Return 1 Return Fib(N - 1) + Fib(N - 2) End Function Call it, explore the Golden Ratio For i = 1 To 25 T1.Text = T1.Text & i & vbTab & Fib(i) & vbTab & (Fib(i) / Fib(i - 1)).ToString("#.#00") & vbCrLf Next
  • 5. AUTHOR: MOHAMMED ABDEL KHALEQ DWIKAT EMAIL: dwikatmo@gmail.com TOPIC: VISUAL BASIC II / FUNCTIONS/SUBS DATE: 1/31/2020 PAGE: 5 OF 7 PPAASSSSIINNGG PPAARRAAMMEETTEERRSS BBYY RREEFFEERREENNCCEE 1. Write a sub Swap that accept 2 variables x and y as parameters, then swap them, test it. Print values of x,y before swap and after swap. Hint: you should pass parameters by reference Sub Swap(ByRef x As Integer, ByRef y As Integer) Dim Temp As Integer Temp = x x = y y = Temp End Sub Dim A As Integer = 10, b As Integer = 7 T1.text = "before Swap " & vbcrlf T1.text = T1.text & "a = " & A & " b = " & b & vbcrlf Swap (A, b) T1.text = T1.text & "After Swap " & vbcrlf T1.text = T1.text & "a = " & A & " b = " & b OOPPTTIIOONNAALL PPAARRAAMMEETTEERRSS Write a function that calculate salary tax for an employee, if the employee is Married, tax is 10% of the salary, if the employee is single, then tax is 15% of the salary, by default, consider employee as being Married Function CalcTax(ByVal salary As Double, Optional ByVal Status As String = "Married") As Double If Status = "Married" Then Return salary * 0.1 Else Return salary * 0.15 End If End Function How to call it? Dim Tax as double Tax = CalcTax(100, "Single") tax will be 15 Tax = CalcTax(100, "Married") tax will be 10 You can call it without the second parameter, because if you didn’t specify it, it is considered by default as Married. Tax = CalcTax(100) same as Tax = CalcTax(100, "Married") tax will be 10
  • 6. AUTHOR: MOHAMMED ABDEL KHALEQ DWIKAT EMAIL: dwikatmo@gmail.com TOPIC: VISUAL BASIC II / FUNCTIONS/SUBS DATE: 1/31/2020 PAGE: 6 OF 7 A nother example with 2 optional parameters Function CalcTax2(ByVal salary As Double, Optional ByVal Gender As String = "Male", Optional ByVal Status As String = "Married") As Double If Status = "Married" Then If Gender = "Male" Then Return salary * 0.10 Else Return salary * 0.12 End If Else If Gender = "Male" Then Return salary * 0.15 Else Return salary * 0.18 End If End If End Function 'here we have 3 parameters which are salary, Gender, Status 'How to call it txtTax.Text = CalcTax2(100) 'use salary only txtTax.Text = CalcTax2(100, "Male")'use salary and Gender 'use salary, gender and status txtTax.Text = CalcTax2(100, "Male", "Single") txtTax.Text = CalcTax2(100, , "Male")'use salary, And status only OOVVEERRLLOOAADDIINNGG Overloading means: defining multiple functions with the same name but with different parameters. WWHHYY DDOO WWEE NNEEEEDD TTOO UUSSEE OOVVEERRLLOOAADDIINNGG?? it is useful, when the data type of a passed parameter is not the same, and we need to call the function with different data types, instead of defining different functions with different names, we use one function name, but with different parameter data types. For example, if we have a function Function abs(ByVal x As Integer) As Integer Return IIf(x < 0, -x, x) End Function If we call is to find the absolute value of -6.254, it will return 6 only, for that, we continue to define the same name for double data types and other data types Function abs(ByVal x As Double) As Double Return IIf(x < 0, -x, x) End Function Function abs(ByVal x As SByte) As SByte Return IIf(x < 0, -x, x) End Function
  • 7. AUTHOR: MOHAMMED ABDEL KHALEQ DWIKAT EMAIL: dwikatmo@gmail.com TOPIC: VISUAL BASIC II / FUNCTIONS/SUBS DATE: 1/31/2020 PAGE: 7 OF 7 CCAALLLLIINNGG AA FFUUNNCCTTIIOONN FFRROOMM AANNOOTTHHEERR FFUUNNCCTTIIOONN Write the correct code to calculate the following formula, use functions only Sum the digits in an integer. Write a function that computes the sum of the digits in an integer. For example, SumDigits(234) returns 9 (2 + 3 + 4). (Hint: Use the % operator to extract digits, and the / operator to remove the extracted digit. For instance, to extract 4 from 234, use 234 % 10 (= 4). To remove 4 from 234, use 234 / 10 (= 23). Use a loop to repeatedly extract and remove the digit until all the digits are extracted. Write a test program that prompts the user to enter an integer and displays the sum of all its digits. Function SumDigits(N As Integer) As Integer Dim Temp As Integer, Remainder As Integer Temp = N Mod 10 Remainder = (N - Temp) / 10 If Remainder = 0 Then Return Temp Return Temp + SumDigits(Remainder) End Function Another simpler example for any number of digits Function SumDigits(N As String) As Integer Dim sum As Integer For i = 0 To N.Length - 1 sum = sum + Val(N(i)) Next Return sum End Function Call it from click on command button as T2.Text = SumDigits(T1.Text)