You are on page 1of 119

INDEX

Content

Page
1

Chapter I :Data
Preface
1-1 Data Types
1-2 Variables
1-3 Assignment statement
1-4 Constants
1-5 The Errors
1-6 Priority rules for Arithmetic operations
Questions
Chapter II :Branching
Preface

2-1 Branching statement using (If Then

2-2 Branching statement using (If ..Then.. Else)

2-3 Branching statement using (If ..Then.. ElseIf)


2-4 Using Logical Operators with (If) statement
2-5 Branching statement using (Select Case)
Practical Exercises
Questions

2
3
5
8
15
21
27
28
33
34
34
38
40
45
48
52
55
59
60

Chapter III :Loops and Timers


Preface

3-1 (For.next) statement


3-2 (Dowhile) statement

60
70

3-3 Using the Timer control


Practical Exercises
Questions

75
78
81
83

Chapter IV:Procedures
Preface

84

4-1 Procedures

85

4-2 Declaration of a Sub Procedure

85

INDEX
Content

Page

4-3 Declaration of a Function

4-4 Exercises on using Functions


4-5 Predefined Functions

92
93
97

Questions

100

Sample Test (1).


Sample Test (2).
Sample Test (3).

103
106
109

ii

Data
By the end of this chapter, student will be able to:

List the different types of data.


Choose the appropriate (Data type).
Declare variables.
Declare constants.
Assign values for variables.
Assign constants.
Specify the type of (Error) in the program.
Build arithmetic expressions according to the
priority rules of arithmetic operations.

Chapter One
Data

Data

Dear student, we previously learned how to design a programs interface of an


application using (Visual Basic.NET) language and, how to adjust properties in
design mode using (Window properties).Also we have acquainted (Code
window) , (Event Procedure) and, how to assign values programmatically to
some Controls properties, thus finding that the Program user can enter values
with different types as shown in figure (1-1).

Figure (1-1) User Interface and data entered


Note the following: ( -1121/21/7- -5), are data values of
different types where;
The Name: represents a Text
Birthdate: represents a Date
Type: represents a Boolean value
The number of family members: represents a numeric value
These values are stored in the RAM with special representation; that varies with
the type of each value.

(2)

Chapter One
Data

Data

Each data type has a way in which data are stored in computer
memory (RAM).
This is mainly for using the computer memory optimally; in terms of
storage space and, arithmetic and logical operations that take place
on these values.

Visual Basic.Net Language provides many data types used to store input values
from the user, or values resulting from the execution of instructions and
commands of the a program.
Data Types provided by (Visual Basic.Net) Language are:
1- Numerical Data Types; that can be used to store numerical data and are
divided into:
a- Integral Numeric Types (such as: Byte- Long Integer Short).
b- Nonintegral Numeric Types (namely: Double- Single Decimal).
2- Character Data Types (namely: String Char).
3- Miscellaneous Data Types are those data that; do not fall under the
Numeric or the Character types (namely: Object Date Boolean).

Each Data Type has:


1. A storage space in the memory: for the data type (Integer);
when used, it occupies (4 bytes).
2. A range of values (the values that can be represented by this
type); the range of values for the data type (Byte) starts with
0 and ends with 255.

(3)

Chapter One
Data

Data

Dear student, we previously studied how to adjust Properties whether by using


(Properties Window), or programmatically through the (Code window).
Adjusting Properties here means to define a value for the Property, this value
has a specific Data type.

Knowing the Data Type


In the (Code window), after you finish writing the assignment statement for the
Property; move the mouse pointer over the Property name, a yellow rectangle
appears in which the Data type for this Property is written after the word (As);
this is shown in the assignment statements for setting the Properties (Text,
AutoSize, Width) for the control (Label1) as shown in figure (1-2):
The property (Text) of type
(String)
The property (AutoSize) of
type (Boolean)
The property (Width) of type
(Integer)
Figure (1-2) Data types for some properties

(Visual Basic. NET) supports types,other than the standard Data Types.

As shown; the statement for setting the Property (BackColor) of the control
(Label1); is displayed in figure (1-3).

Object

Property

Value

Figure (1-3) Data type for the Property (BackColor)

(4)

Chapter One
Data

Data

Dear Student, from what is mentioned above it is clear that Properties


are data storage locations and, they have a Type or (Data Type).

Variables are reserved memory locations to store values temporarily. Variables


have names and Data types; that are created by declaring variables then
assigning values to them depending on their Data Types. These values can be
changed during the execution of program instructions and commands.

Use the (Dim) keyword in combination with the variable name and data type;
write (Dim) then the name of the Variable then the word (As) followed by the
Data Type as shown:

Dim

Variable

As

Data Type

Dim V_Name As String

Dear student, when naming Variables, you must note the following:
1. Variable names must begin with a letter or underscore (_).
2. Variable names Should not contain symbols or special characters (e.g.:

?,*,^, -, +,.) and others.


3. Variable names consist of letters, numbers, and underscores (_).
4. Do not use reserved words (Visual Basic.NET Language Keywords) such as
(single, Dim, As).
5. It is preferable that the Variable name reflects its content.

(5)

Chapter One
Data

Data

Dear student, when choosing a Data Type, you must note the following:
1. The size of data that will be stored in the variable.
2. Identify the Data Type of the values stored in the variable; based on the
arithmetic and logical operations, expected to take place on the variable.

Dear student, design the interface of a program, by adding controls to the


form; that receives input from the user as displayed in figure (1-4):

Figure (1-4) User interface to be designed

(6)

Chapter One
Data

Data

Expected values entered from the user and proposed names and, types as
shown in the table (1-1):

Value

Data Type

Proposed names

)String(

U_Name

)Date(

U_B_D

)Boolean(

U_Gender

)Integer(

U_C_F

Table (1-1) expected values entered from the user


Add the (Event Procedure), also called (Event Handler) for the button ( )
and then declare the variables as shown in figure (1-5):

Figure (1-5) Variables declaration

In this way, we have reserved places in the computer memory


(RAM), to store inputs from the user. This is done by what socalled (Assignment)

(7)

Chapter One
Data

Data

Is a statement that consists of two sides (right hand side and left hand side)
separated by the assignment operator (=); (which doesnt mean the arithmetic
equality). It consists of taking the value on the right side of the assignment
operator (=) and storing it in the element on the left, as in the following
example.

Left side

Assignment
operator

Right side

(Variable)

Abstract value or

or
(Property)

Value from a (Variable) or


(Property) or
Value from an (Expression)

Dim Number As Integer


Number = 5

The first line declares the variable (Number); specifying the type (Integer)
to be the data type.
The second line assigns the abstract value (5) to the variable (Number).
Dim Number1 As Integer
Dim Number2 As Integer
Number1 = 5
Number2 = Number1
The first two lines declare the variable (Number1) and (Number2);
specifying the (Integer) to be the data type.
The third line assigns the abstract value (5) to the variable (Number1).
The fourth line assigns the value of variable (Number1) to the variable
(Number2).
Dim Name As String
Name = Label1.Text

(8)

Chapter One
Data

Data

The first line declares the variable (Name); specifying the type (String) as
data type.
The second line assigns the value of the (Text) property of (Label1)
control; to the variable (Name).
Dim Number As Single
Number = 7

Number = Number / 3
The first line declares the variable (Number); specifying the (Single) data
type.
The second line assigns the abstract value (7) to the variable (Number).
The third line reassigns the variable (Number) using an Expression which
is: (Number /3).
Dim Number As Single = 5.6
You can declare the variable (Number) in one statement; specifying the
(Single) data type and a value of (5.6).

1. You can make assignment for (Variables) during the


declaration or at a later stage.
2. Reassignment of variables can be made many times, so the
term Variable thus-called because of the variation of its
values; at any time during the execution of the program.
3. The values assigned to variables can be (abstract values,
variables, property and, expression).
4. The assignment operator (=) doesnt indicate the arithmetic
equality, it means "is replaced by i.e. (x=x+1), where (x) in
the left side represents the variable or storage, and (x) in the
right side represents the value. If we assume that the value
of (x) equal (5), after this assignment operation (x) becomes
(5+1) the result is 6.

(9)

Chapter One
Data

Data

Dear student, after studying the Assignment operations, we will make


assignment of inputs received from the user to their corresponding Variables.
Declared Variables

U_Name

U_B_D

U_Gender

U_C_F

In this case we will use Controls properties; that receive inputs from the user in
the assignment operation, where we do not change the values of the property
(Name) for these controls as illustrated in table (1-2).

Control

Property

TextBox1

Text

TextBox2

Text

RadioButton1

Checked

TextBox3

Text

Table (1-2) controls properties receiving user inputs


Write the assignment statements as shown in figure (1-6).

Figure (1-6) writing Assignment statements

(10)

Chapter One
Data

Data

The Property (Checked) for the control (RadioButton1) is checked


using (If statement); that will be studied later. If the value of
property (Checked) is (True) then, the value assigned to the variable
(UserGender) is (True), but if it is the opposite the value assigned to
the variable (UserGender) will be (False).

Table (1-3) illustrates the difference between Properties Data Types


and Variables Data Types.

Property

Data type for

Variable

TextBox1.Text

String

U_Name

String

TextBox2.Text

String

U_B_D

Date

TextBox3.Text

String

U_C_F

Integer

properties

Data type for


variables

Table (1-3) illustrating the difference between Properties data types and
Variables data types used.
This difference in type is not allowed when the Assignment is done, but (Visual
Basic.Net) can convert the values to the data type that is compatible with the
variable or, the property to which the value will be assigned. This is called
Implicit conversions.

Dear student, if the variable is on the left side of the Assignment statement, this
indicates where values will be stored; if the variable is on the right side of the
Assignment statement this means that it reflects its value.

(11)

Chapter One
Data

Data

Dear student add the control (Label) after adjusting its properties as shown in
table (1-4) and figure (1-7).

Property

Value

AutoSize

False

Size,Location

Using mouse pointer

BorderStyle

FixedSingle

Table (1-4) the Properties values of the (Label) control

Figure (1-7) the (label) control after adjusting its properties


Open the (Click) event procedure for the Button ( )and then add the
following code:

Me.Label5.Text = UserName &vbCrLf & UserBirthDate & vbCrLf & _


UserGender & vbCrLf & UserNoFamily

(12)

Chapter One
Data

Data

The previous code presents the Assignment statement of a set of


variables for the property (Text) and the control (Label5) where:
Variables are separated from each others by )& vbCrLf &(.
The symbol (&) is used to perform the concatenation of texts.
The reserved word (vbCrLf) is used to create a new line.

If the line of code is somewhat long; the symbol (_) enables


writing lines of code in more than one line, to organize and
simplify the process of reading code.

Me express the current (Form).

Where the (Click) event procedure will be as shown in figure (1-8)

Declaration of variables

Assignment values to
variables

Using variables

Figure (1-8) declaring variables and, assigning values then using them

(13)

Chapter One
Data

Data

After writing code, we press (F5); to perform (Start Debugging) and, we fill the
registration form then, we click the button ( ) as shown in figure (1-9).

Figure (1-9) User interface after data entry


Dear student, (Visual Basic.Net) provides a way to add comments that help the
reader understand the code written in the (Code Window), this is done by
beginning the statement with the keyword (REM) or the apostrophe ( ) where
what is written after, is not considered lines of code and, is neglected during the
program compilation using the (Visual Basic.Net) compiler. This is illustrated in
figure (1-10).

Figure (1-10) Write comments

(14)

Chapter One
Data

Data

They are places reserved in the (RAM) and, have data types; this is done during
the declaration: declaring constants then assigning values depending on their
data types. These values cannot be changed during program execution.

Use the (Const) keyword and, write the name of the Constant then, the word
(As) and constants Data Type then the (=) sign followed by the value of the
constant as shown:

Const

Constant name

As Data Type

= Value

Const C_Name as String = ""

Const C_Name As String = ""


Where the constant (C_Name) was declared, of data type (String) and, its
text value " " is assigned during the declaration.

Const pi As Single = 22 / 7
Where the constant (pi) was declared, of data type (Single) and, its numeric
value 22/7 is assigned during the declaration.

Const BirthDate As Date = #1/25/2011#


Where the constant (BirthDate) was declared, of data type (Date) and, its
value #1/25/2011# is assigned during the declaration.

The apostrophes " " are used while writing text.


The hashes # # are used while writing date or time.

(15)

Chapter One
Data

Data

Dear student, design the window Form as shown in figure (1-11)

Figure (1-11) User interface to be designed


Then open the code window by pressing the button (F7) and, add the (Click)
event procedures for (Button1,Button2) as illustrated in figure (1-12).:

Figure (1-12) adding Event Procedures to the Code Window


Remember
The Area of a circle
The circumference of a circle
Where (

) is the radius and Pi:

)
=22/7)

(16)

Chapter One
Data

Data

Dear student, we will write the code required to calculate the Area of a circle
using the Event Procedure (Button1_Click) and, the circumference of a circle
using the Event Procedure (Button2_Click).The results will be displayed in
control (Label2) when clicking on any of the two buttons.
In the scope of the Event Procedure (Button1_Click), we write the code as
shown in figure (1-13)

Figure (1-13) writing the code to calculate the Area of a circle


The variable (Radius) is declared, then the constant (Pi) is declared with
assigning the value (22/7) to it .The value of the variable (Radius) is assigned
from the Property (TextBox1.Text).The expression (Pi

^ 2) is

assigned to the property (Label2.Text) which follows the arithmetic rule to


calculate the Area of a circle.
After writing code, we press (F5) key to perform (Start Debugging), then we
enter the value of the Radius and, we click the button ( ) as shown in
figure (1-14).

Figure (1-14) calculation of the area bearing in mind its radius

(17)

Chapter One
Data

Data

Dear student, add the code required to calculate the circumference of a circle
in the scope of the Event Procedure (Button2_Click) as follows:

Radius = TextBox1.Text
Label2.Text = pi * Radius * 2

Knowing that the variable (Radius) and the constant (Pi) were
previously declared in the scope of the Event Procedure
(Button1_Click), accordingly messages inside a yellow rectangle
are displayed alerting that the (Radius) and the constant (Pi) are
not declared, although they are declared in the scope of the Event
Procedure (Button1_Click). Here it shows us that variables and
constants cannot be used except in the scope of their declaration
as illustrated in figure (1-15).

Figure (1-15) the code of calculating the area and circumference of a circle

(18)

Chapter One
Data

Data

The yellow rectangle appears when pointing with the mouse to the variable (Pi)
in the second line as shown in form (1-16):

Figure (1-16) Error Statement in the Code


To resolve this problem we repeat the declaration of the variable (Radius) and
the constant (Pi) in the scope of the Event Procedure (Button2_Click) as shown
in figure (1-17).

Figure (1-17) the code after the declaration of the variable (Radius) and the
constant (Pi)

(19)

Chapter One
Data

Data

We can declare Variables and Constants on a Class level and then, we


do not need the declaration process at each scope of the Event
Procedure.

Figure (1-18) the declaration of the variable (Radius) and constant (Pi) on
the class level (Form3)
Where the declaration of the variable (Radius) and the constant (Pi) is done in
the scope of the class (Form3), therefore we can use them within the scope of
the Event Procedures (Button1_Click) and (Button2_Click) that are also declared
in the scope of the class (Form3).
After writing code, we press (F5) to perform (Start Debugging), then we input
the value of the Radius and, we click the button ( ) once and, the
button ( ) again as shown in figure (1-19).

Figure (1-19) User Interface after using the buttons ( ) and, ()

(20)

Chapter One
Data

Data

Dear student, when writing code, it is a must to abide by the rules of the
programming language used; so when you write the code, several types of
errors occur including:
1- Syntax Error : happens when writing code incorrectly as illustrated in the
following examples
Examples
Din X As Single
The variable (X) was declared but there is a mistake in writing the word
(Dim)
Const X As Single
The constant (X) was declared but, its value is not assigned during the
declaration. To overcome this type of error, the (IDE) help us as it does
not allow any error of this type.
2- Logic Error: it leads to incorrect results when executing the program; and
happens if the expressions used in the assignment statement are built
improperly.
Example
When calculating the Area of a circle we used the following code:

Dim Radius As Single


Const X As Single =22/7
Radius =TextBox1.Text
Label2.Text = x * Radius ^ 2

Assume that the code was written as follows:

Dim Radius As Single


Const X As Single =22/7
Radius =TextBox1.Text
Label2.Text = x + Radius ^ 2

(21)

Chapter One
Data

Data

When executing this code, it will run without giving any error messages and the
result will be incorrect, as it will perform the sum instead of the multiplication.
To overcome this type of error, you must review the written code, and test the
program with data already validated, to be sure there are no errors of this type
(Logic Error)
3- Runtime Error that appears during the execution
This type of error is found in lines of code, where the Assignment Statement is
written. For example when you assign a value greater than the Data Type used
or, assign a value that is not equivalent to the variables Data Type or constants
Data Type, and so the Compiler of the language cannot converted this Data
Type.

Dear student, design the window Form as shown in figure (1-20)

Figure (1-20) User interface to be designed

(22)

Chapter One
Data

Data

Write the following code to the (Click) event procedure of the Button ( )as
shown in figure (1-21)

Figure (1-21) the code written to calculate the sum of two numbers

We can declare the two Variables (Arabic) and (Computer) with Data
Type (Byte) which receives values starting from (0) and ends with
(255) .This means that the program user must comply with the limits
of those values and, in case of violation, error occurs during Runtime

while you perform the Assignment to those Variables as shown in the


following cases
The first case
We press (F5) to (Start Debugging), then we click the button ( ) without
entering any data to text boxes as shown in figure (1-22).

Figure (1-22) User interface during Run Time

(23)

Chapter One
Data

Data

The following error message appears to state that, it is not allowed to convert
the blank text value to the type (Byte) and, this occurs as we didnt enter the
degree of the (Arabic language) as shown in figure (1-23).

Figure (1-23) Error message during execution (when entering blank value)
The second case
Perform (Stop Debugging) by pressing the (
) icon, then (Start Debugging) by
pressing (F5), then click the ( )button after entering the text value

) ( in a text box.
The following error message appears which states that, it is not allowed to
convert the text value ( ) " to the type (Byte) and, this occurs as we
entered text values instead of numeric values as shown in figure (1-24).

Figure (1-24) Error message during execution (when entering text)


The third case
Perform (Stop Debugging) by pressing the (
) icon, then (Start Debugging) by
pressing (F5) key then, click the ( )button after entering a numeric value
greater than 255 in one of the text boxes.
The following error message appears as the value entered is greater than the
allowed limit, this occurred because the degree of the (Computer language)
entered is greater than (255) as shown in figure (1-25).

Figure (1-25) Error message during execution (when entering value out of limit)

(24)

Chapter One
Data

Data

The oval shape on each error message indicates the type of error
which is not handled, and these (Runtime) errors can be overcome by
several ways including the following:
1. Visual Basic .Net provides the possibility of handling errors that likely
occur through the Try...Catch...End Try structure, written as follows.

Try
Catch ex As Exception
EndTry
The code that is most likely to show errors during the execution is placed
after the word (Try) and the error handling code is placed after the word
(Catch) as shown in figure (1-26).

Figure (1-26) Using the Try Catch statement

(25)

Chapter One
Data

Data

2. Controlling the data input from the user, by placing controls and adjusting
their properties; through which user can input data correctly as described
in figure (1-27).

Figure (1-27) Controlling user input

In the shown Form window, user can only choose one country from the
displayed list.

(26)

Chapter One
Data

Data

Dear student, we have performed Assignment operations including assigning


Arithmetic expression such as:

Label2.Text = x * Radius * 2
If there is more than one arithmetic operation such as:

5+3*2
Which is performed first the multiplication or addition?

The expression 5 + 3 * 2 is evaluated and the result equals 11. This was
computed by doing the multiplication first then the addition.
But if the parenthesis is used in the expression (5 + 3)* 2; expressions enclosed
in parentheses are evaluated first and the result equals 16.
The operations are executed upon the following order of evaluation:
1.
2.
3.
4.

Parentheses starting from inside out.


Exponentials.
Multiplications and divisions from left to right.
Additions and subtractions from left to right.

From what is previously mentioned, it is clear that it is necessary to take into


account, the priority rules of arithmetic operations; when you create
expressions used in the Assignment statement so that errors of type (Logic
Errors) do not occur; because the result will change in this case without showing
any error messages.

(27)

Chapter One
Data

Data

First: In the following Form window, if it is required to store entries from the
user in variables. Define the corresponding Data Type for each input.

2
3

1.
2.
3.
4.

(28)

Chapter One
Data

Data

Second: In the following code, get the variable names and constants and
their Data Types.

.......................................................................................
.......................................................................................

.......................................................................................
.......................................................................................
Third: In the following code, determine the cause of the displayed error

The cause of errors :

.......................................................................................
.......................................................................................

The cause of errors :

.......................................................................................
.......................................................................................

(29)

Chapter One
Data

Data

Forth: In the following, determine the code to be written as indicated by


the arrows.
Try

Catch ex As Exception

EndTry

Fifth: Determine the type of error in the following, and then perform
the required error handling.
Code

error type

error
handling

Din x As Single
Const x As
Single
Sixth: When writing code the user needs to add specific comment that
will not be executed, so the code must be preceded by:

1. ...............................................................................
OR

2. ...............................................................................

(30)

Chapter One
Data

Data

Seventh: in the following code explain the lines of code, indicated by the
numbers as shown in the figure.

1) ...............................................................................
2) ...............................................................................
Eight: Write the order of execution of Arithmetic operations that follow:

Order

Operation

Multiplications and divisions from left to right.

Parentheses starting from the inside out

Additions and subtractions from left to right

Exponentials.

(31)

Chapter One
Data

Data

Ninth: Evaluate the following Arithmetic expressions and get the results
(A) (5+3)*2
The result .
(B) 5+3*2
The result.
Tenth: State whether the following statements are true () or false (X)
1- One of the Rules for naming variables or constants in the
program is: variable names must begin with a letter or a number.

2- Declaring variables is done using the Dim statement.

3- The variable of type Double takes the value True or False.

4- Variables of types (Integer & Long & Double) are used to store
integers only.

5- User input is received through several controls including TextBox

(32)

Branching
By the end of this chapter, student will be able to:
Use If Then statement.
Use If ThenElse statement.
Use If Then ElseIf statement.
Use Select Case statement.

Chapter Two
Data

Branching

Dear students, we previously learned (FlowCharts); where branching is used to


execute a sequence of steps depending on the result of the condition or the
answer of the question. You will find that writing code is just translating an
algorithm into a programming language with adherence to languages
grammatical rules. Programmatically branching is expressed using special
statements or structures that will be demonstrated through the following
exercises.

The syntax of (IfThen) statement

If conditional Expression Then


code

End if
The (If.Then) structure tests a condition, or a conditional expression written
after (If); if the result is (True) it executes the statements that follow (Then) until
reaching (End if); and, if the result is (False) it executes the statements following
(End If) as shown in figure (2-1).
If X >= 50 Then

X>=50

Msgbox " "

Msgbox(")"
End if
End

Figure (2-1) Simple example for (If ..Then) statement

(34)

Chapter Two
Data

Branching

A conditional expression is part of a program code; its result can be (True) or


(False) depending on the value of: (a Property or a Variable or another piece of
data in the program code).
For example in the conditional expression (Degree>=50) ,if the variable (Degree)
contains a value greater than or equal to 50 ,then the result of the condition is
(True); and if the variable contains a value less than 50, the result will be (False).

Equal to

<>

Not Equal to

>

Greater than

<

Less than

>=

Greater than or equal to

<=

Less than or equal to


Table (2-1) Comparison Operators

100 < > 100

False

as the two values are equal

300 < > 100

True
as the two values are not equal

DEGREE=Textbox1.Text

True

If the value of the property (Text)


for the control (Textbox1) equals

the value of the variable (Degree);


and if it is the opposite it will be
(False).

Table (2-2) Comparison Expressions examples

(35)

Chapter Two
Data

Branching

Create a new project so that the Forms window will be as shown in figure
(2-2)

Figure (2-2) the required Forms window to be designed


When you press the button ( ) , a message appears displaying the
word ( ) as long as the degree is greater than or equal to 50.
We will write code; depending on the Flowchart as shown in table (2-3).

The (Code) is written in the

Start

(Click) event procedure for the


command button (Button1 )

Enter X

X>=50

Msgbox
""

End

Table (2-3) Flowchart and code written for exercise (2-1)

(36)

Chapter Two
Data

Branching

1. The (IF) statement is used to express the condition Is value of


(x) is greater than or equal to 50?
2. The program code can be written for implementing the following
(Algorithm).

Run the program


Input values such as (20, 50, 75) and click the button ( ) in each time.

When you enter any value less than 50, the MessageBox does
not appear because the result of the condition is (False), so the
statement after (End if) which is (End Sub) will be executed; to
terminate the procedure.
This (If) statement can be written, in one line without writing
(End if) as follows:

(37)

Chapter Two
Data

Branching

The (If.Thenelse) statement is different from the previous one: (If.Then); as


it executes a code when the result of the condition is (False).

The syntax of (IfThenElse) statement

If Conditional Expression Then


code

The code in case of True

code

The code in case of False

Else

End if

as shown in table (2-4).


The (Code) is written in the (Click)

start

event procedure for the command


button (Button1 )

Enter X

X>=50

Msgbox

Msgbox

""

""

End

Table (2-4) Flowchart and code written for exercise (2-2)

(38)

Chapter Two
Data

Branching

1. An (Else) statement contains the block of code (statements that


follow (Else) which is executed if the result of the conditional
expression in the (If) statement is (False).
2. The (If) statement can be written, in one line without writing (End if)
as follows:
The (If) statement in one line

as shown in table (2-5).


Start

The (Code) is written in the


(Click) event procedure for the

Get N

command Button
N
divisible
by 2

End

Table (2-5) Flowchart and code written for exercise (2-3)

(39)

Chapter Two
Data

Branching

We tested the value of (N); through the conditional expression (N Mod 2); If it is
divisible by 2 without remainder. Where (Mod) is a mathematical operator that
computes the remainder of a division expression; when the remainder of a division by
2 equals zero, this means there is no remainder; therefore it is an even number.

The (If ThenElse) statement is used when a single condition is tested, the
results of the condition is either (True) or (False), but the (If ...ThenElseIf)
statement is used when you want to check more than one conditional
expression.

The syntax of (IfThenElseIf) statement

If Conditional Expression Then


code

ElseIf Conditional Expression Then


code

ElseIf Conditional Expression Then


.

code

Else

code

End if

as
shown in figure (2-3).

Figure (2-3) the required Forms window for exercise (2-4)

(40)

Chapter Two
Data

Branching

The form accepts a users input (of a number of temperature degrees) in the
textbox (TextBox1). Then by clicking on the command button (), it shows
the messages or or in (Label1) according
to the flowchart shown in figure(2-4):
start

Get D

D =0

Output
""

Output
""

D<0

Output
""

end

Figure (2-4) Flowchart for exercise (2-4)


The (Code) is written in the (Click) event procedure for the command button
( )as follows:

(41)

Chapter Two
Data

Branching

1. Variable (D) is declared of type (single) for the possibility to enter


a decimal number.
2. The (If) statement started with the conditional expression
(Degree = 0).
If the result equals (False), another conditional expression
is tested this is: (Degree < 0).
If the result of (Degree < 0) equals (False); remains the last
possibility that (Degree > 0) which is not explicitly written,
but expressed by (Else) because it is only possibility
remaining.
Press (F5) button from the keyboard to start the Debugging
Enter the numbers like (30 or 0 or-10) and click the button every
time.
Click the button with the (TextBox) empty or containing text, what
do you notice?
We notice that the program stops and runtime error appears as
shown in figure (2-5)

Line where error occurs


Error converting from string
to single

Figure (2-5) Error displayed during execution (Runtime)

(42)

Chapter Two
Data

Branching

Figure (2-5) illustrates the following:


1. The error occurred on (Degree= Me.Textbox1.Tex).
2. What causes the error is that the (TextBox) does not contain a number to
be converted implicitly to the type Single (the data type of the variable
Degree), but there was a problem as a result of the non-convertibility of a
String data type (as the (TextBox) is left blank) to a Single data type.
You can prevent the occurrence of this error using more than one method like:
The first method: To display a message for the user; through an additional (IF)
statement as follows:

Additional (IF) statement


Original code; executed
when you enter numeric
values.

The code; when you


enter string values.

1. The additional (If) statement is used to test if the value of the


property Text of the TexBox is a numerical value ,if the result is
(True) then the original code is executed but, if it is (False)
where the value is non-numeric ,then the bloc of code below
(Else) will be executed
2. The conditional expression (Isnumeric(Textbox1.Text) = 0).is
used in the additional (If ) statement where (Isnumeric) is one of
the predefined functions, used to check the data stored in the
variable or in the TextBox; if it is numerical or string values?

(43)

Chapter Two
Data

Branching

(ISnumeric) function examples; and their results.


The command

The result

MsgBox IsNumeric("youssif")

(False)
Since the value between the
parentheses is non-numeric

MsgBox(IsNumeric(10))

(True)
Since the value between the
Parentheses is numeric

MsgBox IsNumeric(a)

(True)
If the value of the variable (a) is
numeric

MsgBox
IsNumeric(textbox3.text)

(True)
If (TextBox3) contains a numerical
value

Table (2-6) Examples of the function (ISnumeric)


We deduce that the function (Isnumeric) has an input or an argument between
parentheses and a logical output (True) or (false).
We will explain in detail the functions in chapter (4).
The second method: Using the (Try..catch) statement as follows:

Original code

The code when


error occurs

(44)

Chapter Two
Data

Branching

The code is written to perform the following:


1. To display a message box informing the user to enter a numeric
value instead of a string value or a blank value.
2. The (Focus) is a (Method) for the TextBox and is used to set the
cursor focus inside this TextBox.
3. The last line of code makes the property (Text), equal to a blank
character string.

We may need to test more than a conditional expression together in the same
(If) statement, in this case we link between extra conditions by using the logical
operators (And) or the logical Operator (Or).
The logical Operator (And) . If both conditional expressions are (True),
then the result is (True).
The logical Operator (Or) . If either conditional expression is (True), then
the result is (True).
Examples of using the logical Operator (And) assuming that variable (A) and
variable (B) are Boolean variables.
Conditional expression

Result

A= TRUE AND B= TRUE

TRUE

A=TRUE AND B=FALSE

FALSE

A= FALSE AND B= TRUE

FALSE

A= FALSE AND B= FALSE

FALSE

(45)

Chapter Two
Data

Branching

Examples of using the logical Operator (Or) assuming that variable (A) and
variable (B) are Boolean variables.
Conditional expression

Result

A= TRUE OR B= TRUE

TRUE

A=TRUE OR B=FALSE

TRUE

A= FALSE OR B= TRUE

TRUE

A= FALSE OR B= FALSE

FALSE

as
shown in figure (2-6).

Figure (2-6) the required Forms window during execution


It is required that by clicking on the command button () , the
words or is displayed in (Label4) according to the following:
If each degree is greater than or equal to 50 then the word is
displayed.
If any of the degrees is less than 50 then the word is displayed
Refer to exercise (2-2) you will find that, it is the same as this exercise, except
that the conditional expression will test the two degrees together.

(46)

Chapter Two
Data

Branching

The code becomes as follows:

Using (And) requires that (both conditional expressions are


(True), so that the final result is (True).
The result of the condition between (If) and (Then) should be a
Boolean result which is (True) or (False).

One of the two degrees is greater than or equals 50 then the word is
displayed.
Both degrees are less than 50 then the word is displayed
The code becomes as follows

Notice the difference while using (Or) rather than (And)

(47)

Chapter Two
Data

Branching

The (Select Case) statement is similar to (If ThenElseIf) statement


however, it is more effective when the branching depends only on the value
of one variable, thus it makes program code more readable and efficient.

The syntax of (Select Case) statement

Select Case Variable


Case value1
code

Case value2
code

Case value3
..
..

code

Case else
code

End Select

If we draw the flowchart that is compatible with (Select..Case)


statement it will be as shown in figure (2-7).

(48)

Chapter Two
Data

Branching
start

Get D

Case D

Output
""

Output "
"

Output
""

End

Figure (2-7) the Flowchart when using (SelectCase) for exercise (2-7)
Figure (2-7) illustrates more than two possible paths (branches) out of the
decision point; which is a comparison that evaluates a question about the
value of variable (D); and according to this value the branching of code
differs.
The code becomes as follows:

(49)

Chapter Two
Data

Branching

as
shown in figure (2-8).

Listbox1
Label1

Label5

Label2

Label6

Label3

Label7

Label4

Figure (2-8) the required Forms window for exercise (2-8)


By clicking an item from (ListBox1) items, you select a figure from a list
of figures displayed, and the corresponding number of sides, faces and,
vertices of this figure is demonstrated.
The code is written to demonstrate how (SelectIndexChanged) event is
used to determine when the index of selected item in ListBox1 is
changed; (SelectIndexChanged) is the default event for the control
(ListBox1). This event occurs whenever an item from (ListBox1) is
selected.
You can add items in the ListBox using the (Items) property in design
mode. Knowing that items in the listbox are arranged so that the first
item ranked zero and the second item ranked 1, and so on.
We use the property (SelectedIndex) to determine the index of the item
that is selected in the ListBox. When the value of this property is (1) this
means the second item is selected, and so on.

(50)

Chapter Two
Data

Branching

Write code in (SelectedIndexChanged) event for (Listbox1) as follows:

Assign an index to the


specified item in variable(X)
Code written when index
value is zero (cube)

Code written when index value is


1 (parallelogram)

Code written when index value is


2 (Triangular pyramid)
Code written when index
value is 3 (cylinder)

Run the program.


Select one figure from the dropdown list of the (Listbox) and note the
displayed results.
Review what you have studied in mathematics on solid geometry to
ensure results.

(51)

Chapter Two
Data

Branching

1- In science, you have learned that for each element there is an atomic
number, a symbol and a mass number, create a (Project) containing a (Form)
as shown in figure (2-9):

Groupbox1
Label4

RadioButton1
RadioButton2

Label5

RadioButton4

Label6

RadioButton4

Figure (2-9) the required User interface

Selecting one of the elements shown and, clicking on the command button,
will display the corresponding atomic number, symbol and mass number of
this element.

Write the code in (Click) event procedure for the command button as
follows:

(52)

Chapter Two
Data

Branching

2- In geography, you have learned many concepts on Galaxies, planets


and stars ... etc, create a project containing a form as shown in figure (2-10):

ComboBox1

Textbox1

Figure (2-10) the required User interface


It is required that when selecting one of the elements of a ComboBox, the
corresponding definition appears in the TextBox.

(53)

Chapter Two
Data

Branching

1.

Set the value of the property (Multiline) for the (TextBox) to true.

2.

Add the following items (Galaxy - Planet-Moon-Star- Meteoroid - falling


star) for the (ComboBox) control through the property (Items).

3.

Write the code in the (SelectedIndexChanged) event procedure for the


control (ComboBox) as follows:

We have assumed when writing (Code) , the organization of items within the
(ComboBox) where the first item has an (index) 0, the second item has an
(index) 1 and the third item has an (index) 2, ..and, so on.

(54)

Chapter Two
Data

Branching

First: State whether the following statements are true (T) or false (F):
(1)

The number of possible branches when using (If ...Then..Else)

)2(

In (IF) statement the code that follows (Else) is executed when the result

( )

)3(

The operator (&) is one of the logical comparison operators.

( )

)4(

Using the comparison operator (Or), the results of all conditions must be

( )

)5(

The (Select Case) statement is used to test more than one conditional

( )

)6(

If the value of variable (X) is 15 and value of variable (Y) is 350 then the

( )

)7(

The use of (Else) keyword is optional in (If) statement.

( )

)8(

The (and) operator requires that, the result of the two conditions must be

( )

)9(

The property that determines the selected item in a (Listbox) is

statement is 2.
of the conditional expression is (True).

(False) so that the final result is (False).


expression in one conditional statement.

result of the conditional expression (X>10 And Y <500) is false.

(True) so that the final result is (True).


(SelectedIndex).

)10( The (Select..Case) statement is used if there are more than two possible
branches.

(55)

( )

( )
( )

Chapter Two
Data

Branching

Second:
The following code calculates the area of a circle of radius (R).Rewrite
this code in left column so that; the message will be
displayed; when you enter a negative number in (TextBox1); whose
value is assigned to variable (R).

Third: Consider the following code, which determines the appropriate


evaluation of each value (degree) entered in (Textbox1).

This expression is equivalent to


>=85 and <=100
In this case the value of deg is
limited from 85 to 100

(56)

Chapter Two
Data

Branching

Write down the result displayed in (Label1); when you enter the following
values (degrees) in (Textbox1).

Degree
30

Result

84
64.4
-33
zero
114.3

Fourth: The following code is written to solve the first degree equation (y = 3x
+ 2) and gives correct results when you enter numeric values in the (TextBox) ;
but an error occurred while running (Runtime Error) when you entered string
values in the (TextBox). Write the code after solving this problem using an
additional (If) statement, that displays the message " " in a
(label ) control.

(57)

Chapter Two
Data

Branching

Fifth: Choose the result of executing each of the following codes:

The code

The result

a. One
b. Two
c. three

a. True
b. False
c. 15

a. Youssif
Ahmed
b. Ahmed
Youssif
c. Ahmed

a. AXB=63
b. 7X9=63
c. 7X9=A*B

a. First
b. Second
c. Forth

(58)

Loops and Timers


By the end of this chapter, student will be able to:
Use (For.Next) statement to repeat a section
of code a specified number of times.
Use (Do.Loop) statement to keep running a
section of code undefined number of times.
Use the (Timer) control to execute a section of
code at regular intervals.

Chapter Three
Data

Loops and Timers

In previous chapter, we have learned how to execute a series of statements,


based on the evaluation of a conditional expression. In this chapter, you will
learn how to repeat a set of statements many times (which is called Looping)
using (For loop) and (Do loop), you will also learn how to execute a set of
statements at regular intervals using the (Timer) control.

The syntax of the (ForNext) statement


For Variable = Start To End
VB code
Next

The (For...Next) statement should start with the Keyword (For) and end with the
Keyword (Next). A variable is declared in the loop (it is called counter variable);
it has a start value and end value. The statements are repeated inside the loop
until the counter value equals the end value.
We will be skilled on using the For...Next statement; through the following
progressives exercises:

(60)

Chapter Three
Data

Loops and Timers

as
shown in figure (3-1).

Figure (3-1) the required Form window for exercise (3-1)


By clicking the command button, it is required to display the numbers
from 1 to 3 in a Message box.
Write code that depends on the Flowchart as shown in table (3-1).

Start
M=1

Fals
e

M<=3
Tru
e
msgbox
M

M=M+1

End

Table (3-1) Flowchart and code written for exercise (3-1)

(61)

Chapter Three
Data

Loops and Timers

Tracking the code as shown in the table (3-2)


Dim M As Integer
For M=1 to 3
Msgbox M
Next

Msgbox M
Next

Msgbox M
Next

0
1 (The starting value )
1
The increment of M with 1 (M=M+1)
is the value of M greater than the end value (the
result is, False)
2
The increment of M with 1 (M=M+2)
is the value of M greater than the end value (the
result is, False)

1
-

3
The increment of M with 1 (M=M+3)
is the value of M greater than the end value (the
result is, True)

3
-

2
-

Table (3-2) Tracking program code for exercise (3-1)


Each time Visual Basic encounters the (Next) statement, it increments the
counter variable and then, compares the new counter value to the end
value of the loop. If counter is greater than the end value, the For loop
ends and exits the loop of value equals 4.
Start running the program and click the command Button ( 1
3 ) .
Note that the message Box appears and displays the number 1,and when
clicking the OK button another message Box appears that displays the
number 2 and so on till the counter passes the number 3 as shown in
figure (3-2).

Figure (3-2) the Message Box

(62)

Chapter Three
Data

Loops and Timers

Add the TextBox (TextBox1) to the form as shown in figure (3-3).

TextBoxs name: TextBox1

Figure (3-3) the required Form window for exercise (3-2)


Modify the code so that the numbers appear in the (TextBox) as follows:

1. The statement inside the loop is written so that the value of

variable (M); is placed side-by-side next to what already exists in


the (Textbox), this is done by typing the concatenation operator
(&) used to join multiple strings into a single string.

2. When you write the line of code me.textbox1.text = m; you cannot

remark the change in value of variable (M); during the

execution of the program, you only notice its last value


displayed which is 3.

(63)

Chapter Three
Data

Loops and Timers

Start running the program.


Click the command Button; a TextBox appears in the Form as shown in
figure (3-4).

Figure (3-4) the Form window after clicking the button in run mode
Click the (Button) again you will find that the numbers from 1 to 3 are
added once again as shown in figure (3-5).

Figure (3-5) Numbers in the TextBox after you click the button again
So this statement (Me.TextBox1.Text = "") is added before the loop to clear
the contents of the TextBox.
You can also display numbers within (TextBox) so that each number can
appear in a new line by following:
Change the property (Multiline) to (True) in design mode; to allow more
than one line.
Modify the code inside the loop by adding a key input as follows:

(64)

Chapter Three
Data

Loops and Timers

Clear the content of textbox

String constant used to add: the (enter key) symbol and a new line
vbCrLf=Visual Basic Carriage Return Line Feed

Start running the program. then click the command Button


(3 1 )

Figure (3-6) the required numbers appear through lines


Click the button more than once, you will notice that TextBox content is
cleared and numbers are rewritten once again.

The code will be as follows

(65)

Chapter Three
Data

1. The

variable

Loops and Timers

name

(product)

is

declared;

to

store

the

multiplication product; at each time the variable (M) changes its


value.

2. The variable name (str) is declared; to store the multiplication

sentence (1x3= or 2x3= etc ) as a string, at each time the


variable (M) changes its value.

3. The TextBox content is joined with: the value of the variable

(str), the value of the variable (product) and, the concatenation


operator (&).

4. You can write the code without using these variables as follows:

So, why we use the variables?

To facilitate the tracking of code for a Program

Start running the program and, click the command Button, the
multiplication table of number (3) will be displayed as shown in figure (37).

(66)

Chapter Three
Data

Loops and Timers

Figure (3-7) the multiplication table of number (3)

as shown in figure (3-8).

Figure (3-8) the multiplication table of any number you enter in a (TextBox)

(67)

Chapter Three
Data

Loops and Timers

The code will be as follows

Note that number 3 is replaced by the variable (NUM); which contains the
value of the (TextBox).

In previous exercises, the starting value of the counter was always smaller than
the end value, and the increment of the variable was always equal to 1. Using
the (Step) keyword, you can increment or decrement the counter through the
loop; by the value you specify.
To decrement the counter variable, use a negative (Step) value. When you do
this, you should specify an end value that is less than the start value.
The start or end or step values can be integers or decimal numbers or variables
and the syntax is as follows:

The syntax of the (ForNext) statement


For Variable = Start To End [Step n]
code
Next [Variable]

(68)

Chapter Three
Data

Loops and Timers

The syntax of the (ForNext) statement, includes some words


written between parentheses [ ]; this means it is optional to write
these words; in case you dont write any word; a default value

will be taken.
For example, if you do not write the keyword (Step), by default

a value equals 1 is taken. And, if you do not write a variable


name with the (Next) keyword, it takes the same variable
specified with the (For).

To display the
odd numbers
from 1 to 10

To display the
even numbers
from 2 to 10

To display the
numbers
divisible by 3
from 3 to 20

To display the
even numbers
descending from
10 to 1

To display the
numbers from
1.50 to 0.5
decremented by
0.05 each time

To display the
numbers from 1
to the value of B
at increasing
value of C

Table (3-3) Examples on using the (For) statement

(69)

Chapter Three
Data

Loops and Timers

From the examples in the previous table we deduce that:


1. You can specify the rate of increment of the variable; using the (Step)
keyword followed by a number (increment value).
2. In case of, the starting value is greater than the end value; the rate of
increment should be negative (example 4 and 5).
3. The start or end or step values can be decimal numbers; in this case, you
must declare a counter variable that accepts decimal fractions like the
type (Single) (example 5).
4. The start, end or step values can be variables (example 6).
5. We could not write a name for the counter variable after the (Next) as in
the examples.

We have learned how to repeat a set of statements many times using the
(ForNext) statement .But the (Do While...Loop) is used to execute statements
for an undefined number of times; until a certain condition is met. This is useful
if you do not know the number of iterations (repetitions) ahead. For example
the process of entering names in a (TextBox) is repeated a number of times
while; the exit from this loop can be done by entering a particular word in the
Textbox.

The syntax of the (Do .While) statement


Do While conditional expression
code
Loop

The (Do While . . . Loop) keeps executing the code; as long as the conditional
expression is (True).
We will practice how to use this statement; through the following exercises:

(70)

Chapter Three
Data

Loops and Timers

as shown
in figure (3-9).

Listbox1

Button1

Figure (3-9) the required Forms window


When clicking the command button, an (InputBox) should appear so
that the user can enter his first name as shown in figure (3-10).

Figure (3-10) the (InputBox) to receive input from the user


After writing his first name ,the user clicks the (ok) button or press
enter from the keyboard; the name appears in (ListBox1) .An (InputBox)
will be displayed again so that, the user enters his second name and so
on. If the user enters the word (), he terminates the process of
entering values.

(71)

Chapter Three
Data

Loops and Timers

In this exercise we notice that, (Loop) of unknown number of iterations is


used; such a loop will be terminated when we enter the word ".
The (Code) is written in the (Click) event procedure for the command button
(Button1) as follows:

Conditional expression is
False in the case of equality

1. Use the function (InputBox) to receive a value from the user


and return this value in a variable of type (String). Therefore
variable (X) contains what has already been entered.

2. The conditional expression used with (Do While) remains

(True) as long as the value of (X) does not equal the word
" .

3. When we enter the word "the conditional expression


becomes (False) and we exit the loop.
Start running the program and, click the command Button () .
Enter your first name and then the second name and so on, for a
number of times and then type exit.
What do you notice after entering the word ", you notice that the
word is added to the ListBox ,and you exit from the loop as shown in
figure (3-11)

(72)

Chapter Three
Data

Loops and Timers

Figure (3-11) the word "appears in the ListBox


The word "is added to the ListBox, although it represents the condition to
exit from the loop; this is done because the statement that adds a name in the
List takes place before attaining the start of the loop (where the conditional
expression is tested). To prevent displaying the word in the ListBox, we
add a line of code after entering the name and before displaying it in the ListBox
;as in the following code:

The shown condition implies that: when the value of variable (X) equals the
word

then the statement (Exit Do) will be executed; which means the

immediate exit from the loop, without waiting for the test of conditional
expression in (Do..While).
Try running the program again to verify the results of execution.

(73)

Chapter Three
Data

Loops and Timers

You should write the word in the InputBox with the same

spelling written in the code. The misspelling when writing e.g.


(writing the word instead of the previous), leads to nontermination of the loop. We can avoid making mistakes by
writing the condition as follows:

Do While X< >" " And X< >""

You can also add other words, for the exit of the loop , as we
already did e.g. :

Do While X< > " " And X< > " " And X < > " "And
X < > ""

The logical operation (And), implies the execution of what

inside the loop as long as the value of X is not equal to the

word" "And, not equal to the word " " And, not equal to
the word " " And, not equal to the word " " .

(74)

Chapter Three
Data

Loops and Timers

The timer control is used to run code at regular intervals or to execute


code for a specified time, it is very useful when repeating a code related to
time .When you add the (Timer) control to a form ,you have to specify its
main Properties values as follows:

Enabled

False

Determines if the Timer works

If Enabled is set to True, Timer is active


If Enabled is set to False, Timer is not active
And can be set programmatically through code

Interval

100

Determines the number of milliseconds between ticks


of the Timer (one second = 1000 milliseconds)

Table (3-4) Properties of the (Timer) control


The (Tick) event is associated with the Timer control; and means that the
time assigned in the Interval property has passed. When you double click
the timer control; you can add code to the Tick event handler that presents
the default event of the timer.

as shown in figure (3-12).

Label1

Figure (3-12) the required Form window for exercise (3-6)

(75)

Chapter Three
Data

Loops and Timers

Create a new project.


Add the object (Timer) on Form1, as well as the object (Label1) as
shown in figure (3-13).

Label1 control

Timer1 object doesnt


appear on the Form
Change the value of (Interval)
property to (1000)

Change the value of (Enabled)


property to (True)

Figure (3-13) the required Form window for exercise (3-6)


Perform the modifications required to change the properties values of
the displayed controls.
Adjust the Properties of Label1 control so that it appears appealing.
Double click (Timer1) control, and activate the Tick event handler (the
default event of the timer), then write the code as follows.
The event (Tick) for Timer control

(76)

Chapter Three
Data

Loops and Timers

The result of the property (Now) is assigned directly to property (Text) of Label1.
Because the property (Now) contains The Date and Time of the computer.
Start running the program; the date and time appear on the form after
1000 millisecond or (1 second), and the new values of date and time
reappear after the next second and so on.
Then the code written for the event (Tick) displays the Date and Time, every
second, it shows the change in seconds and looks like a digital clock.
The (Label) control displays only the time, if the property (Now) is replaced by
the property (TimeOfDay) as shown:

You can programmatically set the (Timer) to be ON or OFF; by

adjusting the property (Enabled); e.g. click (Button1) to stop the


timer (Timer1) as shown:

(77)

Chapter Three
Data

Loops and Timers

1. Create a new project so that the form window contains a (Label) control
containing the text " "and two Command Buttons .When you run the
project; the (Label) appears for half a second then disappears for half a
second and so on. When you click the Button, the (Label) appears
permanently without disappearing. When you click the Button the
(Label) reappears and disappears again as shown in (3-14):

Figure (3-14) the user interface required to show or hide the (Label) control

Add to the Form the Timer control and adjust its properties as
required.
Insert the appropriate code in the Timers Tick event handler to
maintain the appearance and disappearance of the Timer as follows:

First Method

Second Method

The (Not) operator: is a logical operator used to

get the opposite of what is inside the parentheses

(78)

Chapter Three
Data

Loops and Timers

2. Create a new project so that the forms window appears as shown in


figure (3-15).
Enter a number in the TextBox ,then click the Button , odd
numbers are listed in the ListBox and, sorted in ascending order so that the
greater number in the list will be the number already entered in the Textbox.
And when you click the Button , even numbers are listed in the
ListBox and, sorted in
ascending order so that the
greater number in the list will
be the number already
entered in the Textbox.

Figure (3-15) the required user


interface to display odd
numbers or even numbers

Programmatically the code written in the click event handler of the


Button can be done with two methods as follows:

First Method

Second Method

Write the appropriate code in the click event handler of the Button
that display the even numbers you can do it yourself.
3. Perform the modifications required on exercise 2 to display the numbers
in Descending order instead of Ascending.

(79)

Chapter Three
Data

Loops and Timers

4. Create a new project so that the forms window appears as shown in


figure (3-16).
When you enter a number like 5 and then click on the button

the

sum

of

odd

numbers will be displayed in


Label3.
And when you click on the
button
the sum of even numbers will
be displayed in the same way.

Figure (3-16) the user interface to display the sum of odd or even numbers

Programmatically the code written in the click event handler of the


Button can be done with two methods as follows:

First Method

Second Method

Write the appropriate code in the click event handler of the Button

that display the sum of even numbers you can do it


yourself.

(80)

Chapter Three
Data

Loops and Timers

First: Choose the correct answer for each of the following:


1. The purpose of using the Do while Loop statement is :
a) Repeat the code until the conditional expression becomes (True)
b) Repeat the code as long as condition is (True)
c) Repeat the code as long as the condition is (False)
2. What is the function of Next statement in the (For ..Next ) loop :
a) Increase the value of the counter variable with the increment
value
b) Compare the increment value with the end value of the loop
c) All of the above
3. The best Loop used when you know in advance the number of iterations
a) Do while
b) For ..Next
c) Select ..case
4. After executing the following code what will be displayed in the TextBox
(txt_display) is:
a) 2
b) 246810
c) 2345678910
5. After executing the following code what will be displayed in the Label
(lbl_display) is
a) 10
b) 11
c) 0
6. After executing the following code what will be displayed in the Label
(lbl_display) is
a) 5
b) 10
c) 15

(81)

Chapter Three
Data

Loops and Timers

Second: State whether the following statements are true () or false (X)
1- The command Msgbox.3 & X & 3 displays a message box
containing number 9.

2- The value of (M) after the execution of the loop (For M=3 to 1
Step -1) is 0.

3- If you do not write (Step) with the (For ...Next) statement, it


means that the increment value is zero; by default.

4- If you specify a value of 2500 to the property (Interval) for the


control (Timer); it means 2.5 seconds.

5- You can exit from the loop (Do ...While) based on the conditional
expression.

Third: What will be the value of the variable (r) after the execution of each of
the following code?

( 0.5 1 1.5 )
( overflow 2
( 10 5

(82)

0 )

0 )

Procedures
By the end of this chapter, student will be able to:

Declare the (Sub) procedure.


Call the (Sub) procedure.
Use (Parameters) when declaring a (Sub)
procedure.
Declare a Function.
Call a Function.
Differentiate between a Sub Procedure and a
Function.
List the reasons for using Sub Procedures or
Functions.
Differentiate between variable, constant, and
Function.
Write three of the names of some Predefined
Functions

Chapter Four
Data

Procedures

Dear Student, when adding a new form window, it creates a new (Class) with the
same form name .Within the scope of this (Class), we can declare Event
Procedures as well as variables and constants, that can be declared either within
the scope of the (Event procedures) or within the (Class), also we can declare
what so-called (Block construct), such as (If ... then) statement, and (For ... next)
statement, and others.

Figure (4-1) the Elements declared in the (Code Window)


Note that the user interface will appear as shown in figure (4-3)

Figure (4-2) user interface

(84)

Chapter Four
Data

Procedures

In Figure (4-1) the following elements are declared


1 - A Class of name (Form1).
2 - Variables of names (total, i).
3 - Event procedures of names (Button1_Click, Button2_Click).
You can also declare what so-called (Procedures); this declaration is done only
once and then, you call the procedure many times from anywhere in your
program; which avoids code duplication in places where procedures are called.

Procedures are set of programming statements or units of code.


Procedures must be called by their names, calling a procedure causes
the program to execute procedure's statements or code.

There are two types of procedures in Visual Basic .NET: Sub procedures and
Functions procedures. Sub procedures do not return a value, while Functions
return a value.

You can declare a Sub procedure in a class; if we had a code that will be
repeated in more than one place in this Class; as well as for the organization of
this code, and so it will be easy to read and understand. And then modify it if
necessary.

Sub Name(Parameters)
Code

End Sub

The declaration of a Sub procedure has the following Format:


1- A Sub procedure begins with a (Sub) statement.

(85)

Chapter Four
Data

Procedures

2- A (Name) follows the word Sub; it is the name of the procedure.


3- A set of parenthesis ( ) follows the name; in between the parenthesis is an
optional Parameter list. A parameter is a special variable that receives a
value being passed into a procedure, when it is called.
4- A Code or set of commands and instructions will be executed when calling
the (Sub) procedure.
5- An End sub

The Code written within each event procedure for (Button1_Click) and
(Button2_Click) is repetitive ; except for the starting value written in
each repetition ;where the value in the ( )button starts by (2), and
in the ( )button starts by (1) as shown in figure (4-1).

Dear student, use the Sub procedure to avoid code duplication as shown in
figure (4-3)

Calling a (Sub) Procedure

Calling a (Sub) Procedure


Declaring a (Sub) Procedure

Code executed when you call the


(Sub) procedure

Figure (4-3) declaring and calling a Procedure

(86)

Chapter Four
Data

Procedures

In figure (4-3) a sub Procedure has been declared of name (ShowOddOrEven) ,


the code written in the scope of this Sub Procedure; causes a series of
statements to be executed when calling this procedure.
The names of the procedures have been called (written) in both event procedure
(Button1_Click) and (Button2_Click).

When testing the program, we find that both buttons, the ()


button and the( ) button; when clicking any of them, give the
same result, because the starting value of the iteration (repetition) in
both procedure has the same value 1. As shown in figure (4-4) and
figure (4-5).

Figure (4-4) user interface

Starting value of the


repetition

Figure (4-5) Part of the window code

(87)

Chapter Four
Data

Procedures

To solve the previous problem ;the procedure (ShowOddOrEven) receives


values known as arguments, these arguments are the values (1) or (2) being
passed into the procedure when calling it .These arguments are used to specify
whether the odd numbers will be displayed or the even numbers. This is done by
adding the variable (Start) that will be called later.
as shown in figure (4-6) and figure (4-7).

Declaring a Parameter

Using a Parameter

Figure (4-6) declaring a Parameter


In figure (4-6) a sub Procedure of the name (ShowOddOrEven) has been
declared and a Parameter (a special variable that receives an argument being
passed into the procedure ) named (Start) has been also declared and used in
the code to specify the starting value of the iteration (repetition), accordingly it
displays odd or even numbers.

Setting an Argument value

Figure (4-7) Passing Arguments to Procedures


In figure (4-7) the sub Procedure (ShowOddOrEven) has been called twice, given
a different value in each time, to specify what will be displayed. The odd
numbers or the even numbers, these given values are called arguments.

(88)

Chapter Four
Data

Procedures

When testing the program, we find that both buttons, the ()


button and the( ) button when clicked, give different results as
shown in figure (4-8) and figure (4-9).

Figure (4-8) when clicking the ( )button

Figure (4-9) when clicking the ( )button

(89)

Chapter Four
Data

Procedures

In the procedure declaration, we can use more than one Parameter.

A Parameter allows the calling code to receive values; that doesnt


exist in the procedure and, unidentified in advance; but specified
when you call this procedure.

Dear student, you can develop the sub Procedure of name (ShowOddOrEven)
that receives the start value and end value in the iteration (repetition); as
shown in figure (4-10).

Declaring a Parameter
Using a Parameter

Figure (4-10) the declaration of more parameters


It is clear that two values are given when calling the procedure
(ShowOddOrEven) as shown in figure (4-11)

Calling the procedure


(ShowOddOrEven)
Giving two values

Figure (4-11) Calling the procedure (ShowOddOrEven )

(90)

Chapter Four
Data

Procedures

You can call the Procedure any number of times.

You can also adjust the display of odd and even numbers; as well

as setting their range. For example, if the given values are (5, 35)
the odd numbers from 5 to 35 will be displayed .If the given values
are (8, 45) then the even numbers from 8 to 45 will be displayed
as shown in figure (4-12).

Display the odd numbers from 5 to 35


Or

Display the even numbers from 8 to 45


Figure (4-12)

(91)

Chapter Four
Data

Procedures

We declare a Function if we have a code that returns a value needed in the


program; for example: Circumference of a circle, Area of a square, net salary of
the employee, Tax payable.etc. So that it can be used during the execution of
program instructions or as output to the user.

Function Function Name (Parameters) As DataType


Code
Return Value
EndFunction
Where:
1- The function name follows the word Function.
2- Inside the parenthesis is an optional list of Parameters used in the code
3- Following the parenthesis is As Datatype. The datatype listed is the part of
the declaration that determines the data type of the value returned by the
function.
4- A Code or set of commands and instructions that will be executed when
calling the Function.
5- The value returned by the function.

(92)

Chapter Four
Data

Procedures

Dear student, with the help of your teacher do the following:


1- Design a Forms window as shown in figure (4-13).

Figure (4-13) User interface


2- Open the Code Window, press (F7) key then type the Code as shown in
figure (4-14).

Figure (4-14) The code window where the function (sum) is declared

(93)

Chapter Four
Data

Procedures

Dear student, we declared the (Sum) Function; of Data Type


(Single) that receives two values from the function variables
(First and Second).
A variable named total have been declared of type (Single).
The sum of the two values First and Second will be assigned to

the variable total.


After the function executes, the return statement sends a value
back to the statement and it is assigned to total.
The value total is stored in the name of the function (Sum) as will
be seen when it is called.

3- Create an event procedure for Button1, and then type the code as shown
in figure (4-15).

Figure (4-15) calling the (sum) function

The variables (x) and (y) have been declared and the input values
from a user are assigned to each of them in (TextBox).
The value of the (Sum) function has been assigned to the Property
(Text) of (Label4) control after receiving the two values (x), (y).

(94)

Chapter Four
Data

Procedures

Variables: We can assign values to Variables; during the


declaration and the execution of the Program instructions, as well
as using these values stored.
Constants: We can assign values to Constants; during the
declaration only, as well as using these values stored.
Functions: We cannot assign values to Functions, but function
can be called producing a value that is stored, as well as using
this value stored.

4- Press (F5) key then input the values as shown in figure (4-16).

Figure (4-16) User interface


Dear student, the previous example shows that you can:
1. Declare a Function.
2. Determine its Parameters.
3. Specify the Function type.

(95)

Chapter Four
Data

Procedures

4. Write Code within this Function.


5. Return a value using the Return statement.

It is preferred when naming Functions; to give names related to their


functionality

The declaration of the function (Factorial) ; to calculate the factorial of a number


as shown in figure (4-17).

Figure (4-17) the function (Factorial) to calculate the factorial of a number


The declaration of the function: (Factorial), and the Parameter (Number).
Where the output of this function is an (Integer); also the variables (i) and
(res) are declared; where the variable (i) is a counter for the iteration
process, and (res) to store the factorial calculation.
Calling the function (Factorial)

The call of the function (Factorial) through a (MessageBox)


Calling the function (Factorial); giving a value (5) then displaying the output
through a (MessageBox).

(96)

Chapter Four
Data

Procedures

You call the function (Area); to calculate the area of a circle as shown in figure
(4-18).

Figure (4-18) the function (Area) to calculate the area of a circle


The function (Area), and the Parameter (radius) have been declared; and the
output of this function is declared as (Single); also the variables (x) is
declared as a constant that stores the value (22/7) ,and the variable (res) is
declared to store the calculation of the circle area.
Calling the function (Area)

The call of the function (Area) through a (MessageBox)


Calling the function (Area); giving a value (5) for the radius, then displaying
the output in a message box.

Predefined functions are functions defined in programming languages called


when a program is executed.
We will demonstrate some of these functions:
1. The function (Show) declared within the class (MessageBox); shows a
Message box .The content of this function is determined by the
Parameters given, for example:

(97)

Chapter Four
Data

Procedures

When calling the function, a Message box will be displayed as shown in


figure (4-19)

Figure (4-19) the Message Box


2. The function (IsNumeric) can test a value; if it is numeric or not, where
the result of this function will be (True) when the value is numeric; and
(False) when the value is non-numeric.
Calling the function as follows

When calling the function; the displayed result will be (False) as the value
assigned to it is Five and cannot be converted to a numeric value.

All functions must be written on the right side of the assignment


equation to get the results of these functions.
There are some functions that do not take any parameter while
each function must return a result (output).

The (Sub) Procedures are not used in the assignment statement.


The Event Procedure is considered a (Sub) Procedure.
Parameters given to any Procedure can be (an abstract value or a
variable or a constant or a function).

(98)

Chapter Four
Data

Procedures

First: State whether the following statements are true ( ) or false (X)
1- The Procedure is declared once, while can be called any number
of times.

2- The Predefined Functions should be declared first.

3- The return value of the function (Area) is (Single) as


demonstrated in the declaration:

4- The Parameters of a Procedure can receive values from outside a


procedure.

5- The Sub Procedures are used on both sides of an assignment


statement, while the functions should not be used in any side.

6- The Sub Procedure doesnt return any value, while the function
returns a value.

7- It is required when declaring Procedures; that at least one


Parameter is used.

8- Parameters given to any Procedure can be (an abstract value

Function Area(ByVal radius As Single) As Integer

or a variable or a constant or a function).


Second: Type in front of each statement in column (b), the appropriate number
of column (a)
Serial
A
1
Sub Procedure

Function

Variables

Constants

Serial

B
Is used on the right side of
the assignment statement
and does not have any
value.
Is used on the right side of
the assignment statement
and a value is assigned to it
in declaration only
Is never used in the
assignment statement
Is used on both sides of the
assignment statement

(99)

Chapter Four
Data

Procedures

Third: From the demonstrated code extract the following:

1- Procedure Name:
2- Parameters given to this Procedure and their types:
Fourth: From the demonstrated code extract the following:

1234-

Procedure Name:
Parameters given to this Procedure:
The return value:
The Data type for:
a- A function
b- Parameter given to a function c- the return value

Fifth: From the demonstrated code extract the following:

1234-

Procedure Name:
Parameters given to this Procedure:
The return value:
The Data type for:
a- A function
b- Parameter given to a function c- the return value

(100)

Chapter Four
Data

Procedures

Sixth: Write down if the following is a (Sub) Procedure or a Function:


A-

.....................................................
B-

.....................................................
C-

.....................................................
Seventh: Extract the names of the Functions from the following code:

.....................................................
.....................................................

(101)

Chapter Five
Cyber bullying
By the end of this chapter, the student will be able to:

Define Cyber bullying.


Identify the electronic media of cyber bullying.
Distinguish between cyber bullying forms.
Follow correct behaviors against cyber bullying.
Ask for help from individuals and
organizations responsible for safety when
vulnerabilities occur.

Chapter Five
Data

Cyberbulling

PREFACE
Ethics related to the Internet and all means of information and communication
become one of the topical issues of interest that concerns individuals,
communities and countries.
So in this chapter we look for raising the awareness of our sons towards the
importance of ethics dealing with the Internet, and provide them with
information and skills required to upgrade their personnel safety regarding
online cyber bulling.
Through the Internet we can learn ..., entertain...., communicate and talk
together.
But:
We can also acquire wrong information and know bad people.

An intentionally aggressive behavior using electronic media for the purpose of:
1. Harassment
2. Annoyance
3. Embarrassment
4. Intimidation
5. Threat
6. .etc. .

Electronic attackers use the following media:


1.
2.
3.
4.
5.

Electronic Mail
Electronic forums
Instant Message
Blogging
Social media sites such as Facebook

Forms of cyber bullying include:


1. Anonymity: The use of pseudonyms to hide attacker personality using
electronic media for doing impunity actions.
2. Harassment: Aggressive messages directed against one or more persons

(2)

Chapter Five
Data

Cyberbulling

using electronic media.


3. Cyber stalking: is a type of annoyance using electronic media to stalk or
harass an individual, or a group of individuals frequently.
4. Flaming: the post of aggressive and insulting words using electronic media.
5. Outing: Posting information about a specific person or more improperly.
6. Exclusion: Disregarding one or more person through electronic media.
7. Cyber threats: Sending e-mails that carry threat or menace to one or more
persons.

By following the instructions below:


1.
2.
3.
4.
5.
6.
7.
8.

Do not share a password with anyone.


Set a password that cannot be deduced.
Do not post any private data.
Do not delete hostile or aggressive
messages.
Do not interview any one you met
through the Internet.
Do not send messages when you are
angry.
Inform your parents with what annoy
you when you use the Internet.
The download of software from the
Internet should be done under the
supervision of your teacher or your
parents.

1- AMR said to Yasmin I want to send a message to a friend and I have no email account. Could you give me your user name and password so that I
can send the message?
In your opinion, what can she do?
Answer: She advises Amr not to share a password.

(3)

Chapter Five
Data

Cyberbulling

2- Amr has created his own e-mail account. Yasmin tried finding his
password by writing his name, age and, birthdate then the account was
opened.
In your opinion, what should he do?
Answer: He should set a new password that cannot be deduced.

3- Ramy contributed in Facebook service and published information about


his family also posted his familys pictures and daily activities. A thief
studied such information and knew when there is no person at home.....!
In your opinion, what should he do?
Answer: He should not post any private data.

4- A student complained to his teacher that his friend insulted him in an email message. The teacher said: show me that message; the student said
that he has deleted it. The teacher said: you lost your evidence.
In your opinion, what should he do?
Answer: He should not delete cyber bulling messages.

5- Amr said to his father I came to know someone in a chat room and he
asked me for a meeting.
In your opinion, what was his fathers answer?
Answer: Not to interview anyone you met through the Internet.

6- A dispute happened between two students, and then one of them was
very angry and sent an intimidated and threatening letter to the other.
In your opinion, what should he do?
Answer: He has to be more patient.

(4)

Chapter Five
Data

Cyberbulling

7- A student uses the Internet for doing school activities, through working in
groups with his colleagues and whenever he uses the net , he receives
abusive chat or instant messages .To protect himself from such attack, he
reduces the use of the Internet to avoid such abuse.
In your opinion, what he should do?
Answer: He has to ask his parents for helping him to overcome that
problem.
8- Yasmin has downloaded one of the free programs on her computer; as a
result, dangerous computer virus infections, to the data stored and
belong to Yasmins father, appeared.
In your opinion, what should she do?
Answer: She has to consult her father first, before installing any
program.

(5)

Chapter Five
Data

Cyberbulling

First: State whether the following statements are true () or false (X)
1- Cyber bullying is an intentionally, aggressive behavior using
electronic media for harassment, or aggravation, or
embarrassment, or to intimidate or threaten others.

2- There are no types of cyber bullying within Egyptian society.

3- Anonymity is considered one of the Forms of cyber bullying.

4- An electronic attacker aims to impose psychological pressure on


others using multiple methods through electronic media.

Second: Put ( ) next to the statements that will help you protect yourself from
cyber bullying.
1- Do not share a password with others.

2- The password can be a birthday or something easy to remember.

3- Don't post private information on the Internet.

4- Throw away electronic messages sent from cyber bullies or

attackers.
5- Do not reply to cyber bullies, and do not believe what they
write online.
6- Report about cyber bullying to the competent formations.

Third: A person contributes in one of the social networking sites. Whenever he


communicates with one of the members, or tries to perform a chat or an
instant message, he notices that no one responds to him.
What happens is a form of................ Called ... ... ... ... ....

(6)

Chapter Five
Data

Cyberbulling

Related topics that have already been studied and you can search for
them:
Identification.
Firewall.
Secret codes.
Request for assistance

(7)

Sample Tests

kl

First :State whether the following statements are true (T) or false (F):
1. The number of possible branches when using (If ...Then..Else)

2. The operator (&) is one of the logical comparison operators.

3. If the value of variable (X) is 5 and value of variable (Y) is 7, then the

4. You can call the Procedures only once.

5. The Dim statement is used for declaring (Variables).

statement is 2.

result of the conditional expression (X>=5 And Y <=7) is false.

Second: Choose the correct answers


1- If you specify a value of 3500 to the property (Interval) for the control (Timer);
it means :

a) 3.5 minutes

b) 3.5 seconds

c) 35 seconds

2- Which of the following (SelectCase) statements when evaluated ;its result is


(False),knowing that the value of the variable being tested is 8.
a) Case Is >= 4

b) Case 1 To 6, 8 c) Case Is < 8

3- When you know in advance the number of iterations in a loop (a specific


number of times) ; so the appropriate loop statement is :
a) For...Next

b) If End If

c) Do While...Loop

4- What is the value displayed in the Label control (LblOut) when running the
following code.

Dim i as Integer
For i = 2 To 10 Step 2
lblOut.Text = lblOut.Text & i & ","
Next
a) 2

b) 2,3,4,5,6,7,8,9,10

) 103 (

c) 2,4,6,8,10

Sample Tests

kl

5- Assigning values to constants is done:


a) When you declare constants only.
b) During the the implementation of programs instructions.
c) When you declare constants as well as during the implementation of
programs instructions .
Third: Answer the following

1- Specify the value of each variable after executing the following Code.
Variable

Value

Dim N, K, C As Integer
C = 10
For N = 1 To 10 Step 5
K = K + N
Next
If N >= C Then
C = C + 1
End If

C
K
N

2- Write the order of execution of Arithmetic operations that follow:

Order

Operation

Multiplications and divisions from left to right.

Parentheses starting from inside out

Additions and subtractions from left to right

Exponentials.

) 104 (

kl

Sample Tests

3- Explain the following code represented by the numbers as shown below:

1-
2

) 105 (

Sample Tests

kl

First :State whether the following statements are true (T) or false (F):
1. Use the (If.Then..ElseIf) statement when testing more than one

2. Variables of types (Integer & Long & Double) are used to store

3. The (Or) operator requires that, the result of all conditions must be

4. The (Select Case) statement is used to test more than one conditional

5. The Variable of type (Double) takes the values True or False

conditional expression
integers only.

(False) so that the final result is (False).


expression in one conditional statement.

Second: Choose the correct answers


1- For the function (AddSum( ) );which of the following statements is not correct
when calling this function:
a) X =Y + AddSum()

b) AddSum() = X + Y

c) X = AddSum()

2- For ending a loop; while the condition: (A = 2 ) is reached , the beginning of the
loop will be written as follows :
a) Do While a = 2

b) Do While (a < 2) Or (a >= 2) c) Do While a < > 2

3- Select the error in the following Loop statement:

Dim J As Byte
For J=1 to 500 Step 3
ListBox1.Items.Add( J )
Next
a) You must use the Do. ..While rather than For ...Next
b) It is an endless loop
c) Error in variable type in the loop

) 106 (

Sample Tests

kl

4- The iteration in the For ..Next statement ( For m=10 to 1 Step -2 ) stops
when the value of the variable M:
a) Is greater than the end value
b) Is smaller than the end value
c) Is greater than or smaller than the end value
5- Select the result of the following Arithmetic expression: 2- 2 * (7+2)
a) -16

b) 14

c) 5

Third:Answer the following


1- Rewrite the following code using the (Select ...Case) statement
Dim x As Integer
Select Case x
x = Me.textbox1.text
If x = 0 Then
label1.text =
""

End If
If x > 0 Then
Label1.Text =
""

End If
If x < 0 Then
Label1.Text =
""

End If

End Select

) 107 (

Sample Tests

kl

2- Type in front of each statement in column (b), the appropriate number


of column (a)

Serial

Sub Procedure

Function

Variables

Constants

Serial

Is used on the right side


of the assignment
statement and does not
have any value.
Is used on the right side
of the assignment
statement and a value is
assigned to it in
declaration only
Is never used in the
assignment statement
Is used on both sides of
the assignment
statement

3- Select the type of error in the following Code and then correct as follows

Code

Error type

Dim x As Sangle
Const x As Integer
X=10

) 108 (

Correction

Sample Tests

kl

First :State whether the following statements are true (T) or false (F):
1. The property (SelectedIndex).determines the selected item in a

3. In the If statement (If A>B And B>C..Then ) the result is (True) when

4. The result of the function (IsNumeric) is always (True) or (False).

5. The Variables of type (Integer & Long) are used to store integers only.

(Listbox).
2. The (Select Case) statement is used if there are more than two
possible branches.
(A=3,B=5,C=2).

Second: Choose the correct answer


A) Choose the correct answer

1. The result of the following Code is :

Dim N As Integer
Dim S As Integer
For N = 1 to 100
S=S +N
Next
Label1.Text = S
a) Displaying the numbers from 1 to 100.
b) Displaying the sum of the numbers from 1 to 100.
c) Displaying the product of the numbers from 1 to 100.
2. What is the value displayed in (Label1) control; when executing the following
code:

Dim intNum as Integer = 10


intNum= intNum+2
intNum = intNum Mod 3
Label1.Text = intNum
a) 3

b) 0

c) 4

) 109 (

Sample Tests

kl

3- For ending a loop; while the condition: (A < > 2 ) is reached , the start of the
loop will be written as follows :

a) Do While a = 2

b) Do While (a < 2) Or (a >= 2) c) Do While a < > 2

B) Which of the following is a (Sub Procedure ) or a (Function)

.....................................................

.....................................................
Third: Answer the following questions

1- Specify the value of each variable after executing the following Code.
Bearning in mind that the primary
values for the variables are as
follows:
x = 0, z = 0, j = 1, k = 1, y = 2
Variable

Value

X
Y

If X<Y
Z = K
X = X
Y = Y
Else
Z = K
X = X
Y = Y
End If

Then
+ J
+ 1
- 1
- Y
+ 2
- 2

2- From the demonstrated code extract the following:

) 110 (

Sample Tests

kl

1- Procedure Name:
2- Parameters given to this Procedure:
3- The return value:
4- The Data type for:
a- A function b- Parameter given to a function c- The return value

3- In the following code, determine the cause of the displayed error

The cause of errors :

.......................................................................................
.......................................................................................

The cause of errors :

.......................................................................................
.......................................................................................

) 111 (

You might also like