Lesson 38: Console Applications Part 2

Advanced console programming with decision structures in Visual Basic 2022

Key Takeaway

Decision structures like If..Then..Else and Select Case enable your console applications to respond intelligently to different conditions and inputs.

In this lesson, we'll explore how to implement decision-making structures in Visual Basic 2022 console applications. These structures allow your programs to:

Branch Execution Paths

Execute different code blocks based on conditions

Handle User Input

Respond to different user choices and inputs

Validate Data

Check input validity and handle errors

Create Complex Logic

Build sophisticated program flows

38.1 If..Then..Else Statements

The If..Then..Else structure allows your program to make decisions based on conditions. The basic syntax is:

IfThenElse.vb
If condition Then
    ' Code to execute if condition is true
Else
    ' Code to execute if condition is false
End If

Example 38.1: Simple Arithmetic Check

This application prompts the user to enter two numbers and their sum, then checks if the calculation is correct.

ArithmeticCheck.vb
Module ArithmeticCheck
    Sub Main()
        Console.WriteLine("=== ARITHMETIC CHECKER ===")
        Console.WriteLine()
        
        ' Get user input
        Console.Write("Enter first number: ")
        Dim num1 As Double = Console.ReadLine()
        
        Console.Write("Enter second number: ")
        Dim num2 As Double = Console.ReadLine()
        
        Console.Write("Enter your calculated sum: ")
        Dim userSum As Double = Console.ReadLine()
        
        ' Calculate actual sum
        Dim actualSum As Double = num1 + num2
        
        ' Check if user's calculation is correct
        If userSum = actualSum Then
            Console.WriteLine("Correct! " & num1 & " + " & num2 & " = " & actualSum)
        Else
            Console.WriteLine("Incorrect! " & num1 & " + " & num2 & " should be " & actualSum)
        End If
        
        Console.WriteLine("Press Enter to exit...")
        Console.ReadLine()
    End Sub
End Module
=== ARITHMETIC CHECKER ===
Enter first number:
25
Enter second number:
17
Enter your calculated sum:
42
Correct! 25 + 17 = 42
Press Enter to exit...

Example 38.3: Number Sign Checker

This example uses nested If statements to determine if a number is positive, negative, or zero.

SignChecker.vb
Module SignChecker
    Sub Main()
        Console.WriteLine("=== NUMBER SIGN CHECKER ===")
        Console.WriteLine()
        
        Console.Write("Enter a number: ")
        Dim number As Double = Console.ReadLine()
        
        If number > 0 Then
            Console.WriteLine("The number is positive")
        Else
            If number < 0 Then
                Console.WriteLine("The number is negative")
            Else
                Console.WriteLine("The number is zero")
            End If
        End If
        
        Console.WriteLine("Press Enter to exit...")
        Console.ReadLine()
    End Sub
End Module
=== NUMBER SIGN CHECKER ===
Enter a number:
-5.5
The number is negative
Press Enter to exit...

38.2 Select Case Statements

The Select Case structure evaluates one expression against multiple possible values. It's particularly useful when you have many conditions to check.

SelectCase.vb
Select Case expression
    Case value1
        ' Code for value1
    Case value2
        ' Code for value2
    Case Else
        ' Code when no match found
End Select

Example 38.2: Grade Evaluator

This application evaluates examination grades and displays the corresponding result.

GradeEvaluator.vb
Module GradeEvaluator
    Sub Main()
        Console.WriteLine("=== GRADE EVALUATOR ===")
        Console.WriteLine()
        
        Console.Write("Enter your grade (A, B, C, D, F): ")
        Dim grade As String = Console.ReadLine().ToUpper()
        
        Select Case grade
            Case "A"
                Console.WriteLine("Excellent! You passed with distinction.")
            Case "B"
                Console.WriteLine("Very good! You passed with credit.")
            Case "C"
                Console.WriteLine("Good! You passed satisfactorily.")
            Case "D"
                Console.WriteLine("You passed, but need improvement.")
            Case "F"
                Console.WriteLine("Sorry, you failed. Please try again.")
            Case Else
                Console.WriteLine("Invalid grade entered. Please use A, B, C, D, or F.")
        End Select
        
        Console.WriteLine("Press Enter to exit...")
        Console.ReadLine()
    End Sub
End Module
=== GRADE EVALUATOR ===
Enter your grade (A, B, C, D, F):
B
Very good! You passed with credit.
Press Enter to exit...

Example 38.4: Score to Grade Converter

This example uses Select Case with range expressions to determine a student's performance level based on their score.

ScoreConverter.vb
Module ScoreConverter
    Sub Main()
        Console.WriteLine("=== SCORE TO GRADE CONVERTER ===")
        Console.WriteLine()
        
        Console.Write("Enter your score (0-100): ")
        Dim score As Integer = Console.ReadLine()
        
        Select Case score
            Case 90 To 100
                Console.WriteLine("Grade: A - Excellent!")
            Case 80 To 89
                Console.WriteLine("Grade: B - Very Good!")
            Case 70 To 79
                Console.WriteLine("Grade: C - Good!")
            Case 60 To 69
                Console.WriteLine("Grade: D - Satisfactory")
            Case 50 To 59
                Console.WriteLine("Grade: E - Pass")
            Case 0 To 49
                Console.WriteLine("Grade: F - Fail")
            Case Else
                Console.WriteLine("Invalid score! Please enter a value between 0 and 100.")
        End Select
        
        Console.WriteLine("Press Enter to exit...")
        Console.ReadLine()
    End Sub
End Module
=== SCORE TO GRADE CONVERTER ===
Enter your score (0-100):
85
Grade: B - Very Good!
Press Enter to exit...

Decision Structures Summary

Key concepts for decision structures in VB2022 console applications:

Structure Best For Key Features
If..Then..Else Simple binary decisions Conditions, nested structures
Select Case Multiple possible values Value matching, range expressions

Conditional Logic

Allows programs to make decisions and respond to different inputs

Input Validation

Essential for verifying user input before processing

Code Readability

Select Case improves readability when handling multiple conditions

Practical Exercises

Apply your decision structures knowledge with these hands-on exercises:

Exercise 1: Temperature Advisor

Create a program that:

  1. Asks the user to enter the current temperature
  2. Displays clothing advice based on the temperature:
    • Above 30°C: "Wear light summer clothes"
    • 20-30°C: "Wear t-shirt and shorts"
    • 10-19°C: "Wear a light jacket"
    • Below 10°C: "Wear a heavy coat"

Exercise 2: Simple Calculator

Create a calculator that:

  1. Asks for two numbers
  2. Asks for an operation (+, -, *, /)
  3. Performs the calculation and displays the result
  4. Handles division by zero with an error message

Exercise 3: Day of Week

Create a program that:

  1. Asks the user to enter a number (1-7)
  2. Displays the corresponding day of the week
  3. Handles invalid inputs with an error message

Challenge: BMI Calculator

Create a BMI calculator that:

  1. Asks for weight (kg) and height (m)
  2. Calculates BMI (weight / height²)
  3. Displays the BMI category:
    • Underweight: BMI < 18.5
    • Normal: 18.5 ≤ BMI < 25
    • Overweight: 25 ≤ BMI < 30
    • Obese: BMI ≥ 30

Next Steps

Continue learning with our comprehensive VB2022 tutorials and practical examples.

Related Resources

VB6 Tutorial

Mastering VB6 Programming

Explore Tutorials

Visual Basic Examples

Practical VB code samples for real-world applications

View Examples

Excel VBA Tutorial

Learn how to automate Excel by creating VBA macros

Learn More