0% found this document useful (0 votes)
3 views30 pages

Programming Fundamentals

The document provides an overview of programming fundamentals, including definitions of key terms such as computer programs, programming languages, and the programming process. It outlines the history and evolution of programming languages, differentiating between low-level and high-level languages, and explains the program development life cycle. Additionally, it introduces Microsoft Visual Basic .NET, covering its syntax, structure, and basic components like classes, objects, methods, and variables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views30 pages

Programming Fundamentals

The document provides an overview of programming fundamentals, including definitions of key terms such as computer programs, programming languages, and the programming process. It outlines the history and evolution of programming languages, differentiating between low-level and high-level languages, and explains the program development life cycle. Additionally, it introduces Microsoft Visual Basic .NET, covering its syntax, structure, and basic components like classes, objects, methods, and variables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

PROGRAMMING FUNDAMENTALS

INTRODUCTION
Programming is the process of creating a set of instructions that a computer can follow to
perform specific tasks. The process of designing a program is referred to as algorithm design
Computers do not understand human languages, so programmers use special languages
called programming languages to communicate with them. Programming is essential because
it allows us to create software applications, automate tasks, and solve real-world problems.
By learning programming, one can develop websites, mobile applications, games, and even
artificial intelligence systems.

DEFINITION OF TERMS USED IN PROGRAMMING


Computer Program
A computer program is a set of instructions written in a programming language that tells a
computer what to do. Programs can be as simple as adding two numbers or as complex as
running an entire social media platform like Facebook.

Programming Languages
Programming languages are special languages that programmers use to write instructions for
computers. Some popular programming languages include Python, Java, C++, C, BASIC, Pascal,
COBOL and JavaScript.

Computer Programming
Computer programming is the act of writing, testing, and maintaining computer programs. It
involves designing solutions to problems and then translating those solutions into code that
a computer can execute.

Source Code
Source code is the original code written by a programmer in a programming language before
it is converted into machine-readable form. For example, a Python program written by a
programmer is considered source code.

Object Code
Object code is the machine-readable version of a program, generated after the source code
has been compiled. This is the code that the computer understands and executes.

AJ-KALEMA 1
Assembler
An assembler is a tool that converts assembly language programs into machine code.
Assembly language is a low-level language that is easier to understand than pure machine
code.

Interpreter
An interpreter is a program that reads and executes source code line by line. Languages like
Python and JavaScript use interpreters, which means they do not need to be fully compiled
before running.

Compiler
A compiler is a program that converts the entire source code into object code before the
program runs. Languages like C and Java use compilers, which makes them faster than
interpreted languages.

The difference between the interpreters and compilers:

Features INTERPRETER COMPILER


Execution Translates and execute the code line by line Translate the entire code at once before
execution
Speed Slower because it translates the code during Faster because it translates the entire
execution code before execution
Error Stops when encounters an error, making it Detects all errors after compilation,
handling easier to debug making debugging harder
Output Displays results immediately after executing Displays results only after the entire
each line code is compiled

HISTORY OF PROGRAMMING LANGUAGES


Programming languages have evolved over time to make computer programming easier and more
efficient. The development of programing languages can be divided into low-level and high-level
languages. These categories can be subdivided into further five generations

1. LOW-LEVEL LANGUAGES
Low-level languages are programming languages that are close to machine code and provide
little abstraction from the computer's hardware. They are difficult for humans to read and

AJ-KALEMA 2
write but are efficient for computer processing. They include machine language and
assembly language.

a) Machine Language (First-Generation language -1GL)


Machine language is the lowest level of programming language and consists only of binary
numbers (0s and 1s). Computers can directly understand and execute machine language,
but it is very difficult for humans to write and debug.

ADVANTAGES DISADVANTAGES
• Hard to read and write
• Very fast because the computer does not
• Not portable (specific to a particular
need translation.
type of computer hardware).
• Uses minimal system resources.
• Debugging is extremely difficult.

b) Assembly Language (Second-Generation Language – 2GL)


Assembly language is a low-level language that uses symbolic instructions (mnemonics)
instead of binary code. It is easier to understand than machine language but still requires
knowledge of computer architecture. It requires an assembler to convert it into machine
language.

Advantages and Disadvantages of Low-Level Languages


ADVANTAGES DISADVANTAGES
• Easier to read and write compared to
machine languages. • Still difficult to learn compared to
• Faster execution than in high-level modern programing languages.
languages. • Not portable across different
• Gives programmer control over system computer systems.
hardware.

2. HIGH-LEVEL LANGUAGES
High-level languages are programming languages that are easier to read, write, and
understand because they use human-friendly syntax. They need to be translated into machine
code before execution. These languages use English-like words and symbols, making them
easier to learn and write.

AJ-KALEMA 3
a) Third Generation Languages (3GL)
These include languages like C, C++, Java, and Python. They are structured and
procedural, making them easier to use than low-level languages. Requires a compiler
or interpreter to convert code into machine language.

b) Fourth Generation Languages (4GL)


4GLs were improvement on 3GLs to reduce programing effort by making the
programmer focus on the problem than algorithm or structure of the program. These
languages are designed for database management and automation of complex tasks.
Examples include SQL and MATLAB. Focus on reducing coding effort by providing pre-
built functions.

c) Fifth Generation Languages (5GL) also known as natural languages


These languages are used in artificial intelligence and expert systems. Artificial
intelligence refers to computer system that mimic human-like intelligence. Examples
include Prolog and LISP. It allows the user to define the problems, and the system
figures out the solution.

d) Object-Oriented Languages
These languages focus on objects rather than procedures. In object Oriented
Programing (OOP), a program consists of several objects that interact by sending
messages to each other’s. These objects are linked together through a method known
as association to create a complete program. Examples include Java, C++, and Python.

e) Web Scripting Languages


These are used for web development and creating interactive websites. Web pages are
hypertext documents created in a language called Hypertext Markup Language
(HTML). To enhance interaction and dynamism of HTML web pages, special types of
web programing languages known as scripting languages like JavaScript, VBScript and
Hypertext Preprocessor (PHP) are used. A Script is a small program code written in
scripting language and then appended into HTML program to add functionalities.

BENEFITS AND LIMITATIONS OF HIGH-LEVEL LANGUAGES

AJ-KALEMA 4
Benefits Limitations
• Easier to learn and use than low-level • Programs may run slower than low-
languages. level languages.
• Portable (can run on different types of • They do not give full control over
computers). system hardware.
• Faster development because of simple • Dependence on compilers or
syntax and built-in functions. interpreters to translate code.
• Easier debugging and maintenance.

PROGRAM DEVELOPMENT PROCESS


The Program Development Process is a structured approach to writing software, ensuring
efficiency and correctness. It consists of several key phases, collectively known as the
Program Development Life Cycle (PDLC)

Phases of Program Development Life Cycle

1. Problem Definition
Problem definition is the first step and most important phase of program
development life cycle (PDLC). It involves clearly understanding and describing the
problem than needs to be solved before writing any code. A well-defined problem
ensures that the final program meets user requirements and functions correctly.

2. Algorithm Design
An algorithm is the process of creating a step-by-step procedure to solve the problem
before writing actual code. It acts as a blueprint that guides programmers on how to
structure their programs. The solution to the problem is expressed using flowcharts,
pseudocode or Structured English statements.

Example: algorithm for Calculating the Average of Three Numbers

Using Pseudocode:

AJ-KALEMA 5
Program: Calculating the average of Program: Calculating area of a circle
three numbers BEGIN
START SET as constant PI=3.14
1. Get three numbers from the PRINT “Enter Radius”
user READ radius
2. Add the three numbers Area=PI*radius
3. Divide the sum by 3 to get the PRINT area
average END
4. Display the average
END

3. Program Coding
This involves writing the actual program using a programming language to create a
computer program. This step now coverts an algorithm into a form that a computer
can understand and execute. Most of the high-level languages have common features
as reserved words, operators, identifiers and variables.

❖ Reserved words
Reserved words, also known as Keywords, are special words that have a fixed
meaning in a programming language and can not be used as variable name,
function names or identifiers. These words are predefined and serve specific
function in coding. Examples; for, if, else, while and do.
❖ Identifiers
an identifier is the name given to variable, functions, classes, and other
elements in a program. It helps programmers’ reference and use these
elements in their code.
❖ Operators
An operator is a symbol or keyword used in programming to perform
operations on variables and values. Operators allow a programmer to
manipulate data and perform calculations. Here are types of operators;
1. Arithmetic operators

AJ-KALEMA 6
These operators perform mathematical operations such as addition,
subtraction, multiplication and division.

Operator Name Example Output


+ Addition 10 + 5 15
- Subtraction 10 – 5 5
* Multiplication 10 * 5 50
/ Division 10 / 5 2.0
% Modulus(remainder) 10 % 3 1
** exponentiation 2 **3 8

2. Assignment operators
These operators are used to assign values to variables.
Operators Example Equivalent To
= x=5 x=5
+= x += 3 x=x+3
-= x -= 2 x=x–3
*= x *= 4 x=x*3
/= x /= 2 x=x/3
%= x %= 3 x=x%3

3. Comparison (Relational) operators


These operators compare two values and return True or False.
Operators Meaning Example Output
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 5>3 True
< Less than 5<3 False
>= Greater than or equal to 5 >= 5 True
<= Less than or equal to 5 <= 3 False

4. Logical operators
These operators combine multiple conditions and return True or False.

Operators Meaning Example Output

AJ-KALEMA 7
Return True if both
and (5 > 3) and (10 > 5) True
conditions are true
Return True if at least
Or (5 > 3) or (10 < 5) True
one conditions is true
not Reverses the condition Not (5 > 3) False

❖ Variables
A variable is a name given to a memory location used to store data in a
problem. The value of variable can change during program execution.

4. Program Testing and Debugging


The program testing and debugging are essential steps in software development.
They help ensure that program runs correctly, meets requirements, and is free from
errors.
• Program Testing: the process of executing a program to find errors and verify
its correctness.
• Debugging: the process of identifying, analyzing, and fixing errors in the
program.
There are two types of bugs/Errors that may be encounter when testing a program.
These are:
i. Syntax errors: this occurs when a programmer writes code that does not follow
the correct structure and rules of programming language. These errors prevent
the program from running because the computer does not understand the
incorrect syntax.
ii. Logical errors: it occurs when a program runs without crashing but the output
is not what the programmer intended. This type of error is caused by mistake in
the logic or reasoning of the code, leading to incorrect results.
5. Program Review and Maintenance
Program review and maintenance is the process of evaluating, updating and
improving a software program after it has been developed and deployed. The goal is
to ensure that the program continues to perform efficiently, meets user needs and
remains functional over time.

Characteristics of a Good Program


• Correctness: Produces accurate results.

AJ-KALEMA 8
• Efficiency: Uses minimal system resources.
• Readability: Easy for others to understand and modify.
• Maintainability: Can be updated and improved easily.
• Portability: Can run on different systems without modification.

PROGRAMMING IN VISUAL BASIC .NET

Microsoft Visual Basic .NET


VB.NET is a modern, object-oriented programming language developed by Microsoft.
It runs on the .NET Framework and is used for building Windows applications.
VB.NET replaces older versions like VB6 with enhanced features.
Basic Syntax and Structure of a VB.NET Program
1. Class
A class is a blueprint or template used to create objects. It defines the properties
(data) and methods (actions) that objects will have.

Public Class Student


‘Properties and Method go here’
End Class

Think of a class as a "recipe" or "design" for creating objects.


3. Object
An object is an instance of a class that has state and behavior function. It is created
using the New keyword and can use the properties and methods of the class.

Dim s As New Student()

Example: If Student is a class, then s is one student (object) created from that class.

AJ-KALEMA 9
3. Method
A method is a block of code that performs an action. It is written inside a class and
define the behavior or function to be performed by an object to manipulate data. In

Public Sub SayHell0()


Console.WriteLine(“Hello from student”)
End Sub

VB.NET, a method can be a Sub (no return value) or a Function (returns a value).
Methods allow you to group code that does a specific task.
4. Variable
A variable is used to store data. It must be declared with a data type.

Dim name As String


Dim age As Integer

Variables hold information like names, numbers, or dates.


5. Comments
Comments are notes in the code that help explain what the code is doing. They are

‘This is a single-line comment


‘Declare a variable to store student name
Dim studentName As String

ignored by the computer during execution.


Use comments to make your code easier to understand.
📝 Summary Table
Concept Description Example
Class A blueprint for creating objects Public Class Student
Object An instance of a class Dim s As New
Student()
Method A set of instructions inside a class Public Sub SayHello()
Variable Stores data temporarily during program Dim age As Integer
execution

AJ-KALEMA 10
Comment Notes in the code for explanation ' This is a comment

4. Getting Started with VB.NET 2010 Express


1. Install Visual Basic 2010 Express from Microsoft.
2. Open and create a new Windows Forms Application project.
3. Use the Toolbox to design, and write logic in the Code Window.
📘 Menu Bar and Standard Toolbar in VB.NET
🔹 1. Menu Bar
The Menu Bar is the horizontal bar at the top of the Visual Studio window. It contains
text-based menus that give you access to different commands and features.
🔸 Common Menus in the Menu Bar:
Menu Description
File Create, open, save, and close projects or files
Edit Cut, copy, paste, undo, redo, and find text
View Show or hide tool windows like Toolbox, Solution Explorer, Properties,
etc.
Project Add new items or references to your project
Build Compile (build) your program
Debug Start or stop the program, set breakpoints
Tools Set environment options and configure settings
Help Access help topics and documentation
✅ Tip: Clicking on any menu reveals a drop-down list of commands.

🔹 2. Standard Toolbar
The Standard Toolbar is usually located just below the Menu Bar. It contains icons
(buttons) that give quick access to commonly used commands.
🔸 Common Buttons on the Standard Toolbar:
Icon/Button Function
New Project Create a new project

Open Open an existing project

Save Save the current file

Undo Undo the last action

AJ-KALEMA 11
Redo Redo the undone action

▶️ Start Run the program (Start Debugging)


Stop Stop the running program

Build Build/compile the solution

📘 Forms in VB.NET
A Form is a window or screen in a VB.NET application where users can interact with
the program. It is part of a Graphical User Interface (GUI) and can contain controls
like buttons, labels, textboxes, etc. Think of a form like a blank sheet where you can
place tools (controls) for your program.
🔸 Types of Forms
1. Main Form – The first window that appears when the program runs.
2. Child Form – Additional forms that can be opened from the main form.
🔹 Creating a Form in VB.NET
When you create a new Windows Forms Application in Visual Studio, it automatically
includes a default form called Form1.vb. You can add more forms using:
Project > Add Windows Form...
🔹 Adding Controls to a Form
You can drag and drop controls (like buttons, labels, and textboxes) onto the form
using the Toolbox.
Example controls:
• Label – to display text
• Button – to perform an action when clicked
• TextBox – to allow user input
🔹 Writing Code for a Form
You can double-click on any control to write event-handling code, like when a

Private Sub btnGreet_Click(sender As Object, e As EventArgs) Handles btnGreet.Click


MessageBox.Show(“Hello, welcome!”)
End Sub

button is clicked.

AJ-KALEMA 12
Showing or Hiding a Form

🧰 Toolbox in VB.NET
The Toolbox in VB.NET is a panel that contains a list of controls (tools) you can use
to design your form. You drag and drop items from the Toolbox onto a Form to build

Dim frm As new Form2()


Frm.Show() ‘Show form2
Me.Hide() ‘Hide current form

the user interface (UI) of your program.


🔹 Where is the Toolbox?
• The Toolbox is usually located on the left side of the Visual Studio window.
• If it is not visible, you can open it by clicking:
View > Toolbox

🔹 Common Controls in the Toolbox


Control Icon Purpose
Label Displays static text

TextBox Allows the user to enter text

Button Performs an action when clicked

CheckBox Lets the user select yes/no (true/false)

RadioButton Select one option from a group

ListBox Shows a list of selectable items

ComboBox Dropdown list where user can select an item

PictureBox Displays images

Timer Executes code after a time interval

🔹 How to Use the Toolbox


1. Open the Toolbox.
2. Click and drag a control onto the Form.
3. Resize and position the control as needed.
4. Use the Properties Window to change the control’s name, text, color, size, etc.

AJ-KALEMA 13
5. Double-click the control to write code for its event (e.g., Button Click).

📘 Key Windows in VB.NET Environment


1️⃣ Solution Explorer
Solution Explorer is a panel that shows all the files and components of your project.
🔸 What it displays: Forms (e.g., Form1.vb), Code files, Images, References (external
libraries), Project name and structure
✅ What you can do:
• Open forms or files by double-clicking
• Rename or delete files
• Add new items (like new forms or classes)
Think of it as the "table of contents" for your project.

2️⃣ Properties Window


The Properties Window lets you change the settings of a selected control or form.
🔸 Common properties you can change:
Property Description
Name Name of the control in your code
Text Text displayed on the control
BackColor Background color
Font Font style and size
Enabled Determines if the control is usable
Use this window to customize the appearance and behavior of controls.
3️⃣ Code Window
The Code Window is where you write the actual code (instructions) that your
program will follow.
🔸 How to open: Double-click any control (e.g., a button) on the form.

Private Sub btnHello_Click(sender As Object, e As EventArgs) Handles btnHello.Click


MessageBox.Show(“Hello, world!”)
End Sub

This is the "brain" of your program where all logic is written.

AJ-KALEMA 14
7. Running the Program
Click Start or press F5 to compile and run your program.
Errors will be shown in the Error List window.
💾 Saving a VB.NET Project
Saving means storing your work (forms, code, settings) so that you can open and
continue your project later. This prevents loss of your work.
🔸 Steps to Save a VB.NET Project
📝 When you create a new project:
1. Go to File > New > Project.
2. Choose Windows Forms App (.NET Framework).
3. Give your project a Name (e.g., "MyFirstApp").
4. Choose a Location where you want to save it on your computer.
5. Click Create.
💾 To save your work while editing:
• Click File > Save All
OR
• Press Ctrl + Shift + S on your keyboard
OR
• Click the Save All icon on the toolbar (looks like two floppy disks )
This saves:
• The current form (e.g., Form1.vb)
• The code file
• The entire project structure
🔸 What Gets Saved?
When you save a VB.NET project, these main parts are stored:
File/Folder Purpose
.sln file The solution file that opens the whole project
Form1.vb The form's design and code
bin and obj folders Contain compiled files (automatically created)
Project Folder All your project files are saved here

AJ-KALEMA 15
📂 Opening an Existing VB.NET Project
Opening an existing project means loading a previously saved VB.NET project so
you can continue working on it or run it again.
🔸 Steps to Open an Existing Project in Visual Studio
1. Start Visual Studio
o Double-click the Visual Studio icon on your desktop or search for it in
the Start menu.
2. Click on "Open a project or solution"
o On the start screen, click: Open a project or solution
3. Find your project folder
o Navigate to the folder where you saved your project.
4. Open the solution file (.sln)
o Look for a file with the extension .sln (e.g., MyFirstApp.sln).
o Select it and click Open.
5. Project Loads in Visual Studio
o You will see the Form, Solution Explorer, and your code.
o You can now edit or run your project.
➕ Adding New Forms in VB.NET
A Form is a window or screen in your application where users can interact.
You can add multiple forms to your project to create different windows or dialogs.
🔸 Why Add New Forms?
• To create different screens (e.g., a Login form, Settings form)
• To organize your program better
• To allow multiple windows in your app
🔹 How to Add a New Form
1. Open your project in Visual Studio.
2. Go to the Menu Bar
Click:
3. Project > Add Windows Form...
4. Add New Item Window Appears
o Select Windows Form from the list.
o Give the form a name (e.g., Form2.vb).

AJ-KALEMA 16
o Click Add.
5. New Form Opens
o You will see a blank form design window.
o You can add controls (buttons, labels, etc.) to this form.

📝 Comments, Declarations, Variable Types, and Constants in VB.NET


1️⃣ Comments
Comments are lines in your code that explain what the code does but are ignored
by the computer when running the program.
• How to write comments in VB.NET?
Use a single quote ' before the comment.
' This is a comment
Comments help explain the code to anyone reading it
2️⃣ Declarations
Declaration is the process of creating variables or constants in your program
by giving them a name and data type.
Example of variable declaration:

Dim age As Integer


Dim name As String

Dim means "Dimension" — used to declare a variable.


3️⃣ Variable Types
Variables store data of different types. Some common types in VB.NET:
Data Type Stores Example
Integer Whole numbers (no decimals) 10, -5, 100
Double Numbers with decimals 3.14, 9.99
String Text (letters, words) "Hello", "VB.NET"
Boolean True or False values True, False
Char Single character "A", "b"
🔢 Constants in VB.NET
A constant is a value that does not change while the program runs. You give it a
name, and you cannot modify its value later.

AJ-KALEMA 17
2️⃣ Named Constant
A named constant means you give the constant a specific name so you can use it
in your code instead of the actual value.

Const MaxScore As Interger = 100


Const WelcomeMessage As String = “Welcome to VB>NET!”

This makes your code easier to read and maintain.


Here, MaxScore and WelcomeMessage are named constants.
3️⃣ String Constants
String constants hold text values that don’t change.

Const SchoolName As String = “Greenwood High School”


Const Greeting As String = “Hello, student!”

These are used when you have fixed messages or names in your program.
4️⃣ Numeric Constants

Const Pi As Double = 3.14159


Const DaysInWeek As Integer = 7

Numeric constants hold numbers (integers, decimals) that remain the same.
Use numeric constants for fixed numbers like mathematical values, limits, or
counts.

🌐 Scope and Declaration in VB.NET


Scope refers to the area or part of the program where a variable or constant can
be accessed or used.
🔸 Types of Scope in VB.NET
Scope Type Description Example Location
Local Scope Variable or constant is accessible only within Inside a single Sub
a procedure (Sub or Function) where it is or Function
declared.

AJ-KALEMA 18
Module-Level Accessible to all procedures within the Declared at the top
Scope same module (form or class). of a form or class
Public Scope Accessible from any module or form in the Declared as Public
(Global) entire project. in a module
🔹 Examples of Declarations and Scope
Local Variable (Local Scope)

Sub ShowMessege()
Dim message As String = “Hello” ‘Only accessible inside ShowMessage
MsgBox(message)
End Sub

message cannot be used outside ShowMessage.


Module-Level Variable (Form-Level Scope)

Public Class Form1


Dim counter As Integer = 0 ‘Accesible by all procedures in Form 1
Sub Increment()
Counter += 1
End Sub

Sub ShowCounter()
MsgBox(“Count:”& counter)
End Sub
End Class

counter is shared between Increment and ShowCounter inside Form1.


Public Variable (Global Scope)

Public Module Globals


Public username As String = “Guest”
End Module

In a module file:
userName can be accessed from anywhere in the project.

AJ-KALEMA 19
📦 User-Defined Data Types in VB.NET

🔹 What Are User-Defined Data Types?


Sometimes, built-in data types (like Integer, String) are not enough to group
related data together. User-defined data types allow you to create your own
custom data structure that can hold different kinds of related data in one unit.
🔸 How to Create a User-Defined Data Type
In VB.NET, you use the Structure keyword to define a new data type.
🔹 Example: Define a Structure

Structure
Dim StudentID As Integer
Dim Name As String
Dim Age As Integer
Dim Grade As String
End Structure

🔸 How to Use a User-Defined Data Type

Dim stud As Student


Stud.StudentId = 101
Stud.Name = “Alice”
Stud.Age = 16
Stud.Grade = “A”

You can now use stud to store all student details together.
📝 Summary Table
Concept Description Example
User-Defined Data A custom structure holding Structure Student ... End
Type related data Structure
Fields Variables inside the structure StudentID, Name, Age
Instance Variable of the new data type Dim stud As Student

🔤 Declaration Using Suffixes in VB.NET


In VB.NET, suffixes are letters added to numeric values to tell the compiler what
data type the number is. This helps the compiler understand the type without
needing to declare a variable explicitly.

AJ-KALEMA 20
🔸 Common Suffixes and Their Data Types
Suffix Data Type Example Meaning
D Double Dim x = 10.5D Treats 10.5 as Double
F Single Dim y = 5.5F Treats 5.5 as Single (float)
@ Decimal Dim z = 100@ Treats 100 as Decimal
L Long Dim n = 12345L Treats 12345 as Long integer
& Long Dim m = 12345& Also Long integer
% Integer Dim i = 100% Treats 100 as Integer
! Single Dim s = 3.14! Treats 3.14 as Single
🔹 Examples of Using Suffixes

Dim price As Decimal = 99.99@ ‘Decimal number


Dim pi As Double = 3.14159D ‘Double precison
Dim count As Integer = Long = 100% ‘Integer
Dim bigNumber As Long = 123456L ‘Long integer

🔸 Why Use Suffixes?


• To specify the data type of a numeric literal directly.
• Useful when you want to make sure the number is treated as a specific type
without extra declarations.
• Helps avoid errors caused by incorrect assumptions about number types.

➕➖ VB.NET Operators
Operators are symbols or keywords used to perform operations on variables and
values.
For example: addition, comparison, or checking conditions.
🔸 Categories of Operators in VB.NET
Category Description Example
Arithmetic Operators Perform math calculations +, -, *, /
Comparison Operators Compare values and return True or False =, <>, <, >
Logical Operators Combine multiple conditions (True/False And, Or,
logic) Not
Assignment Operator Assigns a value to a variable =

AJ-KALEMA 21
Concatenation Joins (adds) strings together &
Operator
1️⃣ Arithmetic Operators
Operator Meaning Example Result
+ Addition 5+3 8
- Subtraction 10 - 4 6
* Multiplication 6*2 12
/ Division 9/3 3.0
\ Integer Division 10 \ 3 3
Mod Remainder 10 Mod 3 1
^ Exponentiation 2^3 8

2️⃣ Comparison Operators


Operator Meaning Example Result
= Equal to 5=5 True
<> Not equal to 4 <> 3 True
> Greater than 6>2 True
< Less than 3<1 False
>= Greater or equal 4 >= 4 True
<= Less or equal 2 <= 5 True

3️⃣ Logical Operators


Operator Meaning Example Result
And True if both are True True And False False
Or True if at least one is True True Or False True
Not Reverses the condition Not True False
AndAlso Short-circuit And x < 5 AndAlso y > 0 More efficient
OrElse Short-circuit Or x = 5 OrElse y = 10 More efficient

4️⃣ Assignment Operator


Operator Meaning Example
= Assigns a value Dim x As Integer = 10

AJ-KALEMA 22
5️⃣ Concatenation Operator (Strings)
Operator Meaning Example Result
& Joins strings "Hello" & " " & "World" "Hello World"

📚 Library Functions in VB.NET


Library functions are predefined functions that come with VB.NET to help you
perform common tasks quickly. You don’t need to write the code yourself — just
call the function and provide the required values (called arguments).
🔸 Categories of Library Functions
1. Mathematical Functions
2. String Functions
3. Date and Time Functions
4. Conversion Functions

1️⃣ Mathematical Functions


Function Description Example Result
Math.Sqrt(x) Returns the square root of x Math.Sqrt(25) 5
Math.Abs(x) Returns the absolute value of x Math.Abs(-10) 10
Math.Round(x) Rounds x to the nearest whole Math.Round(2.7) 3
number
Math.Max(a, b) Returns the larger of two numbers Math.Max(5, 8) 8
Math.Min(a, b) Returns the smaller of two Math.Min(5, 8) 5
numbers

2️⃣ String Functions


Function Description Example Result
Len(str) Returns length of a string Len("Hello") 5
LCase(str) Converts string to lowercase LCase("VB.NET") "vb.net"
UCase(str) Converts string to uppercase UCase("hello") "HELLO"
Left(str, n) Returns first n characters Left("Computer", 3) "Com"
Right(str, n) Returns last n characters Right("Computer", 3) "ter"

AJ-KALEMA 23
Mid(str,
start, Extracts part of string Mid("Computer", 2, 3) "omp"
length)
Removes spaces from both
Trim(str) Trim(" Hello ") "Hello"
ends

3️⃣ Date and Time Functions


Function Description Example Result Example
Now() Returns current date and Now() 12/06/2025
time 10:15:00 AM
Today Returns current date only Today 12/06/2025
DateAdd Adds interval to a date DateAdd("d", 5, Today) 17/06/2025
DateDiff Finds difference between DateDiff("d", 162 (days)
two dates #1/1/2025#, Today)
Day(), Extract parts of a date Day(Today) 12
Month(),
Year()

4️⃣ Conversion Functions


Function Description Example Result
CInt(value) Converts to Integer CInt("25") 25
CDbl(value) Converts to Double CDbl("3.14") 3.14
CStr(value) Converts to String CStr(123) "123"
Val(string) Extracts number from a string Val("123abc") 123

✅ 22. Using the Format Function in VB.NET


The Format function is used to control how numbers, dates, or strings are
displayed.
Syntax: Format(expression, format_style)

AJ-KALEMA 24
🔸 Example 1: Formatting Numbers

Dim price As Double = 12345.5


MsgBox(Format(price, “Currency”)) ‘Output: $1,234.50

🔸 Example 2: Formatting Dates

Dim today As Date = Now


MsgBox(Format(today, “dd-MM-yyyy”)) ‘Output: 12-06-2025

🔸 Common Format Styles:


Style Description Example Output
"Currency" Displays with currency symbol $1,234.50
"General Date" Date and time 12/06/2025 10:00 AM
"Short Date" Date only 12/06/2025
"Long Date" Full written date Thursday, June 12, 2025
"0.00" Fixed decimal places 3.14
🔢 23. Converting Numeric String to Value
Sometimes numbers come as strings (e.g., from a textbox), and we need to
convert them to numeric values to do calculations.
🔸 Common Conversion Functions:
Function Converts To Example Output
CInt() Integer CInt("25") 25
CDbl() Double CDbl("3.14") 3.14
Val() Any number Val("45abc") 45
🔸 Example:

Dim numStr As String = “100”


Dim num As Integer = Cint(numStr)
MsgBox(num +50) ‘Output: 150

🔤 24. Converting Numeric Value to String


You may need to display a number in a message box, label, or textbox. You must
convert it to a string first.

AJ-KALEMA 25
🔸 Common Conversion Methods:
Method Description Example Output
CStr() Converts any value to String CStr(123) "123"
.ToString() Method available on all numbers 123.ToString() "123"
🔸 Example:

Dim marks As Integer = 85


Dim message As String = “You scored” & marks.ToString()
MsgBox(message) ‘Output: You scored 85

✅ 25. Control Structures in VB.NET


Control structures are parts of a program that control the flow of execution. They
help the computer decide, repeat actions, or choose between options.
🔸 Types of Control Structures:
1. Decision Making (Conditional Statements)
2. Loops (Repetition Statements)
3. Select Case Statement
✅ Sequence in VB.NET
Sequence is the simplest control structure in programming. It means that the
statements (instructions) are executed one after another, in the order they appear.
Think of it like following steps in a recipe:
Step 1 ➜ Step 2 ➜ Step 3

🔸 Key Points:
• Code runs from top to bottom.
• Each line is executed once.
• There are no decisions or loops involved.

Dim name As String


Dim age As Integer
Name =”Joy”
Age = 16
MsgBox(“Name:” &name)
MsgBod(“Age:” & age)

AJ-KALEMA 26
🔸 Example:

✅ Explanation: 🔸 Real-Life Example of Sequence:


1. The variable name is declared. Imagine getting ready for school:
2. The variable age is declared. 1. Wake up
3. A name is stored in name. 2. Brush your teeth
4. A value is stored in age. 3. Take a shower
5. A message box shows the name. 4. Put on uniform
6. A message box shows the age. 5. Eat breakfast
Each step happens in order, one after This is sequence – you follow the
another. steps one by one.

✅ Selections in VB.NET (Decision Making)


Selection (also called decision making) is a control structure that allows a program to make
choices. The program checks a condition, and then chooses what to do based on whether the
condition is True or False.
📌 Example from Real Life:
If it’s raining, take an umbrella.
If it’s not raining, don’t take one.
This is selection!
🔸 Types of Selection in VB.NET
1️⃣ If...Then
Used to do something only if a condition is True.

Dim age As Integer = 16


If age >= 18 Then
MsgBox( “You are allowed to vote”)
End If

✅ If age is 18 or more, it shows the message.

AJ-KALEMA 27
2️⃣ If...Then...Else
Used when you want to choose between two options.

Dim score As Integer = 45


If scoree >= 50 Then
MsgBox( “You Passed”)
Else If
MsgBox(“You Failed”)
End If

✅ If the score is 50 or more, it shows “Passed.”


❌ Otherwise, it shows “Failed.”

3️⃣ If...ElseIf...Else
Used when you have more than two choices.

Dim marks As Integer = 75


If marks >= 80 Then
MsgBox( “Grade A”)
ElseIf marks >=60 Then
MsgBox(“Grade B”)
Else
MsgBox(“Grade C”)
End If

✅ The program checks conditions one by one and runs the first one that is True.
4️⃣ Select Case
Used when testing one variable with many possible values.

Dim day As Integer = 2


Select Case day
Case 1
MsgBox(“Sunday”)
Case 2
MsgBox(“Monday”)
Case 1
MsgBox(“Tueday”)
Case 1
MsgBox(“Thurday”)
End Select

AJ-KALEMA 28
✅ The program checks the value of day and shows the correct message.

📌 Summary Table
Statement Type Used For Example Keyword
If...Then Run only if condition is True If condition Then
If...Then...Else Choose between 2 options Else
If...ElseIf...Else Choose from many options ElseIf
Select Case Many values of one variable Select Case

🔁 Looping in VB.NET (Repetition)


Looping is a control structure that lets you repeat a group of statements multiple times.
Instead of writing the same code many times, you can use a loop to do it automatically.
📌 Example from Real Life:
Imagine you want to clap your hands 5 times.
Instead of saying: Clap! Clap! Clap! Clap! Clap!
You just say: Repeat "Clap!" 5 times
🔸 Types of Loops in VB.NET

1️⃣ For...Next Loop


Use this when you know exactly how many times you want to repeat something.

For i As Integer = 1 To 5
MsgBox(“Clap number: ” & i)
Next

✅ This code shows message boxes from 1 to 5.


2️⃣ Do While...Loop
This loop runs as long as the condition is True.

Dim i As Integer = 1
Do While I <= 3
MsgBox( “Number is:” & i)
I +=1
Loop

✅ This will display numbers 1, 2, and 3.

AJ-KALEMA 29
3️⃣ Do...Loop While
This version runs the code first, then checks the condition.

Dim i As Integer = 1
Do
MsgBox( “I = ” & i)
I +=1
Loop While i<= 3

✅ It works like Do While, but it always runs at least once, even if the condition is False at
the start.
4️⃣ Do Until...Loop
This loop runs until the condition becomes True.

Dim i As Integer = 1
Do Until i > 3
MsgBox( “i is:” & i)
I +=1
Loop

✅ It stops when i becomes greater than 3.S

AJ-KALEMA 30

You might also like