0% found this document useful (0 votes)
46 views

Logical Operators: And, Or, and Not

Logical operators AND, OR, and NOT allow combining multiple comparison tests or conditions into a single compound comparison expression. The NOT operator has the highest precedence, followed by AND, then OR. For multiple comparisons, evaluation follows precedence order unless parentheses explicitly indicate otherwise. The IsNumeric function returns True if a string is numeric, False otherwise. Repetition structures like the For/Next loop repeat instructions a specified number of times or until a condition is met. The For/Next loop specifies the number of repetitions with a counter variable.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Logical Operators: And, Or, and Not

Logical operators AND, OR, and NOT allow combining multiple comparison tests or conditions into a single compound comparison expression. The NOT operator has the highest precedence, followed by AND, then OR. For multiple comparisons, evaluation follows precedence order unless parentheses explicitly indicate otherwise. The IsNumeric function returns True if a string is numeric, False otherwise. Repetition structures like the For/Next loop repeat instructions a specified number of times or until a condition is met. The For/Next loop specifies the number of repetitions with a counter variable.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 12

LOGICAL OPERATORS: AND, OR, and NOT

- allow us to combine two or more comparison tests or conditions into a single compound
comparison expression

OPERATOR ORDER OF USEGE EXAMPLE DESCRIPTION


PRECEDENCE
Not 1 Not (A>B) Returns True if the expression (A>B) is
false; returns False if the expression is
true
And 2 (A>B) And (C<D) Returns True if both expressions are true
Or 3 (A>B) Or (C<D) Returns True if at least one of the
expressions is true
Example:

If IsNumeric(txtNum1.Text) And (sngA>sngB) Then


SngC = sngA + (sngB-Val(txtNum1.Text)
End If

For multiple comparison expressions in one selection structure, evaluation follows he order of precedence unless
ecplicitly indicated by parentheses.

Example:
Evaluate the result of the following compound comparison expression:

(1 > 3) Or (2 = 2) And (3 < = 2)


Solution:

(False) Or (True) And (False)

Step 1: (False) Or False since (True) And (False) = False


Step 2: False since False Or False = False

Final Result: FALSE

The IsNumeric ( ) function:


- a “built-in” Boolean function procedure; returns True if the argument string is convertible to a numeric
value, returns False if otherwise
Examples:
StrEntry = “100.3”
StrInput = “34rth”

IsNumeric(strEntry) = True
IsNumeric(strInput) = False

Exercises:
1. Make a program (flowchart of the algorithm and the corresponding VB codes) that accepts the coefficients
A, B and C (thru textboxes) of a quadratic equation of the form Ax 2+Bx+C=0 then would compute and
display the roots of the equation in a label. The program should be able to accept equations with complex
roots (i.e., x1 = 1 + 2.5i; x2 = 1 - 2.5i).

2. Refer to the CASH REGISTER Application program that you have made during the previous laboratory
session. You may have noticed that the program would work perfectly only when the user will enter valid
entries on the 3 textboxes. The program would not be efficient if some or all of the entries are invalid. For
example, entering a discount of more than 100% would give you a negative selling price.

Improve the Cash Register application program (flowchart and codes) so that it would not:
1. accept non-numeric, negative, empty or zero (except for the discount) entries
2. accept discount of more than 70%
3. cash amount which is less than the selling price.

Add a label on the GUI. Display on this label the messages that would point the errors committed by the
user. Selling price would only be computed and displayed if nothing is wrong with the item price and the
discount. Change would only be computed and displayed if there is nothing wrong with the selling price
and the cash entry.
THE REPETITION OR LOOPING CONTROL STRUCTURES

- Used to implement program instructions that are to repeat either a specified number of times, or until
some condition (called the loop condition) is met.

3 General Forms of the Repetition Structure:


1. For Next Loop
2. Do While Loop
3. Do Until Loop

1. FOR NEXT LOOP:


- also called the automatic counter loop.
- The number of repetitions is specified by a counter variable.

Flowchart:

VB Syntax

For counter variable= start value To end value step stepvalue


Start value [loop instructions]

Next counter variable

Codition FALSE *
containing Counter variable- the name of the control variable
the end Start value- numeric value that tells the loop where to
value begin, start of count
Counter End value- end of count
incrementation or Step value- increment or decrement amount for the
decrementation counter variable each time the loop
TRUE is processed or iterated
Loop instruction
* start value, end value and step value must be all
numeric and must be compatible in datatype
to be repeated
Example No. 1:

For intCount= 1 To 3 step 1


Print intCount
Next intCount

intCount = 1

Output:

intCount
F For Next loop Example No. 1
<= 3 1
? 2
intCount = 3
intCount + 1
T

Print intCount

Example No. 2:

Given a form with an ImageBox of an airplane, write the event procedure that would make it move to the right.
HINT: Left property of an ImageBox- the distance of an object or control to the left edge of the form

MOVING PLANE

imgPlane

20 twips MOVE PLANE cmdMove

Solution:
To move the plane to the right, we must therefore increase the Left property successively until the imageBox is,
shall we say, 2, 500 twips from the left edge of the form. Let us assume that this value of Left property is still
within the form or that the form is sufficiently wide enough.
Successive increase of the Left property is best implemented by an iteration process. We will use an increment of
twips per iteration.

Flowchart:

START Codes or the Event Procedure:

Private Sub cmdMove_Click( )


IntCount = 0
Dim intCount As Integer

IntCount = 20 For intCount = 20 To 2500 Step 10


ImgPlane.Left = intCount
Next intCount

End Sub

IntCount < IntCount = intCount + 10


=
F 2,500 ?
T
Left Property of image
= intCount

END

Example 3. Moving the plane around the form for a specified number of items.

Consider again the Move Plane application program. Revise the event procedure so that this time when the
commamdbutton is clicked, the plane will move around the form for a specified no. of times which is to be entered
in a textbox also placed within the same form. Hint: aside from the Left property, we also have the Top property

MOVING PLANE

imgPlane

20 twips

cmdPlane
MOVE PLANE
txtNum
EXERCISES:

1. Draw a flowchart and write its corresponding For/Next loop statement that will sum up all odd numbers
from 1 to 99.

2. Draw a flowchart and write its corresponding For/Next Loop statement that will compute the average of all
integer numbers from 3 to 15.

3. Make an application program (GUI, Flowchart, VB Codes) that asks for any non-zero positive integer and
then displays its summation (ex.  4 =1 + 2 + 3 + 4 = 10,  3 = 1 + 2 + 3 =6)

4. Make an application program (GUI, Flowchart, VB Codes) that asks for zero or any positive integer and
then displays its factorial (Ex. 4! = 1 * 2 * 3 * 4 = 24, 3 ! = 1 * 2 * 3 = 6)

5. Make an application program (GUI, Flowchart, VB Codes) that asks for any two positive integers n and r
and then displays the corresponding binomial coefficient. NOTE: n  r. Use the formula:

n!
B C (n, r) =
r! ( n  r )!
The Do While/Loop loop and Do/Loop Until loop

Do While/Loop loop - repeats a block of instructions while a condition is True


- also called the pretest loop because it evaluates/tests the condition before
processing any other instructions within the loop
- it may be possible that the loop instruction(s) will not be executed even once if the
test condition is not satisfied the first time the loop is iterated

Do/Loop Until loop - repeats a block of instructions until a condition becomes True
- also called the post-test loop. This loop is always iterated at least once as there is
no restriction when it is initiated

The Do While/Loop loop:


FLOWCHART SYNTAX

Do While <condition>
[ loop instruction(s)]
False Loop
<condition
>
True Example:

Loop Do While intCount <= 3


instruction(s) lngSum = lngSum + intCount
intCount = intCount + 1
Loop

The Do/Loop Until loop:


FLOWCHART SYNTAX

Do
[loop instruction(s)]

Loop Until <condition>


Loop
instruction(s)
Example:

Do
False lngSum = lngSum + intCount
<condition intCount = intCount + 1
>
True Loop Until intCount > 3
Unlike the For/Next loop that is automatically terminated by an end value, Do While/Loop or Do/Loop Until are
condition-terminated. They are usually employed by programmers to count unspecified number of items, track
subtotals or totals and compute averages.

There are variables that are usually used within repetition structures in connection with counting or accumulating.
 A counter is a numeric variable that is used for counting. It is incremented by a constant value
 An accumulator is used for adding something together. It is incremented by an amount that varies.
 A variable that is used to signify beginning or ending of iteration process is called a sentinel.

Example- A Sentinel Controlled Program that Calculates and Displays Average of Numbers

Screen Shoots of the GUI:


Flowchart:

START

Declare
variables

Prompt user to input


first no by InputBox

F
There
is
Input ?
T
Increment counter by 1 Prompt user to
input another
number
By InputBox
Convert input and
accumulate to sum

F T
Counte Compute average
r > 0?

Display “no
numbers entered” Display
in a label average in a
label

END

VB Codes:

Private Sub cmdGetNums_Click ()


Dim strInputNum As String ` this is the sentinel variable
Dim intCount As Integer ` this is the counter variable
Dim sngSum As Single ` this is the accumulator variable
Dim sngAvg As single

StrInputNum = InputBox(“Enter a number then click OK.”, “INPUT”)


Do While strInputNum <> “” ` empty string s the sentinel value
intCount = intCount + 1 ` update counter
sngSum = sngSum + Val(strInputNum) ` update accumulator
strInputNum = InputBox(“Enter another number then click OK._
Click CANCEL if you have nothing more to enter”,_
“INPUT”)
Loop

` determines if at least 1 number was entered

If intCount > 0 Then


SngAvg = sngSum/intCount
1b1Avg.Caption = Format (sngAvg, “#,##0.#0”)
Else
1b1Avg.Caption = “No numbers were entered.”
End If

End Sub

EXERCISES:

1. Draw a flowchart and write a do While/Loop loop statement that sums up the squares of odd numbers from
1 to 101
2. Draw a flowchart and write a Do/Loop Until Loop statement that would sum up all integers from 5 to 21
3. Draw a flowchart and write a Do/Loop Until loop statement that would compute the average of the first 20
even numbers starting from 22
4. Convert the two loop statements that you have written in Exercises 1 and 2, this time use the Do/Loop Until
and the Do While/Loop, respectively.

Programming Activities:

1. Revise the algorithm in the previous example, (Get Numbers) this time use the Do/Loop Until loop. Add a
new feature in your program in which it can identify the smallest and the biggest number entered and these
two numbers are displayed in separate labels.
2. Make a program that calculates and approximation of the either of the functions cos x, sin x and e x. Use the
power of series form of these functions.

(1) n x 2 n 1 x x3 x5
sin x         .......... .
n  0 ( 2n  1)! 1 3! 5!

( 1) n x 2 n x2 x4 x6
cos x   (2n)!  1 
2!

4!

6!
   ............
n 0

xn x2 x3
ex    1  x      ...........
n  0 n! 2! 3!

Note: there would be a limit to the no. of terms of the series since the factorial evaluation (by computer) is
limited.

3. Research about the Newton-Rhapson method in solving roots of equations. Implement a program that
utilizes the method to solve for a positive cube root of any positive number.
SPECIAL TOPIC: The Randomize and Rnd Function

Consider the following event procedure:

Private Sub cmdExample_Click ()


Dim intNum1 As Integer, intNum2 As Integer

Randomize

IntNum1 = Int((10 – 1+ 1 * Rnd + 1)


IntNum2 = Int((10 –1 + 1 * Rnd + 1)

1b1Num1.Caption = Str(intNum1)
1b1Num2.Caption = Str(intNum2)

End Sub

The program above displays two numbers (any number from 1 to 10) everytime the associated command button is
clicked.

Important Keywords:

Randomize- a keyword that initialize the VB random number generator


Rnd Functoion- generates the random number, produces any decimal number within the 0 to 1 range; including 0
but not including 1 ( 0 to 0.999999999999….)

Formula: (Upperbound - Lowerbound + 1) * Rnd + Lowerbound

Upperbound- highest number to be generated


Lowerbound- lowest number to be generated

Example:Rocket Race Apllication:

Private Sub CmdStart_Click()


Dim intRnd1 as Integer, intRnd2 As Integer

Randomize

Do While imgRocket1.Top > 0 And imgRocket2.Top > 0 ` do loop while neither


Of the two rockets
Is a the top
intRnd1 = Int((50 – 1- +1) * Rnd + 10) ` generates 2 random
intRnd2 = Int((50 – 10 +1) * Rnd + 10) numbers

imgRocket1.Top = imgRocket1.Top – intRnd1 ` subtracts the random no


imgRocket2.Top = imgRocket2.Top – intRnd2 ` from the Top property
Loop
If imgRocket1.Top <= 0 And imgRocket2.Top < =0 Then
MsgBox “It’s a tie!!!”
Else
If imgRocket1.Top < = 0 Then
MsgBox “ Rocket 1 wins!!!”
Else
MsgBox “ Rocket 2 wins!!!”
End If
End If

imgRocket1.Top = 4200
imgRocket2.Top = 4200

End Sub

What happens is that the Top property of the two image boxes(planes) are decremented by random numbers for
every loop iteration. Loop stops if at least one of the image boxes reaches the minimum Top property value (“the
finish line”).

Exercise:

1. Write the event procedure for an application program that generates any three number combination for the
Swertres lottery game. Your program will randomly generate any number from 0 to 9, convert the number
to a string, concatenate to an accumulator string variable and do this thrice to form the three number
combination. The resulting three number combination is then displayed in a label.

2. Write a program (GUI, psuedocodes/flowchart, VB codes) that generate a six character password
ramdomly composed of number digits (0 to 9) and the vowels of the alphabet. Examples: 3ao8u1, iea5aa,
o591ai, etc.

You might also like