Professional Documents
Culture Documents
علوم الحاسبات (برمجة) (محاضرة 1-5)
علوم الحاسبات (برمجة) (محاضرة 1-5)
Collage of Engineering
Department of Petroleum
Computer Programming
First Year
By
Visual Basic 2010 is the latest version of Visual Basic launched by Microsoft in 2010. Which evolved
from the earlier DOS version called BASIC. A graphical-based language allows the user to work
directly with graphics. Visual Basic is derived from the “visual” term refers to the method used to
create the graphical user interface (GUI). The “Basic” term refers to the BASIC (Beginners All-
Purpose Symbolic Instruction Code) language, a language used by more programmers.
1. Start menu >> Programs >> Microsoft Visual Studio 2010 Express >> Microsoft Visual Basic 2010
Express
2. New Project
3. Windows Forms Application
4. The main window of the program
1
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Menu Bar
Tool Bar
Solution Explorer
Form Window
Toolbox
Menu Bar: Contains a standard command and specific command like (File, Edit, View, Project,
Format, Debug, Run, etc.).
Tool Bar: Contains several icons that provide quick access to commonly used features.
Error List windows: display the errors that could be occurred in the program
Solution Explorer: The Solution Explorer contains a list of files and forms in your project. If
the Solution Explorer isn’t visible, go the View menu and select Solution Explorer to display it.
Form1 (Form) window: contains a form named Form1, which is where the program’s Graphical
User Interface (GUI) will be displayed. A GUI is the visual portion of the program, this is where
the user enters data (called inputs) to the program and where the program displays its results
(called outputs). We refer to the Form1 window simply as “the form”. Forms are the foundation
for creating the interface of an application. You can use the forms to add windows and dialog
boxes to your application. You can also use them as containers for items that are not a visible part
of the application’s interface. For example, you might have a form in your application that serves
as a container for graphics that you plan to display in other forms.
2
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Toolbox controls
The Toolbox contains the controls you need to design a form. You can click on a control in the
Toolbox and drag it to the form to make it a part of the user interface. Each control in the Toolbox
has a special use, just like the tools in real toolbox. You’ll soon learn how to use some of the basic
tools in the Toolbox.
Properties Window
The Properties window contains a list of properties for each control. When you select the form or any
control on a form, the Properties window displays the properties for that control. The column on the
left contains the names of the properties for that control. The column on the right contains the settings
for the properties. You can change these settings, and thus change your program, by clicking on the
name of the property and changing its setting on the right. Each control has its own unique set of
properties. Most controls have similar properties so be careful to select the correct control on the form
before you make changes to any properties. Table (2) explain objective of the properties window.
3
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Use the Debug menu, Start Debugging option, or Press the F5 function key to run the project, or
Click the shortcut green arrow on the shortcut toolbar.
Example 1: Design a form with one text box and two Commands button. Write a code so when run
project and click on Button1 (O.k.) display the word (Welcome) in text box, and when click on
Button2 (Close) terminate the program and return back to the form interface.
4
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Solution:
Creating the Interface: The first step in building a Visual Basic application is to create the forms
that will be the basis for your application’s interface. Then you draw the objects that make up the
interface on the forms you create.
1. Adding a text box to the form. Double-click the toolbox’s textbox to create
a text box with sizing handles in the center of the form.
2. Adding a Button1 to the form. Click on button and draw button1 to form then the button appears
on form.
3. Repeat step 2 to add a Button2 to the form.
Setting Properties
The next step is to set properties for the objects. The properties window provides an easy way to set
properties for all objects on a form. For Example1, you’ll need to change three property settings. Use
the default setting for all other properties.
Object Property Setting
Name Form1
Form1 Text Example1
Font Bold and size 12
Name Button1
Button1 Text O.k
Font Bold and size 12
Name Button 2
Button2
Text Close
Font Bold and size 12
Name Textbox1
TextBox
Text Empty
5
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Writing Code:
The code editor window is where you write Visual Basic code for your application. Code consists of
language statements, constants, and declarations. To open the code window, double-click the form or
control for which you choose to write code, or from the Project Explorer window, select the name of
a form and choose the View code button.
In the Object list box, select the name of an object in the active form. Or double click of an
object.
In the procedure list box, select the name of an event for the selected object. The Click
procedure is the default procedure for a command button and the Load is default procedure
for a form.
An event procedure for a control combines the control’s actual name (specified in the name
property), an underscore ( _ ), and the event name. For example, (Button1_click).
Type the code between the Private Sub and the End Sub statements.
Example 2: Design a form shown in figure below, with three Text boxes and Button. Write code in
the Button1 (Execute). So when run project enter the Student Name in TextBox (TextBox1) and the
Father Name in TextBox (TextBox2). When click on Button1 (Execute) display the Full Name in the
TextBox (TextBox3).
6
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Solution:
Creating the Interface.:
1. Adding a Label to the form1. Double-click the Label’s Label to create a Label with sizing
handles in the center of the form1.
2. Repeat step 1 to add Label2 and Label3.
3. Adding a Textbox to the form1. Double-click the toolbox’s textbox to create a text box with
sizing handles in the center of the form1.
4. Repeat step 3 to add TextBox2 and Textbox3.
5. Adding a Button1 to the form. Click on button and draw Button to form then the Button1 appears
on form1.
7
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Setting Properties
Object Property Setting
Name Form1
Form1 Text Example2
Font Bold and size 12
Name Button1
Button1 Text Execute
Font Bold and size 12
Name Textbox1
TextBox1
Text Empty
Name Textbox2
TextBox2
Text Empty
Name Textbox3
TextBox3
Text Empty
Name Label1
Label1 Text Student name
Font Bold and size 12
Name Label1
Label2 Text Student name
Font Bold and size 12
Name Label1
Label3 Text Father name
Font Bold and size 12
Writing Code:
Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
TextBox3.Text = TextBox1.Text + " " + TextBox2.Text
End Sub
8
University of Basrah
Collage of Engineering
Department of Petroleum
Computer Programming
Fundamentals of programming in
Visual Basic
First Year
By
1. Integer: A variable of type integer requires 2 bytes of memory and can hold the
whole numbers from -32768 to 32767.
2. Long: A variable of type Long requires 4 bytes of memory and can hold the whole
numbers from -2147483648 to 2147483647.
3. Single: A variable of type Single requires 4 bytes of memory and can hold 0, the
numbers from 1.4012923x10-45 to 3.40283x1038 with the most seven significant
digits, and the negatives of these numbers.
1
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
4. Double: A variable of type Double requires 8 bytes of memory and can hold 0, the
numbers from 4.94065x10-324 to 1.7976x10308 with at most 14 significant digits and
the negatives of these numbers.
5. Currency: The currency data type is particularly useful for calculations involving
money. A variable of type Currency requires 8 bytes of memory and can hold any
number from -9x1014 to 9x1014.
1. Boolean: A variable of type Boolean requires 2 bits of memory and holds either the
value True or False. If boolVar is a Boolean variable, then the statement Print
boolVar displays (1) when the value is True and displays (0) when the value is False.
2. Date: A variable of type Date requires 8 bytes of memory and holds numbers
representing dates from January 1St 100 To December 31St 9999. Values of dateVar
are displayed in the form month/day/year (for example, 5/12/1996).
3. String: A variable of type string requires 1 byte of memory per character and can
hold a string of up to 32,767 characters, string values are enclosed in quotes.
4. Variant: A variable of type variant can be assigned numbers, Strings and several
other types of data. A variable of type variant requires 16 bytes of memory and can
hold any type of data. When values are assigned to a variant variable, Visual Basic
keeps track of the "type" of data that has been sorted. By default, Visual Basic uses
the variant data type.
2
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
2.2 Variables
Variables are like mail boxes in the post office. The contents of the variables changes
every now and then, just like the mail boxes. In term of VB2010, variables are areas
allocated by the computer memory to hold data. Like the mail boxes, each variable
must be given a name. To name a variable in Visual Basic 2010, you have to follow a
set of rules.
Variable Names
The following are the rules when naming the variables in Visual Basic 2010
In Visual Basic 2010, one needs to declare the variables before using them by assigning
names and data types. If you fail to do so, the program will show an error. They are
normally declared in the general section of the codes' windows using the Dim statement.
3
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Example 2.1
End Sub
You may also combine them in one line, separating each variable with a comma, as
follows:
2.3 Constants
Constants are different from variables in the sense that their values do not change
during the running of the program.
4
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Example 2.3
Const Pi As Single=3.142
End Sub
1. The simplest operators carry out arithmetic operations. These operations in their
order of precedence are:
7
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Examples:
Label2.Text = 3 \ 2
Label3.Text = 3 Mod 2
Label4.Text = 3 * 2
Label5.Text = 3 + 2
Label6.Text = 3 - 2
Label7.Text = 3 \ 2 * 4
Label8.Text = 3 * 2 \ 4
Label9.Text = (3 / 2) * 2
Label10.Text = 3 * 2 ^ 2
End Sub
End Class
8
University of Basrah
Collage of Engineering
Department of Petroleum
Computer Programming
Lecture Four
Control Structures
First Year
By
4. Control Structures
In this chapter, you will learn how to write Visual Basic code that can make
decision when it process input from the users, and control the program flow in
the process. Decision making process is an important part of programming
because it will help solve practical problems intelligently so that it can provide
useful output or feedback to the user. For example, we can write a Visual Basic
program that can ask the computer to perform certain task until a certain condition
is met, or a program that will reject non-numeric data. In order to control the
program flow and to make decisions, we need to use the conditional operators
and the logical operators together with the If control structure. To effectively
control the Visual Basic program flow, we shall use the If control structure
together with the conditional operators and logical operators. There are basically
three types of If control structures, namely:
• If ...Then
• If – Then –Else
• Select Case
1
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Example 4-1: Write a program to enter the value of two variables (X and Y).
Find and print the maximum value for two variables. Design form window and
select all the control objects are used.
Solution
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim x, y, max As Integer
x = Val(TextBox1.Text)
y = Val(TextBox2.Text)
max = x
If y > x Then max = y
TextBox3.Text = CStr(max)
End Sub
End Class
2
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Example 4.2: Used (If-Then Goto) condition to write a program for the
previous Example 4.1
Solution:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim x, y, max As Integer
x = Val(TextBox1.Text)
y = Val(TextBox2.Text)
If y > x Then max = y : GoTo 10
max = x
10: TextBox3.Text = CStr(max)
End Sub
End Class
Note: The statement Exit Sub used to stop the program without return to the
project window.
3
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
4
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
4.2.2 (If – Then – Else) statement: The If – Then - Else statement allows the
programmer to specify that a different action is to be performed when a certain
action specified by the VB expression if the condition is True than when the
condition is false, an alternative action will be executed. The general format for
the If - Then - Else statement is
If condition Then
VB expression
Else
VB expression
End If
Example 4.4: Used (If – Then – Else) condition to write a program for the
previous Example 4.1
Solution
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim x, y, max As Integer
x = Val(TextBox1.Text)
y = Val(TextBox2.Text)
If y > x Then
max = y
Else
max = x
End If
TextBox3.Text = CStr(max)
End Sub
End Class
5
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
4.2.3 Nested (If – Then – Else) statement: If there are more than two alternative
choices, using just If – Then - Else statement will not be enough. In order to
provide more choices, we can use If...Then... Else statement inside If...Then...Else
structures. The general format for the Nested If...Then…Else statement is
Example 4.5: Write a program to enter the value of variable (Mark). Find the
grade using If – Block statement and display the value of grade in a text box.
When the value of variable (Mark) exceed 100, write a Message Box (Wrong
entry, please Re-enter the Mark). Design form window and select all the control
objects are used.
6
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Solution:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim Mark As Single, Grade As String
Mark = Val(TextBox1.Text)
If Mark > 100 Then
MessageBox.Show("Wrong entry, Re-enter the Mark")
TextBox1.Text = "" : TextBox2.Text = "" : Exit Sub
ElseIf Mark >= 90 Then
Grade = "Excellent"
ElseIf Mark >= 80 Then
Grade = "Very Good"
ElseIf Mark >= 70 Then
Grade = "Good"
ElseIf Mark >= 60 Then
Grade = "Medium"
ElseIf Mark >= 50 Then
Grade = "Pass"
Else : Grade = "Fail"
End If
TextBox2.Text = (Grade)
End Sub
7
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
dimension while the If – ElseIf statement control structure may evaluate only one
expression, each If – ElseIf statement may also compute entirely different
dimensions. Select- Case is more convenient to use than the If- Else - End If. The
format of the Select Case control structure is as follows:
8
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Solution 1
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim Mark As Integer, Grade As String
Mark = Val(TextBox1.Text)
Select Case Mark
Case 0 To 49
Grade = "Fail"
Case 50 To 59
Grade = "pass"
Case 60 To 69
Grade = "medium"
Case 70 To 79
Grade = "good"
Case 80 To 89
Grade = "very good"
Case 90 To 100
Grade = "excellent"
Case Else
MessageBox.Show("wrong entry, please re-enter the mark")
TextBox1.Text = ""
TextBox2.Text = ""
Exit Sub
End Select
TextBox2.Text = Grade
End Sub
End Class
9
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Solution 2
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim Mark As Integer, Grade As String
Mark = Val(TextBox1.Text)
Select Case Mark
Case Is > 100, Is < 0
MessageBox.Show("wrong entry, please re-enter the mark")
TextBox1.Text = "" : TextBox2.Text = "" : Exit Sub
Case Is >= 90
Grade = "excellent"
Case Is >= 80
Grade = "very good"
Case Is >= 70
Grade = "good"
Case Is >= 60
Grade = "medium"
Case Is >= 50
Grade = "pass"
Case Is <= 49
Grade = "fail"
End Select
TextBox2.Text = (Grade)
End Sub
End Class
10
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
H.W
1. Write a program to enter a user name and display the message (hello) three
times. The first one for (Mena), the second one for (Nastia) and the third for any
user as a guest.
2. Design a form with four TextBoxes and three Buttons. Design the program so
that the values of num1, num2, and Symbol are entered into separate three text
boxes. Write a code to perform (add, subtract, multiply and divide) when pressing
on Button (Calculate). Display the result in separate text box. The Button (Clear)
used to clear values in TextBoxes. Click Button (Exit) to end the program and
return to the project window.
11
University of Basrah
Collage of Engineering
Department of Petroleum
Computer Programming
Lecture Five
Loops (Repetition) Structures
First Year
By
The arguments counter, start, end, and increment are all numeric. The increment
argument can be either positive or negative. If increment is positive, start must be
less than or equal to end or the statements in the loop will not execute. If
increment is negative, start must be greater than or equal to end for the body of
the loop to execute. If steps isn’t set, then increment defaults to 1.
In executing the For loop, visual basic:
1. Sets counter equal to start.
2. Tests to see if counter is greater than end. If so, visual basic exits the loop (if
increment is negative, visual basic tests to see if counter is less than end).
3. Executes the statements.
4. Increments counter by 1 or by increment, if it’s specified.
5. Repeats steps 2 through 4.
1
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
For Example:
1- For I=0 To 10 step 5
Statements
Next I
2- For counter = 100 To 0 Step -5
Statements
Next counter
Example 5-1: Design a form and write code to find the summation of numbers
(from 0 to 100) using For Next Loop.
Solution
Public Class Form1
Private Sub Button1_Click ( )
Dim i, Total As Integer
Total = 0
For i = 0 To 100
Total = Total + i
Next i
MessageBox.Show("Total=" +
CStr(Total))
End Sub
End Class
2
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Example 5-2: Design a form and write code to find the summation of even
numbers (from 0 to 100) using For Next Loop.
Solution:
Private Sub Button1_Click ( )
Dim i, Total As Integer
Total = 0
For i = 0 To 100 Step 2
Total = Total + i
Next i
TextBox1.Text = CStr (Total)
End Sub
Example 5-3: Design a form and write code to find the summation of odd
numbers (from 0 to 100) using For Next Loop.
Solution:
Private Sub Button1_Click ( )
Dim i, Total As Integer
Total = 0
For i = 0 To 100
If i Mod 2 = 1 Then Total = Total + i
Next i
Label1.Text = CStr (Total)
End Sub
3
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
5-2 Do –Loop
Use a Do loop to execute a block of statements and indefinite number of times.
There are several variations of Do…Loop statement, but each evaluates a numeric
condition to determine whether to continue execution. In the following
Do…Loop, the statements execute as long as the condition is True.
When Visual Basic executes this Do...Loop, it first tests condition. If condition is
False, it skips past all the statements. If it’s True, Visual Basic executes the
statements and then goes back to the Do while statement and tests the condition
again. Consequently, the loop can execute any number of times, as long as
condition is True. The statements never execute if initially False.
Example 5-4: Design a form and write code to find the summation of numbers
(from 0 to N) using Do While Loop.
Solution
Private Sub Button1_Click ( )
Dim i, N, Total As Integer
Total = 0
N = Val(TextBox1.Text)
i=0
Do While i <= N
Total = Total + i
i=i+1
Loop
TextBox2.Text = CStr(Total)
End Sub
4
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Example 5-5: Design a form and write code to find the summation of
numbers (from 0 to N) using Do Loop While.
Solution
5
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Example 5-6: Design a form and write code to find the summation of numbers
(from 0 to N) using Do Until Loop.
Solution
6
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Example 5-7: Design a form and write code to find the summation of numbers
(from 0 to N) using Do Loop Until.
Solution
7
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
The exit statement allows you to exit directly from For Loop and Do Loop, Exit
For can appear as many times as needed inside a For loop, and Exit Do can appear
as many times as needed inside a Do loop (the Exit Do statement works with all
version of the Do Loop syntax). Sometimes the user might want to get out from
the loop before the whole repetitive process is executed; the command to use is
Exit For To exit a For...Next Loop or Exit Do To exit a Do… Loop, and you can
place the Exit For or Exit Do statement within the loop; and it is normally used
together with the If...Then...statement.
Example 5-8: Design a form and write code to print numbers (from 1 to 10) on
listBox using For Next statement and stop printing at number 6 using Exit For.
Solution
8
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Example 5-9: Design a form and write code to print numbers (from 0 to 10) on
listBox using Do While statement and stop printing at number 5 using Exit Do.
Solution
Private Sub Button1_Click()
Dim x As Integer
x=0
Do While x < 10
ListBox1.Items.Add(x)
x=x+1
If x = 5 Then
ListBox1.Items.Add("The program is
exited at x=5")
Exit Do
End If
Loop
End Sub
9
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Example 5-10: Write VB program to print the following figure. Print the figure
in TextBox.
*
**
***
****
Solution
Private Sub Button1_Click ( )
Dim i, j As Integer
For i = 1 To 4
For j = 1 To i
TextBox1.AppendText(("*" & " "))
Next j
TextBox1.AppendText(vbNewLine)
Next i
End Sub
10
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Example 5-11: Create a Visual Basic Project to find the value of the following
series.
Write the code program so that the value of constants (a, and b) are entered into
text boxes. When the users click checkbox, calculate the value of series (where
the total number of terms is equal 20). When the user unchecked the checkbox,
the number of terms (N) is entered into input box and calculate the value of series.
Display the value of series (Sum) in a separate text box.
Solution
Private Sub Button1_Click ( )
Dim a, b, Sum, N As Integer
a = Val(TextBox1.Text)
b = Val(TextBox2.Text)
Sum = b
If CheckBox1.Checked = True Then
For I = 1 To 20
Sum = Sum + a * I
Next
Else
N = Val (InputBox ("No. of terms="))
For I = 1 To N
Sum = Sum + a * I
Next
End If
TextBox3.Text = CStr(Sum)
End Sub
11
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
H.W
1. Write a program to generate the numbers from 0 to N, display the result using
List Box.
2. Write a program to generate the numbers from 0 to N, and increase the counter
10 each time, then display the result using List Box.
3. Write a program to print even numbers from 1 to N using do while loop.
4. Write a program to find the summation of the numbers from 5 to 15.
5. Write a program to print multipliers of 5 (from 5 to N).
12
Example : Create a Visual Basic Project to find the value of the following series.
Write the code program so that the number of terms (N) is entered into TextBox.
Display the result (Pi) in separate text box when click on Button (Find Pi).
Solution
Public Class Form1
Private Sub Button1_Click()
Dim S, N, I, T, Pi As Double
N = Val(TextBox1.Text)
S=0
For I = 1 To N
T=1/I^2
S=S+T
Next
Pi = Math.Sqrt(S * 6)
TextBox2.Text = CStr(Pi)
End Sub
End Class
Q1\ Write a program to generate the numbers following
Solution
(1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71) on ListBox.
Solution
Private Sub Button1_Click()
Dim x As Integer
For x = 1 To 71 Step 5
ListBox1.Items.Add(x)
Next
End If
Next
End Sub
Q4\ Write a program to generate the numbers following
Next
End Sub
University of Basrah
Collage of Engineering
Department of Petroleum
Computer Programming
Lecture Six
Functions
First Year
By
Visual Basic offers a rich assortment of built-in functions. The numeric and string
variables are the most common used variables in programming. Therefore, Visual
Basic provides the user with many functions to be used with a variable to perform
certain operations or type conversion. Detailed description of the function in
general will be discussed in the following functions section. The most common
functions for (numeric or string) variable X are stated in the following table.
Function Description
Y= Math.Abs(X) Absolute of X, |X|
Y= Math.Sqrt(X) Square root of X , √𝑋
Y= Math.Sign (X) (-1 or 0 or 1) for (X<0 or X=0 or X>0)
Y= Math.Exp (X) ex
Y= Math.Log (X) Natural logarithms, ln𝑋
Y= Math.Log(X)/ Math.Log (10) Log𝑋
Y= Math.Sin (𝑋)
Y= Math.Cos (𝑋) Trigonometric functions
Y= Math.Tan (𝑋)
Y= Math.ASin (𝑋) Inverse Trigonometric functions
Y= Math.ACos (𝑋)
Y= tan−1(𝑋) (Where X angle in radian).
Y= Math.ATan (𝑋)
Y= Int(X) Integer of X
Y= Fix(X) Take the integer part
1
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Ex 6-1:
*Private Sub Button1_Click()
Dim num1, num2 As Integer
num1 = Val(TextBox1.Text)
num2 = Math.Abs(num1)
Label1.Text = num2
End Sub
*Private Sub Button2_Click()
Dim num1, num2 As Single
num1 = Val(TextBox2.Text)
num2 = Math.Exp(num1)
Label2.Text = num2
End Sub
*Private Sub Button3_Click()
Dim num1, num2 As Single
num1 = Val(TextBox3.Text)
num2 = Fix(num1)
Label3.Text = num2
End Sub
*Private Sub Button4_Click()
Dim num1, num2 As Single
num1 = Val(TextBox4.Text)
num2 = Math.Log(num1)
Label4.Text = num2
End Sub
*Private Sub Button5_Click()
Dim num1, num2 As Single
num1 = Val(TextBox5.Text)
num2 = Int(num1)
Label5.Text = num2
End Sub
2
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Examples:
Private Sub Button1_Click()
Dim A, B, C, D, M, L, H As String
H= My Name Is
A = LCase(H)
B = UCase(H)
C = Mid(H, 3, 5)
D = LSet(H, 7)
M = RSet(H, 4)
L = Len(A)
TextBox1.Text = A
TextBox2.Text = B
TextBox3.Text = C
TextBox4.Text = D
TextBox5.Text = M
TextBox6.Text = L
End Sub
3
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Ex 6-2: Design a visual basic program with two textboxes. One is used to enter
any string and the other is used to display the inverse of this string.
Private Sub Button1_Click()
Dim x As String
Dim i, y As Integer
x = TextBox1.Text
y = Len(x)
For i = y To 1 Step -1
TextBox2.Text &= Mid (x, i, 1)
Next
End Sub
Visual Basic provides several conversion functions can used to convert values
into a specific data type. The following table describes the convert function.
Function Description
The function CDbl converts, integer, long integer, and single
precision numbers to double-precision numbers. If x is any
CDbl
number, then the value of CDbl(x) is the double-precision number
determined by x.
The function CInt converts long integer, single-precision, and
double precision numbers to integer numbers. If x is any number,
CInt
the value of CInt(x) is the (possibly rounded) integer constant that
x determines.
The function CLng converts integer, single precision and double-
precision numbers to long integer numbers. If x is any number,
CLng
thevalue of CLng(x) is the (possibly rounded) long integer that x
determines.
The function CSng converts integer, long integer, and double-
precision numbers to single-precision numbers. If x is any number,
CSng
the value of CSng(x) is the single-precision number that x
determines.
4
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
The objective of MsgBox is to produce a pop-up message box and prompt the user
to click on a command button before he /she can continues. This format is as
follows:
The first argument, Prompt, displays the message in the message box. The Style
Value determines the type of command buttons appear on the message box, as
shown in Table 10.1. The Title argument will display the title of the message
board.
5
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
yourMsg is a variable that holds values that are returned by the MsgBox ( )
function. The type of buttons being clicked by the users determines the values. It
has to be declared as Integer data type in the procedure or in the general
declaration section. Table 10.2 shows the values, the corresponding named
constant and buttons.
Ex 6-3:
6
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
To make the message box looks more sophisticated, you can add an icon besides
the message. There are four types of icons available in VB2010 as shown in Table
10.3
16 vbCritical
32 vbQuestion
48 vbExclamation
64 vbInformation
7
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Ex 6-4
An InputBox function allows the user to enter a value or a message in a text box.
8
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Ex 6-5:
Private Sub Button1_Click()
Dim userMsg As String
userMsg = InputBox("What is your message?", "Message Entry Form", "Enter
your messge here", 500, 700)
If userMsg <> "" Then
MessageBox.Show("userMsg")
Else
MessageBox.Show("No Message")
End If
9
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Functions and Subroutines are programs designed for specific task, and could
be called from the main program or from sub-procedures without pre definition
or declaration. Users are allowed to call in any number of times which save the
main program space, since it avoids reputation of code these subroutines could
be designed by user or could be previously built.
function procedures and sub procedures share the same characteristics, with
one important difference- function procedures return a value (i. g., give a value
back) to the caller, whereas sub procedures do not.
Function Procedures
10
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Call statement
X= Name (Value1)
Sub Procedures
Call statement
11
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Ex 6-6: Create a program that calculates the cube root of a number, by using
function.
This BMI calculator is a Visual Basic 2010 program that can calculate the body
mass index of a person based on his or her body weight in kilogram and the body
height in meter. BMI can be calculated using the formula weight/ (height )2,
where weight is measured in kg and height in meter.
12
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
If the BMI is more than 30, a person is considered obese. You can refer to the
following range of BMI values for your weight status.
Underweight = <18.5
Normal weight = 18.5-24.9
Overweight = 25-29.9
Obesity = BMI of 30 or greater
Solution
Public Class Form1
Public Function BMI (ByVal height, ByVal weight)
Return (weight) / (height ^ 2)
End Function
13
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
The function to calculate the future value involves three parameters namely the
present value (PV), the interest rate (i) and the length of period (n).
Solution
14
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed
Ex 6-9: Write a code program to read three integer numbers. Using a define sub
procedure (Minimum) to determine the smallest of three integers. Display the
smallest value in TextBox.
Solution
15