Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

ENSC 26 COMPUTER APPLICATIONS IN ENGINEERING LABORATORY MODULES

PRE-LAB HANDOUT 1: Using Variables and Operators

INTRODUCTION TO COMPUTER PROGRAMMING

Computer programming is the development of instructions that a computer can follow. A computer
program is an organized list of step-by-step instructions, called algorithms, which dictate the manner of
operation of a computer. Computer programs are written using a programming language with its own
specific set of grammatical rules or commands for writing algorithms.

VISUAL BASIC

Computers, at its most basic level, can only understand two distinct electrical states, namely, the on and
off states; or 1 and 0 codes, respectively, in the binary number system. This computer programming
language, which is a combination of binary codes or hexadecimal instructions a computer responds to
directly, is called machine language. However, due to the difficulty of writing in machine language, most
modern programs are instead written in high-level languages that uses English and mathematical symbols
in its instructions. High-level languages are then translated back into machine language using assemblers,
interpreters and/or compilers.

Visual BASIC is a high-level, object-oriented programming language which evolved from the earlier DOS
version called BASIC (Beginners' All-purpose Symbolic Instruction Code). The language uses common
words, as well as grammatical structures, from the English language. Where a book has chapters with
paragraphs that contain sentences consisting of words, programs written in Visual BASIC follows a similar
structure: modules are like chapters, procedures are like paragraphs, and programming statements are
like sentences.

In many ways, Visual BASIC is much like any formal


language that has rules that define how "words"
and "symbols" (or programming elements) are used
to write programs. Programming elements in Visual
BASIC include statements, declarations, methods,
operators, and keywords. These programming
elements can then be used to write programming
statements under a specific arrangement or syntax.
For example, the phrase "the age of a male student
is 20" can be written as:
Student_male_age = 20

Throughout the course, Visual Basic available in Visual Studio 2019 will be used. You can download the
free community version here: https://visualstudio.microsoft.com/downloads. Use your UP-issued Office
365 credentials to sign-in. As the course discussion develops, the tools available and code syntax rules to
be used for each programming structure shall be explained.
THE VISUAL BASIC USER INTERFACE

Visual BASIC, as part of the Visual Studio Suite of Microsoft, utilizes a system called Integrated
Development Environment (IDE) which employs similar user interfaces across all components of the suite.
The Visual Studio IDE is a creative launching pad that you can use for many aspects of software

Page 1 of 14
ENSC 26 COMPUTER APPLICATIONS IN ENGINEERING LABORATORY MODULES

development - editing, debugging, building code, and then publishing an app. Over and above the
standard editor and debugger that most IDEs provide, Visual Studio includes compilers, code completion
tools, graphical designers, and many more features to ease the software development process. It has a
toolbox on the left, solution explorer on the right, and a code/design view at the center.

1. Open Visual Studio


The start window appears with various options for cloning a repo, opening a recent project, or creating a
brand-new project. Choose Create a new project. The Create a new project window dialogue box opens
and shows several project templates to choose from. A template contains the basic files and settings
needed for any given project type.

2. Create a new project.


The foundation of Visual Studio .NET-based software development are projects and
solutions. A project is a collection or a group of related source files which can then
be compiled to create an executable file or a program component. Those files can
include source codes, icons, images, data files, and so on. The file extension reflects
the type of project created: a C# project (.csproj), a Visual Basic project (.vbproj), or
a database project (.dbproj).
A project is contained within a solution. A solution is simply a container for one or
more related projects, along with build information, Visual Studio window settings,
and any miscellaneous files that are not associated with a particular project. A
solution is described by a text file (extension .sln) with its own unique format; it is not
intended to be edited by hand. Visual Studio uses two file types (.sln and .suo) to
store settings for solutions: the .sln file organizes projects, project items, and solution items in the solution;
the .suo file (Solution User Options) stores user-level settings and customizations, such as editor window
positions and breakpoint settings. You may delete a .suo file since it is not required to build the projects
in the solution.
To display the template we will use, choose Visual Basic from the Language dropdown list, Windows (or
MacOS) from the Platform dropdown list, and Desktop (or Console) from the Project-Types dropdown
list (15 options are available). Then choose Next.
The course discussion shall be limited to the use of a Console or a Desktop template for developing

Page 2 of 14
ENSC 26 COMPUTER APPLICATIONS IN ENGINEERING LABORATORY MODULES

algorithms. The desktop template uses the standard Windows-based application that employs forms,
textboxes, scroll bars, and other objects in the Windows interface. The console application, meanwhile,
uses a command-line interface similar to MS DOS or a Unix Terminal.

3. Configure your new project.


Fill the field for the Project name box, assign the directory location for your project files, and then choose
Create. Visual Studio creates a solution for your app and opens your new project. Congratulations
👏👏👏, you are ready to code!

Using Windows Forms Application


Choosing the Windows Forms Application opens the design view of Visual BASIC. A designer is a visual
surface onto which you can add controls such as buttons and lists. At the middle of the displayed screen
is the primary form where different objects can be added through the toolbox on the left side. Additional
forms may be added in the project through the standard toolbar on top or through the solution explorer
on the right. The solution explorer also serves as a window for browsing between forms and modules in a

Page 3 of 14
ENSC 26 COMPUTER APPLICATIONS IN ENGINEERING LABORATORY MODULES

project and navigating all items in your solution. Detailed discussions for each component of the IDE
follows below. You can also find more details on Visual Studio IDE productivity features such as Live Share,
CodeLens, Quick Actions and Peek Definition in https://docs.microsoft.com/en-us/visualstudio/get-
started/visual-studio-ide?view=vs-2019.

Solution
Explorer
Form
Toolbox
Window

Properties
Window

Error List Window

▪ The Form – the primary element of your program’s interface. It serves as a container that allows
other objects (or controls) to be inserted. There are three ways to insert controls on the form:
Double-click the control in the Toolbox. The control immediately appears on the top-left
corner of the Form. Multiple addition of controls in this manner results to a cascaded display
of the added objects.
Click and hold the control on the Toolbox and drag-drop it onto the Form.
Click the control on the Toolbox once and draw the size (i.e., width and height) of the control
in the Form.
▪ The Toolbox Window – displays icons for controls and other items that can be
added to the Visual Studio project. It only displays items appropriate to the
type of file you are working on, i.e., it is deactivated when you are in the code
editor view.
▪ The Properties Window – allows the user to view and change the design-time
properties and events of selected objects located in editors and designers. You can also use it to
edit and view file, project, and solution properties. When you select an object in a Form Designer
or in the Solution Explorer, the Properties Window content updates to display different types of
editing fields such as edit boxes, dropdown lists, and links to custom editor dialog boxes. To
change a property’s value, simply click the property from the list in the left column and enter the
new value in the right column. If you accidentally close this window, simply press F4 to restore it.
▪ The Solution Explorer - located on the upper-right side of the user-interface by default, it manages
the files in the project. When you right-click on Form1.vb, for example, the list of commands
available for Form1 is displayed, such as the shortcut keys to shift between the Design (the view
with the form in the middle) and Code Editor (the view with the codes and navigation bar): F7 and
Shift+F7, respectively. You can also switch between a Solution view to a Folder view of your project.
If you accidentally close this window, simply press Ctrl+R to restore it.

Page 4 of 14
ENSC 26 COMPUTER APPLICATIONS IN ENGINEERING LABORATORY MODULES

▪ The Error List Window – displays information about a specific error message, and lets you perform
the following tasks:
Display the errors, warnings, and messages produced while you write code.
Find syntax errors noted by IntelliSense - a set of features that displays information about
your code directly in the editor (e.g., syntax tips) and, in some cases, write small bits of code
through automatic completion.
Find deployment errors, certain Static Analysis errors, and errors detected while applying
Enterprise Template policies.
Double-click any error message entry to open the file where the problem occurs and move
to the error location.
Filter which entries are displayed, and which columns of information appear for each entry.
Search for specific terms and scope the search to just the current project or document.
▪ The Code Editor Window - where you can edit code or design a user interface such as a window
with buttons and text boxes. You can use the navigation bar (the dropdown boxes at the top of the
code window) to go directly to code in a codebase: the left to navigate to another project that the
current file belongs to, the middle to navigate to the controls and forms in your current project
(e.g. Form1 events or button controls), or the right to navigate directly to an event, a procedure or
other member of a class which the selected object may respond to or perform.

Navigation Bar

Code Editor

Page 5 of 14
ENSC 26 COMPUTER APPLICATIONS IN ENGINEERING LABORATORY MODULES

4. Saving your project

On the menu bar, choose File > Save All. Alternatively, you can choose the Save All button on the
toolbar or use the shortcut key Ctrl+Shift+S. You only need to do this once. Succeeding saves can be done
by clicking the Save icon in the toolbar or pressing the shortcut key Ctrl+S.

X
Form

X
Toolbox
Window

FUNDAMENTALS OF WRITING PROGRAM ALGORITHMS IN VISUAL BASIC

Creating Expressions with Variables and Operators


An expression is a segment of code that performs an arithmetic operation and then returns a value. For
example, 5+4 is a simple addition expression. It consists of two parts: the operands (5 and 4) and the value
(9) returned when the expression is evaluated. The operator (+) specifies the type of operation to be
executed. For an expression to be relevant to the program, the value that is returned must be used in a
process. The most common thing to do is to assign it to a variable, as shown:
Dim intSum As Integer = 5 + 4

Shown on below is a list of arithmetic operators available in Visual BASIC. Note that the priority of
operation execution is exponentiation, multiplication, division, integer division, modulo, addition and
subtraction. For example, the expression 13 \ 10 / 5 Mod 5 would result to 1 → 10 / 5 = 2; 13 \ 2 = 6; 6
mod 5 = 1. Expressions, though, may also be grouped using parentheses “()” to override the precedence
order above, as shown in this example: (13 \ 10) / 5 mod 5 would now result to 0.2 → 13 \ 10 = 1; 1 / 5 =
0.2; 0.2 mod 5 = 0.2.
Floating points (i.e. non-integer values) are also
considered in Mod operations. Remainder values
can be floating points. Therefore, 17.5 mod 5 = 2.5;
12 mod 4.3 = 3.4; and 47.9 Mod 9.35 = 1.15.
Furthermore, the number of decimal places of the
result of modulo will follow either the operand or
operator, depending on which of the two has the
higher number of decimal places. However, in some languages (e.g. PHP), floating points are disregarded
altogether in modulo operation.

Page 6 of 14
ENSC 26 COMPUTER APPLICATIONS IN ENGINEERING LABORATORY MODULES

Using String Variables to Organize Words


A string is any series of text characters, such as letters, numbers, special characters, and spaces. Strings
can be human- readable phrases or sentences, such as "The quick brown fox jumps over the lazy dog," or
an unintelligible combination of characters, such as "@#fTWREA3 35Gert". The ampersand character (&)
may be used to sequentially combine two or more strings through concatenation, as shown in the example
below:

Dim strA As String = "Concatenating"


Dim strB As String = "Without"
Dim strC As String = "With"
Dim strD As String = "Spaces"
' Displays "ConcatenatingWithoutSpaces"
MsgBox(strA & strB & strD)
' Displays "Concatenating With Spaces"
MsgBox(strA & " " & strC & " " & strD)

Note that " " was used to enclose a single space character. Such symbols are used to assign literals of a
data type. In the case above, a space was concatenated with the other strings in the second MsgBox code.
However, to prevent Visual BASIC from treating the space character as a simple literal when the code was
written, the character was enclosed with "". The other types of literal inclusion or appended symbols shall
be discussed in the lecture class.

Page 7 of 14
ENSC 26 COMPUTER APPLICATIONS IN ENGINEERING LABORATORY MODULES

WINDOWS FORMS APPLICATION: SAMPLE CODES

Let us now create sample programs using the windows forms application template. When the design
interface is loaded, you would need to add objects to your form, specify applicable object properties, and
add code to your objects in the editor window. The steps are detailed below.
Sample Code 1

1. Add one TextBox, two Buttons, a MenuStrip and two Labels.


The sequence objects are added is reflected in that object’s
TabIndex property. The Tabindex number of a control determines
the order in which controls are navigated to on a form when the
user presses the Tab key. The first object added gets a value of 0,
the next object has 1, and so on. Therefore, it is important that the
following objects are added in a form in this sequence: (a) all
input TextBoxes, (b) the main button, e.g. OK, Compute,
Calculate, etc., (c) the Reset button and (d) the MenuStrip.
Multiple labels can be added in any order afterwards. The
Final Program Interface
MenuStrip, meanwhile, has the following objects:

2. Select each object, one at a time, and change the specific object properties indicated in the table
presented below.
To add Access Keys (the underlined letter in a button, e.g. O and R, that can be used to execute the
command using Alt + Access Key), add an ampersand character (&) before the letter which will be
assigned as the access key. Notice that there are also prefixes inserted before each assigned name of a
button. For example, “btn” for button, “frm” for form and “txt” for textboxes. These are naming conventions
used by programmers to easily identify the type of object they are working with especially during coding

Page 8 of 14
ENSC 26 COMPUTER APPLICATIONS IN ENGINEERING LABORATORY MODULES

3. Add the codes to btnOK, btnReset, ResetToolStripMenuItem and ExitToolStripMenuItem


The simplest way to add code to your objects is to double-click the object. This leads you to the code
editor where Visual Basic automatically creates the default event associated to the control, e.g. click for a
button. Alternatively, you can choose btnOK and its corresponding Click event from the middle- and
right-sections of the navigation bar in the code editor, respectively (refer to the diagram below). If you’re
still in the design view, press F7 to switch to the code editor screen.

1 1 3 1

2 1

2
4 1

btnOK Eventhandler

Type the program statements for each control below inside its corresponding event. The codes for
btnReset would (a) clear all text the user entered in the textbox and (b) bring the focus (i.e. cursor) back
onto the same textbox. Note, though, that the line of code is order specific in Visual Basic. If txtName.Focus
() was written before txtName.Clear(), focusing on the textbox would first be performed instead of the
clearing of text content. Although the code order is not really critical in this instance, in calculations and
string operations, however, ordering is very crucial and would highly affect the output displayed by the
program.

Page 9 of 14
ENSC 26 COMPUTER APPLICATIONS IN ENGINEERING LABORATORY MODULES

Control.Event Program Statements


MsgBox("Hello " & txtName.Text & “!”,,
btnOK.Click "Hello”)
txtName.Clear()
btnReset.Click
txtName.Focus()
txtName.Clear()
ResetToolStripMenuItem.Click
txtName.Focus()
ExitToolStripMenuItem.Click End

Unlike C and all of its derivative languages, Visual BASIC is not case sensitive. Also, there is an auto-
complete and auto-suggest feature when you write codes. This feature, called intellisense, speeds up
code development by reducing keyboard input. Use the arrow keys to choose from the options VB
provides and then press the tab, enter, or space key to accept the auto-complete suggestion into your
code.

4. Save your work initially with Ctrl+Shift+S. Your final code should look like this:

5. Run the program by pressing F5.

Sample Output

Page 10 of 14
ENSC 26 COMPUTER APPLICATIONS IN ENGINEERING LABORATORY MODULES

Sample Code 2

1. Add two GroupBox, two Buttons, three TextBox, a MenuStrip


and four Labels.
The following objects are added in a form in this sequence: (a) all
input TextBoxes, (b) the main button, e.g. OK, Compute,
Calculate, etc., (c) the Reset button and (d) the MenuStrip.
Multiple labels can be added in any order afterwards. The
MenuStrip, meanwhile, has the following objects:

2. Select each object, one at a time, and change the specific object properties indicated in the table
presented below.

3. Add the codes to btnCompute, btnReset, CyanToolStripMenuItem, PinkToolStripMenuItem,


AboutToolStripMenuItem, ResetToolStripMenuItem, and ExitToolStripMenuItem

1 1 3 1

2 4
1 1

Page 11 of 14
ENSC 26 COMPUTER APPLICATIONS IN ENGINEERING LABORATORY MODULES

btnCompute Eventhandler

Control.Event Program Statements


btnReset.Click txtNumA.Clear()
txtNumB.Clear()
ResetToolStripMenuItem.Click txtSum.Clear()
txtNumA.Focus()
CyanToolStripMenuItem.Click Me.BackColor = Color.Cyan
PinkToolStripMenuItem.Click Me.BackColor = Color.Pink
MessageBox.Show("This program computes the sum
AboutToolStripMenuItem.Click of two numbers.” , “About”)
ExitToolStripMenuItem.Click End

4. To compute for the sum of the two numbers, the input value from the textboxes “txtNumA” and
“txtNumB” should be stored in a variable. The syntax for declaring variables is:

Dim VariableName As DataType

For the input values, follow the following variable declarations:

Dim dblNumA As Double


Dim dblNumB As Double
Dim dblSum As Double
dblNumA = txtNumA.Text
dblNumB = txtNumB.Text

Once the input values are stored, you can now proceed with the operation to be used for the
computation of the sum of two numbers. The value of the sum will be stored in the variable dblSum.
To display the sum in the text box “txtSum”, follow the syntax below:

txtSum.Text = dblSum

Page 12 of 14
ENSC 26 COMPUTER APPLICATIONS IN ENGINEERING LABORATORY MODULES

5. Save your work initially with Ctrl+Shift+S. Your final code should look like this:

6. Run the program by pressing F5.

Page 13 of 14
ENSC 26 COMPUTER APPLICATIONS IN ENGINEERING LABORATORY MODULES

TIP: Intellisense also reveals the properties and methods available for use to an object when "." is
pressed. For example, you can change the backcolor of a textbox by using the code
Textbox.BackColor = Color.Red (for default colors, use Color.Empty). Notice that after typing
“textbox.” or “color.”, Visual Basic offers code suggestions.
TIP: The current form is not called into code using its name (e.g., frmMain) but by using the keyword
"Me". Hence to change the backcolor of the current form to the default value, write Me.BackColor
= Color.Empty.
TIP: DO NOT double-click a textbox or label, no meaningful code will ever be associated with them.
TIP: One button (e.g. the main compute button) should be assigned as the AcceptButton for your
form. Whenever a user presses the ENTER key, the button’s click event is activated even if another
control on the form has the focus. In the same manner, a CancelButton can also be assigned; its
click event is activated whenever the ESC key is pressed.
TIP: You can also investigate other useful features included in object properties such as Enabled
(True or False), FormBorderStyle (Sizable, FixedSingle, etc.), ReadOnly (True or False) and
StartPosition (WindowsDefaultPosition, CenterScreen, etc.)

References:

Microsoft Digital Network.


Campano, Allen C. ENSC 26 Pre-Lab Handout. 2010. Engineering Science Department, CEAT, UPLB
Sanchez, PRP. (2017). ENSC 26. Retrieved from https://sites.google.com/site/ensc26prpsanchez/home

Prepared by: Reviewed by:

JEAN NORMAN M. ICARO AIDREAN P. OPACO

Page 14 of 14

You might also like