0% found this document useful (0 votes)
9 views7 pages

Understanding Functions in Visual Basic

A function is a named block of code that performs a specific task and returns a value. There are two types of functions: inbuilt functions provided by Visual Basic and user-defined functions created by the programmer. User-defined functions encapsulate common code, making it easier to reuse and maintain. Functions can accept parameters using ByVal to pass a copy of the argument or ByRef to pass the argument by reference. String manipulation involves changing or altering strings using methods like Substring(), Replace(), and Trim(). Practice questions test skills like removing vowels, reversing words, removing duplicates, and checking for palindromes and anagrams.

Uploaded by

shammahzuze05
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)
9 views7 pages

Understanding Functions in Visual Basic

A function is a named block of code that performs a specific task and returns a value. There are two types of functions: inbuilt functions provided by Visual Basic and user-defined functions created by the programmer. User-defined functions encapsulate common code, making it easier to reuse and maintain. Functions can accept parameters using ByVal to pass a copy of the argument or ByRef to pass the argument by reference. String manipulation involves changing or altering strings using methods like Substring(), Replace(), and Trim(). Practice questions test skills like removing vowels, reversing words, removing duplicates, and checking for palindromes and anagrams.

Uploaded by

shammahzuze05
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

PROGRAMMING PART 3

[CHIBI TINODAISHE M]
FUNCTION
WHAT IS A FUNCTION ?

1. A function is a named block of code that performs a specific task and returns a value.
2. There are sub programs that perform a specific function and they return a value to the calling
program
3. Functions can be used to encapsulate common code, making it easier to reuse and maintain.
4. There are two types of function that are to be known at A level :
1) Inbuilt functions
2) User defined functions

User Defined functions


 Functions that are created by a programmer(you).
 They are used to perform any task that the programmer needs, and can be used to make code
more reusable and efficient.
 A function is built on top of the sub main or at the end of the end sub.
Format
 Function function name (parameter list) As Data type Add function

Example

Function sumfunction(num1 As Integer, num2 As Integer) As Integer


Dim sum As Integer
sum = num1 + num2
Return sum
End Function

Sub Main()
Dim num1, num2, sum As Integer
[Link]("Enter the first number")
num1 = [Link]
[Link]("Input the second number") Calling statement for a
num2 = [Link] function to work there is need
of a calling statement
sum = sumfunction(num1, num2)
[Link](num1 & " + " & num2 & " = " & sum)
Else MsgBox("input numrical terms")
End If
[Link]()
End Sub

Passing Parameter
 A passing parameter, or argument is a value that is passed into a function when it is
called
 Lets use an example to make this more concrete
 So you have a function called square(x), which takes a number as an argument and
returns the square of that number.

We have two methods

Byval
 It means that a copy of the argument is made and that a copy is passed into function.
 We are going to copy the actual value from number 1 is placed to a variable to the argument
within the value
Function sumfunction(ByVal num1 As Integer, ByVal num2 As Integer) As Integer

ByRef
 We are not moving the value but the location where the value we are going to use is stored.

Function sumfunction(ByRef num1 As Integer, ByRef num2 As Integer) As Integer

Inbuilt functions
 Are functions that are provided by the visual basic language itself.
 They can be used to perform a variety of tasks, such as string manipulation, mathematical
operations, and date and time calculations.
 Inbuilt functions are called directly from your code, without the need to create a separate
function definition.
 They are typically very efficient, and can save you a lot of time and effort when writing code
 Examples in string manipulation
 Left(
 Right(
 Mid(
 Instr(
 InstrRev(
 Ucase
 Replace
 Len(
 Mathematical Functions
 Sqr()
 Exp()
 Int()
 Rnd()
 Round()
 Sin()
 Cos()
 Tan()
 Date and time functions
 Date()
 Time()
 DateAdd()
 DateDiff()
 DatePart()
 FormatDateTime() etc.

NB : sometimes you are not asked to use these inbuilt functions but from the function you can
tell that use of inbuilt functions to validate the program is needed study the question carefully

Typical exam question


 Write a program that asks the user to enter a number and prints out the square of that number.
If the user enters a negative number, the program should print "Invalid number" and ask the
user to enter a new number.
Use Visual [Link] and the inbuilt [Link]() function.(10)

Solution
Dim n As Integer
Dim result As Integer
[Link]("Please enter a number: ")
n = [Link]()
If n < 0 Then
[Link]("Invalid number")
[Link]("Please enter a number greater than 0.")
Else
result = [Link](n, 2)
[Link](result)
End If
[Link]()

Recursion
 Is technique which a function calls itself repeatedly until a certain condition is met.
 It’s a way of breaking down a complex problem into a smaller , simpler problems.
 Example let’s say you want to write a function that prints the numbers from 1 to 1o.
 You could write a for loop to do this, or you could use recursion.
 To use recursion you would write a function that prints the first number and then calls itself
with the next number.
 This process would continue until it reached 10.
Typical exam question

Write a function that will calculate the factorial of a given number(10)

Solution
Imports [Link]
Module Module1
Function factorial(ByVal n As Integer)
If n = 0 Then
Return 1
Else
Return n * factorial(n - 1)
End If
End Function
Sub Main()
WriteLine("Input the number")
Dim n As Integer = ReadLine()
Dim result As Integer = factorial(n) 'calling the function and storing the value
into the result variable
WriteLine(result)
ReadKey()
End Sub
End Module

String Manipulation
 String manipulation is the process of changing or altering a string of text.
 This can involve adding, removing, or changing characters or substrings, or performing
other operations like reversing the order of characters or finding specific patterns.
 There are a variety of methods and techniques for string manipulation in Visual
[Link].
 Some common methods are Substring(), Replace(), Trim(), and Format().

Typical exam question


 Write a program that takes a sentence as input and replaces every instance of the letter
"e" with the letter "o". If a letter is not an "e", do not replace it.
 This question requires you to use the Substring() and IndexOf() methods, as well as a
few other techniques.(15)

Solution
Module Module1
Function ReplaceEWithO(sentence As String) As String
Dim newSentence As String = ""
Dim index As Integer = 0
Do While index < [Link]
Dim charIndex As Integer = [Link]("e", index)
If charIndex >= 0 Then
newSentence += [Link](index, charIndex - index)
newSentence += "o"
index = charIndex + 1
Else
newSentence += [Link](index)
Exit Do
End If
Loop

Return newSentence
End Function
Sub Main()
Dim sentence As String = "This is a sentence with the letter e in it."
Dim newSentence As String = ReplaceEWithO(sentence)

[Link](newSentence)
[Link]()
End Sub

End Module

Practice Questions

1. Write a program that takes a string as input and returns a new string with all the vowels
removed.
2. Write a program that takes a string as input and returns a new string with all the words
reversed.
3. Write a program that takes a string as input and returns a new string with all the
duplicate characters removed.
4. Write a program that takes a string as input and returns a new string with all the
characters sorted in alphabetical order.
5. Write a program that takes a string as input and returns a new string with all the words
capitalized.
6. Write a program that takes a sentence as input and checks if it is a palindrome (i.e., it reads the
same forwards and backwards).
7. Write a program that takes two sentences as input and checks if they are anagrams of each
other (i.e., they contain the same letters in different orders).
8. Write a program that takes a sentence as input and counts the number of occurrences of each
letter in the sentence.

For the solutions to question contact details below


Programming is a simple and pure form of programming.

-Chibi Tinodaishe M

Cell:0781081816

Email: tinodaishemchibi@[Link]

Isaiah 43 vs 2

THANK YOU
=====================================================

Common questions

Powered by AI

To check if a given sentence is a palindrome in Visual Basic.NET, use string manipulation methods to first clean the string by removing spaces and converting it to a uniform case. Then, reverse the string using the Substring() method, comparing it with the original string. For instance, "Function IsPalindrome(sentence As String): Clean = sentence.Replace(" ", "").ToLower(), Reverse = StrReverse(Clean), Return Clean = Reverse". This checks if the altered sentence reads the same backwards, indicating a palindrome .

Recursion in Visual Basic.NET involves a function calling itself to solve smaller instances of a problem, often used in mathematical computations like calculating factorials. For example, a factorial function can be defined recursively: "Function factorial(ByVal n As Integer): If n = 0, Return 1, Else, Return n * factorial(n - 1)" . The benefits of recursion include simpler code for problems that can naturally be divided into similar sub-problems and avoiding loops, but potential drawbacks include increased memory usage and risk of stack overflow if the recursion depth is too high .

ByVal and ByRef are two methods of passing parameters to functions in Visual Basic.NET. ByVal passes a copy of the argument to the function, meaning any changes to the parameter within the function do not affect the original variable. For example, in the function definition "Function sumfunction(ByVal num1 As Integer, ByVal num2 As Integer)", changes to num1 and num2 within the function do not alter their original values outside the function . ByRef, on the other hand, passes a reference to the original argument, so changes within the function affect the variable outside the function as well. In the definition "Function sumfunction(ByRef num1 As Integer, ByRef num2 As Integer)", modifications to num1 or num2 would reflect outside the function .

String manipulation methods in Visual Basic.NET, such as Substring(), Replace(), and IndexOf(), are preferable when working with standard string operations due to their optimized performance and reliability. These inbuilt methods are thoroughly tested and more efficient than custom algorithms for standard tasks like replacing characters, trimming strings, or finding substrings. Using these methods also enhances code readability and maintainability, as they leverage well-documented APIs over potentially error-prone custom solutions .

To remove duplicate characters from a string in Visual Basic.NET while maintaining the order of the first occurrence, initiate a new string to build the result. Traverse the input string, appending only characters that haven't been added yet, potentially using a HashSet to track seen characters. Example implementation: "Function RemoveDuplicates(input As String): Dim result As New StringBuilder(), seen As New HashSet(Of Char): For Each char In input: If Not seen.Contains(char) Then result.Append(char): seen.Add(char) End If Next: Return result.ToString()". This approach efficiently produces a string with duplicates removed .

Inbuilt functions in Visual Basic.NET are predefined functions provided by the language, allowing developers to perform common tasks efficiently without needing to write lengthy code. They are categorized based on the tasks they perform: string manipulation (e.g., Left(), Right(), Mid()), mathematical operations (e.g., Sqr(), Exp(), Int(), Rnd()), and date/time calculations (e.g., Date(), Time(), FormatDateTime()). These functions streamline development by handling repetitive tasks directly from code, saving time and effort .

To implement a function that counts occurrences of each letter in a sentence in Visual Basic.NET, initialize a Dictionary to track character frequencies. Iterate over the sentence, updating the dictionary with character counts using a loop. For example: "Function CountLetters(sentence As String): Dim charCount As New Dictionary(Of Char, Integer): For Each char In sentence: If charCount.ContainsKey(char) Then charCount(char) += 1 Else charCount(char) = 1 End If Next: Return charCount". This representation counts each letter's occurrences in the input .

To convert a loop-based algorithm to a recursive function in Visual Basic.NET, start by identifying the base case, such as the stopping condition. For printing numbers 1 to 10, the base case could be if the number exceeds 10. Next, rewrite the loop logic into a function that performs an action and calls itself with updated parameters. For example: "Function PrintNumbers(ByVal n As Integer): If n <= 10, Output n: PrintNumbers(n + 1)". This approach replaces iterative repetition with successive function calls that achieve the same progression through numbers .

User-defined functions offer several advantages in programming. They encapsulate common code, making it easier to reuse and maintain code efficiently. By organizing tasks into discrete modules, these functions streamline complex processes and improve code readability. In Visual Basic.NET, user-defined functions can be flexibly tailored to perform any task the programmer requires, thereby enhancing reusability and efficiency .

Built-in date and time functions in Visual Basic.NET, like Date(), Time(), and FormatDateTime(), offer significant benefits by providing an abstraction layer that simplifies complex date manipulations. They are optimized for performance and accuracy, reducing the likelihood of errors associated with manual calculations. However, limitations may include their fixed functionality, which may not cover specialized use cases or custom formats, necessitating a combination of inbuilt and custom logic in some cases .

You might also like