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:
Option Strict On
Module ForceSummary
Sub Main()
Dim forceN As Double = 42.0
Console.WriteLine(forceN.ToString() & " N")
End Sub
End ModuleExecution 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
Here, n is the number of readings and each Fi is measured in newtons. Visual Basic arrays begin at index zero. An array with Length equal to n therefore has a final valid index of n−1.
Place these statements inside Sub Main:
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 N, so the mean is 45 N. Initializing the total inside the loop would erase previous contributions.
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:
Function ScaleForce(ByVal forceN As Double,
ByVal factor As Double) As Double
Return forceN * factor
End FunctionThe 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 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 N, 124 N, 130 N and 128 N. The loaded area is constant at 0.00250 m2. Your reporting rule flags a mean pressure strictly greater than 48.0 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.
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.LengthThe running totals are 118 N, ________ N, ________ N and ________ N. The mean uses the number of readings, not the largest index:
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 Pa, divide the pascal result by 1000.
Place this function at module level:
Function PressureKPa(ByVal forceN As Double,
ByVal areaM2 As Double) As Double
Return (forceN / areaM2) / 1000.0
End FunctionThen call it inside Main, after calculating meanForceN:
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:
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 kPa.
Use > because the rule specifies strictly greater than the limit. Formatting the displayed value does not change the unrounded value stored in meanPressureKPa.
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 IfThe comparison is
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.
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.
A component is accepted when its measured length is between 0.0980 m and 0.1020 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?