Visual Basic Programming for Engineering Calculations

Visual Basic Programming lets you turn an engineering calculation into a repeatable sequence of instructions. You can store measurements, evaluate formulas, repeat calculations and report whether a result meets a specified condition. The examples here use Visual Basic .NET console programs. This identifies the language variant so that you can interpret its declarations, arrays and procedures consistently.

Organize a small program

A variable is a named storage location whose value can change during execution. Declare one with Dim, give it a meaningful name and specify its type using As. Statements normally execute in order unless a decision, loop or procedure call changes that order.


A small console program can use this structure:


Visual Basic
Option Strict On

Module ForceSummary
    Sub Main()
        Dim forceN As Double = 42.0
        Console.WriteLine(forceN.ToString() & " N")
    End Sub
End Module


Execution starts in Sub Main. The containing Module groups related procedures. Console.WriteLine displays a result, and & joins text. An apostrophe starts a comment that explains code without executing it. Indentation makes the boundaries of each block easier to see.

Choose types and preserve units

Choose a type that matches the quantity you intend to store.


Type

Suitable use

Example

Double

Measurements with fractional values

Force in newtons

Integer

Whole-number counts and indexes

Number of readings

Boolean

A true-or-false condition

Whether a limit is exceeded

String

Text

A specimen identifier


Double uses finite binary floating-point precision, so many decimal fractions are approximate. Keep intermediate values unrounded and round the displayed result as required. Option Strict On, placed at the beginning of the file, helps expose potentially lossy implicit conversions, such as assigning a Double variable directly to an Integer variable.


Use +, -, *, / and ^ for addition, subtraction, multiplication, floating-point division and exponentiation. Parentheses make the intended grouping explicit. The backslash operator \ performs integer division; with positive integer operands, it discards the fractional quotient. For example, 11 / 4 gives 2.75, whereas 11 \ 4 gives 2.



Names such as forceN document units, but Visual Basic does not enforce those units. Convert inputs to a consistent unit system before combining them.

Repeat calculations over measurements

An array stores related values under one name. For a nonempty set of force readings, the arithmetic mean is


F‾=1n∑i=0n−1Fi\overline{F}=\frac{1}{n}\sum_{i=0}^{n-1}F_i


Here, nn is the number of readings and each FiF_i is measured in newtons. Visual Basic arrays begin at index zero. An array with Length equal to nn therefore has a final valid index of n−1n-1.


Place these statements inside Sub Main:


Visual Basic
Dim forcesN() As Double = {42.0, 47.0, 46.0}
Dim totalN As Double = 0.0

For i As Integer = 0 To forcesN.Length - 1
    totalN += forcesN(i)
Next

Dim meanN As Double = totalN / forcesN.Length


+= adds to the existing value. For...Next includes its final counter value when reached; its default step is one. The total becomes 135 N135\ \text{N}, so the mean is 45 N45\ \text{N}. Initializing the total inside the loop would erase previous contributions.


A flowchart shows initialization, repeated accumulation of array elements, and calculation of a mean.


Make decisions and return results

Use If...Then...Else...End If to select a block. Comparisons such as meanN > limitN produce Boolean values. Use >= when equality belongs in the condition, and AndAlso when two conditions must both hold.


A function is a named procedure that returns a value. Define it inside the module, outside Sub Main:


Visual Basic
Function ScaleForce(ByVal forceN As Double,
                    ByVal factor As Double) As Double
    Return forceN * factor
End Function


The parameters name its inputs; As Double after the parameter list specifies its return type. Inside Main, Dim scaledN As Double = ScaleForce(45.0, 1.2) stores the returned 54 N54\ \text{N}. For these numeric parameters, ByVal gives the function local copies, so changing a parameter does not change the caller's variable.



What to remember

  • Declare measurements, counts and conditions with suitable types.
  • Track units and distinguish / from \.
  • Initialize totals before loops and respect array bounds.
  • Store function results and handle cases where a mean has no readings.

Example: Reporting Pressure from Force Readings

A compression-test logger records four force readings: 118 N118\ \text{N}, 124 N124\ \text{N}, 130 N130\ \text{N} and 128 N128\ \text{N}. The loaded area is constant at 0.00250 m20.00250\ \text{m}^2. Your reporting rule flags a mean pressure strictly greater than 48.0 kPa48.0\ \text{kPa} as above the limit.


Use Visual Basic .NET with Option Strict On. Place calculation and reporting statements inside Sub Main, and place the function inside the containing module but outside Sub Main. Retain unrounded values during calculation.


a) Store the readings in an array and use a For...Next loop to calculate their mean force.


The readings can contain fractional values in future tests, so use a Double array and a Double accumulator. Use an Integer counter to visit the four valid indexes, zero through three. Initialize the accumulator before the loop.


Visual Basic
Dim forcesN() As Double = {118.0, 124.0, 130.0, 128.0}
Dim totalN As Double = 0.0

For i As Integer = 0 To forcesN.Length - 1
    totalN += forcesN(i)
Next

Dim meanForceN As Double = totalN / forcesN.Length


The running totals are 118 N, ________ N, ________ N and ________ N. The mean uses the number of readings, not the largest index:


F‾=118+124+130+1284 N=5004 N=125 N.\overline{F}=\frac{118+124+130+128}{4}\ \text{N} =\frac{500}{4}\ \text{N} =125\ \text{N}.


The mean force is 125 N, which lies between the smallest and largest readings.


b) Write a function named PressureKPa that accepts force in newtons and positive area in square metres. Use it to calculate the mean pressure in kilopascals.


Pressure is force divided by area. With newtons and square metres, the result is in pascals. Since 1 kPa=1000 Pa1\ \text{kPa}=1000\ \text{Pa}, divide the pascal result by 1000.


pkPa=F/A1000.p_{\text{kPa}}=\frac{F/A}{1000}.


Place this function at module level:


Visual Basic
Function PressureKPa(ByVal forceN As Double,
                     ByVal areaM2 As Double) As Double
    Return (forceN / areaM2) / 1000.0
End Function


Then call it inside Main, after calculating meanForceN:


Visual Basic
Dim areaM2 As Double = 0.00250
Dim meanPressureKPa As Double = PressureKPa(meanForceN, areaM2)


Because the area is constant, dividing the mean force by that area gives the mean pressure:


p‾=125 N0.00250 m2=50000 Pa=50.0 kPa.\begin{aligned} \overline{p}&=\frac{125\ \text{N}}{0.00250\ \text{m}^2}\\ &=50000\ \text{Pa}\\ &=50.0\ \text{kPa}. \end{aligned}


The function returns 50.0 kPa. Storing that returned value makes it available for the subsequent comparison.


c) Add code that displays the mean pressure to one decimal place and reports whether it exceeds the limit. State what happens at exactly 48.0 kPa48.0\ \text{kPa}.


Use > because the rule specifies strictly greater than the limit. Formatting the displayed value does not change the unrounded value stored in meanPressureKPa.


Visual Basic
Dim limitKPa As Double = 48.0
Console.WriteLine(meanPressureKPa.ToString("F1") & " kPa")

If meanPressureKPa > limitKPa Then
    Console.WriteLine("Above limit")
Else
    Console.WriteLine("Within limit")
End If


The comparison is


50.0 kPa>48.0 kPa.50.0\ \text{kPa}>48.0\ \text{kPa}.


The program displays a pressure of 50.0 kPa and reports Above limit. At exactly 48.0 kPa, the strict comparison is false, so the program reports Within limit. Using >= would incorrectly flag equality under the stated rule.

A Visual Basic .NET program processes 17 sensor events recorded over 4 seconds. It also counts complete groups containing four events each. The following statements execute inside Sub Main:


Visual Basic
Dim eventCount As Integer = 17
Dim durationS As Integer = 4
Dim ratePerS As Double = eventCount / durationS
Dim fullGroups As Integer = eventCount \ 4


What values are stored in ratePerS and fullGroups?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

An engineer is writing a Visual Basic calculation for a plate whose area is fixed at 0.018 m2. The value is known when the program is compiled, and the declaration must prevent later assignment to that name.


Complete both statements with the exact Visual Basic keyword or type name.


The declaration should begin with rather than Dim to enforce the fixed value. To store the area using Visual Basic's built-in 64-bit floating-point type, write after As.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A component is accepted when its measured length is between 0.0980 m0.0980\ \text{m} and 0.1020 m0.1020\ \text{m}, including both endpoints. In a Visual Basic .NET program, lengthM is a Double containing the measured length in metres.


Which condition should follow If and precede Then to implement this rule?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice