Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... ·...

97
DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria PAGE 1 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes FREE, NOT FOR SALE! Abridged Lecture Notes For DCS 105 Introduction to Programming (I) prepared and delivered by Adamu Auwal Gene MCPN @IACC, Ahmadu Bello University, Zaria Nigeria

Transcript of Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... ·...

Page 1: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 1 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Abridged Lecture Notes For

DCS 105 Introduction to Programming (I)

prepared and delivered by

Adamu Auwal Gene MCPN @IACC, Ahmadu Bello University, Zaria – Nigeria

Page 2: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 2 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

A Gentle Introduction to VB.NET Strings, Selection and Iteration

Abridged Lecture Notes For

DCS 105 Introduction to Programming (I)

Diploma in Computer Science

Year I, Semester I

Prepared and Delivered

By

Adamu Auwal Gene MCPN Chartered Information Technology Professional

@Iya Abubakar Computer Centre, Ahmadu Bello University, Zaria – Nigeria

Last Updated: February, 2013

Page 3: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 3 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Contents

INTRODUCTION ................................................................................................................................................... 5

JUST SOME FEW RULES PLEASE, BEFORE WE START ........................................................................................... 6

WHAT YOU SHALL LEARN .................................................................................................................................... 8

SECTION I: STRING MANIPULATION ................................................................................................................... 9

1.0: Introduction ......................................................................................................................................... 9

1.1: Inputting strings at run time ................................................................................................................ 9

1.2: Inputting numbers at run time .......................................................................................................... 13

1.3: Class Exercise: Find The Bug(s)! ........................................................................................................ 16

1.4: Assigning string literals (yes, you are "tied up" in Strings!)............................................................... 17

1.5: Concatenating strings ........................................................................................................................ 19

1.6: A quick look at a dozen VB.NET built-in string functions .................................................................. 22

1.6.1 Counting string length with Length ......................................................................................... 22

1.6.2 Joining strings with Concat() .................................................................................................. 23

1.6.3 Splitting strings with Split() .................................................................................................. 23

1.6.4 Trimming strings with Trim() .................................................................................................. 27

1.6.5 Deleting characters from a string with Remove() ................................................................... 27

1.6.6 Inserting characters into a string with Insert() .................................................................... 28

1.6.7 Replacing characters in a string with Replace() .................................................................... 29

1.6.8 Padding strings left or right with PadRight() and PadLeft() ............................................. 30

1.6.9 Converting string capitalizations with ToUpper() and ToLower() ....................................... 31

1.6.10 Getting part of a string with Substring() ............................................................................. 31

1.6.11 Reversing strings with StrReverse() .................................................................................... 33

1.6.12 Copying strings with Copy() .................................................................................................... 33

1.7: Class Exercises: Find the bugs! ......................................................................................................... 33

1.8: Extra Credits: Can You?..................................................................................................................... 35

SECTION II: DECISION AND SELECTION ............................................................................................................ 36

2.0: Introduction ....................................................................................................................................... 36

2.1: Working with single-line and block IF statements ............................................................................ 40

2.2: Working with IF...THEN...ELSE statements .............................................................................. 42

2.3: Working with IF-THEN-ELSEIF statements .................................................................................. 44

2.4: Working with compound conditions containing logical operators ................................................... 46

2.5: Class Exercises: Find the bugs! ......................................................................................................... 50

Page 4: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 4 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

2.6: Making a case for CASE and SELECT CASE statements .................................................................. 51

2.7: Extra Credits: Can You?..................................................................................................................... 56

SECTION III: ITERATION AND LOOPING ............................................................................................................ 58

3.0: Introduction ....................................................................................................................................... 58

3.1: Looping with FOR...NEXT statement ............................................................................................. 59

3.1.1 Generating and printing even numbers with FOR...NEXT loop ............................................. 62

3.1.2 Generating and printing sums of numbers with FOR...NEXT loop ........................................ 63

3.1.3 Generating and printing sum of a series with FOR...NEXT loop (1) ....................................... 64

3.1.4 Generating and printing sum of a series with FOR...NEXT loop (2) ....................................... 65

3.1.5 Generating and printing sum of a series with FOR...NEXT loop (3) ....................................... 67

3.1.6 Implementing the StrReverse() function with FOR...NEXT loop ..................................... 69

3.1.7 Implementing the String.Replace() function with FOR...NEXT loop ............................. 71

3.1.8 Counting the number of words in a sentence with FOR...NEXT loop .................................... 73

3.1.7 Generating and printing Fibonacci sequence with FOR...NEXT loop ..................................... 74

3.2: Looping with DO...LOOP statement ............................................................................................... 77

3.2.1 Generating and printing even numbers with DO...WHILE statement .................................... 79

3.2.2 Generating and printing sums of numbers with DO...WHILE statement ............................... 81

3.2.3 Generating and printing sum of a series with DO...LOOP UNTIL statement (1) .................. 82

3.2.4 Generating and printing sum of a series with DO...LOOP UNTIL statement (2) .................. 83

3.2.5 Generating and printing sum of a series with DO...LOOP UNTIL statement (3) .................. 84

3.2.6 Implementing the StrReverse() function with DO...LOOP WHILE statement ................. 85

3.2.7 Implementing the String.Replace() function with DO...LOOP WHILE statement ........ 87

3.2.8 Counting the number of words in a sentence with DO...LOOP UNTIL statement ............... 88

3.3: Looping with WHILE...WEND statement ........................................................................................ 89

3.3.1 Generating and printing even numbers with WHILE...WEND statement ............................... 90

3.3.2 Generating and printing sums of numbers with WHILE...WEND statement ........................... 90

3.3.3 Generating and printing sum of a series with WHILE...WEND statement (1) ......................... 91

3.3.4 Generating and printing sum of a series with WHILE...WEND statement (2) ......................... 92

3.3.5 Generating and printing sum of a series with WHILE...WEND statement (3) ......................... 93

3.3.6 Implementing the StrReverse() function with WHILE...WEND loop ................................. 94

3.3.7 Implementing the String.Replace() function with WHILE...WEND statement ............... 95

3.4: A word about infinite loops ............................................................................................................... 96

3.5: Extra Credits: Can You?..................................................................................................................... 96

Page 5: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 5 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

INTRODUCTION ELCOME TO the second part of your DCS105 course, Introduction to

Programming (I). In the first part of the course, you must have learnt the

basics of programming with Visual Basic.NET 2008/2010 using the

Console approach to applications development. In this manual, we shall

continue in that line and our topics of programming interest shall include strings,

selection and iteration. You can download this lecture notes and more from my website,

which can be accessed anytime at http://www.auwalgene.com/mystudents/lecturenotes

Please be reminded that this is a hands-on,

practical-intensive course whereby you

shall be expected to not just read the

concepts of programming, but to also try

them out on a computer and get to

understand how programming works for

real. You will see lots of general concepts

explained and you will also see lots of step-

by-step directions for carrying out simple

programming tasks that will enable you

master how to think like a good

programmer and thus, successfully develop

applications that work correctly and

efficiently.

Thus, as you read, you should also take time

out to practice what you read on a

computer that has Microsoft Visual Studio

2008 or 2010 installed. I emphasize that

you should by all means endeavour to

carry out the tasks yourself, exactly as

directed in this manual (and as you shall

be guided in the lab).

This material is broadly divided into three

sections, each of which has one or more

concepts explained and tasks or exercises

to keep you busy. You are advised to go

through the manual in sequence, starting

with the first section.

IMPORTANT NOTE: It is YOUR PERSONAL

RESPONSIBILITY to keep your files in a

neat and easily accessible manner. All

tasks described in this manual build upon

preceding tasks; so losing your file simply

means you would have to start all over

again – on your own! Also NOTE that all

students’ lab works shall be continuously

assessed and graded individually.

Finally, I take no responsibility for any

spelling or grammaticl errors found in this

manual. My written English is probably

none too good, so I won't take offence at

any corrections from any Grammar Nazi out

there: I am a programmer, not a literary

genius!

Best regards, and happy programming!

M-Auwal Gene mcpn @IACC, ABU Zaria February, 2013

W

Page 6: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 6 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

JUST SOME FEW RULES PLEASE, BEFORE WE START

1: Attendance Policy: Please note

that all students are expected to

attend every class and lab session on

time. Punctuality is expected, and is

part of your cumulative continuous

assessment. In case of unexpected

events that make it impossible for

any student to attend class or lab

sessions, such students should

contact me (or any other Instructor

in charge) via phone call or send an

SMS text message briefly explaining

why they would not be in the class or

lab.

2: Extra Credit: Occasionally there

are opportunities for students to earn

extra credits for exceptionally

excellent work or enthusiastic

attitude towards study in the this

course. There is no guarantee that

there will be extra credit

opportunities every time; but

whenever the opportunity arises, all

students will have an equal chance of

earning those extra credits.

Maximum extra credit obtainable by

any student is 5 points (out of 100).

3: Assignments: To evaluate

students’ learning progress, one or

more take-home assignments shall be

given to students at the end of every

class or lab session. Those

assignments will mostly be based on

current topics being discussed; but

may also sometimes include work

outside of the current topic.

4: Make-Up and Late Policy: All

assignments that are handed in late

will be docked 2% per day that they

are late, unless arrangements have

been made at least 48 hours before

the due date. The term “LATE” refers

to all assignments that are turned in

after the class or lab time on the

assignment’s due date. Please note

that I am not responsible for you not

having your personal laptop, or not

having Internet access, or not having

access to the lab computers to enable

you do your assignments. You will

normally be given freedom to do all

practical assignments in the lab if you

properly approach the Centre’s

Operations Manager or any of the Lab

Support Staff on duty.

5: Grading Policy: The following

grading policy shall apply during this

Page 7: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 7 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

course (both theory and practical

labs are covered):

Please note that every student’s

grade totally depends on what he or

she has achieved during the course:

the grades will be earned, not given!

6: Lab Etiquette: Since we are a

large class in a large lab, let us all

faithfully follow these four simple

rules in order to make life easy for

everyone:

i. Be punctual. Coming in late

disrupts your fellow students.

If you are going to be late for a

lab session, perhaps you should

not bother coming to the lab, as

you might not be able to catch

up anyway.

ii. Do not leave the lab early

unless it is an emergency.

iii. No texting, phone calls or

Internet browsing during class

or lab sessions.

iv. Kindly turn off cell phones, and

Internet access. If your phone

rings during a class or lab

session or you are seen

browsing the ’Net during a

class or lab session, you shall

be penalized – and your

penalty is to provide snacks

and drinks for the Instructor at

the next class or lab session.

Page 8: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 8 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

WHAT YOU SHALL LEARN So, we've already said (in the introduction)

that this manual introduces you to three

important programming concepts in Visual

Basic.NET 20008/2010. The overriding

emphasis of this manual is on teaching you

how to write usable and correct programs

from logical analyses. The intention is to

help you develop skills that utilize simple

but straightforward programming

techniques which you find extremely useful

not only in your VB.NET programming

adventures, but also provide a very solid

foundation for further study of other

programming languages. Upon completion

of this manual, you should be able to

achieve the following learning objectives,

among others:

String Manipulation

Code elementary string expressions.

Understand how to handle numeric input as against string input at runtime.

Use the concatenation operators (+ and & ) to join string variables and literals.

Understand how to use at least a dozen built-in string functions to process string data.

Try out a number of exercises to figure out whether you understand strings well

enough.

Decision and Selection

Write single-line and block IF statements.

Translate an if-then-else structure into a valid VB.NET IF statement.

Correctly code compound conditions using logical operators AND and OR.

Use SELECT CASE statement to simplify code.

Try out a number of exercises to figure out whether you understand selection well

enough.

Iteration and Looping

Explain the term “looping”.

Correctly code FOR...NEXT statements.

Correctly code DO and LOOP statements.

Correctly code WHILE...WEND statements.

Try out a number of exercises to figure out whether you understand iteration and

looping well enough.

Page 9: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 9 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

SECTION I: STRING MANIPULATION “Practice thyself even in the things thou dispairest of accomplishing. For even the left hand,

which is ineffectual for all other things for want of practice, holds the bridle more vigorously

than the right hand: for it has been practiced in this.” – Roman Emperor Marcus Aurelius Antoninus (161 AD – 180 AD)

1.0: Introduction

You might have learnt in previous

lectures that there are quite a

number of different data types or

data classes. For example, we

generally have data types that are

classified as numeric data and those

that are classified as non-numeric

data (can you give some examples of

both?).

Well, the numeric data types can be

integers, single, double, or byte; while

the non-numeric types can be string,

object, and so on. Our interest here is

on string data types.

String constants must be enclosed in

double quotation marks; and all

variables that are intended to hold

sting values must be declared as type

String using Dim statement.

In this short section, you shall be

learning just two or three things

about strings to get started; but you

shall learn several more things about

strings in DCS106 when you continue

your exploration of introductory

programming with VB.NET.

1.1: Inputting strings at run time

Let us start by looking at a simple

program. Say, you need to write a

program that will require the user to

type in his or her name and then say

something nice to the user. The name

of a user is a string data type, and the

program could be made to work like

the screenshots shown in Fig. 1.1a -

Fig. 1.1c (next page).

You may not bother much about the

header information displayed at the

top when the program runs. Just

focus on the line that says "What is

your name, please?" in Fig. 1.1a.

By now, you know that you could get

that line printed using a simple

Console.WriteLine command, right?

So it goes like so:

Console.WriteLine ("What is your name, please?")

Page 10: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 10 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Fig. 1.1a

Fig. 1.1b

Fig. 1.1c

Page 11: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 11 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

The line that reads "Gene" in Fig.

1.1b is actually what the user typed

in at the keyboard; and you also do

know by now that you can read data

from the keyboard using

Console.ReadLine statement, right?

So that one was achieved using the

command:

strName = Console.ReadLine ()

Of course, the variable strName was

earlier declared using a statement

like so:

Dim strName As String

And finally, the last line that says

"Nice to meet you, Gene" in Fig. 1.1c

was generated using another

Console.WriteLine statement, this

time around including the name that

the user type. It was actually done

like this:

Console.WriteLine ("Nice to meet you, " &

strName)

Source Code Listing 1.1 shows the

complete program that generated the

outputs in Fig. 1.1a - Fig. 1.1c.

STOP & TYPE: Source Code Listing 1.1

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 1.1 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program simply demonstrates how to *") 07 Console.WriteLine("* declare a String variable that could *") 08 Console.WriteLine("* store data entered from the keyboard. *") 09 Console.WriteLine("********************************************") 10 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 11 Console.WriteLine("********************************************") 12 13 Console.WriteLine() 'just a blank line to make the display neat 14 15 Console.WriteLine("What is your name, please?") 16 Dim strName As String 17 strName = Console.ReadLine() 18 19 Console.WriteLine("Nice to meet you, " & strName) 20 21 Console.ReadKey() 'hold the window until user presses any key 22 End Sub 23 End Module

Page 12: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 12 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

The meat of the action in Source Code

Listing 1.1 actually starts at line

number 15 and ends at line number

19. I have numbered the code lines

for easy reference and this is how it is

going to be in this manual

throughout. In reality, you don't have

to number your code lines in Visual

Basic.NET.

You will recall we have already said

in the introduction to this section

that all string literals must be

enclosed within double quotation

marks. So, at line 15 we just print out

the string literal "What is your name,

please?" on the screen. That is called

a prompt. Prompts don't actually do

anything other than display messages

on the screen; but even at that, they

are quite useful because they make

programs to be user-friendly (i.e.

they to make it easy for the user to

understand and use the program).

So after displaying the prompt, the

next thing is to write the code that

will actually let the user type in his or

her name. That is done at line 17

with the statement strName =

Console.ReadLine(). What that

statement does is to display a

blinking cursor and accepts whatever

the user types in at the keyboard and

it will continue to accept whatever

that is typed until the user presses

the ENTER key. This is actually done

by the Console.ReadLine() part of the

statement.

After the user types in the data and

presses the ENTER key, whatever

that the user typed is stored in the

variable strName. Visual Basic.NET

will usually not allow you to use

variables without first declaring them

properly however, hence the variable

strName was declared first at line 16

before it is used to store the user's

name at line 17. strName was declared

as String because we expect it to

store string data, not numeric or any

other type of data. Note that lines 17

and 18 could actually be combined

into one to read:

Dim strName As String = Console.ReadLine()

So after successfully accepting the

user's data and storing it in the

variable strName, we move on to line

19 to display "Nice to meet you"

using the Console.WriteLine

statement. Notice that we use the

ampersand symbol, &, to join the

string literal "Nice to meet you,"

and the string variable strName. This

is called concatenation, and we shall

discuss more about it later in this

section.

Page 13: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 13 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Then at line 21 we use the

Console.ReadKey() statement to hold

the window until user presses any

key (if we don't do this, the window

will automatically close and the user

will not get to see the last output of

the program).

So in summary, you have seen how

easy it is to write VB.NET code to

accept a string from the keyboard

and assign it to a variable and then

print out the contents of the variable.

The three key things you must have

learnt here are:

how to properly declare a

variable to hold string data.

how to properly write

Console.ReadLine statement to

read in string data from the

keyboard.

how to properly enclose string

literals in double quotation

marks (you have plenty of

those string literals from line

03 to 11).

1.2: Inputting numbers at run time

By now you know that an important

part of computer code is allowing

your user to input data into the

program. Input can be text, key

presses or even a data feed from a

motion sensor games controller. We

have already handled simple text

input in section 1.1. Now we shall

look at how to properly capture

numeric data input from the

keyboard.

Background: All data accepted into

Visual Basic.NET console programs

through the Console.Read or

Console.ReadLine statements will be

taken as text or string data. Thus,

even when you type numbers upon

being prompted, those numbers will

be seen as string data (i.e. an input

like 224399 will be seen the same

way as ABU Zaria or any other string

for that matter). So, how do you

make your VB.NET console

applications read numbers and see

them as numbers?

The answer is to convert the input

from string into its proper numeric

representation. Luckily, VB.NET has

many built-in functions that you can

use to do that.

Page 14: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 14 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

So let's assume for example that you

are to write code that will require the

user to enter a number and you are

to compute and add 12.5% of the

number to itself and then print out

the results. (If you type in 20 for

example, then your program should

compute 12.5% of 20, print the

original 20, the 12.5% of 20 and the

final sum of the original 20 + its

12.5%). The screenshots in Fig. 1.2a

and Fig. 1.2b illustrate what we need

to achieve.

Fig. 1.2a

Fig. 1.2b

Source Code Listing 1.2 shows the complete source codes that generated the

outputs in Fig. 1.2a and Fig. 1.2b.

Page 15: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 15 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

STOP & TYPE: Source Code Listing 1.2

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 1.2 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to handle *") 07 Console.WriteLine("* numeric input entered from the keyboard *") 08 Console.WriteLine("********************************************") 09 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 10 Console.WriteLine("********************************************") 11 12 Console.WriteLine() 'just a blank line to make the display neat 13 14 Console.Write("Please enter an integer number: ") 15 Dim intNumber As Integer 16 intNumber = CInt(Console.ReadLine()) 17 18 Console.WriteLine() 'just a blank line to make the display neat 19 Console.WriteLine("The number entered is " & intNumber) 20 21 Dim dblPercent As Single 22 dblPercent = (12.5 / 100) * intNumber 23 24 Console.WriteLine() 'just a blank line to make the display neat 25 Console.WriteLine("12.5% of " & intNumber & " is " & dblPercent) 26 27 Console.WriteLine() 'just a blank line to make the display neat 28 Console.WriteLine("The number + 12.5% of the number is " & (intNumber + dblPercent)) 29 30 Console.ReadKey() 'hold the window until user presses any key 31 End Sub 32 End Module

Source Code Listing 1.2 Explained

There is nothing especially new from

line 01 to 14. At line 15, we declare

an Integer variable that will hold

whatever the user is going to type in

and line 16 actually accepts the input

from the keyboard and assigns it to

the integer variable previously

declared at line 14.

Notice, however, that there is a

wrapper function, CInt, which

converts whatever the user types in

into its integer equivalent before

assigning it to the variable intNumber.

The CInt function is one of the very

numerous data conversion or

typecasting functions available in

VB.NET. The work of such functions

is to convert data from one type to

another. You will recall that whatever

that comes in from the keyboard is

regarded as string or text data and in

Page 16: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 16 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

this case, the CInt function will try to

convert that input into its Integer

equivalent. If we wanted to convert

to double data type, then we would

use CDbl and if it is to byte, we shall

use CByte. More on VB.NET data

conversion functions later.

The math is done from lines 19 to 28

and the results are displayed

appropriately.

Notes:

At line 16, the statement:

intNumber = CInt(Console.ReadLine())

could also be written as:

intNumber = Integer.Parse(Console.ReadLine())

Also note that both CInt and Integer.Parse will work only if the user actually

types numbers at the keyboard. If the user types in non-numeric data, the

program will fail and crash. There are many ways you can "bullet-proof" your

applications against crashing, but we shall not concern ourselves with that yet.

1.3: Class Exercise: Find The Bug(s)!

A new student of Visual Basic.NET console applications development is tasked to

write a simple program that will read the amount of litres bought at a petrol

station and determine the total price of the purchase. Assume a litre of petrol

costs 97.00. The student turned in the program given below but there is trouble

running it. Detect the error(s) in the code and suggest ways to make it work

correctly.

Page 17: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 17 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

01 Module Module1 02 Sub Main() 03 Console.Write("How many litres were bought? ") 04 Dim dblLitres As Double 05 06 Console.ReadLine() 07 dblLitres = Double.Parse(Console.ReadLine()) 08 dblLitres = Convert.ToDouble(Console.ReadLine()) 09 10 Console.WriteLine("A litre costs 97.00") 11 Console.WriteLine("The total price is " & dblLitres * 97.0) 12 13 Console.ReadKey() 'hold the window until user presses any key 14 End Sub 15 End Module

1.4: Assigning string literals (yes, you are "tied up" in Strings!)

You can assign string data values to

variables just as you can assign

numeric values to variables. The

string data you assign to variables

must be "tied up" in double quotation

marks of course, as we have already

pointed out. Examples of string literal

assignment statements include the

following:

strName = "Auwal Gene"

strAddress = "24B, Admiralty Drive, Green Zone Estate, Abuja"

strLGA = "Kaiama"

strState = "Kwara"

strPhone = "08032126160"

strPhone = "+2348032126160"

In all of the above, the string literals

are enclosed in double quotation

marks. Now, what happens if your

string literal is also supposed to

contain a double quotation mark?

For example, what if you want to

assign the string literal He said,

"come here" and I blinked to a

variable called strConversation? Will

you write it as below?

Page 18: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 18 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

strConversation = "He said, "come here" and I blinked"

The answer is no, of course. The proper way to do it would be:

strConversation = "He said, ""come here"" and I blinked"

i.e. you need to "escape" the double

quotes by specifying it twice where

you want it to be part of the string.

To illustrate further, we write the

code in Source Code Listing 1.3 and

we get the output shown in Fig. 1.3

STOP & TYPE: Source Code Listing 1.3

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 1.3 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to handle *") 07 Console.WriteLine("* double quotes that are part of a string *") 08 Console.WriteLine("********************************************") 09 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 10 Console.WriteLine("********************************************") 11 12 Console.WriteLine() 'just a blank line to make the display neat 13 14 'Next, declare a string variable and assign the string literal 15 Dim strConversation As String = "He said, ""come here"" and I blinked" 16 Console.WriteLine(strConversation) 'print it out 17 18 Console.WriteLine() 'just a blank line to make the display neat 19 20 'Declare another string variable and assign a string literal 21 Dim strMyName As String = "My name is ""M-Auwal Gene III""" 22 Console.WriteLine(strMyName) 'print it out 23 24 Console.ReadKey() 'hold the window until user presses any key 25 End Sub 26 End Module

Fig. 1.3

Page 19: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 19 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

1.5: Concatenating strings

Concatenating one string to another

means combining or joining both

strings. In VB.NET, the + operator

has the primary purpose of adding

numbers, but it can also concatenate

numeric operands with string

operands. Of course, you remember

that the & operator also concatenates

strings. In Source Code Listing 1.4

below, the value of both strResult1

and strResult2 will be blueberry, as

shown in the output captured in Fig.

1.4

STOP & TYPE: Source Code Listing 1.4

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 1.4 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use the *") 07 Console.WriteLine("* + and & operators to join two strings. *") 08 Console.WriteLine("********************************************") 09 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 10 Console.WriteLine("********************************************") 11 12 Console.WriteLine() 'just a blank line to make the display neat 13 14 'Declare the various string variables to hold data 15 Dim strMine As String 16 Dim strYours As String 17 Dim strResult1 As String 18 Dim strResult2 As String 19 20 strMine = "blue" 21 strYours = "berry" 22 strResult1 = strMine + strYours 23 strResult2 = strMine & strYours 24 25 Console.WriteLine("String 1 = " & strMine) 26 Console.WriteLine() 27 Console.WriteLine("String 2 = " & strYours) 28 Console.WriteLine() 29 Console.WriteLine("The 2 strings concatenated with + gives " & strResult1) 30 Console.WriteLine() 31 Console.WriteLine("The 2 strings concatenated with & gives " & strResult1) 32 33 Console.ReadKey() 'hold the window until user presses any key 34 End Sub 35 End Module

Fig. 1.4

Page 20: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 20 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

You can also concatenate more than two strings together of course. For example,

you might want to add a space character between a first name and a last name, as

shown in Source Code Listing 1.5 below.

STOP & TYPE: Source Code Listing 1.5

01 Module Module1 Sub Main() Console.WriteLine("********************************************") Console.WriteLine("* DCS105 Source Code Listing 1.5 *") Console.WriteLine("********************************************") Console.WriteLine("* This program demonstrates how to *") Console.WriteLine("* concatenate more than two strings. *") Console.WriteLine("********************************************") Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") Console.WriteLine("********************************************") Console.WriteLine() 'just a blank line to make the display neat 'Declare the various string variables to hold data Dim strFirstName As String Dim strLastName As String Dim strFullName1 As String Dim strFullName2 As String 'Get the first and last names from the user Console.Write("Your first name: ") strFirstName = Console.ReadLine() Console.Write("Your last name: ") strLastName = Console.ReadLine() 'Concatenate the first and last name, without putting 'a space character between them. strFullName1 = strFirstName + strLastName 'Concatenate the first and last name, putting 'a space character between them. strFullName2 = strFirstName + " " + strLastName Console.WriteLine() Console.WriteLine("The strings concatenated without a space: " & strFullName1) Console.WriteLine() Console.WriteLine("The strings concatenated with a space: " & strFullName2) Console.ReadKey() 'hold the window until user presses any key End Sub End Module

The outputs of Source Code Listing 1.5 are shown in Fig. 1.5a- Fig. 1.5c

Page 21: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 21 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Fig. 1.5a

Fig. 1.5b

Fig. 1.5c

Page 22: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 22 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

1.6: A quick look at a dozen VB.NET built-in string functions

VB.NET is very rich in built-in string functions. The number of

string functions available are many indeed, as you can see in

the screenshot on this page.

These built-in string functions add power and speed to your

programming skills; as they allow you to get things done

pretty quickly without having to always code everything from

scratch. In other words, novice and seasoned VB.NET

programmers alike can easily replace entire custom functions

in their programs with a single line of code through these

built-in functions.

You may not see a use for some of these functions quite yet,

but you should familiarize yourself with them nonetheless, for

you are certainly going to need them by the time you move on

to intermediate and advanced level VB.NET programming.

Because of VB.NET's numerous functions, expect to refer to

this section several times before you uncover all that can be

accomplished with these functions.

1.6.1 Counting string length with Length

Say you have a word or sentence stored in a string variable

and you want to know how many characters are in that word

or sentence. VB.NET has a built-in function that will let you do

that effortlessly. The name of the function is Length, and its

syntax is as illustrated below:

Dim strT as String = "Gene" Console.WriteLine(strT.Length)

The above will print 4 because the string Gene has four

characters in it. What number will the following print as the length of strT? Will

it print 11 or 12?

Dim strT as String = "Gene is a poet." Console.WriteLine(strT.Length)

Page 23: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 23 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

The actual answer is 15! Yes, because the spaces are characters too, so they are

counted!

1.6.2 Joining strings with Concat()

We have already seen how to join or concatenate strings using the plus or

ampersand operators. Another way is to use the Concat method of the String

class.

Concat expects two parameters and will return a new string that is the

concatenation (addition) of the first string and the second string.

Example:

Dim str1 As String

Dim str2 As String

str1 = "Gene "

str2 = "is a poet"

Concsole.WriteLine(String.Concat(str1, str2))

The above will print Gene is a poet

1.6.3 Splitting strings with Split()

The built-in function Split separates or splits strings as the name suggests. It

simply splits a string into an array of substrings. There are many ways to use this

function but one of the simplest ways expects you to specify a delimiter to use in

splitting or separating the original string into pieces. A delimiter is usually a

single character like comma, space or semi-colon. Here's an example of how the

Split function works:

Fig. 1.6

Page 24: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 24 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

STOP & TYPE: Source Code Listing 1.6

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 1.6 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use the *") 07 Console.WriteLine("* Split function to tokenize or break a *") 08 Console.WriteLine("* string into pieces. *") 09 Console.WriteLine("********************************************") 10 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 11 Console.WriteLine("********************************************") 12 13 Console.WriteLine() 'just a blank line to make the display neat 14 15 'Declare a string variable to hold user input 16 Dim strS As String 17 18 Console.Write("Type any sentence: ") 19 strS = Console.ReadLine() 20 21 'Declare an unbounded string array variable 22 Dim strPieces() As String 23 24 'Split the string wherever it has blank spaces, store result in strPieces 25 strPieces = strS.Split(" ") 26 27 Console.WriteLine() 'just a blank line to make the display neat 28 29 'Lets know how many words are in the sentence 30 Console.WriteLine("The sentence '" & strS & "' contains " & strPieces.Length & " words.") 31 32 Console.ReadKey() 'hold the window until user presses any key 33 End Sub 34 End Module

Source Code Listing 1.6 Explained

I think line 22 is the most interesting line to start at in Source Code Listing 1.6.

The statement Dim strPieces() As String is declaring a string variable no doubt;

but this kind of string variable (with empty brackets) is an example of an array

variable. An array variable is capable of holding not just one data value, but

many data values of the same kind. We shall properly learn about arrays in

DCS106 but for now, let's just have a quick look at how an array variable makes

life easier:

Instead of writing the following:

Page 25: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 25 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Dim strData1 As String = "Auwal Gene"

Dim strData2 As String = "24B, Admiralty Drive, Green Zone Estate"

Dim strData3 As String = "Kaiama"

Dim strData4 As String = "Kwara"

Dim strData5 As String = "08032126160"

Dim strData6 As String = "+2348032126160"

You could do it like so with an array:

Dim strData(5) As String

strData(0) = "Auwal Gene"

strData(1) = "24B, Admiralty Drive, Green Zone Estate, Abuja"

strData(2) = "Kaiama"

strData(3) = "Kwara"

strData(4) = "08032126160"

strData(5) = "+2348032126160"

One obvious fact from the above two

code snippets is that with an array,

you only need to declare the variable

once and subsequently use indices to

access the various elements of the

array. This shall be explained further

in the class and also when you learn

about arrays proper in DCS106.

Okay, so now you get it. strPieces is

declared as a string array variable

because by the time we split the

sentence into pieces, each piece will

be a single string data item that will

fit into an index in the strPieces()

array.

Now at line 25, we write the single

line of code strPieces =

strS.Split(" ") that will split the

sentence that was already entered by

the user and stored in strS at line 19

of Source Code Listing 1.6.

What the statement at line 25 does is

take strS, scan it from beginning to

end, and break it up wherever it finds

the blank space " ". Let's take a

concrete example:

Assume the user typed "Well, I

think VB.NET is the best

programming platform.", then:

Page 26: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 26 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

strS = "Well, I think VB.NET is the best programming platform."

And when we apply the Split() function to strS using the statement strPieces =

strS.Split(" "), strS gets broken up and the pieces are stored in strPieces as

follows:

strPieces(0) = "Well,"

strPieces(1) = "I"

strPieces(2) = "think"

strPieces(3) = "VB.NET"

strPieces(4) = "is"

strPieces(5) = "the"

strPieces(6) = "best"

strPieces(7) = "programming "

strPieces(8) = "platform."

On the other hand, if we apply the Split() function to strS using the statement

strPieces = strS.Split(","), strS gets broken up wherever there are comas

and the pieces are stored in strPieces as follows:

strPieces(0) = "Well"

strPieces(1) = " I think VB.NET is the best programming platform."

Now, what will the result be if we apply the Split() function to strS using the

statement strPieces = strS.Split(".")?

To finish off on our explanation of Source Code Listing 1.6, we look at line 30

where we try to know how many words are in the sentence that was typed in by

the user:

Console.WriteLine("The sentence '" & strS & "' contains " & strPieces.Length & " words.")

Page 27: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 27 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

The Length function not only counts characters in a string, but also counts the

number of elements in an array!

1.6.4 Trimming strings with Trim()

Quite often, it is necessary to remove leading and/or trailing spaces from a string.

A leading space is space that comes before a string, while a trailing space is

space that comes after a string. For example:

str1 = "Gene " (trailing space)

str2 = " Gene" (leading space)

str3 = " Gene " (leading and trailing spaces)

From the above, str1 has a trailing space, str2 has a leading space, while str3

has both a leading and a trailing spaces. So now you get it, right? Okay, so to

remove any of those spaces from either end of a string, you could use the Trim()

approach as follows:

str4 = str1.Trim()

str5 = str2.Trim()

str6 = str3.Trim()

Note: The Trim() function removes spaces only from the beginning and end of

strings. If you need to remove spaces within a string, you'll need to go by a

different approach, using the Replace() function. Also, if you want to remove

spaces only at the beginning of a string only, then use TrimStart() and if you

want to remove spaces only at the end of a string, use TrimEnd().

1.6.5 Deleting characters from a string with Remove()

The String.Remove() method

removes a specified number of

characters in the original string and

returns a new string. The function

removes characters beginning at a

specified position, as the following

example illustrates:

Dim strS As String = "This is becoming more interesting!"

strS = strS.Remove(16)

Page 28: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 28 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

GOOD TO KNOW

Note that VB.NET starts counting

strings and arrays from zero

rather than from one; hence the

position of "n" in the string

"Gene" is 2, not 3!

The above should result in strS being

truncated to "This is becoming",

meaning that it removes everything

that occurs from position 16 in the

original string (i.e. it preserves

everything from position 0 – 15, but

removes everything else thereafter).

Another way of using the Remove()

function is to add a second parameter

to indicate the end point where we

want the removal to stop. So let us

still use our sample string but modify

our call to the Remove() function as

follows:

Dim strS As String = "This is becoming more interesting!"

strS = strS.Remove(16, 5)

In this case, we are telling the

Remove() function to go to index 16

and remove 5 characters from the

original string, starting from that

16th index. This will result in the

string "more" being removed from the

original string, thus leaving strS to

now contain the string "This is

becoming interesting!".

Note that the start index (i.e. the first

parameter) specified for the Remove()

function must be a numeric value

that must not be more than the total

number of characters in the original

string, otherwise you would get a

run-time error and the application

will crash.

1.6.6 Inserting characters into a string with Insert()

The String.Insert() method can be used to fix in a

character or a string inside another string at a specific

position. Assuming you have the following string

literal for example:

strT = "Gene is a poet"

Page 29: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 29 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

And now you want to insert the qualifier "speculative" before "poet" so that the

string now becomes "Gene is a speculative poet", you could do it like this:

Dim strT As String = "Gene is a poet"

strT = strT.Insert(9, "speculative")

The above will produce "Gene is aspeculative poet", which is not exactly what

we want (notice that "a" and "speculative" are lumped together). We want a

proper sentence with proper spacing, so we can modify our code like so:

strT = strT.Insert(9, " speculative")

or

strT = strT.Insert(10, "speculative ")

1.6.7 Replacing characters in a string with Replace()

If you ever need to replace some

characters in a string with another

character or string, the

String.Replace() method lets you do

that effortlessly. For example, of you

want to replace every "e" with "i"

in "Gene" so that it now becomes

"Gini", you can use the Replace()

method to achieve that as follows:

Dim strName As String = "Gene"

Dim strNewName As String = strName.Replace("e", "i")

The variable strNewName will now contain the string "Gini". You may also want to

do the changes and permanently change the original string (without creating a

new derived string):

Dim strName As String = "Gene"

strName = strName.Replace("e", "i")

Page 30: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 30 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

And if you want to replace all double spaces in a sentence with a single space, you

could write:

myString = myString.Replace(" ", " ")

Another example: What will strT become after running the codes below?

Dim strT As String = "The ink bottle is spilling ink on the dustbin"

strT = strT.Replace("in", "on")

1.6.8 Padding strings left or right with PadRight() and PadLeft()

"Padding" a string means adding

some characters to it either from the

beginning or at the end. So if you

have a string strS = "Gene is a

poet", you could pad it with three

stars to the right (i.e. at the end of the

string) to make it become like so:

strS = "Gene is a poet***".

The function String.PadLeft() or

String.PadRight() pads the string

with a character for a given length.

The function expects you to specify

two parameters, namely the total

number of characters that the

original string will have after the

padding, and character to pad the

original string with. You may choose

to specify only the first parameter

though and this has its own effects as

you shall know shortly.

So, the original string in our example

strS = "Gene is a poet" contains 14

characters. After padding it on the

right with three stars, the total length

will be 17 characters. Hence, we can

write the following code to correctly

add three stars to the original string:

Dim strS As String = "Gene is a poet"

strS = strS.PadRight(17, "*")

After running the above code, we

should now have strS becoming

strS = "Gene is a poet***"

Assuming you write something like

strS = strS.PadRight(17) without

specifying what character to pad the

original string with, the function will

just add spaces by default to make it

up to the specified total length of 17.

Now, the original string in our

working example has 14 characters.

Page 31: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 31 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Here are what you'll get if you specify

the following number of characters

with PadRight():

strS.PadRight(20, "*")

--> Gene is a poet******

strS.PadRight(14, "*")

--> Gene is a poet

strS.PadRight(10, "*")

--> Gene is a poet

That is to say that if you specify a

number that is equal to the exact

number of characters as in the

original string, nothing gets added to

it and if you also specify a number

that is less than the original number

of characters in the string, nothing

gets added. You get something added

if and only if the number specified is

greater than the total number of

characters in the original string.

1.6.9 Converting string capitalizations with ToUpper() and ToLower()

There is a function in VB.NET that

can convert the entire letters in a

string to their uppercase (i.e. capital

letters) equivalent; and there is also

another one that converts letters to

lowercase. Behind the scenes, these

methods actually create a new string

rather than changing the original

string.

The function that turns everything to

uppercase is String.ToUpper, while

String.ToLower converts strings to

their lowercase equivalent. Both

functions are pretty easy to use:

Dim strS As String = "Gene is a poet"

strS = strS.ToUpper

Yields "GENE IS A POET"

strS = strS.ToLower

Yields "gene is a poet"

1.6.10 Getting part of a string with Substring()

Given a string, you could want to

"slice" some smaller portion out of

the original string for whatever

reason, and the slice could come from

Page 32: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 32 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

any part of the string (i.e. at the

beginning, at the end, or just from

anywhere within). The Substring()

method gets you a part of a string,

starting from a specified start

position to a specified end position.

Let's look at an example:

Dim strS As String = "The man is good at programming"

Dim strT As String = strS.Substring (4, 11)

With the above, strT will contain the

substring "man is good", because the

starting index is 4 and we are

interested only in 11 characters

thereafter.

It is also possible to specify only the

starting point for the Substring()

function and ignore the number of

characters we want to return. In that

case, the function will return

everything starting from the specified

index to the end of the string, as

illustrated thus:

Dim strS As String = "The man is good at programming"

Dim strT As String = strS.Substring (8)

With the above, strT will contain the

substring "is good at programming",

because the starting index is 8 and

the function will return everything

from that index by default, since we

did not explicitly specify how many

characters to return.

Note that the first parameter for

Substring() must be an integer and

not a real number. Note also that if

the specified first parameter is

greater than or equal to the number

of characters in the original string, an

error will occur and the program will

crash.

Finally, you should also note that just

like most other string functions in

VB.NET, the Substring() method is

also zero-based (i.e., the first position

of a string is 0, not 1).

Page 33: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 33 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

1.6.11 Reversing strings with StrReverse()

One of the simplest ways to reverse a

string is to use the StrReverse()

function. Reversing a string means

turning it around so that the last

character is now the first and the first

one is now the last. For example, if

you reverse the string "Gene", you get

"eneG"; while reversing the string

"IACC-ABU" gives "UBA-CCAI". Here is

how to use StrReverse():

Dim strT As String = "I love Dot NET Programming!" Dim strNewT As String = StrReverse(strT)

With the above, strNewT will contain the string "!gnimmargorP TEN toD evol I".

1.6.12 Copying strings with Copy()

A simple way to copy a string to another is to use the String.Copy() method. The

method works similar to assigning a string to another using the = operator.

Examples are straightforward:

Dim strT As String = "I love Dot NET Programming!"

Dim strNewT As String = String.Copy(strT)

With the above, the contents of strT will be copied into strNewT.

1.7: Class Exercises: Find the bugs!

1. The code statement below was written by a VB.NET student to declare a

string variable and assign a string literal containing double quotes.

Detect any errors in the statement and suggest a proper way to write it:

Dim strVar = String As "Please pronounce the word """genre"""

2. New VB.NET programmer Chinyere is writing a program to create a

database of the names, addresses and birth dates of her friends. She

Page 34: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 34 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

begins by declaring one of the string variables as follows, but VB.NET

doesn't like what she's doing:

Dim FriendName = String

Can you help Chinyere out of her problem by telling her what she's

doing wrong and then suggest a correct way of doing her variable

declaration?

3. In a bid to print out a string variable that had been previously declared

and used to store data value, novice VB.NET student Abubakar wrote the

following line of code but he is not getting expected output:

Console.WriteLine("I'm glad to meet you & strUserName")

What is wrong with the above, and how should Abubakar write his code

to get the desired output?

4. Given the string strS = "Now is the time for all good people to

come to the aid of this country", Aisha wants to use a VB.NET built-

in function to get the substring "time for all good people" out of the

original string by writing the following line of code:

Dim strT As String = strS(Substring, 12, 24)

What will the code return, and what corrections should Aisha make to

her code to make it run and return the desired substring?

5. Given the string strS = "I hate stubborn bugs in my codes!", Oriyomi

wants to write a VB.NET statement that will delete the word "stubborn"

from the given string. Below is what he wrote but the compiler keeps on

returning a runtime error. Detect the error in Oriyomi's code and

suggest a correct way of writing it to achieve his goal:

strT = strS.Delete(7, "stubborn")

Page 35: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 35 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

1.8: Extra Credits: Can You?

Write a complete VB.NET console application that will accept your friend's

surname, favourite colour and height. Then let your program proceed as

follows:

i. Take the first letter of the surname and replace it with the question

mark character, "?"

ii. Insert a caret symbol, ^, in-between every letter of the favourite

colour (e.g. Yellow becomes Y^e^l^l^o^w).

iii. Take the integer part of the height and use it as an index to remove

the character at the nth index of the surname (e.g. if surname typed is

Olanrewaju and height is 5.74, the program should remove the

character at the 5th index of Olanrewaju).

Page 36: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 36 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

SECTION II: DECISION AND SELECTION

2.0: Introduction

Normally, VB.NET sequentially

executes statements in the source

codes from the first statement to the

last. That is what we call sequential

execution. Life will be too boring if

things are always left to proceed in

their default sequential tendencies

however, hence we usually introduce

conditions into our affairs to make

matters more interesting. Let's take

a few simple real-life examples:

Assume you have this pretty straight

routine way of life: you wake up in

the morning, clean up, walk out the

street, take a bus and head to school.

This you do every school day.

But simple and straight as it is, your

daily morning life is not actually that

routine. In fact, most of our so-called

"daily routines" are not that routine –

at least not at the level of thought.

When you wake up in the morning,

you may not just clean up and hit the

streets. Usually, it involves some

subtle "if" conditions that you

consider in your thoughts without

even knowing it. For example, you

might subconsciously think "if I had

swept the house last night before

going to bed then let me just get into

the bathroom and clean up" (else

you'd better sweep the house first

before entering the bathroom).

See there? You don't always hit the

shower, you first think it out before

actually doing it.

A variant of that would be "If the

weather is too cold I'll bathe with hot

water" – again you are considering a

condition before deciding on what

kind of bath you shall be having (cold

or hot).

Another example yet is "if my clothes

are already ironed, then I can put

them on and begin my journey to

school".

Okay, I believe you are getting it by

now, but we can take one more

delicious example now: suppose that

there is a really delicious piece of

fried chicken breast-and-wing cutting

on the plate in front of you, just

begging to be eaten. But you are on a

diet. The chicken is clearly asking for

it. So what do you do, eat the chicken

and ruin your diet? Or stick to your

diet and let somebody else have that

delicious treat? You might even be

saying this to yourself:

"If I eat the chicken then my diet will

be ruined"

Page 37: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 37 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

or

"If I don't eat the chicken then I will

be on course for a slimmer figure"

So you see, all of the above examples

are conditional logic – they are

something you use in your daily life

all the time, without even realizing

you're doing it.

If you consider it carefully, you'll

notice that the last example about

eating fried chicken or not eating it

uses the words IF and THEN in the

sentences. Of course, the above

sentences can still be constructed

without explicitly using IF and THEN,

as in the following:

"I can maintain my dieting plan for a

slimmer figure on the condition that

I will not eat chicken"

and

"I will eat the chicken on the

condition that my diet will be ruined"

Conditional logic is all about that

little IF word. And as you will see

shortly, you can even add ELSE to it,

like so:

"if my clothes are already ironed, then

I can put them on and begin my

journey to school else I'll have to iron

them first before putting them on and

going to school"

Or we can make it neater like we do

in programming:

IF my clothes are already ironed, THEN

I can put them on and begin my

journey to school

ELSE

I'll have to iron them first before

putting them on and going to school

And that is what conditional logic is

all about – saying what happens if

one condition is met, and what

happens if the condition is not met.

VB.NET uses those same words - If,

Then, Else for conditional logic (there

is also the End If word that wraps

things up nicely).

Let's try something out:

Imagine it's your birthday and many

people come to celebrate at your

little party. One of the people you are

looking forward to meeting is called

Auwal Gene. You have heard about

him but you have never seen or met

him. So how do you know him from

out of the many people who would be

at your party?

The simplest thing to do is when

people come over to say 'hello' or

'happy birthday' to you at the party,

simply ask them their name and if

any of them says "I am Auwal Gene",

then you could they excitedly

proclaim "ah, so you are the

Page 38: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 38 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

speculative poet I have been hearing

so much about! I'm glad you came to

my party and..."

Okay, so you get the gist now; so let's

look at this code snippet that will

take in a user's name and if the name

typed in happens to be Auwal Gene

then print the sentence "ah, so you

are the speculative poet I have been

hearing so much about! I'm glad you

came to my party!"

STOP & TYPE: Source Code Listing 2.1

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 2.1 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use the *") 07 Console.WriteLine("* If statement to decide what to print. *") 08 Console.WriteLine("********************************************") 09 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 10 Console.WriteLine("********************************************") 11 12 Console.WriteLine() 'just a blank line to make the display neat 13 14 'Declare a string variable to hold user input 15 Dim strUserName As String 16 17 Console.Write("What is your name please? ") 18 strUserName = Console.ReadLine() 19 20 Console.WriteLine() 'just a blank line to make the display neat 21 22 'Test if it is Auwal Gene and print a sentence 23 If strUserName = "Auwal Gene" Then Console.WriteLine("ah, so you are the speculative poet I have been" & vbNewLine & "hearing so much about! I'm glad you came to my party!") 24 Console.WriteLine() 'just a blank line to make the display neat 25 Console.WriteLine("Press any key to continue...") 26 Console.ReadKey() 'hold the window until user presses any key 27 End Sub 28 End Module

Page 39: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 39 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Source Code Listing 2.1 Explained

I think the "big thing" in Source Code

Listing 2.1 is found at line 23 where

we use the If...Then statement in a

single line (never mind that the line

had to be "broken" into 2 lines

because it won't fit the paper's

width). We are telling VB.NET that it

should print the sentence only If

strUserName = "Auwal Gene".

Notice that typing in anything that is

not exactly "Auwal Gene" will result

in the program not printing the

output "ah, so you are the

speculative poet I have been

hearing so much about! I'm glad

you came to my party!" Instead, it

will just move on to the next

executable line and ask the user to

press any key to continue...

This is especially important to

understand, because when VB.NET

(and all other standard programming

languages) compare strings, by

default they compare them to match

exactly (except if otherwise indicated

that you want the comparison to be

done differently). For this reason,

"Auwal Gene" is not the same thing as

"AUWAL GENE" or "auwal gene" or

"Auwal gene" or "AuWaL geNE".

So how then can you modify Source

Code Listing 2.1 and tell it to ignore

case differences (i.e. capitalization

differences) in what you type and just

go on to recognize the user once they

type in anything that matches the

desired name? I mean, how do you

make the program a little intelligent

so that it can understand that "Auwal

Gene" or "AUWAL GENE" or "auwal

gene" or "Auwal gene" or "auWaL

gENe" are all the same name?

There are almost a thousand and one

ways to do that, but one simple way

is to use our ToUpper (or ToLower)

built-in string function to change the

default comparison behaviour of

VB.NET. You can simply change line

23 to the following and it will work

no matter the capitalization, so long

as you type in something that

matches "Auwal Gene":

If strUserName.ToUpper = "AUWAL GENE" Then Console.WriteLine("ah, so you are the

speculative poet I have been" & vbNewLine & "hearing so much about! I'm glad you came to

my party!")

And that's all you need to do. Try it

out and see!

One more thing that might be

probably new to you in line 23 is the

Page 40: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 40 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

built-in string constant vbNewLine. It

simply tells VB.NET to insert a new

line character into the string at that

point so that when the string is

printed on the screen, it will "break"

into the next line as if you actually

pressed the ENTER key at that point

while typing the string.

2.1: Working with single-line and block IF statements

Source Code Listing 2.1 has introduced us to the single-line IF statement already.

A single-line IF statement is simply an IF statement that takes on the form:

IF (some condition) THEN (do something)

So you could have something like the following few:

If intK = 12 Then Console.WriteLine("That is a dozen")

If strGender = "F" Then Console.WriteLine("Not eligible to enroll")

If boolBitValue = 0 Then Console.WriteLine("All lights out!")

If strPost = "President" Then strSalutation = "Your Excellency Sir!"

And so on... Notice from the last example above that IF statements don't always

have to be followed by a Console.WriteLine command when the condition holds

true.

So, that is how the single-line IF statement goes. Programmers prefer to work

with the "structured" version of things however, and even the IF statement too

has that version and it goes something like so:

IF (some condition) THEN

(do something)

END IF

Thus, we can re-write line 23 of Source Code Listing 2.1 as follows:

If strUserName = "Auwal Gene" Then

Console.WriteLine("ah, so you are the speculative poet I have been" & vbNewLine _

& "hearing so much about! I'm glad you came to my party!")

End If

Or, if we want to still handle the capitalization issues, then it would be coded as:

Page 41: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 41 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

GOOD TO KNOW

Apart from making your code tidier, the

block IF structure also allows you to

write more than one line of code within

the condition block, for example:

If intAge < 18 Then

strT = "You'll have ice cream"

bytC = 1

Console.Write("You are a minor")

End If

With the above, we have three lines of

code within the block, and you can have

even more, depending on what your

code is supposed to do.

If strUserName.ToUpper = "AUWAL GENE" Then

Console.WriteLine("ah, so you are the speculative poet I have been" & vbNewLine _

& "hearing so much about! I'm glad you came to my party!")

End If

And so, the other examples we have already considered will be re-written in the

block format as follows:

If intK = 12 Then

Console.WriteLine("That is a dozen")

End If

If strGender = "F" Then

Console.WriteLine("Not eligible to enroll")

End If

If boolBitValue = 0 Then

Console.WriteLine("All lights out!")

End If

If strPost = "President" Then

strSalutation = "Your Excellency Sir!"

End If

And so on... Now that is a lot tidier. Note that we

start a new line after the word Then. The first

line contains our condition: "If the following

condition is met". The second line is what we

want to do if the condition is indeed met. And

the third line tells VB.NET that the If statement

ends right here.

Page 42: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 42 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

GOOD TO KNOW

Code Indentation: You will notice that in

all the block IF structures given as

examples in this manual, we have

always indented the codes inside the

IF...THEN and ELSE...END IF clocks. This

makes the code both neater and easier

to read. Proper and consistent code

indentation is a very good coding style

that is strongly recommended in

VB.NET and other major programming

languages; so do get used to it! :-)

2.2: Working with IF...THEN...ELSE statements

All the IF conditionals that we have

considered so far gave only a single

pathway of execution if the tested

condition holds. We have not

explicitly provided an alternative

pathway of execution if the tested

condition fails. Although what we

have been doing so far will work, it is

always a better programming

practice to explicitly specify the

alternative way to go should the test

condition fail. Good enough, VB.NET

give us the ELSE clause, which we can

specify in both the single-line and

block IF statements. Some examples

will be good:

If intK = 12 Then Console.WriteLine("That is a dozen") Else Console.WriteLine("Unknown quantity")

If strGender = "F" Then Console.WriteLine("Not Eligible ") Else Console.WriteLine("Eligible")

If boolBitValue = 0 Then Console.WriteLine("All lights out!") Else Console.WriteLine("Lights on!")

If strPost = "President" Then strS = "Your Excellency Sir!" Else strS = "Fellow Countryman!"

And the block IF versions of the above will be:

If intK = 12 Then

Console.WriteLine("That is a dozen")

Else

Console.WriteLine("Unknown quantity")

End If

If strGender = "F" Then

Console.WriteLine("Not Eligible")

Else

Console.WriteLine("Eligible")

End IF

If boolBitValue = 0 Then

Console.WriteLine("All lights out!")

Else

Console.WriteLine("Lights on!")

End If

If strPost = "President" Then

strS = "Your Excellency Sir!"

Else

strS = "Fellow Countryman!"

End If

Page 43: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 43 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Now let us revisit your birthday party

guests and try to find out who is

Auwal Gene among them. We have

already seen how we can use the IF

statement to determine if a guest's

name is Auwal Gene and how we can

then proceed to print the sentence

"ah, so you are the speculative poet I

have been hearing so much about! I'm

glad you came to my party and..."

Now we want to specify what the

code should explicitly print if the

name entered is not Auwal Gene.

STOP & TYPE: Source Code Listing 2.2

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 2.2 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use *") 07 Console.WriteLine("* If-Then-Else to decide what to print. *") 08 Console.WriteLine("********************************************") 09 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 10 Console.WriteLine("********************************************") 11 12 Console.WriteLine() 'just a blank line to make the display neat 13 14 'Declare a string variable to hold user input 15 Dim strUserName As String 16 17 Console.Write("What is your name please? ") 18 strUserName = Console.ReadLine() 19 20 Console.WriteLine() 'just a blank line to make the display neat 21 22 'Test if it is Auwal Gene and print a sentence 23 If strUserName.ToLower() = "auwal gene" Then 24 Console.WriteLine("ah, so you are the speculative poet I have been" & vbNewLine _ 25 & "hearing so much about! I'm glad you came to my party!") 26 Else 27 Console.WriteLine("Okay, thanks for coming to my party.") 28 End If 29 30 Console.WriteLine() 'just a blank line to make the display neat 31 Console.WriteLine("Press any key to continue...") 32 Console.ReadKey() 'hold the window until user presses any key 33 End Sub 34 End Module

Page 44: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 44 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

2.3: Working with IF-THEN-ELSEIF statements

So far, we have explored only relatively simple IF and IF-THEN-ELSE statements,

because we have been dealing with examples that handle only one condition or

one out of two conditions. But what if we have more than two conditions to test

for? So for example we have written:

If strPost = "President" Then

strS = "Your Excellency Sir!"

Else

strS = "Fellow Countryman!"

End If

The above is obviously testing only for the post of "President" and "Others". But

what if we now want to test for President, Traditional Ruler, Chief Judge and

then others? We would need to use a modified version of the IF-THEN-ELSE-END

IF statement like so:

If strPost = "President" Then

strS = "Your Excellency Sir!"

ElseIf strPost = "Chief Judge" Then

strS = "Your Lordship Sir!"

ElseIf strPost = "Traditional Ruler" Then

strS = "Your Royal Highness Sir!"

Else

strS = "Fellow Countryman!"

End If

Page 45: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 45 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

With the above structure, we are now using the ElseIf statement to test for more

than two possible conditions and in the end, only one of the conditions will hold

true and the code will execute accordingly. Source Code Listing 2.3 is a complete

program that will ask the user to type in their post and then the program will

salute the user according to what he or she types.

STOP & TYPE: Source Code Listing 2.3

Module Module1 Sub Main() Console.WriteLine("********************************************") Console.WriteLine("* DCS105 Source Code Listing 2.3 *") Console.WriteLine("********************************************") Console.WriteLine("* This program demonstrates how to use ElseIf *") Console.WriteLine("* to select out of more than 2 conditions. *") Console.WriteLine("********************************************") Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") Console.WriteLine("********************************************") Console.WriteLine() 'just a blank line to make the display neat 'Declare a string variable to hold user input Dim strPost As String, strS As String Console.Write("What is your job position please? ") strPost = Console.ReadLine() Console.WriteLine() 'just a blank line to make the display neat If strPost.ToLower() = "president" Then strS = "Your Excellency Sir!" ElseIf strPost.ToLower() = "traditional ruler" Then strS = "Your Royal Highness Sir!" ElseIf strPost.ToLower() = "chief judge" Then strS = "Your Lordship Sir!" Else 'any thing else is considered ordinary citizen strS = "Fellow Countryman!" End If Console.WriteLine() 'just a blank line to make the display neat Console.WriteLine(strS) Console.WriteLine("Press any key to continue...") Console.ReadKey() 'hold the window until user presses any key End Sub End Module

Page 46: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 46 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

2.4: Working with compound conditions containing logical operators

IF statements are powerful

constructs that can add great

flexibility and intelligence to your

programs; and they can become even

more powerful and interesting if the

IF statements are used in conjunction

with logical operators (AND, OR).

So for example, if I want to test

whether your gender is M (male) and

your age is 18 or greater before

considering you as eligible for

conscription (into the Army), I can do

this type of testing in VB.NET by

using our IF statement as usual, but

this time around the test conditions

are two, not just one – so we use AND

to do the double test as follows:

Page 47: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 47 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

If strGender = "M" And intAge >= 18 Then

Console.WriteLine("You are eligible for conscription!")

Else

Console.WriteLine("You are NOT eligible for conscription!")

End If

You can see how we used the logical

operator And to test for both

conditions before proceeding. With

the above, both conditions must be

true before the program will print

the message "You are eligible for

conscription!". If only one of the

conditions is true (e.g. you are male

but below 18 or you are above 18 but

not male) then the test condition fails

and it will instead print "You are NOT eligible for conscription!"

Of course, you can test for more than

two conditions also, as in the

following:

If strGender = "M" And intAge >= 18 And strCountry = "Nigeria" Then

Console.WriteLine("You are eligible for conscription!")

Else

Console.WriteLine("You are NOT eligible for conscription!")

End If

In a situation whereby you want the code to do something if just any one of the

specified conditions is satisfied rather than all of the conditions, then you would

use the Or operator instead of the And operator. So for example the statement "if

you are under 12 years old or you are female, then you'll have chocolates otherwise

you'll have meat pie" can be written programmatically as follows:

If strGender = "F" Or intAge < 12 Then

Console.WriteLine("You will have chocolates")

Else

Console.WriteLine("You will have meat pie")

End If

So with the above, the string "You will have chocolates" will be printed if

strGender contains the value "F" or if intAge contains a value less than 12. But if

Page 48: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 48 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

GOOD TO KNOW

When using logical operators to test

conditions, use AND if all the conditions

must be satisfied before the code

branches to the specified path. If you

only need some or part of the

conditions to be satisfied, then use OR.

strGender contains anything other than "F", and intAge is not less than 12, the

output will be "You will have meat pie".

Of course, you can combine And and Or operators in the same IF test, as in the

following example:

If (strGender = "F" And intAge < 12) Or (intKeyCode = 13) Then

Console.WriteLine("You will have a pink-coloured dress")

Else

Console.WriteLine("You will have a white gown")

End If

With the above, we are testing for two possible

conditions using Or; but the first (i.e. the left)

part of the Or test contains a composite test of

its own using And. This is perfectly legal, and is

only but a small tip of the iceberg concerning

what you can do with the IF construct when

combined with logical operators.

Source Code Listing 2.4 illustrates a complete program that accepts a user's age

and decides what to print based on the range of the age specified by the user.

Take your time to type it in correctly and supply various values when you run it

to see how it works:

AGE RANGE MESSAGE TO PRINT

0 – 9 You are a kid, be appeased with these sweets!

10 – 12 You are a minor, don't be mischievous!

13 – 19 You are a teenager, watch your manners!

20 – 35 You are a young adult, we hope you can cope!

36 – 50 You are a mature adult, much is expected from you!

51 – 70 You are an experienced fellow, we count on you!

71 – 99 You are a senior citizen, your wisdom is immeasurable!

Anything Else You are probably not a living being at this time!

Page 49: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 49 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

STOP & TYPE: Source Code Listing 2.4

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 2.4 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use *") 07 Console.WriteLine("* logical AND to select out of many options*") 08 Console.WriteLine("********************************************") 09 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 10 Console.WriteLine("********************************************") 11 12 Console.WriteLine() 'just a blank line to make the display neat 13 14 Dim intAge As Integer, strS As String 15 16 Console.Write("What is your age, please? ") 17 intAge = CInt(Console.ReadLine()) 18 19 If intAge >= 0 And intAge <= 9 Then 20 strS = "You are a kid, be appeased with these sweets!" 21 ElseIf intAge >= 10 And intAge <= 12 Then 22 strS = "You are a minor, don't be mischievous!" 23 ElseIf intAge >= 13 And intAge <= 19 Then 24 strS = "You are a teenager, watch your manners!" 25 ElseIf intAge >= 20 And intAge <= 35 Then 26 strS = "You are a young adult, we hope you can cope!" 27 ElseIf intAge >= 36 And intAge <= 50 Then 28 strS = "You are a mature adult, much is expected from you!" 29 ElseIf intAge >= 51 And intAge <= 70 Then 30 strS = "You are an experienced fellow, we count on you!" 31 ElseIf intAge >= 71 And intAge <= 99 Then 32 strS = "You are a senior citizen, your wisdom is immeasurable!" 33 Else 'any thing else is considered a non-living person 34 strS = "You are probably not a living being at this time!" 35 End If 36 37 Console.WriteLine() 'just a blank line to make the display neat 38 Console.WriteLine(strS) 39 Console.WriteLine("Press any key to continue...") 40 Console.ReadKey() 'hold the window until user presses any key 41 End Sub 42 End Module

Page 50: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 50 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Now, let's have a word about how to properly use the And operator on a single

variable. Notice in Source Code Listing 2.4 the format with And:

19 If intAge >= 0 And intAge <= 9 Then

20 strS = "You are a kid, be appeased with these sweets!"

21 ElseIf intAge >= 10 And intAge <= 12 Then

22 strS = "You are a minor, don't be mischievous!"

23 ElseIf intAge >= 13 And intAge <= 19 Then

:

:

:

You can see how the variable intAge is repeated twice for each test:

If intAge >= 0 And intAge <= 9 Then

You will get an error if you just put something like this:

If intAge >= 0 And <= 9 Then

The same rule applies too when you are testing with Or operator, so get used to

it!

2.5: Class Exercises: Find the bugs!

1. What is wrong with the following if statements, and how would you write

them correctly?

If strG Is = "M" Console.WriteLine("You are male")

If strG = "M" And bytK Is 1 And Console.Write("You are qualified")

If strG Is = "M" Or Not Then Console.Write("You are not male")

Page 51: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 51 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

2.6: Making a case for CASE and SELECT CASE statements

Concept: In the preceding sections,

you learned how you can use the

IF...THEN statement to make your

program test some conditions and

execute certain routines depending in

the outcomes of the tested

conditions. Using IF...THEN

statement is fun, and it also makes

your programs seem intelligent. You

will now be introduced to a more

powerful tool for decision making in

VB.NET programming: the combined

SELECT CASE and CASE structure.

Yes, I call it "combined" because the

CASE keyword cannot, as it were, be

used alone. It has to be used in

combination with the SELECT CASE

statement, which happens to have the

look of the block IF structure.

Every SELECT CASE statement must

have a corresponding END SELECT

(just like every block IF statement

must have a matching END IF, you

remember?). And there is one more

thing to note: the CASE keyword must

have at least one parameter and we

can have as many CASE keywords as

desired within the SELECT CASE and

END SELECT structure.

To illustrate further, let us go back to

our salutation examples. Here, we

show the code from the section on

IF-THEN-ELSEIF with its SELECT CASE

equivalent:

If strPost = "President" Then

strS = "Your Excellency Sir!"

ElseIf strPost = "Chief Judge" Then

strS = "Your Lordship Sir!"

ElseIf strPost = "Traditional Ruler" Then

strS = "Your Royal Highness Sir!"

Else

strS = "Fellow Countryman!"

End If

Select Case strPost

Case "President"

strS = "Your Excellency Sir!"

Case "Chief Judge"

strS = "Your Lordship Sir!"

Case "Traditional Ruler"

strS = "Your Royal Highness Sir!"

Case Else

strS = "Fellow Countryman!"

End Select

You can quickly see that the SELECT

CASE structure is so similar to the

block IF structure; and it is so very

simple, too (just as simple to use as

the block IF structure, actually). But

you should never use SELECT CASE if

Page 52: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 52 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

a simple block IF statement would

work. Sometimes, using SELECT CASE

can be overkill, and it can also add to

the confusion that complex logic

statement can provide. In other

words, SELECT CASE should be used

only when writing codes that involve

such selection procedures that are so

long and complex that using the block

IF structure would not make it

economical.

The SELECT CASE structure allows for

multiple lines of code to appear

under every CASE keyword. The

example given above has only one

line of code for every CASE, but just

like the block IF structure, there can

actually be more than one line of

code for each CASE statement –

depending on what your program is

supposed to be doing.

The following example shows a

SELECT CASE code segment with three

code lines after each CASE statement:

Select Case strPost

Case "President"

strS = "Your Excellency Sir!"

dblAllowance = dblSalary * (34.9/100)

intPriorityCode = 1

Case "Chief Judge"

strS = "Your Lordship Sir!"

dblAllowance = dblSalary * (22.8/100)

intPriorityCode = 2

Case "Traditional Ruler"

strS = "Your Royal Highness Sir!"

dblAllowance = dblSalary * (14.7/100)

intPriorityCode = 3

Case Else

strS = "Fellow Countryman!"

dblAllowance = dblSalary * (4.0/100)

intPriorityCode = 4

End Select

The above way of writing code with

SELECT CASE is especially very

important when there are multiple

lines of code that follow a CASE

statement in the SELECT CASE

structure.

Page 53: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 53 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Let us take an example: You will

recollect in Source Code Listing 2.4

how we wrote a complete program

that accepts a user's age and decides

what to print based on the range of

the age specified by the user. We

used IF-THEN-ELSEIF structure to

write that code. Now we shall write

the SELECT CASE equivalent of that

code, as given in Source Code Listing

2.5. Take your time to type it in

correctly and supply various values

when you run it to see how it works:

STOP & TYPE: Source Code Listing 2.5

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 2.5 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use *") 07 Console.WriteLine("* SELECT CASE to select out of many options*") 08 Console.WriteLine("********************************************") 09 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 10 Console.WriteLine("********************************************") 11 12 Console.WriteLine() 'just a blank line to make the display neat 13 14 Dim intAge As Integer, strS As String 15 16 Console.Write("What is your age, please? ") 17 intAge = CInt(Console.ReadLine()) 18 19 Select Case intAge 20 Case 0 To 9 21 strS = "You are a kid, be appeased with these sweets!" 22 Case 10 To 12 23 strS = "You are a minor, don't be mischievous!" 24 Case 13 To 19 25 strS = "You are a teenager, watch your manners!" 26 Case 20 To 35 27 strS = "You are a young adult, we hope you can cope!" 28 Case 36 To 50 29 strS = "You are a mature adult, much is expected from you!" 30 Case 51 To 70 31 strS = "You are an experienced fellow, we count on you!" 32 Case 71 To 99 33 strS = "You are a senior citizen, your wisdom is immeasurable!" 34 Case Else 35 strS = "You are probably not a living being at this time!" 36 End Select 37 38 Console.WriteLine() 'just a blank line to make the display neat 39 Console.WriteLine(strS) 40 Console.WriteLine("Press any key to continue...") 41 Console.ReadKey() 'hold the window until user presses any key 42 End Sub 43 End Module

Page 54: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 54 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Notice that I threw in one trick there:

CASE n1 To n2. This is necessary

because we are now using a range of

values for our test conditions, rather

than just a single value. Thus we

specify a range from n1 to n2 with the

CASE statements above. So, this is like

saying "if the age falls between the

range of 13 and 19 inclusive, then

print so and so...". Notice also, how

we used CASE ELSE statement to trap

illegal values at line 34.

Now we shall consider yet another

good example: Assume we want to

enter the age of school children into

the computer and determine whether

they should belong to (i) pre-

nursery, (ii) nursery or (iii) primary

school. Also, based on their age, we

want to know if they should be given

biscuits, sweets or oranges for

refreshment. Finally, we shall also

decide if they should pay N10, N20,

or N50 as PTA levy. The following

table details the conditions:

Age Range Message Refreshment PTA Levy

2 – 3 The child belongs to Pre-Nursery Sweets 10.00

4 – 5 The child belongs to Nursery Oranges 20.00

6 – 11 The child belongs to Primary Biscuits 50.00

Anything Else The child belongs to Nowhere Nothing 00.00

STOP & TYPE: Source Code Listing 2.6

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 2.6 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use *") 07 Console.WriteLine("* SELECT CASE to select out of many options*") 08 Console.WriteLine("********************************************") 09 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 10 Console.WriteLine("********************************************") 11 12 Console.WriteLine() 'just a blank line to make the display neat 13 14 Dim intAge As Integer, strSchool As String 15 Dim strRefreshment As String, sglPTA As Single 16 17 Console.Write("What is the child's age, please? ") 18 intAge = CInt(Console.ReadLine()) 19 20 Select Case intAge 21 Case 2, 3 22 strSchool = "Pre-Nursery" 23 strRefreshment = "SWEETS" 24 sglPTA = 10.0

Page 55: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 55 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

25 Case 4, 5 26 strSchool = "Nursery" 27 strRefreshment = "ORANGES" 28 sglPTA = 20.0 29 Case 6 To 11 30 strSchool = "Primary" 31 strRefreshment = "BISCUITS" 32 sglPTA = 50.0 33 Case Else 34 strSchool = "No" 35 strRefreshment = "NOTHING" 36 sglPTA = 0.0 37 End Select 38 39 Console.WriteLine() 'just a blank line to make the display neat 40 Console.WriteLine("The child belongs to " & strSchool & " Section.") 41 Console.WriteLine("The child may have " & strRefreshment & " for refreshment.") 42 Console.WriteLine("The child's PTA levy is " & FormatNumber(sglPTA, 2)) 43 44 Console.WriteLine() 'just a blank line to make the display neat 45 Console.WriteLine("Press any key to continue...") 46 Console.ReadKey() 'hold the window until user presses any key 47 End Sub 48 End Module

Notice at line 21 how I threw in a

new way of using CASE, by saying

CASE 2, 3 instead of saying CASE 2

To 3. Line 25 also uses a similar

approach. This is perfectly legal, and

is tidy if you want the same code

segment to execute for a number of

values that may or may not be

consecutive. For example, if you

want your code to execute for values

of, say, 5, 6, 7, 8 and 9 then you would

naturally use CASE 5 To 9 rather than

CASE 5, 6, 7, 8, 9. However, the

most natural way to go for the case of

values like 5, 9, 17 and 30 would be

to use CASE 5, 9, 17, 30.

Finally, line 42 uses the built-in

number formatting function to tell

VB.NET that you want whatever that

is printed to show two decimal

places.

Page 56: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 56 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Class Exercise: Write the complete IF-THEN-ELSEIF equivalent of Source Code

Listing 2.6.

2.7: Extra Credits: Can You?

Assume a computer science student has first C.A. score, second C.A. score

and final exams score in a course called DCS105. Write a complete VB.NET

console application that will accept all the three scores of the student,

compute the total score and then determine the final grade and remarks of

the student in that course according to the following criteria:

Total Score Range Grade

Letter Remarks

00 – 50 F Failed

51 – 60 P Passed

61 – 70 C Credit

71 – 80 A Very Good

81 – 100 A+ Excellent

Page 57: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 57 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Conditions:

i. If the user enters a negative value for any of the scores, the program

should display an error message that will say "Please enter only

positive integer for scores" and terminate.

ii. First C.A. score must not be more than 10, second C.A. must not be

more than 15, and final exam scores must not be more than 75.

iii. You may use either the IF-THEN-ELSEIF construct or the SELECT CASE

construct to implement the program.

iv. The program's outputs should be similar to the one shown below:

Page 58: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 58 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

SECTION III: ITERATION AND LOOPING

3.0: Introduction

As you already probably know, a loop

is something that goes round and

round and round. So if I tell you to

move your finger around in a loop,

you would know what to do

immediately. In programming, loops

go round and round and round, too.

In fact, they go round and round until

you tell them to stop. You can write

codes without using loops (as you

have been doing all this while); but

there are times when using them

makes your life so much easier.

With VB.NET, the various loop

structures available will generally

allow one or more lines of code to

execute repeatedly; and the

repetition can continue until:

i. a condition is True, or

ii. a condition is False, or

iii. for a fixed number of times

Let's get concrete with an example:

say, you need to write code to print

the integers 1, 2, 3, 4, .... all the way to

10. You can do so by simply writing

something like so:

Console.WriteLine("1, 2, 3, 4, 5,

6, 7, 8, 9, 10")

Good, but not cool! What if you were

to print a million or more numbers?

Or what if you are supposed to

generate a series of even numbers,

prime numbers or factors of 3? Will

you stress yourself generating each

term of the series and write them all

out like the above? Obviously not!

Computers are not only fast, but good

at calculations too (that's why they

are called computers in the first

place!). So, we can easily tell the

computer to automatically calculate

each term in whatever series we are

generating and print it out then go

calculate the next term and print and

calculate the next term and print...

and so on until the last term of the

series is generated and printed.

If you tell the computer to repeatedly

generate and print each term of the

series from the first to the last, you

are actually telling the computer to

iterate or loop. To make the concept

clearer, let's look at an iterative

algorithm for generating and printing

the first positive 10 integers on the

number line:

Page 59: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 59 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Approach A Approach B

1 Set Number = 1 1 Set Number = 0

2 Print Number 2 Set Number = Number + 1

3 Set Number = Number + 1 3 Print Number

4 If Number <= 10 Goto Step 2 4 If Number < 10 Goto Step 2

5 Stop 5 Stop

Both the first and second approach in

the above algorithms are correct. In

the first approach, we start by setting

the variable Number to a value of 1 and

at step 2, that 1 is printed. Next is to

increment the value of that variable,

Number, by 1 so that Number now

contains the value 2; and then we test

at step 4 to see if we have reached or

not reached the last term of the series

we are generating. If we have not

reached, we go back to step 2 where

the current value of Number (i.e. 2) is

printed. Then step 3 increments the

value of Number by 1 again so that it

now contains 3 and we test again to

see if we have reached the last term

of the series. You can see how this

algorithm iterates or loops over the

process of generating and printing

each term of the series between steps

2 and 4. The moment the variable

Number contains a value greater than

10, the algorithm will no longer loop

back to step 2 but move on to step 5

instead. The same principle applies in

the second approach, only that the

initial value of Number is set to zero

and the test condition is using "less

than", rather than "less than or equal

to" to see if we have reached the end

of the iteration.

3.1: Looping with FOR...NEXT statement

We can use the FOR...NEXT statement to implement the above algorithm in actual

VB.NET code. The FOR...NEXT statement will be a simple 3-line code as follows:

For intNum = 1 To 10

Console.WriteLine(intNum)

Next intNum

Page 60: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 60 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Analysis: In the above FOR...NEXT code snippet, the statement For intNum = 1

To 10 is explained as follows:

For is a VB.NET keyword that tells the compiler that it is about to begin a

loop.

The variable intNum serves as the loop counter – it counts how many times

the loop has executed so far. In the statement, intNum is given an initial

starting value of 1 and a final terminal value, 10; meaning that the looping

will execute and count from 1 through 10.

The complete statement For intNum = 1 To 10 means something like this:

"prepare to execute the following codes in a loop, you will start counting the

loop from 1 and you will stop at 10; and you will use the variable intNum to

count the loop as it executes"

The "body" of the loop consists of only one statement in our example, which is the

output statement Console.WriteLine(intNum). Every time the loop iterates, this

statement will print out the current value stored in the variable intNum.

The last statement, Next intNum, works as follows:

It tells the program to move on to the next iteration; and

It automatically increments the value of intNum by 1 before actually moving

on to the next iteration.

The following flow diagram explains the workings of this simple FOR...NEXT loop:

Page 61: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 61 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

The FOR...NEXT loop has the simplest form as shown in the example above;

though the complete format is something like this:

FOR loop_counter = start_point TO end_point STEP increment_value

one or more program

statements

NEXT loop_counter

The STEP part specifies by how many steps the loop_counter should be

incremented at every iteration. It is optional and can be omitted. If omitted,

VB.NET assumes a default incremental step of 1. So in our example of generating

and printing normal integers 1 to 10, the value of intNum is always automatically

incremented by 1 whenever the program reaches the Next intNum statement.

So if we want to generate even numbers from 2 to 20 using the FOR...NEXT

construct for example, then we would include the Step option in our loop as

follows:

For intNum = 2 To 20 Step 2

Console.WriteLine(intNum)

Next intNum

The above will print 2, 4, 6, 8, 10, 12, 14, 16, 18, 20. Can you figure out what the

following code segment will print?

For intNum = 21 To 2 Step -3

Console.WriteLine(intNum)

Next intNum

How about this one?

For intNum = 2 To 21 Step -3

Console.WriteLine(intNum)

Next intNum

Page 62: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 62 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Class Exercise: Write code that...

Use FOR...NEXT loop to write a program to compute and print the final answer of

the following arithmetic: 602 + 562 + 522 + 482 + 442 + 402 + 362

3.1.1 Generating and printing even numbers with FOR...NEXT loop

Source Code Listing 3.1 generates

and prints even numbers starting

from 2 to whatever value the user

wants. The program asks the user to

specify where he or she wants the

even number generation to stop.

Note that the user may not always

type in correct data (for example, the

user may type in an odd number as

the stopping point instead of an even

number).

This program intelligently takes care

of that before generating and printing

the even numbers. If the user actually

specifies an even number, then the

program generates and prints all

even numbers from 2 to the specified

end point; otherwise if the user

specifies an odd number then the

program generates and prints all

even numbers from 2 to the last even

number before the specified odd

number (e.g. if user specifies 17 as

the last number, then the program

will stop after generating even

number 16) .

Of course, this extra check is not

necessary in this simple case, but in

real-world non-trivial programming,

it is always a good practice to check

user inputs in this way before

proceeding with the calculations or

other tasks that the program is meant

to perform.

Page 63: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 63 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

STOP & TYPE: Source Code Listing 3.1

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 3.1 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use *") 07 Console.WriteLine("* FOR...NEXT loop to generate and print *") 08 Console.WriteLine("* even numbers from 2 to a user-specified *") 09 Console.WriteLine("* end point. *") 10 Console.WriteLine("********************************************") 11 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 12 Console.WriteLine("********************************************") 13 14 Console.WriteLine() 'just a blank line to make the display neat 15 16 Dim e As Integer, e2 As Integer 17 18 Console.Write("Enter the last even number to generate: ") 19 e2 = CInt(Console.ReadLine()) 20 21 'if number entered is not even, make it even 22 If e2 Mod 2 <> 0 Then e2 = e2 - 1 23 24 For e = 2 To e2 Step 2 25 Console.Write(e & vbTab) 26 Next 27 28 Console.WriteLine() 'just a blank line to make the display neat 29 Console.WriteLine("Press any key to continue...") 30 31 Console.ReadKey() 'hold the window until user presses any key 32 End Sub 33 End Module

3.1.2 Generating and printing sums of numbers with FOR...NEXT loop

In this section, we want to

write code to generate

and print integers 1 – 10

and as we generate each

number, we are going to

cumulatively add it up to a

variable that stores the

sum of the integers. In the

end, we are going to print

out that cumulative sum.

Source Code Listing 3.2 is

the code.

Page 64: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 64 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

STOP & TYPE: Source Code Listing 3.2

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 3.2 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use *") 07 Console.WriteLine("* FOR...NEXT loop to generate integers 1-10*") 08 Console.WriteLine("* and print their sum. *") 09 Console.WriteLine("********************************************") 10 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 11 Console.WriteLine("********************************************") 12 13 Console.WriteLine() 'just a blank line to make the display neat 14 15 Console.Write("Generating integers 1 - 10. Press ENTER key to generate the next number:") 16 Dim intNumber As Integer, intSum As Integer 17 18 Console.WriteLine() 'just a blank line to make the display neat 19 20 intSum = 0 'begin by storing zero in the sum 21 For intNumber = 1 To 10 22 Console.WriteLine(intNumber) 23 intSum = intSum + intNumber 24 25 Console.ReadKey() 'hold the window until user presses any key 26 Next 27 28 Console.WriteLine() 'just a blank line to make the display neat 29 Console.WriteLine("Sum of the 10 integers = " & intSum) 30 31 Console.WriteLine("Press any key to continue...") 32 33 Console.ReadKey() 'hold the window until user presses any key 34 End Sub 35 End Module

3.1.3 Generating and printing sum of a series with FOR...NEXT loop (1)

Next, we want to write code to compute and print the sum and average of the first

fifty positive integers (i.e. numeric digits 1 – 50). Source Code Listing 3.3 is the

code. There some important things about this code that are not mentioned in this

manual, but they shall be

discussed in class; so make

sure you attend classes

regularly and pay attention

in class when this concept is

being explained!

Page 65: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 65 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

STOP & TYPE: Source Code Listing 3.3

Module Module1 Sub Main() Console.WriteLine("********************************************") Console.WriteLine("* DCS105 Source Code Listing 3.3 *") Console.WriteLine("********************************************") Console.WriteLine("* This program demonstrates how to use *") Console.WriteLine("* FOR...NEXT loop to compute the sum and *") Console.WriteLine("* average of the first 50 integers. *") Console.WriteLine("********************************************") Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") Console.WriteLine("********************************************") Console.WriteLine() 'just a blank line to make the display neat Console.Write("Generating integers 1 - 50:") Dim intNumber As Integer, intSum As Integer Dim sglAvg As Single Console.WriteLine() 'just a blank line to make the display neat intSum = 0 'begin by storing zero in the sum For intNumber = 1 To 50 Console.Write(intNumber & vbTab) intSum = intSum + intNumber Next sglAvg = intSum / 50 Console.WriteLine() 'just a blank line to make the display neat Console.WriteLine("Sum of the 50 integers = " & intSum) Console.WriteLine("Average of the 50 integers = " & sglAvg) Console.WriteLine() 'just a blank line to make the display neat Console.WriteLine("Press any key to continue...") Console.ReadKey() 'hold the window until user presses any key End Sub End Module

3.1.4 Generating and printing sum of a series with FOR...NEXT loop (2)

Now take a good look at the following equation:

The task is to write code that will

solve the equation and print the

answer. Before we begin, let's try and

analyse it first:

All terms of the equation have a

certain pattern, they are all fractions

of 1 (the numerator) and the

denominators are all regular powers

of 2 starting from 5 and ending at 9.

Page 66: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 66 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

We can easily solve for this equation

by putting the powers in a FOR...NEXT

loop as we generate and calculate

each term, which is then cumulatively

added to S. Source Code Listing 3.4

does it; and make sure you pay

attention in class when this concept

is explained because many things not

mentioned in this manual shall be

discussed in class!

STOP & TYPE: Source Code Listing 3.4

Module Module1 Sub Main() Console.WriteLine("********************************************") Console.WriteLine("* DCS105 Source Code Listing 3.4 *") Console.WriteLine("********************************************") Console.WriteLine("* This program demonstrates how to use *") Console.WriteLine("* FOR...NEXT loop to compute and print the*") Console.WriteLine("* sum of a series with fracrtional terms. *") Console.WriteLine("********************************************") Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") Console.WriteLine("********************************************") Console.WriteLine() 'just a blank line to make the display neat Dim p As Integer, S As Single S = 0 'begin by storing zero in the sum, S For p = 5 To 9 S = S + (1 / 2 ^ p) 'compute current term and add to S Next Console.WriteLine("Computed answer = " & S) Console.WriteLine() 'just a blank line to make the display neat Console.WriteLine("Press any key to continue...") Console.ReadKey() 'hold the window until user presses any key End Sub End Module

Page 67: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 67 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

3.1.5 Generating and printing sum of a series with FOR...NEXT loop (3)

Here again is the series:

It is essentially the same series as in

section 3.1.4, if you look carefully. As

with the series used in section 3.1.4,

all terms of the series here also have

a certain pattern: they are all

fractions of 1 (the numerator) and

the denominators are all regular

powers of 2. Unlike in section 3.1.4

where the powers of 2 start from 5

and end at 9 however, this time

around the powers of 2 actually start

from 0 (zero) and goes on and on to

any nth power.

Yes, we say the powers of 2 in the

above equation start from zero

because the above is exactly

equivalent to the following:

So, just like we did in section 3.1.4,

we can also easily solve for this

equation by putting the powers in a

FOR...NEXT loop as we generate and

calculate each term, which is then

cumulatively added to S. The power

of 2 in the equation starts from zero

of course, and ends at n – which

means the last power is not fixed –

which means we will need to ask the

user to specify what they want the

last power to be before we set up the

loop and start the computations.

Source Code Listing 3.5 does it; and

make sure you pay attention in class

when this concept is explained

further because many things not

mentioned in this manual shall be

discussed in class!

STOP & TYPE: Source Code Listing 3.5

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 3.5 *") 05 Console.WriteLine("********************************************")

Page 68: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 68 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

06 Console.WriteLine("* This program demonstrates how to use *") 07 Console.WriteLine("* FOR...NEXT loop to compute and print the*") 08 Console.WriteLine("* sum of a series with fractional terms *") 09 Console.WriteLine("* up to the nth term. *") 10 Console.WriteLine("********************************************") 11 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 12 Console.WriteLine("********************************************") 13 14 Console.WriteLine() 'just a blank line to make the display neat 15 16 Dim p As Integer, n As Integer, S As Single 17 18 Console.Write("Enter the nth power of 2 (integer only): ") 19 n = CInt(Console.ReadLine()) 20 21 S = 0 'begin by storing zero in the sum, S 22 For p = 0 To n 23 S = S + (1 / 2 ^ p) 24 Next 25 Console.WriteLine("Computed answer = " & S) 26 27 Console.WriteLine() 'just a blank line to make the display neat 28 Console.WriteLine("Press any key to continue...") 29 30 Console.ReadKey() 'hold the window until user presses any key 31 End Sub 32 End Module

Page 69: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 69 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

3.1.6 Implementing the StrReverse() function with FOR...NEXT loop

We looked at a dozen or so built-in

VB.NET string functions in section 1.6

of this manual. One of the built-in

functions discussed was the

StrReverse() function, which takes a

string and turns it around so that the

last character is now the first and the

first one is now the last. For example,

if you reverse the string "Gene", you

get "eneG"; while reversing the string

"IACC-ABU" gives "UBA-CCAI".

Now we want to write a VB.NET

program that will ask the user to type

in a word or a sentence and, without

using the built-in StrReverse()

function, we shall reverse whatever

the user types in and print out both

the original user input and the

reversed version.

This is done using a FOR...NEXT loop

in conjunction with the Substring()

function, as illustrated in Source Code

Listing 3.6:

Page 70: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 70 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

STOP & TYPE: Source Code Listing 3.6

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 3.6 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonsterates how to use *") 07 Console.WriteLine("* FOR...NEXT loop in conjunction with the *") 08 Console.WriteLine("* built-in String.Substring function to *") 09 Console.WriteLine("* implement the StrReverse function. *") 10 Console.WriteLine("********************************************") 11 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 12 Console.WriteLine("********************************************") 13 14 Console.WriteLine() 'just a blank line to make the display neat 15 16 Dim i As Integer, strS As String, strR As String 17 18 Console.Write("Enter a word or sentence: ") 19 strS = Console.ReadLine() 20 21 strR = "" 'begin by storing an empty string in the reversed string, strR 22 23 'begin the loop from last character down to first character: 24 For i = strS.Length - 1 To 0 Step -1 25 strR = strR & strS.Substring(i, 1) 'concatenate reversed string 1 char at a time 26 Next 27 Console.WriteLine() 'just a blank line to make the display neat 28 29 Console.WriteLine("Original string = " & strS) 30 Console.WriteLine("Reversed string = " & strR) 31 32 Console.WriteLine() 'just a blank line to make the display neat 33 Console.WriteLine("Press any key to continue...") 34 35 Console.ReadKey() 'hold the window until user presses any key 36 End Sub 37 End Module

Page 71: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 71 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

3.1.7 Implementing the String.Replace() function with FOR...NEXT loop

We can also implement the

String.Replace()function using a

loop. You will recall that the

String.Replace()function lets you

replace some characters in a string

with another character or string. For

example, of you want to replace

every "e" with "i" in "Gene" so that

it now becomes "Gini", you can use

the Replace() method to achieve that.

In this section, we shall now write

our own custom code to replace

characters in a string entered by the

user, and we shall not use the built-in

String.Replace()method. Please

make sure you are in class and do pay

serious attention when this code is

being explained in the class!

STOP & TYPE: Source Code Listing 3.7

01 Module 1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 3.7 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use *") 07 Console.WriteLine("* FOR...NEXT loop to implement the built-in*") 08 Console.WriteLine("* String.Replace function. *") 09 Console.WriteLine("********************************************") 10 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 11 Console.WriteLine("********************************************") 12 13 Console.WriteLine() 'just a blank line to make the display neat 14 15 Dim i As Integer 16 Dim strS As String 'original string entered by user 17 Dim strC As Char 'character to replace 18 Dim strR As Char 'character to replace with 19 Dim strFinal As String 'final string after processing 20 21 Console.Write("Enter a word or sentence: ") 22 strS = Console.ReadLine() 23 24 Console.Write("Enter a character you want to replace: ") 25 strC = CChar(Console.ReadLine()) 26 27 Console.Write("Enter a character to replace with: ") 28 strR = CChar(Console.ReadLine()) 29 30 strFinal = "" 'begin by storing an empty string in the final string 31 For i = 0 To strS.Length - 1 31 If CChar(strS.Substring(i, 1)) = strC Then 32 strFinal = strFinal & strR 'do the replacement 33 Else 34 strFinal = strFinal & strS.Substring(i, 1) 'leave original character intact 35 End If 36 Next 37 Console.WriteLine() 'just a blank line to make the display neat

Page 72: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 72 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

38 39 Console.WriteLine("Original string = " & strS) 40 Console.WriteLine("Final string = " & strFinal) 41 42 Console.WriteLine() 'just a blank line to make the display neat 43 Console.WriteLine("Press any key to continue...") 44 45 Console.ReadKey() 'hold the window until user presses any key 46 End Sub 47 End Module

Class Exercise: Did you

observe that in the first

output, the program

correctly replaced every "e" with "a"; whereas in the second output, it failed to

convert every "E" in the uppercase "GENE" to "a" or "A"? now who will explain

why this is so, and how can the program be modified to make it take care of

everything irrespective of capitalization in the input string?

Page 73: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 73 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

3.1.8 Counting the number of words in a sentence with FOR...NEXT loop

We have used the String.Split()

method to count the number of

words in a sentence. Now we want to

write code that will count the

number of words in a sentence but

without using the built-in Split()

method of VB.NET. The code to

accomplish this is shown in Source

Code Listing 3.8. The code assumes

that each word in a sentence is

separated from the next by a single

blank space.

STOP & TYPE: Source Code Listing 3.8

01 Module 1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 3.8 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to count *") 07 Console.WriteLine("* words in a sentence using FOR...NEXT loop*") 08 Console.WriteLine("********************************************") 09 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 10 Console.WriteLine("********************************************") 11 12 Console.WriteLine() 'just a blank line to make the display neat 13 14 'Declare a string variable to hold user input 15 Dim strSentence As String 16 17 Console.Write("Type any sentence: ") 18 strSentence = Console.ReadLine() 19 20 Dim i As Integer, wordCount As Integer 21 22 wordCount = 0 'nothing has been counted yet 23 24 For i = 0 To strSentence.Length - 1 25 If strSentence.Substring(i, 1) = " " Then wordCount = wordCount + 1 26 Next 27 28 'make up for the last word, and do so only if 29 'the sentence typed by the user is not blank: 30 If strSentence.Length > 0 Then 31 wordCount = wordCount + 1 32 End If 33 34 Console.WriteLine() 'just a blank line to make the display neat 35 36 Console.WriteLine("The sentence '" & strSentence & "' contains " & wordCount & " words.") 37 38 Console.WriteLine() 'just a blank line to make the display neat 39 Console.WriteLine("Press any key to continue...") 40 Console.ReadKey() 'hold the window until user presses any key 41 End Sub 42 End Module

Page 74: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 74 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

The second output was

generated when the user

pressed the ENTER key

without typing anything.

3.1.7 Generating and printing Fibonacci sequence with FOR...NEXT loop

(Fibonacci is pronounced "fi-bo-na-

chee"). The Fibonacci Sequence or

Fibonacci Series is the series of

numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

and so on. Starting from zero and

one, the next number in the series is

found by adding up the two numbers

before it.

The 2 is found by adding the

two numbers before it (1+1)

Similarly, the 3 is found by

adding the two numbers before

it (1+2),

And the 5 is (2+3),

and so on!

Page 75: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 75 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

So, the next number in the sequence

above would be 21+34 = 55. It is that

simple! Here is a longer list: 0, 1, 1, 2,

3, 5, 8, 13, 21, 34, 55, 89, 144, 233,

377, 610, 987, 1597, 2584, 4181,

6765, 10946, 17711, 28657, 46368,

75025, 121393, 196418, 317811, ...

The history behind Fibonacci series

can be found anywhere on the web if

you just google "fibonacci series".

So, how do we write code, using a

FOR...NEXT loop, to generate the

Fibonacci sequence up to any nth

term? Source Code Listing 3.9 shows

us how to do that for the first 10

numbers in the series:

STOP & TYPE: Source Code Listing 3.9

01 Module 1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 3.9 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use *") 07 Console.WriteLine("* FOR...NEXT loop to generate and print the") 08 Console.WriteLine("* first 10 numbers of Fibonacci sequence. *") 09 Console.WriteLine("********************************************") 10 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 11 Console.WriteLine("********************************************") 12

Page 76: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 76 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

13 Console.WriteLine() 'just a blank line to make the display neat 14 15 Console.WriteLine("Generating Fibonacci Sequence." & vbNewLine & "Press ENTER key to generate the next number:") 16 17 Console.WriteLine() 'just a blank line to make the display neat 18 19 Dim F1 As Integer, F2 As Integer, NextF As Integer 20 F1 = -1 21 F2 = 1 22 23 For i = 1 To 10 24 NextF = F1 + F2 'compute the next number in the series 25 Console.WriteLine(NextF) 26 Console.ReadKey() 'hold the window until user presses any key 'swap the numbers to make room for the next number 27 F1 = F2 28 F2 = NextF 'hold the window until user presses any key 29 Next 30 31 Console.WriteLine() 'just a blank line to make the display neat 32 Console.WriteLine("Press any key to continue...") 33 Console.ReadKey() 'hold the window until user presses any key 34 End Sub 35 End Module

Note: make sure you are in the class and do pay rapt attention when this code

shall be explained to you.

Page 77: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 77 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

3.2: Looping with DO...LOOP statement

In the previous section, we worked

with lots of FOR...NEXT examples

whereby we knew that we only

wanted to loop over some actions for

a fixed number of times. Using

FOR...NEXT in those cases was perfect

because we knew in advance how

many times the loop was going to

iterate. But what if we don't know

exactly how many times the loop will

go?

In that case, we would need to look

elsewhere for the perfect kind of loop

that will correctly handle iterations

that cannot be counted and fixed in

advance. Luckily for us, VB.NET does

have another kind of loop which is

not counter-controlled like the

FOR...NEXT loop. It is called the

DO...LOOP, and it is a type of event-

controlled loop.

The DO...LOOP can take on any of the

following three general structures in

VB.NET:

DO DO DO WHILE (condition)

: : :

: : :

LOOP UNTIL (condition) LOOP WHILE (condition) LOOP

In general, the DO...LOOP keeps on

executing its enclosed statements

while or until the specified condition

is true. With the first two versions,

the loop will execute at least once;

but it may not even execute at all in

the third version if the specified

condition does not hold true to start

with. Let's take some examples to

generate integers 1 to 10 using the

three DO...LOOP variants:

Page 78: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 78 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Example 1: Generating and printing integers 1 -10 using DO...LOOP UNTIL

01 Dim number as Integer

02 number = 1

03 Do

04 Console.WriteLine(number)

05 number = number + 1

06 Loop Until number > 10

07 Console.ReadKey()

With the above, we begin by

declaring and setting the value of

number to 1; then we issue the

command that tells VB.NET to begin

doing all of the statements that follow

at lines 04 and 05 until number

becomes greater than 10. Within the

DO...LOOP UNTIL body, we repeatedly

print the current value of number and

increment number by 1. Since number

initially started at 1, it will eventually

exceed 10 and the condition will no

longer hold so the loop will end

naturally and program execution will

proceed to line 07.

So in summary, the DO...LOOP keeps

going round and around. And when it

gets to the bottom, it tests the

condition. It is really answering a Yes

or No question at the Loop Until

number > 10 statement: is the number

inside the variable called number now

greater than 10? If it is indeed

greater than 10, VB.NET jumps out of

the loop entirely and goes to line 07,

otherwise it will loop back to line 04

where the variable number gets

incremented by 1 and printed.

Example 2: Generating and printing integers 1 -10 using DO...LOOP WHILE

01 Dim number as Integer

02 number = 1

03 Do

04 Console.WriteLine(number)

05 number = number + 1

06 Loop While number <= 10

07 Console.ReadKey()

Page 79: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 79 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

With Example 2 above, we altered the code at line 06 and replaced UNTIL with

WHILE. Note also that the condition is now <= 10. If we had used Loop While

number < 10 at line 6, then the loop will iterate and generate only digits 1-9,

rather than 1-10.

Class Exercise: How can we modify the code in Example 2 above so that we can

use Loop While number < 10 in the test condition?

Example 3: Generating and printing integers 1 -10 using DO WHILE...LOOP

01 Dim number as Integer

02 number = 1

03 Do While number <= 10

04 Console.WriteLine(number)

05 number = number + 1

06 Loop

07 Console.ReadKey()

From the three examples above, you can see that the DO...LOOP allows you to

either evaluate a condition at the beginning (example 3) or at the end (examples

1 and 2) of the loop. We shall now write a series of codes to translate all the tasks

that were accomplished using FOR...NEXT loop in the last section into their

DO...LOOP equivalents.

3.2.1 Generating and printing even numbers with DO...WHILE statement

Source Code Listing 3.2.1 generates

and prints even numbers starting

from 2 to whatever value the user

wants. The program asks the user to

specify where he or she wants the

even number generation to stop.

Note that the user may not always

type in correct data (for example, the

user may type in an odd number as

the stopping point instead of an even

number).

This program intelligently takes care

of that before generating and printing

the even numbers. If the user actually

specifies an even number, then the

Page 80: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 80 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

program generates and prints all

even numbers from 2 to the specified

end point; otherwise if the user

specifies an odd number then the

program generates and prints all

even numbers from 2 to the last even

number before the specified odd

number (e.g. if user specifies 17 as

the last number, then the program

will stop after generating even

number 16) .

Of course, this extra check is not

necessary in this simple case, but in

real-world non-trivial programming,

it is always a good practice to check

user inputs in this way before

proceeding with the calculations or

other tasks that the program is meant

to perform.

STOP & TYPE: Source Code Listing 3.2.1

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 3.2.1 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use *") 07 Console.WriteLine("* DO...LOOP iteration to generate and print") 08 Console.WriteLine("* even numbers from 2 to a user-specified *") 09 Console.WriteLine("* end point. *") 10 Console.WriteLine("********************************************") 11 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 12 Console.WriteLine("********************************************") 13 14 Console.WriteLine() 'just a blank line to make the display neat 15 16 Dim e As Integer, e2 As Integer 17 18 Console.Write("Enter the last even number to generate: ") 19 e2 = CInt(Console.ReadLine()) 20 21 'if number entered is not even, make it even 22 If e2 Mod 2 <> 0 Then e2 = e2 - 1 23 e = 2 24 Do While e <= e2 25 Console.Write(e & vbTab) 26 e = e + 2 'increment to the next even number 27 Loop 28 29 Console.WriteLine() 'just a blank line to make the display neat 30 Console.WriteLine("Press any key to continue...") 31 32 Console.ReadKey() 'hold the window until user presses any key 33 End Sub 34 End Module

Page 81: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 81 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

3.2.2 Generating and printing sums of numbers with DO...WHILE statement

In this section, we want to

use DO...WHILE code to

generate and print integers 1

– 10 and as we generate each

number, we are going to

cumulatively add it up to a

variable that stores the sum

of the integers. In the end, we

are going to print out that

cumulative sum. Source Code

Listing 3.2.2 is the code.

STOP & TYPE: Source Code Listing 3.2.2

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 3.2.2 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use *") 07 Console.WriteLine("* DO...LOOP iteration to generate integers*") 08 Console.WriteLine("* 1-10 and print their sum. *") 09 Console.WriteLine("********************************************") 10 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 11 Console.WriteLine("********************************************") 12 13 Console.WriteLine() 'just a blank line to make the display neat 14 15 Console.Write("Generating integers 1 - 10. Press ENTER key to generate the next number:") 16 Dim intNumber As Integer, intSum As Integer 17 18 Console.WriteLine() 'just a blank line to make the display neat 19 20 intNumber = 1 'set initial value for numbers to generate 21 intSum = 0 'begin by storing zero in the sum 22 Do While intNumber <= 10 23 Console.WriteLine(intNumber) 24 intSum = intSum + intNumber 25 26 Console.ReadKey() 'hold the window until user presses any key 27 intNumber = intNumber + 1 28 Loop 29 30 Console.WriteLine() 'just a blank line to make the display neat 31 Console.WriteLine("Sum of the 10 integers = " & intSum) 32 33 Console.WriteLine("Press any key to continue...") 34 Console.ReadKey() 'hold the window until user presses any key 35 End Sub 36 End Module

Page 82: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 82 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

3.2.3 Generating and printing sum of a series with DO...LOOP UNTIL statement (1)

Next, we want to write code to compute and print the sum and average of the first

fifty positive integers (i.e. numeric digits 1 – 50). Source Code Listing 3.2.3 is the

code. There are a few important things about this code that are not mentioned in

this manual, but they shall be discussed in class; so make sure you attend classes

regularly and pay attention in class when this concept is being explained!

STOP & TYPE: Source Code Listing 3.2.3

Module Module1 Sub Main() Console.WriteLine("********************************************") Console.WriteLine("* DCS105 Source Code Listing 3.3 *") Console.WriteLine("********************************************") Console.WriteLine("* This program demonstrates how to use *") Console.WriteLine("* FOR...NEXT loop to compute the sum and *") Console.WriteLine("* average of the first 50 integers. *") Console.WriteLine("********************************************") Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") Console.WriteLine("********************************************") Console.WriteLine() 'just a blank line to make the display neat Console.WriteLine("Generating integers 1 - 50:") Dim intNumber As Integer, intSum As Integer Dim sglAvg As Single intSum = 0 'begin by storing zero in the sum For intNumber = 1 To 50 Console.Write(intNumber & vbTab) intSum = intSum + intNumber Next

Page 83: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 83 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

sglAvg = intSum / 50 Console.WriteLine() 'just a blank line to make the display neat Console.WriteLine("Sum of the 50 integers = " & intSum) Console.WriteLine("Average of the 50 integers = " & sglAvg) Console.WriteLine() 'just a blank line to make the display neat Console.WriteLine("Press any key to continue...") Console.ReadKey() 'hold the window until user presses any key End Sub End Module

3.2.4 Generating and printing sum of a series with DO...LOOP UNTIL statement (2)

Now, we shall also solve for the equation below, as we have already done using

FOR...NEXT loop:

STOP & TYPE: Source Code Listing 3.2.4

Module Module1 Sub Main() Console.WriteLine("********************************************") Console.WriteLine("* DCS105 Source Code Listing 3.2.4 *") Console.WriteLine("********************************************") Console.WriteLine("* This program demonstrates how to use *") Console.WriteLine("* DO...LOOP UNTIL to compute and print the ") Console.WriteLine("* sum of a series with fractional terms. *") Console.WriteLine("********************************************") Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") Console.WriteLine("********************************************") Console.WriteLine() 'just a blank line to make the display neat Dim p As Integer, S As Single S = 0 'begin by storing zero in the sum p = 5 'the powers of 2 start at 5 Do S = S + (1 / 2 ^ p) p = p + 1 Loop Until p > 9 Console.WriteLine("Computed answer = " & S) Console.WriteLine() 'just a blank line to make the display neat Console.WriteLine("Press any key to continue...") Console.ReadKey() 'hold the window until user presses any key End Sub End Module

Page 84: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 84 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

3.2.5 Generating and printing sum of a series with DO...LOOP UNTIL statement (3)

Again, we have already analyzed and solved for the series below in section 3.1.5

using FOR...NEXT, but now we shall use DO...LOOP UNTIL to solve it:

STOP & TYPE: Source Code Listing 3.2.5

01 Module Module1 Sub Main() Console.WriteLine("********************************************") Console.WriteLine("* DCS105 Source Code Listing 3.2.5 *") Console.WriteLine("********************************************") Console.WriteLine("* This program demonstrates how to use *") Console.WriteLine("* DO...LOOP UNTIL to compute and print the ") Console.WriteLine("* sum of a series with fractional terms *") Console.WriteLine("* up to the nth term. *") Console.WriteLine("********************************************") Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") Console.WriteLine("********************************************") Console.WriteLine() 'just a blank line to make the display neat Dim p As Integer, n As Integer, S As Single Console.Write("Enter the nth power of 2 (integer only): ") n = CInt(Console.ReadLine()) S = 0 'begin by storing zero in the sum, S p = 0 'powers of 2 begin from zero Do S = S + (1 / 2 ^ p) p = p + 1 Loop Until p > n

Page 85: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 85 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Console.WriteLine("Computed answer = " & S) Console.WriteLine() 'just a blank line to make the display neat Console.WriteLine("Press any key to continue...") Console.ReadKey() 'hold the window until user presses any key End Sub End Module

3.2.6 Implementing the StrReverse() function with DO...LOOP WHILE statement

We looked at a dozen or so built-in

VB.NET string functions in section 1.6

of this manual. One of the built-in

functions discussed was the

StrReverse() function, which takes a

string and turns it around so that the

last character is now the first and the

first one is now the last. For example,

if you reverse the string "Gene", you

get "eneG"; while reversing the string

"IACC-ABU" gives "UBA-CCAI".

Now we want to write a VB.NET

program that will ask the user to type

in a word or a sentence and, without

using the built-in StrReverse()

function, we shall reverse whatever

the user types in and print out both

the original user input and the

reversed version.

This is done using a DO...LOOP WHILE

statement in conjunction with the

Substring() function, as illustrated in

Source Code Listing 3.2.6:

Page 86: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 86 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

STOP & TYPE: Source Code Listing 3.2.6

01 Module Module1 Module Module1 Sub Main() Console.WriteLine("********************************************") Console.WriteLine("* DCS105 Source Code Listing 3.2.6 *") Console.WriteLine("********************************************") Console.WriteLine("* This program demonstrates how to use *") Console.WriteLine("* DO...LOOP WHILE statement in conjunction*") Console.WriteLine("* with the built-in Substring function to *") Console.WriteLine("* implement the StrReverse function. *") Console.WriteLine("********************************************") Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") Console.WriteLine("********************************************") Console.WriteLine() 'just a blank line to make the display neat Dim i As Integer, strS As String, strR As String Console.Write("Enter a word or sentence: ") strS = Console.ReadLine() strR = "" 'begin by storing an empty string in the reversed string, strR i = strS.Length - 1 'begin from the last character in the sentence Do strR = strR & strS.Substring(i, 1) 'concatenate the reversed string one char at a time i = i - 1 Loop While i >= 0 Console.WriteLine() 'just a blank line to make the display neat Console.WriteLine("Original string = " & strS) Console.WriteLine("Reversed string = " & strR) Console.WriteLine() 'just a blank line to make the display neat Console.WriteLine("Press any key to continue...") Console.ReadKey() 'hold the window until user presses any key End Sub End Module

Page 87: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 87 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

3.2.7 Implementing the String.Replace() function with DO...LOOP WHILE statement

We can also implement the

String.Replace()function using a

loop, as we have done in section 3.1.7

using a FOR...NEXT loop. Now we

shall do it again but this time around,

we shall be using a DO...LOOP WHILE

statement:

STOP & TYPE: Source Code Listing 3.2.7

01 Module Module1 Sub Main() Console.WriteLine("********************************************") Console.WriteLine("* DCS105 Source Code Listing 3.2.7 *") Console.WriteLine("********************************************") Console.WriteLine("* This program demonstrates how to use *") Console.WriteLine("* DO...LOOP WHILE statement in conjunction*") Console.WriteLine("* with the built-in Substring function to *") Console.WriteLine("* implement the String.Replace function. *") Console.WriteLine("********************************************") Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") Console.WriteLine("********************************************") Console.WriteLine() 'just a blank line to make the display neat Dim i As Integer = 0 Dim strS As String 'original string entered by user Dim strC As Char 'character to replace Dim strR As Char 'character to replace with Dim strFinal As String = "" 'final string after processing Console.Write("Enter a word or sentence: ") strS = Console.ReadLine() Console.Write("Enter a character you want to replace: ") strC = CChar(Console.ReadLine()) Console.Write("Enter a character to replace with: ") strR = CChar(Console.ReadLine()) Do If CChar(strS.Substring(i, 1)) = strC Then strFinal = strFinal & strR 'do the replacement Else strFinal = strFinal & strS.Substring(i, 1) 'leave the original character intact End If i = i + 1 Loop While i < strS.Length Console.WriteLine() 'just a blank line to make the display neat Console.WriteLine("Original string = " & strS) Console.WriteLine("Final string = " & strFinal) Console.WriteLine() 'just a blank line to make the display neat Console.WriteLine("Press any key to continue...") Console.ReadKey() 'hold the window until user presses any key End Sub End Module

Page 88: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 88 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

3.2.8 Counting the number of words in a sentence with DO...LOOP UNTIL statement

We have used the String.Split() method to count the number of words in a

sentence; and we have also used FOR...NEXT loop to count the number of words in

a sentence. Now you will write the DO...LOOP UNTIL equivalent of the FOR...NEXT

version we wrote in section 3.1.8. You will do this a take-home assignment and

the turn-in date shall be communicated to you in the class.

Page 89: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 89 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

3.3: Looping with WHILE...WEND statement

The WHILE...WEND loop is also another

frequently used loop format in

VB.NET. If you are working on code

developed by someone else, you may

find a code block that starts with a

WHILE statement and ends with a WEND

statement. That is a WHILE...WEND

loop.

This type of loop works the same as a

DO...WHILE loop with the WHILE clause

in the DO statement. The WHILE...WEND

loop has the following general

format:

WHILE (condition)

:

:

:

WEND

So let's say you want your program to keep on waiting until the user types

"STOP" and presses the ENTER key, you could use the WHILE...WEND loop as

follows:

Module Module1 Sub Main() Dim strT As String = "" While strT.ToUpper <> "STOP" Console.Write("What should I do now?") strT = Console.ReadLine() End While Console.WriteLine() Console.Write("Okay, I've stopped now...") Console.ReadKey() End Sub End Module

Page 90: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 90 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

3.3.1 Generating and printing even numbers with WHILE...WEND statement

Source Code Listing 3.3.1 generates

and prints even numbers starting

from 2 to whatever value the user

wants. The FOR...NEXT and DO...LOOP

versions have been written before;

now we are going to look at the

WHILE...WEND version.

STOP & TYPE: Source Code Listing 3.3.1

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 3.3.1 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use *") 07 Console.WriteLine("* WHILE...WEND loop to generate and print *") 08 Console.WriteLine("* even numbers from 2 to a user-specified *") 09 Console.WriteLine("* end point. *") 10 Console.WriteLine("********************************************") 11 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 12 Console.WriteLine("********************************************") 13 14 Console.WriteLine() 'just a blank line to make the display neat 15 16 Dim e As Integer, e2 As Integer 17 18 Console.Write("Enter the last even number to generate: ") 19 e2 = CInt(Console.ReadLine()) 20 e = 2 21 While e <= e2 22 Console.Write(e & vbTab) 23 e = e + 2 24 Next 25 26 Console.WriteLine() 'just a blank line to make the display neat 27 Console.WriteLine("Press any key to continue...") 28 29 Console.ReadKey() 'hold the window until user presses any key 30 End Sub 31 End Module

3.3.2 Generating and printing sums of numbers with WHILE...WEND statement

In this section, we want to write code

to generate and print integers 1 – 10

and as we generate each number, we

are going to cumulatively add it up to

a variable that stores the sum of the

integers. In the end, we are going to

print out that cumulative sum. We

have used the FOR...NEXT and

DO...LOOP versions of this code

before, and now we are going to look

at the WHILE...WEND equivalent as

shown in Source Code Listing 3.3.2.

Page 91: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 91 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

STOP & TYPE: Source Code Listing 3.3.2

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 3.3.2 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use *") 07 Console.WriteLine("* WHILE...WNED loop to generate integers *") 08 Console.WriteLine("* 1-10 and print their sum. *") 09 Console.WriteLine("********************************************") 10 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 11 Console.WriteLine("********************************************") 12 13 Console.WriteLine() 'just a blank line to make the display neat 14 15 Console.Write("Generating integers 1 - 10. Press ENTER key to generate the next number:") 16 Dim intNumber As Integer, intSum As Integer 17 18 Console.WriteLine() 'just a blank line to make the display neat 19 20 intSum = 0 'begin by storing zero in the sum 21 intNumber = 0 22 While intNumber < 10 23 intNumber = intNumber + 1 24 Console.WriteLine(intNumber) 25 intSum = intSum + intNumber 26 Console.ReadKey() 'hold the window until user presses any key 27 Wend 28 29 Console.WriteLine() 'just a blank line to make the display neat 30 Console.WriteLine("Sum of the 10 integers = " & intSum) 31 32 Console.WriteLine("Press any key to continue...") 33 34 Console.ReadKey() 'hold the window until user presses any key 35 End Sub 36 End Module

3.3.3 Generating and printing sum of a series with WHILE...WEND statement (1)

Next, we want to write code to

compute and print the sum and

average of the first fifty positive

integers (i.e. numeric digits 1 – 50).

Source Code Listing 3.3.3 is the code,

using a WHILE...WEND loop:

STOP & TYPE: Source Code Listing 3.3.3

Module Module1 Sub Main() Console.WriteLine("********************************************") Console.WriteLine("* DCS105 Source Code Listing 3.3.3 *") Console.WriteLine("********************************************") Console.WriteLine("* This program demonstrates how to use *") Console.WriteLine("* FOR...NEXT loop to compute the sum and *") Console.WriteLine("* average of the first 50 integers. *") Console.WriteLine("********************************************")

Page 92: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 92 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") Console.WriteLine("********************************************") Console.WriteLine() 'just a blank line to make the display neat Console.Write("Generating integers 1 - 50:") Dim intNumber As Integer, intSum As Integer Dim sglAvg As Single Console.WriteLine() 'just a blank line to make the display neat intSum = 0 'begin by storing zero in the sum intNumber = 0 While intNumber < 50 Console.Write(intNumber & vbTab) intSum = intSum + intNumber intNumber = intNumber + 1 Wend sglAvg = intSum / 50 Console.WriteLine() 'just a blank line to make the display neat Console.WriteLine("Sum of the 50 integers = " & intSum) Console.WriteLine("Average of the 50 integers = " & sglAvg) Console.WriteLine() 'just a blank line to make the display neat Console.WriteLine("Press any key to continue...") Console.ReadKey() 'hold the window until user presses any key End Sub End Module

3.3.4 Generating and printing sum of a series with WHILE...WEND statement (2)

Again, we have already written the code for the equation below, now we write

the WHILE...WEND version:

STOP & TYPE: Source Code Listing 3.3.4

Module Module1 Sub Main() Console.WriteLine("********************************************") Console.WriteLine("* DCS105 Source Code Listing 3.3.4 *") Console.WriteLine("********************************************") Console.WriteLine("* This program demonstrates how to use *") Console.WriteLine("* WHILE...WEND loop to compute and print *") Console.WriteLine("* sum of a series with fractional terms. *") Console.WriteLine("********************************************") Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") Console.WriteLine("********************************************") Console.WriteLine() 'just a blank line to make the display neat

Page 93: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 93 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

Dim p As Integer, S As Single S = 0 'begin by storing zero in the sum, S p = 5 While p < 9 S = S + (1 / 2 ^ p) 'compute current term and add to S p = p + 1 Next Console.WriteLine("Computed answer = " & S) Console.WriteLine() 'just a blank line to make the display neat Console.WriteLine("Press any key to continue...") Console.ReadKey() 'hold the window until user presses any key End Sub End Module

3.3.5 Generating and printing sum of a series with WHILE...WEND statement (3)

Here again is the series, now we write the WHILE...WEND equivalent:

STOP & TYPE: Source Code Listing 3.3.5

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 3.3.5 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use *") 07 Console.WriteLine("* WHILE...WEND loop to compute and print *") 08 Console.WriteLine("* the sum of a series with fractional terms") 09 Console.WriteLine("* up to the nth term. *") 10 Console.WriteLine("********************************************") 11 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 12 Console.WriteLine("********************************************") 13 14 Console.WriteLine() 'just a blank line to make the display neat 15 16 Dim p As Integer, n As Integer, S As Single 17 18 Console.Write("Enter the nth power of 2 (integer only): ") 19 n = CInt(Console.ReadLine()) 20 21 S = 0 'begin by storing zero in the sum, S 21 p = 0 22 While p < n 23 S = S + (1 / 2 ^ p) 23 p = p + 1 24 Wend 25 Console.WriteLine("Computed answer = " & S) 26

Page 94: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 94 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

27 Console.WriteLine() 'just a blank line to make the display neat 28 Console.WriteLine("Press any key to continue...") 29 30 Console.ReadKey() 'hold the window until user presses any key 31 End Sub 32 End Module

3.3.6 Implementing the StrReverse() function with WHILE...WEND loop

STOP & TYPE: Source Code Listing 3.3.6

01 Module Module1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 3.3.6 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use a *") 07 Console.WriteLine("* WHILE...WEND loop in conjunction with the") 08 Console.WriteLine("* built-in String.Substring function to *") 09 Console.WriteLine("* implement the StrReverse function. *") 10 Console.WriteLine("********************************************") 11 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 12 Console.WriteLine("********************************************") 13 14 Console.WriteLine() 'just a blank line to make the display neat 15 16 Dim i As Integer, strS As String, strR As String 17 18 Console.Write("Enter a word or sentence: ") 19 strS = Console.ReadLine() 20 21 strR = "" 'begin by storing an empty string in the reversed string, strR 22 23 'begin the loop from last character down to first character: i = strS.Length - 1 24 While i > 0 25 strR = strR & strS.Substring(i, 1) 'concatenate reversed string 1 char at a time i = i - 1 26 Wend 27 Console.WriteLine() 'just a blank line to make the display neat 28 29 Console.WriteLine("Original string = " & strS) 30 Console.WriteLine("Reversed string = " & strR) 31 32 Console.WriteLine() 'just a blank line to make the display neat 33 Console.WriteLine("Press any key to continue...") 34 35 Console.ReadKey() 'hold the window until user presses any key 36 End Sub 37 End Module

Page 95: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 95 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

3.3.7 Implementing the String.Replace() function with WHILE...WEND statement

STOP & TYPE: Source Code Listing 3.3.7

01 Module 1 02 Sub Main() 03 Console.WriteLine("********************************************") 04 Console.WriteLine("* DCS105 Source Code Listing 3.3.7 *") 05 Console.WriteLine("********************************************") 06 Console.WriteLine("* This program demonstrates how to use *") 07 Console.WriteLine("* WHILE...WEND loop to implement the *") 08 Console.WriteLine("* built-in String.Replace function. *") 09 Console.WriteLine("********************************************") 10 Console.WriteLine("* (c) 2013, M-Auwal Gene @IACC, ABU Zaria. *") 11 Console.WriteLine("********************************************") 12 13 Console.WriteLine() 'just a blank line to make the display neat 14 15 Dim i As Integer = 0 16 Dim strS As String 'original string entered by user 17 Dim strC As Char 'character to replace 18 Dim strR As Char 'character to replace with 19 Dim strFinal As String 'final string after processing 20 21 Console.Write("Enter a word or sentence: ") 22 strS = Console.ReadLine() 23 24 Console.Write("Enter a character you want to replace: ") 25 strC = CChar(Console.ReadLine()) 26 27 Console.Write("Enter a character to replace with: ") 28 strR = CChar(Console.ReadLine()) 29 30 strFinal = "" 'begin by storing an empty string in the final string 31 While i < strS.Length - 1 32 If CChar(strS.Substring(i, 1)) = strC Then 33 strFinal = strFinal & strR 'do the replacement 34 Else 35 strFinal = strFinal & strS.Substring(i, 1) 'leave original character intact 36 End If 37 i = i + 1 38 Wend 39 Console.WriteLine() 'just a blank line to make the display neat 40 41 Console.WriteLine("Original string = " & strS) 42 Console.WriteLine("Final string = " & strFinal) 43 44 Console.WriteLine() 'just a blank line to make the display neat 45 Console.WriteLine("Press any key to continue...") 46 47 Console.ReadKey() 'hold the window until user presses any key 48 End Sub 49 End Module

Page 96: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 96 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

3.4: A word about infinite loops

An infinite loop (also known as endless loop) is a

loop that lacks a functional exit so that it repeats

indefinitely. You will recall that a loop is a sequence

of instructions that is continually repeated until a

certain condition is reached. An infinite loop

performs the same set of instructions without

ending, thereby "freezing" the computer.

All the loops we have considered in this manual so

far do end after some number of iterations, but it is

possible to somehow carelessly write loops that will never end. You must always

write your codes carefully to avoid entering into an infinite loop; otherwise the

system will eventually freeze and you may not be able to do anything else unless

you reboot the system.

3.5: Extra Credits: Can You?

1. Use DO...LOOP and WHILE...WEND to write a

program that will generate and print the first 24

numbers in the Fibonacci Sequence, starting from

zero.

2. The sample output on this page shows a simple

multiplication table for 2. Use FOR...NEXT,

DO...LOOP and WHILE...WEND to write a program

that will generate and print a simple multiplication

table for any number from 1 to 20 as shown in this

example.

Page 97: Abridged Lecture Notes For DCS 105 - Auwal Genemystudents/lecturenotes/vb_dot_net_strings... · DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration

DCS105 Course Manual: A Gentle Introduction to VB.NET Strings, Selection & Iteration 2013 © IACC, ABU Zaria

PAGE 97 Downloaded from http://www.auwalgene.com/mystudents/lecturenotes

FREE, NOT FOR SALE!

WE’RE DONE FOR NOW, GOOD BYE!

ELL, that will be all in this gentle introduction to strings, decision

making and looping. I hope you found it both useful and enjoyable.

Next semester, we shall be discussing more about these concepts in

DCS106 (Introduction to Programming II). As a look-ahead, here are some of the

things we shall be studying in greater depth then:

algorithms, pseudocodes and flowcharts

working with nested loops

working with one-dimensional arrays

a deeper look at functions

passing arrays as parameters to functions

working with two-dimensional arrays (a.k.a. matrices)

bullet-proofing your programs through error handling

inheritance and polymorphism in oop

GUI programming

and so much more... See you then

Download more resources at: http://www.auwalgene.com/mystudents/lecturenotes

Connect with me on Facebook at: http://www.facebook.com/auwalgene3

Drop me a comment or two on my website: http://www.auwalgene.com/comments

Tell me something via e-mail at: [email protected]

Send SMS text messages to my mobile phone at +234 (0) 8032126160

Thank you for reading, and happy programming!

W