119
i INDEX Content Page Chapter I :Data 1 Preface 2 1-1 Data Types 3 1-2 Variables 5 1-3 Assignment statement 8 1-4 Constants 15 1-5 The Errors 21 1-6 Priority rules for Arithmetic operations 27 Questions 28 Chapter II :Branching 33 Preface 34 2-1 Branching statement using (If …Then 34 2-2 Branching statement using (If ..Then.. Else) 38 2-3 Branching statement using (If ..Then.. ElseIf) 40 2-4 Using Logical Operators with (If) statement 45 2-5 Branching statement using (Select …Case) 48 Practical Exercises 52 Questions 55 Chapter III :Loops and Timers 59 Preface 60 3-1 (For….next) statement 60 3-2 (Do…while) statement 70 3-3 Using the Timer control 75 Practical Exercises 78 Questions 81 Chapter IV:Procedures 83 Preface 84 4-1 Procedures 85 4-2 Declaration of a Sub Procedure 85

Prep 3 2nd term

Embed Size (px)

DESCRIPTION

Prep 3 2nd term

Citation preview

i

INDEX

Content

Page

Chapter I :Data 1

Preface 2

1-1 Data Types 3

1-2 Variables 5

1-3 Assignment statement 8

1-4 Constants 15

1-5 The Errors 21

1-6 Priority rules for Arithmetic operations 27

Questions 28

Chapter II :Branching 33

Preface 34

2-1 Branching statement using (If …Then 34

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

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

2-4 Using Logical Operators with (If) statement 45

2-5 Branching statement using (Select …Case) 48

Practical Exercises 52

Questions 55

Chapter III :Loops and Timers 59

Preface 60

3-1 (For….next) statement 60

3-2 (Do…while) statement 70

3-3 Using the Timer control 75

Practical Exercises 78

Questions 81

Chapter IV:Procedures 83

Preface 84

4-1 Procedures 85

4-2 Declaration of a Sub Procedure 85

ii

INDEX

Content

Page

4-3 Declaration of a Function 92

4-4 Exercises on using Functions 93

4-5 Predefined Functions 97

Questions 100

Sample Test (1). 103

Sample Test (2). 106

Sample Test (3). 109

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.

Data

(2)

Data

Chapter One

Dear student, we previously learned how to design a program’s 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: (ياسمين تامر - 7/21/1121 are data values of ,(5-أنثى -

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.

Data

(3)

Data

Chapter One

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’.

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).

Data

(4)

Data

Chapter One

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

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

As shown; the statement for setting the Property (BackColor) of the control

(Label1); is displayed in figure (1-3).

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

Object Property Value

Data

(5)

Data

Chapter One

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.

Data

(6)

Data

Chapter One

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

Data

(7)

Data

Chapter One

In this way, we have reserved places in the computer memory (RAM), to store inputs from the user. This is done by what so-called (Assignment)

Expected values entered from the user and proposed names and, types as

shown in the table (1-1):

Proposed names Data Type Value U_Name (String) اسم المستخدم U_B_D (Date) تاريخ الميالد

U_Gender (Boolean) النوع U_C_F (Integer) عدد أفراد األسرة

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

Data

(8)

Data

Chapter One

Is a statement that consists of two sides (right hand side and left hand side)

separated by the assignment operator (=); (which doesn’t 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) or

(Property)

= Abstract value or

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

Data

(9)

Data

Chapter One

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 (=) doesn’t 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.

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).

Data

(10)

Data

Chapter One

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).

Property Control Text TextBox1 Text TextBox2 Checked RadioButton1 Text TextBox3

Table (1-2) controls ‘properties receiving user inputs

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

Figure (1-6) writing Assignment statements

Data

(11)

Data

Chapter One

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.

Data type for variables

Variable Data type for properties

Property

String U_Name String TextBox1.Text Date U_B_D String TextBox2.Text Integer U_C_F String TextBox3.Text

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.

Data

(12)

Data

Chapter One

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

Value Property False AutoSize Using mouse pointer Size,Location FixedSingle BorderStyle

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

Data

(13)

Data

Chapter One

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 other’s 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)

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

Declaration of variables

Assignment values to

variables

Using variables

Data

(14)

Data

Chapter One

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

Data

(15)

Data

Chapter One

The apostrophes " " are used while writing text.

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

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 constant’s 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.

Data

(16)

Data

Chapter One

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)

Data

(17)

Data

Chapter One

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

Data

(18)

Data

Chapter One

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).

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

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

Data

(19)

Data

Chapter One

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)

Data

(20)

Data

Chapter One

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, (محيط الدائرة)

Data

(21)

Data

Chapter One

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

Data

(22)

Data

Chapter One

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 variable’s Data Type or constant’s

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

Data

(23)

Data

Chapter One

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

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

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

Data

(24)

Data

Chapter One

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 didn’t 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)

Data

(25)

Data

Chapter One

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.

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

Try

Catch ex As Exception

EndTry

Data

(26)

Data

Chapter One

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

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

Data

(27)

Data

Chapter One

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. Parentheses starting from inside out.

2. Exponentials.

3. Multiplications and divisions from left to right.

4. 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.

Data

(28)

Data

Chapter One

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.

1. …………………………………………………………………………………

2. …………………………………………………………………………………

3. …………………………………………………………………………………

4. …………………………………………………………………………………

1

2

3

4

Data

(29)

Data

Chapter One

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 :

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

Data

(30)

Data

Chapter One

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.

error handling

error type Code

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. ...............................................................................

Data

(31)

Data

Chapter One

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:

Operation Order Multiplications and divisions from left to right. ( ) Parentheses starting from the inside out ( )

Additions and subtractions from left to right ( )

Exponentials. ( )

1

2

Data

(32)

Data

Chapter One

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

Branching

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

Use If …Then statement.

Use If …Then…Else statement.

Use If …Then… ElseIf statement.

Use Select …Case statement.

Data

(34)

Branching

Chapter Two

X>=50

Msgbox " ناجح"

End

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 language’s

grammatical rules. Programmatically branching is expressed using special

statements or structures that will be demonstrated through the following

exercises.

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

Msgbox("ناجح")

End if

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

The syntax of (If…Then) statement

If conditional Expression Then

code

End if

Data

(35)

Branching

Chapter Two

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

False as the two values are equal

100 < > 100

True as the two values are not equal

300 < > 100

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).

DEGREE=Textbox1.Text

Table (2-2) Comparison Expressions examples

Data

(36)

Branching

Chapter Two

Start

Enter X

X>=50 Msgbox

"ناجح"

End

Create a new project so that the Form’s window will be as shown in figure

(2-2)

Figure (2-2) the required Form’s 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 (Click) event procedure for the command button (Button1 )

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

Data

(37)

Branching

Chapter Two

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).

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:

Run the program

Input values such as (20, 50, 75) and click the button ( نتيجة ) in each time.

Data

(38)

Branching

Chapter Two

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

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

as shown in table (2-4).

The (Code) is written in the (Click) event procedure for the command button (Button1 )

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

The syntax of (If…Then…Else) statement If Conditional Expression Then code Else code End if

The code in case of True

The code in case of False

start

Enter X

X>=50

Msgbox

"ناجح"

End

Msgbox

"راسب"

Data

(39)

Branching

Chapter Two

Start

Get N

N

divisible

by 2

الرقم زوجي

الرقم فردى

End

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:

as shown in table (2-5).

The (Code) is written in the (Click) event procedure for the command Button

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

The (If) statement in one line

Data

(40)

Branching

Chapter Two

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 …Then…Else) statement is used when a single condition is tested, the

results of the condition is either (True) or (False), but the (If ...Then…ElseIf)

statement is used when you want to check more than one conditional

expression.

as

shown in figure (2-3).

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

The syntax of (If…Then…ElseIf) statement If Conditional Expression Then

code ElseIf Conditional Expression Then

code ElseIf Conditional Expression Then

code . .

Else code

End if

Data

(41)

Branching

Chapter Two

The form accepts a user’s 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):

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

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

:as follows (اختبار)

start

Get D

D =0 Output

"صفر"

end

D<0 Output

"تحت الصفر"

Output

"فوق الصفر"

Data

(42)

Branching

Chapter Two

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)

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

Line where error occurs

Error converting from string

to single

Data

(43)

Branching

Chapter Two

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:

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?

Original code; executed

when you enter numeric

values.

The code; when you

enter string values.

Additional (IF) statement

Data

(44)

Branching

Chapter Two

(ISnumeric) function examples; and their results.

The resultThe command (False)

Since the value between the parentheses is non-numeric

MsgBox IsNumeric("youssif")

(True) Since the value between the

Parentheses is numeric

MsgBox(IsNumeric(10))

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

numeric

MsgBox IsNumeric(a)

(True) If (TextBox3) contains a numerical

value

MsgBox

IsNumeric(textbox3.text)

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:

The code when

error occurs

Original code

Data

(45)

Branching

Chapter Two

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.

ResultConditional expression TRUE A= TRUE AND B= TRUE FALSE A=TRUE AND B=FALSE FALSE A= FALSE AND B= TRUE

FALSE A= FALSE AND B= FALSE

Data

(46)

Branching

Chapter Two

Examples of using the logical Operator (Or) assuming that variable (A) and

variable (B) are Boolean variables.

ResultConditional expression TRUE A= TRUE OR B= TRUE TRUE A=TRUE OR B=FALSE TRUE A= FALSE OR B= TRUE

FALSE A= FALSE OR B= FALSE

as

shown in figure (2-6).

Figure (2-6) the required Form’s 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.

Data

(47)

Branching

Chapter Two

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).

The code becomes as follows:

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)

Data

(48)

Branching

Chapter Two

The (Select …Case) statement is similar to (If …Then…ElseIf) 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.

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

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

The syntax of (Select …Case) statement

Select …Case Variable Case value1 code Case value2 code Case value3 code .. .. Case else code End Select

Data

(49)

Branching

Chapter Two

Figure (2-7) the Flowchart when using (Select…Case) 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:

start

Get D

Case D

Output

"صفر"

End

Output

"تحت الصفر"

Output " فوق

"الصفر

Data

(50)

Branching

Chapter Two

as

shown in figure (2-8).

Figure (2-8) the required Form’s 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.

Label1

Label4

Label3

Label2

Listbox1

Label5

Label6

Label7

Data

(51)

Branching

Chapter Two

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

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.

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)

Data

(52)

Branching

Chapter Two

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):

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:

Label4

Label5

Label6

Groupbox1

RadioButton1

RadioButton2

RadioButton4

RadioButton4

Data

(53)

Branching

Chapter Two

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):

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.

ComboBox1

Textbox1

Data

(54)

Branching

Chapter Two

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.

Data

(55)

Branching

Chapter Two

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

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

)1(

) ( In (IF) statement the code that follows (Else) is executed when the result of the conditional expression is (True).

(2)

( ) The operator (&) is one of the logical comparison operators. (3) ( ) Using the comparison operator (Or), the results of all conditions must be

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

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

(5)

( ) If the value of variable (X) is 15 and value of variable (Y) is 350 then the result of the conditional expression (X>10 And Y <500) is false.

(6)

( ) The use of (Else) keyword is optional in (If) statement. (7) ( ) The (and) operator requires that, the result of the two conditions must be

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

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

(9)

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

(10)

Data

(56)

Branching

Chapter Two

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

Data

(57)

Branching

Chapter Two

Write down the result displayed in (Label1); when you enter the following

values (degrees) in (Textbox1).

Result Degree 30 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.

Data

(58)

Branching

Chapter Two

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

The result The code S

a. One

b. Two c. three

1

a. True

b. False c. 15

2

a. Youssif

Ahmed

b. Ahmed

Youssif c. Ahmed

3

a. AXB=63

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

4

a. First

b. Second c. Forth

5

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.

Data

(60)

Loops and Timers

Chapter Three

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 (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:

The syntax of the (For…Next) statement

For Variable = Start To End

VB code

Next

Data

(61)

Loops and Timers

Chapter Three

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).

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

Start

M<=3

M=1

msgbox

M

End

M=M+1 Tru

e

Fals

e

Data

(62)

Loops and Timers

Chapter Three

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

- 0 Dim M As Integer - 1 (The starting value ) For M=1 to 3

1 1 Msgbox M

- The increment of M with 1 (M=M+1)

is the value of M greater than the end value (the

result is, False)

Next

2 2 Msgbox M

- The increment of M with 1 (M=M+2)

is the value of M greater than the end value (the

result is, False)

Next

3 3 Msgbox M

- The increment of M with 1 (M=M+3)

is the value of M greater than the end value (the

result is, True)

Next

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

2

Data

(63)

Loops and Timers

Chapter Three

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.

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

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

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

TextBox’s name: TextBox1

Data

(64)

Loops and Timers

Chapter Three

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:

Data

(65)

Loops and Timers

Chapter Three

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

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

Data

(66)

Loops and Timers

Chapter Three

1.The variable 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 (3-

7).

Data

(67)

Loops and Timers

Chapter Three

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)

Data

(68)

Loops and Timers

Chapter Three

The syntax of the (For…Next) statement

For Variable = Start To End [Step n]

code

Next [Variable]

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:

Data

(69)

Loops and Timers

Chapter Three

The syntax of the (For…Next) statement, includes some words written between parentheses [ ]; this means it is optional to write these words; in case you don’t 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 1

To display the

even numbers

from 2 to 10 2

To display the

numbers

divisible by 3

from 3 to 20 3

To display the

even numbers

descending from

10 to 1 4

To display the

numbers from

1.50 to 0.5

decremented by

0.05 each time

5

To display the

numbers from 1

to the value of B

at increasing value of C

6

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

Data

(70)

Loops and Timers

Chapter Three

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

(For…Next) 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 (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:

The syntax of the (Do ….While) statement

Do While conditional expression

code Loop

Data

(71)

Loops and Timers

Chapter Three

as shown

in figure (3-9).

Figure (3-9) the required Form’s 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.

Listbox1

Button1

Data

(72)

Loops and Timers

Chapter Three

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.

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:

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)

Conditional expression is

False in the case of equality

Data

(73)

Loops and Timers

Chapter Three

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.

Data

(74)

Loops and Timers

Chapter Three

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 non-termination 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 " نهاية " .

Data

(75)

Loops and Timers

Chapter Three

Label1

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:

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

False Enabled

Determines the number of milliseconds between ticks of the Timer (one second = 1000 milliseconds)

100 Interval

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).

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

Data

(76)

Loops and Timers

Chapter Three

Create a new project.

Add the object (Timer) on Form1, as well as the object (Label1) as

shown in figure (3-13).

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.

Change the value of (Enabled)

property to (True) Change the value of (Interval)

property to (1000)

Timer1 object doesn’t

appear on the Form

Label1 control

The event (Tick) for Timer control

Data

(77)

Loops and Timers

Chapter Three

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:

Data

(78)

Loops and Timers

Chapter Three

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 Timer’s Tick event handler to

maintain the appearance and disappearance of the Timer as follows:

Second Method First Method

The (Not) operator: is a logical operator used to get the opposite of what is inside the parentheses

Data

(79)

Loops and Timers

Chapter Three

2. Create a new project so that the form’s 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:

Second Method First 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.

-

Data

(80)

Loops and Timers

Chapter Three

4. Create a new project so that the form’s 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:

Second Method First 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.

Data

(81)

Loops and Timers

Chapter Three

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

Data

(82)

Loops and Timers

Chapter Three

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 – 0 (

)10 – 5 – 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

Data

(84)

Procedures

Chapter Four

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

Data

(85)

Procedures

Chapter Four

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.

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.

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.

Data

(86)

Procedures

Chapter Four

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).

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

Dear student, use the Sub procedure to avoid code duplication as shown in

figure (4-3)

Figure (4-3) declaring and calling a Procedure

Declaring a (Sub) Procedure

Code executed when you call the (Sub) procedure

Calling a (Sub) Procedure

Calling a (Sub) Procedure

Data

(87)

Procedures

Chapter Four

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).

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).

Figure (4-4) user interface

Figure (4-5) Part of the window code

Starting value of the repetition

Data

(88)

Procedures

Chapter Four

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).

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.

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.

Declaring a Parameter

Using a Parameter

Setting an Argument value

Data

(89)

Procedures

Chapter Four

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

Data

(90)

Procedures

Chapter Four

In the procedure declaration, we can use more than one Parameter. A Parameter allows the calling code to receive values; that doesn’t

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).

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)

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

Declaring a Parameter

Using a Parameter

Calling the procedure

(ShowOddOrEven)

Giving two values

Data

(91)

Procedures

Chapter Four

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)

Data

(92)

Procedures

Chapter Four

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.

Data

(93)

Procedures

Chapter Four

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

1- Design a Form’s 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

Data

(94)

Procedures

Chapter Four

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.

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).

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

Data

(95)

Procedures

Chapter Four

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.

Data

(96)

Procedures

Chapter Four

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).

Data

(97)

Procedures

Chapter Four

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:

Data

(98)

Procedures

Chapter Four

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).

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.

Data

(99)

Procedures

Chapter Four

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:

Function Area(ByVal radius As Single) As Integer

) ( 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 doesn’t 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 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)

B Serial A Serial Is used on the right side of the assignment statement and does not have any value.

Sub Procedure 1

Is used on the right side of the assignment statement and a value is assigned to it in declaration only

Function 2

Is never used in the assignment statement

Variables 3

Is used on both sides of the assignment statement

Constants 4

Data

(100)

Procedures

Chapter Four

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:

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

…………………… ………………………………………… ……………………….

Fifth: From the demonstrated code extract the following:

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

…………………… ………………………………………… ……………………….

Data

(101)

Procedures

Chapter Four

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:

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

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

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.

Data

(2)

Cyberbulling

Chapter Five

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. Electronic –Mail

2. Electronic forums

3. Instant Message

4. Blogging

5. 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

Data

(3)

Cyberbulling

Chapter Five

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- AMR said to Yasmin” I want to send a message to a friend and I have no e-mail 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.

1. Do not share a password with anyone. 2. Set a password that cannot be deduced. 3. Do not post any private data. 4. Do not delete hostile or aggressive

messages. 5. Do not interview any one you met

through the Internet. 6. Do not send messages when you are

angry. 7. Inform your parents with what annoy

you when you use the Internet. 8. The download of software from the

Internet should be done under the supervision of your teacher or your parents.

Data

(4)

Cyberbulling

Chapter Five

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 family‘s 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 e-mail 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 father’s 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.

Data

(5)

Cyberbulling

Chapter Five

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 Yasmin’s father, appeared.

In your opinion, what should she do?

Answer: She has to consult her father first, before installing any program.

Data

(6)

Cyberbulling

Chapter Five

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 ... ... ... ... ....

Data

(7)

Cyberbulling

Chapter Five

Related topics that have already been studied and you can search for

them:

Identification.

Firewall.

Secret codes.

Request for assistance

klنميسبلسيبل

( 103 )

Sample Tests

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

statement is 2. ) ( 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

result of the conditional expression (X>=5 And Y <=7) is false. ) ( 4. You can call the Procedures only once. ) ( 5. The Dim statement is used for declaring (Variables).

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 (Select…Case) 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 c) 2,4,6,8,10

klنميسبلسيبل

( 104 )

Sample Tests

5- Assigning values to constants is done: a) When you declare constants only. b) During the the implementation of program’s instructions. c) When you declare constants as well as during the implementation of

program’s instructions .

Third: Answer the following 1- Specify the value of each variable after executing the following Code.

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

Operation Order Multiplications and divisions from left to right. ( ) Parentheses starting from inside out ( ) Additions and subtractions from left to right ( ) Exponentials. ( )

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

Value Variable C K N

klنميسبلسيبل

( 105 )

Sample Tests

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

………………………………………………………………………………………

1-…………………………………………………………………………………

1

2

1

2

klنميسبلسيبل

( 106 )

Sample Tests

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

) ( 1. Use the (If.Then..ElseIf) statement when testing more than one conditional expression

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

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

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

) ( 5. The Variable of type (Double) takes the values True or False 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

klنميسبلسيبل

( 107 )

Sample Tests

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

Select Case x

End Select

Dim x As Integer

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

klنميسبلسيبل

( 108 )

Sample Tests

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

B Serial A Serial

Is used on the right side of the assignment statement and does not have any value.

Sub Procedure 1

Is used on the right side of the assignment statement and a value is assigned to it in declaration only

Function 2

Is never used in the assignment statement

Variables 3

Is used on both sides of the assignment statement

Constants 4

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

Correction Error type Code Dim x As Sangle Const x As Integer

X=10

klنميسبلسيبل

( 109 )

Sample Tests

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

) ( 1. The property (SelectedIndex).determines the selected item in a (Listbox).

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

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

) ( 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.

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

klنميسبلسيبل

( 110 )

Sample Tests

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.

2- From the demonstrated code extract the following:

If X<Y Then

Z = K + J

X = X + 1

Y = Y - 1

Else

Z = K - Y

X = X + 2

Y = Y - 2

End If

Bearning in mind that the primary

values for the variables are as

follows:

x = 0, z = 0, j = 1, k = 1, y = 2

Value Variable X Y Z

klنميسبلسيبل

( 111 )

Sample Tests

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 : .......................................................................................

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