Click here to Skip to main content
15,886,199 members
Articles / Programming Languages / Visual Basic
Article

VB.NET Solution for working with random files : Create, List, Update, and Delete

Rate me:
Please Sign up or sign in to vote.
3.75/5 (21 votes)
13 Jan 20043 min read 248.6K   2.1K   30   13
How to prepare an application for working with random files using VB.NET

Introduction

In this article, I will try to explain how to prepare an application for working with random files using VB.NET. Before starting, I want say that this application is just a sample for working with random files. Only the usage of random files are concentrated on, not the functionality of the program. If this is clear, we can start ;)

Implementation

In the first step, we are creating a new project and placing a TabControl on to the form. Then, create four tabs on the TabControl (select TabPages property and create these tabs) by names, “Create”, “Input”, “Output”, and “Search” as shown in Figure 1. below.

Figure 1. TabControl on the form

In the second step, use TextBox, Label, Button, and ListBox components and form the tab pages as shown below.

Figure 2. Tab page “Create”

Figure 3. Tab page “Input”

Figure 4. Tab page “Output”

Figure 5. Tab page “Search”

Now, the form will look like the form in Figure 6. below. Note that the “Exit” button is placed on the form to just terminate the application.

Figure 6. Application form

In the third step, we are starting to write source code for our application. First of all, let’s define a global variable, record type and write a function to find the last record number of the random file.

VB
'Create a global variable. This variable will keep the 
'position of related record.
Dim Position As Integer

'Create a record type. The name of the record 
'type is given as "Person".
Structure Person
   Dim ID As Integer
   Dim Name As String
   Dim Surname As String
End Structure

'This is the function that we are using to find a last 
'record’s number in the random file.
Private Function FindLastRecordNo() As Integer
    Dim Temp As Person, FileNumber As Integer
    
    'Get the available file number.    
    FileNumber = FreeFile()
    
    'Open the file by using the FileOpen statement 
    'in a random mode with       
    'only read access. The name of the file 
    'will be same as the text in the  
    'TextBox1 (Textbox1 is on the "Create" tab page). 
    'Len(Temp) function is use 
    'to determine the size of record in bytes. 
    FileOpen(FileNumber, TextBox1.Text, OpenMode.Random,  _
      OpenAccess.Read, , Len(Temp))
    
    FindLastRecordNo = 1
    
    'EOF() function is using to detect the end of file.
    Do While Not EOF(FileNumber)
        'FileGet() function is using to get a record from random file.
        FileGet(FileNumber, Temp, )
        FindLastRecordNo = FindLastRecordNo + 1
    Loop

    'Close the file.
    FileClose(FileNumber)
End Function

Here are the event procedures and explanations of important statements. Note that “...” is used, instead of writing arguments, in each procedure title because of easy readability. This is only for Exit button to terminate the application.

VB
Private Sub Button1_Click(…) Handles Button1.Click
        End
End Sub
This event procedure is for Create button on the “Create” tab page.
VB
Private Sub Button2_Click(…) Handles Button2.Click
        Dim RecLength As Long, Employee As Person

        'Get the next available file number.
        FileNum = FreeFile()
        
        'Open the new random file with the FileOpen statement.
        FileOpen(FileNum, TextBox1.Text, _
          OpenMode.Random, , , Len(Employee))
        
  'Close the file.
  FileClose(FileNum)
End Sub
When the user clicks Insert button on the “Input” tab page, this procedure will run and save the new record at the end of the random file.
VB
Private Sub Button3_Click(…) Handles Button3.Click
        Dim Employee As Person, LastRecord As Integer
        
        'Find the last record number of random file. FindLastRecordNo() 
        'function, which is shown above, is called.
        LastRecord = FindLastRecordNo() 

        FileNum = FreeFile()
        FileOpen(FileNum, TextBox1.Text, OpenMode.Random, , , Len(Employee))
        Employee.ID = Val(TextBox2.Text)
        Employee.Name = TextBox3.Text
        Employee.Surname = TextBox4.Text

        'Put the Employee record into the random file as a last record.
        FilePut(FileNum, Employee, LastRecord)

        FileClose(FileNum)
End Sub
Read all records in the random file and put these records into the Listbox one by one. This is the procedure for Read button on the “Output” tab page.
VB
Private Sub Button4_Click(…) Handles Button4.Click
  Dim Employee As Person, Count As Integer, Temp As String
  FileNum = FreeFile()
  FileOpen(FileNum, TextBox1.Text, OpenMode.Random, , , Len(Employee))
  Count = 1
  ListBox1.Items.Clear()
  Do While Not EOF(FileNum)
      'Read the record on the position Count.
      FileGet(FileNum, Employee, Count)

      'str() function is used to convert integer to string.
      Temp = Str(Employee.ID) + "  " + Employee.Name + _
        "  " + Employee.Surname
      
      'Add the string into Listbox.
      ListBox1.Items.Add(Temp)
      Count = Count + 1
  Loop
  FileClose(FileNum)
End Sub
This is the Find button on the “Search” tab page. It is searching all records in the random file until it finds Employee ID in the record is equal to the ID in the TextBox5 (Textbox5 is assigned to Employee Id on the “Search” tab page.)
VB
Private Sub Button6_Click(…) Handles Button6.Click
        Dim Employee As Person
        FileNum = FreeFile()
        FileOpen(FileNum, TextBox1.Text, _
          OpenMode.Random, , , Len(Employee))
        Do While Not EOF(FileNum)
            FileGet(FileNum, Employee, )
            If Employee.ID = Val(TextBox5.Text) Then
                'Keep the current position of record 
                'in "Position" variable to 
                'use in further use such as update or delete operations.
                Position = Loc(FileNum) 
    
                'Change enable status for some Textboxes.
                TextBox5.Enabled = False
                TextBox6.Enabled = True
                TextBox7.Enabled = True
                Button5.Enabled = True
                Button6.Enabled = False
                Button7.Enabled = True
            
               'Show the Employee name and surname in the related Textboxes.
                TextBox6.Text = Employee.Name
                TextBox7.Text = Employee.Surname
                Exit Do
            End If
        Loop
        FileClose(FileNum)
End Sub
This procedure is for Update button (“Search” tab page) and is to update the record. We know the position of found record from Find procedure and we will use this position to overwrite the information of Employee on this record.
VB
Private Sub Button5_Click(…) Handles Button5.Click
        Dim Employee As Person
        FileNum = FreeFile()
        FileOpen(FileNum, TextBox1.Text, _
          OpenMode.Random, , , Len(Employee))
      
        'Seek() function is used to move the pointer 
        'to any position of random file.
        Seek(FileNum, Position)

        'Update the information of an Employee.
        Employee.ID = Val(TextBox5.Text)
        Employee.Name = TextBox6.Text
        Employee.Surname = TextBox7.Text
        FilePut(FileNum, Employee, )
        FileClose(FileNum)

        'Change the enable status of some Textboxes and 
        'clear the texts in these Textboxes.
        TextBox5.Enabled = True
        TextBox6.Enabled = False
        TextBox7.Enabled = False
        Button5.Enabled = False
        Button6.Enabled = True
        Button7.Enabled = False
        TextBox5.Text = ""
        TextBox6.Text = ""
        TextBox7.Text = ""
End Sub
This procedure is for Delete button (“Search” tab page) and is to delete the record. In this procedure, we are opening our random file and one temporary file. Then copying all records except the record, which its position number kept by Position variable, into the temporary file. After that, we delete our random file and rename the temporary file by giving the same name as deleted random file. This name is found in the Textbox1 (“Create” tab page.)
VB
Private Sub Button7_Click(…) Handles Button7.Click
  Dim Employee As Person, FileNum1, FileNum2 As Integer
  FileNum1 = FreeFile()
  FileOpen(FileNum1, TextBox1.Text, OpenMode.Random, _
     OpenAccess.Read, , Len(Employee))
  FileNum2 = FreeFile()
  
  'This is for temporary random file.
  FileOpen(FileNum2, "abcdefg.tnt", OpenMode.Random, _
     OpenAccess.Write, , Len(Employee))

  Do While Not EOF(FileNum1)
      'We used "Position-1" because we do not want to 
      'copy the record, which its 
      'record position is equal to Position variable, 
      'to the temporary file. 
      'When the pointer comes to the previous record, 
      'we want it to read the 
      'record which its position is equal to Position 
      'variable and do not write 
      'this into temporary file (Else statement). 
      'For example, if we want to 
      'delete third record (Position=3), when the
      'pointer comes to the record 2 
      '(loc(FileNum1)=Position-1 condition is valid), 
      'it will make only 
      'FileGet(). This means that it will not 
      'write the record 3 to temporary 
      'file. Note that; FileGet() function reads 
      'record 3 when pointer is on record 2. 
      If (Loc(FileNum1) <> Position - 1) Then
         FileGet(FileNum1, Employee, )
         FilePut(FileNum2, Employee, )
      Else
         FileGet(FileNum1, Employee, )
      End If
  Loop

  FileClose(FileNum1)
  FileClose(FileNum2)

  'Delete the random file.
  Kill(TextBox1.Text)

  'Rename the temporary file by giving the same 
  'name as deleted random file.
  Rename("abcdefg.tnt", TextBox1.Text)

  'Change the enable status of some Textboxes 
  'and clear the texts in these 
  'Textboxes.
  TextBox5.Enabled = True
  TextBox6.Enabled = False
  TextBox7.Enabled = False
  Button5.Enabled = False
  Button6.Enabled = True
  Button7.Enabled = False
  TextBox5.Text = ""
  TextBox6.Text = ""
  TextBox7.Text = ""
End Sub

Have a nice day!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Instructor / Trainer
Turkey Turkey
Asst. Prof. in Eastern Mediterranean University.

Comments and Discussions

 
Questioni m new in this fild so i need help :( plz help me , plz plz :'( Pin
jacksudhir24-Aug-12 7:39
jacksudhir24-Aug-12 7:39 
2.1 Write a program which reads date of birth and finds age and zodiac sun sign.

Module Module1
Sub Main()
Dim s As Date
Dim d, m, y, y0 As Double
System.Console.WriteLine("Enter your date of birth in MM/DD/YYYY format")
s = System.Console.ReadLine()
y = datepart("YYYY", s)
y0 = datepart("YYYY", today)
System.Console.Write("Your age is ")
System.Console.WriteLine(y0 - y)
m = datepart("M", s)
d = datepart("D", s)
System.Console.Write("Zodiac: ")
Select Case m
Case 1
If d <= 20 Then
System.Console.WriteLine("Capricorn")
Else
System.Console.WriteLine("Aquarius")
End If
Case 2
If d <= 19 Then
System.Console.WriteLine("Aquarius")
Else
System.Console.WriteLine("Pisces")
End If
Case 3
If d <= 20 Then
System.Console.WriteLine("Pisces")
Else
System.Console.WriteLine("Aries")
End If
Case 4
If d <= 20 Then
System.Console.WriteLine("Aries")
Else
System.Console.WriteLine("Taurus")
End If
Case 5
If d <= 21 Then
System.Console.WriteLine("Taurus")
Else
System.Console.WriteLine("Gemini")
End If
Case 6
If d <= 21 Then
System.Console.WriteLine("Gemini")
Else
System.Console.WriteLine("Cancer")
End If
Case 7
If d <= 22 Then
System.Console.WriteLine("Cancer")
Else
System.Console.WriteLine("Leo")
End If
Case 8
If d <= 21 Then
System.Console.WriteLine("Leo")
Else
System.Console.WriteLine("Virgo")
End If
Case 9
If d <= 23 Then
System.Console.WriteLine("Virgo")
Else
System.Console.WriteLine("Libra")
End If
Case 10
If d <= 23 Then
System.Console.WriteLine("Libra")
Else
System.Console.WriteLine("Scorpio")
End If
Case 11
If d <= 22 Then
System.Console.WriteLine("Scorpio")
Else
System.Console.WriteLine("Sagittarius")
End If
Case 12
If d <= 22 Then
System.Console.WriteLine("Sagittarius")
Else
System.Console.WriteLine("Capricorn")
End If
Case Else
System.Console.WriteLine("Invalid")
End Select
End Sub
End Module



2.2 Write a program which converts a string into upper case, lower case and title case without using string manipulation functions.

Imports System

Module Demo2
Public str1 As String

Sub Main()
Console.WriteLine("Entre any String")
str1 = Console.ReadLine()
Console.WriteLine("Select any one opration")
Console.WriteLine("1. To Upper case")
Console.WriteLine("2. To Lower case")
Console.WriteLine("3. To Title case")
Dim o As Integer
o = Integer.parse(Console.readLine())
Select Case o
Case 1
strUp(str1)
Case 2
strLow(str1)
Case 3
strTitle(str1)
Case Else
Console.WriteLine("Invalid Choise/n")
End Select
End Sub
Public Sub strUp(ByVal s As String)
Dim s1, s2 As String
Dim i, j As Integer
Dim a As Char
s1 = s
s2 = ""
Try
For i = 0 To s1.length
If asc(s1(i)) >= 97 And asc(s1(i)) <= 122 Then
a = s(i)
j = asc(a) - 32
a = Convert.ToChar(j)
s2 += a
Else
s2 = s2 + s(i)
End If
Next
Catch ex As Exception
Console.WriteLine("")
Console.WriteLine("Uppercase of " & s1 & " is " & s2)
End Try
End Sub
Public Sub strLow(ByVal s As String)
Dim s1, s2 As String
Dim i, j As Integer
Dim a As Char
s1 = s
s2 = ""
Try
For i = 0 To s1.length
If asc(s1(i)) < 91 And asc(s1(i)) >= 65 Then
a = s(i)
j = asc(a) + 32
a = Convert.ToChar(j)
s2 += a
Else
s2 = s2 + s(i)
End If
Next
Catch ex As Exception
Console.WriteLine("")
Console.WriteLine("Lowercase of " & s1 & " is " & s2)
End Try
End Sub
Public Sub strTitle(ByVal s As String)
Dim s1, s2 As String
Dim i, j As Integer
Dim a As Char
Dim f As Integer
s1 = s
f = 0
s2 = ""
Try

If Asc(s1(0)) <> 32 And asc(s1(0)) >= 97 And asc(s1(0)) <= 122 Then
j = asc(s(0)) - 32
a = Convert.ToChar(j)
s2 += a
Else
s2 += s(0)
End If
For i = 1 To s1.length
If Asc(s1(i)) = 32 Then
s2 += " "
Do
If asc(s(i + 1)) = 32 Then
s2 += " "
i += 1
f = 1
Else
f = 0
Exit Do
End If
Loop While (f = 1)
If (asc(s1(i + 1)) >= 97 And asc(s1(i + 1)) <= 122) And f = 0 Then
a = s(i + 1)
j = asc(a) - 32
a = Convert.ToChar(j)
s2 += a
i += 1
Else
s2 += s(i + 1)
i += 1
End If
ElseIf (asc(s1(i)) < 91 And asc(s1(i)) >= 65) And f = 0 Then
a = s(i)
j = asc(a) + 32
a = Convert.ToChar(j)
s2 += a
Else
s2 += s(i)
End If
Next
Catch ex As Exception
Console.WriteLine("")
Console.WriteLine("Title case of is: " & s2)
End Try
End Sub
End Module




2.3 Write a program to sort a dynamic array of strings. Accept the strings until user enters “End”.

Imports Microsoft.VisualBasic
Imports System
Module m
Sub main()
Dim i, j As Integer
Dim s(1), str, st As String
i = 0
Do
Console.writeline("Enter string")
str = console.readline()
If strcomp(str, "end") = 0 Then
Exit Do
Else
ReDim Preserve s(i + 1)
s(i) = str
End If
i = i + 1
Loop
For i=0 to ubound(s)
For j=0 to ubound(s)
If strcomp(s(i), s(j)) < 0 Then
st = s(i)
s(i) = s(j)
s(j) = st
End If
next
next
i = 1
Console.writeline("Sorted String")
Do
Console.writeline(s(i))
i = i + 1
Loop While (i <= ubound(s))
End Sub
End Module



2.4 Write a program to implement a menu driven calc. Handle the exceptions using unstructured error handling.

Module Module1
Sub Main()
Console.WriteLine("Select your choice..")
Console.WriteLine("1.Addition")
Console.WriteLine("2.substraction")
Console.WriteLine("3.multiplication")
Console.WriteLine("4.division")
Console.WriteLine("5.Power")
Console.WriteLine()
Dim s As String = Console.ReadLine()
Console.WriteLine()
Console.Write("Enter the first digit: ")
Dim a As Double = CDbl(Console.ReadLine())
Console.WriteLine()
Console.Write("Enter the second digit:")
Dim b As Double = CDbl(Console.ReadLine())
Dim d As Double
Console.WriteLine()
On Error GoTo handler
If s = 1 Then
Console.WriteLine("The addition is: " & (a + b))
ElseIf s = 2 Then
Console.WriteLine("The substraction is: " & (a - b))
ElseIf s = 3 Then
Console.WriteLine("The multiplication is: " & (a * b))
ElseIf s = 4 Then
Console.WriteLine("The division is: " & (a \ b))
Exit Sub
handler:
Console.WriteLine("for the division operation the second digit must not be ZERO.....")
ElseIf s = 5 Then
Console.WriteLine("The power of " & a & " ^ " & b & " is : " & (a ^ b))
Else
Console.WriteLine("invalid choice...")
End If
End Sub
End Module



2.5 Write a program which reads an expression in postfix. Evaluate the
expression using stack collection.

Imports Microsoft.VisualBasic
Imports System
Imports System.Collections
Module m
Sub main()
Dim s As String
console.writeline("enter a postfix expression")
s = console.readline()
s=s+"$"
console.write("Result is : ")
console.writeline(post(s))
End Sub
Function post(ByVal ex As String) As Double
Dim i As Integer
Dim op1, op2, r As double
Dim st As New stack
i = 0
Do
If ex(i) >= "0" And ex(i) <= "9" Then
st.push(asc(ex(i))-48)
ElseIf ex(i) = "+" Or ex(i) = "-" Or ex(i) = "*" Or ex(i) = "/" Or ex(i) = "^" Then
op2 = st.pop()
op1 = st.pop()
Select Case ex(i)
Case "+"
r = op1 + op2
Case "-"
r = op1 - op2
Case "*"
r = op1 * op2
Case "/"
r = op1 / op2
Case "^"
r = op1 ^ op2
End Select
st.push(r)
End If
i = i + 1
Loop Until (ex(i) = "$")
r = st.pop()
Return r
End Function
End Module








2.6 Write a program which encrypts a given file using ceaser cipher method.

Imports system
Imports system.io
Module m
Sub main()
Dim p, c As String
Dim key As Integer
Dim fs As New FileStream("d:\c.txt", FileMode.open, FileAccess.Readwrite)
Dim r As New StreamReader(fs)
Dim w As New StreamWriter(fs)
console.writeline("enter key")
key = int(console.readline())
p = ""
While (r.peek() >= 0)
p = r.readline()
End While
c = ceaser(p, key)
w.write("ceaser ciphertext: ")
w.writeline(c)
w.flush()
w.close()
console.writeLine("ceaser cipher is done in given file")
End Sub
Function ceaser(ByVal s As String, ByVal k As Integer) As String
Dim i, t As Integer
Dim c As String
c = ""
For i = 0 To len(s) - 1
t = (k Mod 26) + asc(s(i))
If (t > 90 And t <= 97) Or (t > 122) Then
t = t - 26
c = c + chr(t)
Else
c = c + chr(t)
End If
Next
Return c
End Function
End Module



2.7 Write a program to demonstrate the use of mybase and myclass.

Imports System
Module m
Public Class base
Dim a As Single
Public Sub New(ByVal aa As Single)
a = aa
End Sub
Public Sub dis()
MyClass.printdata()
End Sub
Public Overridable Sub printdata()
console.writeline("Base Class")
End Sub
End Class
Public Class derive
Inherits base
Sub New(ByVal b As Single)
MyBase.new(b)
End Sub
Public Overrides Sub printdata()
console.writeline("Derive Class")
End Sub
End Class
Sub main()
Dim d As New derive(10)
d.printdata()
d.dis()
End Sub
End Module




2.8 Write a program to demonstrate delegates with VB .Net

Imports System
Module m
Delegate Sub delmy(ByVal s As String)
Sub main()
Dim del As delmy
del = AddressOf dis
del.invoke("This is by Delegates")
End Sub
Sub dis(ByVal str As String)
console.writeline(str)
End Sub
End Module





2.9 Write a program to demonstrate inheritance and interfaces in VB .Net

Imports System
Module m
Public Interface i
Sub print()
End Interface
Public Class base
Public Sub New()
console.writeline("Base Class")
End Sub
End Class
Class derive
Inherits base
Implements i
Sub New()
console.writeline("Derive Class")
End Sub
Sub print() Implements i.print
console.writeline("From Interface")
End Sub
End Class
Sub main()
Dim d As New derive
d.print()
End Sub
End Module




2.10 Write a program to demonstrate method overloading and method overriding in VB .Net

Imports System
Module m
Public Class base
Dim a As Integer
Public Sub dis()
MyClass.printdata()
End Sub
Public Overridable Sub printdata()
console.writeline("Base Class")
End Sub
End Class
Public Class derive
Inherits base
Public Overloads Sub dis(ByVal s As String)
MyBase.dis()
console.writeline(s)
End Sub
Public Overrides Sub printdata()
console.writeline("Derive Class")
End Sub
End Class
Sub main()
Dim d As New derive
d.printdata()
d.dis("By Derive Class method")
End Sub
End Module




//some more programs about 10 more //





2.1 Write a program to give example of implicit and explicit type conversions.

 The implicit program are shown as:

Imports System
Module m
Sub main()
Dim a, b As Integer
Dim c As Double
Console.writeline("Enter 2 integers")
a = CInt(Console.readline())
b = CInt(console.readline())
c = a * b
Console.Writeline("Multiple : {0}", c)
End Sub
End Module


 The explicit conversion program is shown as:

Imports System
Module m
Sub main()
Dim a, b As Double
Dim c As integer
Console.writeline ("Enter 2 integers")
a = CDbl (Console.readline())
b = CDbl (console.readline())
c = Cint (a / b)
Console.Writeline ("Divide: {0}", c)
End Sub
End Module







2.2 Write a program which multiplies two numbers if they are integers otherwise prints their data types.


Imports System
Module m
Sub main()
Dim a, b, c as integer
Console.writeline ("Enter 2 numbers")
a= console.readline()
b= console.readline()
c= a * b
If c.typeof() is integer then
Console.writeline (c)
Else
Console.writeline (get type () )
End if






2.3 Write a program which counts Interest = Pnr/100 and show in ##.00 format and also count Total Amount by P + (Pnr/100), show in ##, ###.00 format.


Imports System
Module m
Sub main()
dim P, N, R, Int, T as double

Console.Writeline ("Enter the Principle")
P = console.readline()
Console.Writeline ("Enter the Rate of interest")
R = console.readline()
Console.Writeline ("Enter the Number of years")
N = console.readline()

Int= P * N * R / 100
Console.Writeline ("Interest: {0}", Int)

T = P+ (1P*N*R/100)
Console.Writeline("Total Amount: {0}", T)

End sub
End module








2.4 Write a program which accepts number from user and calculate factorial value by user defined function.


Imports System
Module m
Sub main()
Dim n, i as integer
Dim fact as integer = 1
Console.Writeline ("enter the number")
n= console.readline()
For i=1 to n step 1
Fact = fact * i
Next
Console.Writeline ("factorial: {0}", fact)
End sub
End module



2.5 Write a program to give example of pass by value and pass by reference.

Imports System
Module m
Dim j As Integer = 10
Sub incr (ByVal c As Integer)
c = c + 1
Console.Writeline(c)
End Sub
Sub decr (ByRef c As Integer)
c = c - 1
End Sub
Sub main()
incr(j)
Console.Writeline (j)
Decr (j)
Console.Writeline (j)
End Sub
End Module

2.6 Write a program which checks the number is prime or not.

Imports System
Module m
Sub main()
Dim I, N as Integer
Console.Writeline ("enter the number")
n= console.readline()
For I = 2 to N - 1
If N Mod I = 0 Then
Console.Writeline ("THE NUMBER IS NOT A PRIME NUMBER")
End If
Next I
Console.Writeline ("THE NUMBER IS A PRIME NUMBER")
End Sub
End Module




2.7 Write a program to give example of method overloading.
 Imports System
Module m
Sub main()
Dim r, p as integer
Dim d, b, p1 as double
Console.Writeline ("enter the radius of circle")
r= console.readline()
console.writeline("enter the depth of square")
d= console.readline()
console.writeline("enter the breadth of square")
b= console.readline()
p= area(r)
p1= area(d,b)
console.writeline("area of circle: {0}", p)
console.writeline("area of square: {0}", p1)
end sub
function area(byval r as integer) as integer
return r*r
end function
function area(byval d as double, byval b as double) as double
return d*b
end function
end module




2.8 Write a program to implement arithmetic calculator using console which handles Divide by Zero Exception and Arithmetic Exception.
 Module Module1
Sub Main()
Console.Writeline ("Select your choice...”)
Console.Writeline ("1.Addition")
Console.Writeline ("2.substraction")
Console.Writeline ("3.multiplication")
Console.Writeline ("4.division")
Console.Writeline ("5.Power")
Console.Writeline ()
Dim s as String = Console.Readline()
Console.Writeline ()
Console.Writeline ("Enter the first digit: ")
Dim a As Double = CDbl (Console.Readline())
Console.Writeline()
Console.Write ("Enter the second digit :")
Dim b as Double = CDbl (Console.Readline())
Dim d as Double
Console.Writeline()
On Error GoTo handler
If s = 1 Then
Console.Writeline ("The addition is: " & (a + b))
ElseIf s = 2 Then
Console.Writeline ("The subtraction is: " & (a - b))
ElseIf s = 3 Then
Console.Writeline ("The multiplication is: " & (a * b))
ElseIf s = 4 Then
Console.Writeline ("The division is: " & (a \ b))
Exit Sub
Handler:
Console.Writeline ("for the division operation the second digit must not be ZERO.....")
ElseIf s = 5 Then
Console.Writeline ("The power of” & a & " ^ " & b & " is: " & (a ^ b))
Else
Console.Writeline ("invalid choice...")
End If
End Sub
End Module






2.9 Write a program to sort an array which accepts number from user and store it into dynamic array.
 Module Module1
Sub Main()

Dim array As Integer()= new integer() {34,23,56,22,55,45}

System.Array.Sort(Of Integer)(array)

Dim value As Integer
For Each value In array
Console.WriteLine(value)
Next
End Sub
End Module




2.10 Write a program which reads expression in postfix and evaluate the expression using stack collection.
 Imports Microsoft.VisualBasic
Imports System
Imports System.Collections
Module m
Sub main()
Dim s As String
console.writeline("enter a postfix expression")
s = console.readline()
s=s+"$"
console.write("Result is : ")
console.writeline(post(s))
End Sub
Function post(ByVal ex As String) As Double
Dim i As Integer
Dim op1, op2, r As double
Dim st As New stack
i = 0
Do
If ex(i) >= "0" And ex(i) <= "9" Then
st.push (asc(ex(i))-48)
ElseIf ex(i) = "+" Or ex(i) = "-" Or ex(i) = "*" Or ex(i) = "/" Or ex(i) = "^" Then
op2 = st.pop ()
op1 = st.pop ()
Select Case ex(i)
Case "+"
r = op1 + op2
Case "-"
r = op1 - op2
Case "*"
r = op1 * op2
Case "/"
r = op1 / op2
Case "^"
r = op1 ^ op2
End Select
st.push(r)
End If
i = i + 1
Loop Until (ex(i) = "$")
r = st.pop()
Return r
End Function
End Module
AnswerRe: i m new in this fild so i need help :( plz help me , plz plz :'( Pin
jacksudhir24-Aug-12 7:40
jacksudhir24-Aug-12 7:40 
GeneralThe code in the article should be updated... Pin
Ray Cassick17-May-08 6:34
Ray Cassick17-May-08 6:34 
GeneralRe: The code in the article should be updated... Pin
Blue stone20-Oct-08 0:15
Blue stone20-Oct-08 0:15 
GeneralRe: The code in the article should be updated... Pin
Ray Cassick20-Oct-08 2:01
Ray Cassick20-Oct-08 2:01 
GeneralRandom File Access Wraper Pin
Polymorpher10-May-08 8:52
Polymorpher10-May-08 8:52 
Generalabout globle variable Pin
bapu28898-Apr-07 3:07
bapu28898-Apr-07 3:07 
QuestionCan not use array in structure? Pin
Anonymous19-Sep-05 21:13
Anonymous19-Sep-05 21:13 
Generalinclude array in structure Pin
Anonymous19-Sep-05 21:11
Anonymous19-Sep-05 21:11 
Question&quot;Random&quot; files? Pin
dog_spawn14-Jan-04 5:32
dog_spawn14-Jan-04 5:32 
AnswerRe: &quot;Random&quot; files? Pin
Michael Russell14-Jan-04 9:46
Michael Russell14-Jan-04 9:46 
GeneralRe: &quot;Random&quot; files? Pin
dog_spawn14-Jan-04 14:10
dog_spawn14-Jan-04 14:10 
GeneralRe: &quot;Random&quot; files? Pin
Fluid Dynamics Software18-Oct-07 13:14
Fluid Dynamics Software18-Oct-07 13:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.