0% found this document useful (0 votes)
7 views4 pages

Multi-Dimensional Array Examples

Uploaded by

cyrusjhon2004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views4 pages

Multi-Dimensional Array Examples

Uploaded by

cyrusjhon2004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

' Example 1: Chess Board (Continued)

Private Sub MultiDimensionalExample1()


Dim chessBoard(7, 7) As String ' 8x8 board

' Initialize empty board


Dim row As Integer, col As Integer
For row = 0 To 7
For col = 0 To 7
chessBoard(row, col) = "--"
Next col
Next row

' Set up white pieces


chessBoard(7, 0) = "WR" ' White Rook
chessBoard(7, 1) = "WN" ' White Knight
chessBoard(7, 2) = "WB" ' White Bishop
chessBoard(7, 3) = "WQ" ' White Queen
chessBoard(7, 4) = "WK" ' White King
chessBoard(7, 5) = "WB" ' White Bishop
chessBoard(7, 6) = "WN" ' White Knight
chessBoard(7, 7) = "WR" ' White Rook

' Set up black pieces


chessBoard(0, 0) = "BR" ' Black Rook
chessBoard(0, 1) = "BN" ' Black Knight
chessBoard(0, 2) = "BB" ' Black Bishop
chessBoard(0, 3) = "BQ" ' Black Queen
chessBoard(0, 4) = "BK" ' Black Bishop
chessBoard(0, 5) = "BB" ' Black Knight
chessBoard(0, 6) = "BN" ' Black Rook
chessBoard(0, 7) = "BR" ' Black Rook

' Display the board


[Link] "Chess Board:"
[Link] String(33, "-")
For row = 0 To 7
[Link] "| ";
For col = 0 To 7
[Link] chessBoard(row, col) & " | ";
Next col
[Link]
[Link] String(33, "-")
Next row
End Sub

' Example 2: Student Grade Tracker


Private Sub MultiDimensionalExample2()
' Array structure: student, subject (Math, English, Science, History)
Dim grades(4, 3) As Integer
Dim students(4) As String
Dim subjects(3) As String

' Initialize student names


students(0) = "John"
students(1) = "Jane"
students(2) = "Bob"
students(3) = "Alice"
students(4) = "Charlie"
' Initialize subject names
subjects(0) = "Math"
subjects(1) = "English"
subjects(2) = "Science"
subjects(3) = "History"

' Assign random grades


Dim i As Integer, j As Integer
For i = 0 To 4 ' For each student
For j = 0 To 3 ' For each subject
grades(i, j) = Int(Rnd * 41) + 60 ' Random grade 60-100
Next j
Next i

' Display grade report


[Link] "Student Grade Report:"
[Link] "Student" & Space(10) & "Math English Science History Average"
[Link] String(60, "-")

For i = 0 To 4
Dim total As Integer
[Link] students(i) & Space(16 - Len(students(i)));

For j = 0 To 3
[Link] Format(grades(i, j), "00") & Space(6);
total = total + grades(i, j)
Next j

[Link] Format(total / 4, "0.0")


Next i
End Sub

' Example 3: Monthly Sales by Region


Private Sub MultiDimensionalExample3()
' Array structure: region, month
Dim sales(3, 11) As Currency ' 4 regions, 12 months
Dim regions(3) As String
Dim months(11) As String

' Initialize regions and months


regions(0) = "North"
regions(1) = "South"
regions(2) = "East"
regions(3) = "West"

months(0) = "Jan": months(1) = "Feb": months(2) = "Mar"


months(3) = "Apr": months(4) = "May": months(5) = "Jun"
months(6) = "Jul": months(7) = "Aug": months(8) = "Sep"
months(9) = "Oct": months(10) = "Nov": months(11) = "Dec"

' Generate random sales data


Dim i As Integer, j As Integer
For i = 0 To 3
For j = 0 To 11
sales(i, j) = (Rnd * 50000) + 10000 ' Random sales 10000-60000
Next j
Next i

' Display sales report


[Link] "Regional Monthly Sales Report"
[Link] "Region" & Space(8) & "Total Sales" & Space(4) & "Average"
[Link] String(50, "-")

For i = 0 To 3
Dim total As Currency
For j = 0 To 11
total = total + sales(i, j)
Next j

[Link] regions(i) & Space(12 - Len(regions(i))) & _


Format(total, "$#,##0") & Space(4) & _
Format(total / 12, "$#,##0")
Next i
End Sub

' Example 4: Seating Chart


Private Sub MultiDimensionalExample4()
' Array structure: row, seat
Dim seating(5, 9) As String ' 6 rows, 10 seats per row
Dim seatStatus(5, 9) As Boolean ' True if occupied

' Initialize all seats as empty


Dim row As Integer, seat As Integer
For row = 0 To 5
For seat = 0 To 9
seating(row, seat) = "---"
seatStatus(row, seat) = False
Next seat
Next row

' Simulate some reservations


seating(0, 4) = "A01": seatStatus(0, 4) = True
seating(2, 3) = "B12": seatStatus(2, 3) = True
seating(4, 7) = "C23": seatStatus(4, 7) = True

' Display seating chart


[Link] "Theater Seating Chart"
[Link] "SCREEN"
[Link] String(50, "-")

For row = 0 To 5
[Link] "Row " & (row + 1) & ": ";
For seat = 0 To 9
If seatStatus(row, seat) Then
[Link] "[" & seating(row, seat) & "] ";
Else
[Link] "[ ] ";
End If
Next seat
[Link]
Next row
End Sub

' Example 5: Inventory Management System


Private Sub MultiDimensionalExample5()
' Array structure: product, attributes (ID, Name, Quantity, Price, Reorder
Level)
Dim inventory(9, 4) As Variant
' Initialize sample inventory
Dim i As Integer
For i = 0 To 9
' Product ID
inventory(i, 0) = "P" & Format(i + 1, "000")

' Product Name (sample names)


Select Case i
Case 0: inventory(i, 1) = "Laptop"
Case 1: inventory(i, 1) = "Mouse"
Case 2: inventory(i, 1) = "Keyboard"
Case 3: inventory(i, 1) = "Monitor"
Case 4: inventory(i, 1) = "Printer"
Case Else: inventory(i, 1) = "Product " & (i + 1)
End Select

' Quantity
inventory(i, 2) = Int(Rnd * 100) + 1

' Price
inventory(i, 3) = (Rnd * 1000) + 10

' Reorder Level


inventory(i, 4) = 10
Next i

' Display inventory report


[Link] "Inventory Management Report"
[Link] "ID" & Space(8) & "Product" & Space(12) & "Qty" & Space(6) & _
"Price" & Space(8) & "Reorder Level"
[Link] String(60, "-")

For i = 0 To 9
[Link] inventory(i, 0) & Space(6) & _
Left(inventory(i, 1) & Space(18), 18) & _
Format(inventory(i, 2), "000") & Space(6) & _
Format(inventory(i, 3), "$#,##0.00") & Space(4) & _
inventory(i, 4)

' Check if reorder is needed


If CInt(inventory(i, 2)) <= CInt(inventory(i, 4)) Then
[Link] Space(5) & "*** REORDER NEEDED ***"
End If
Next i
End Sub

Common questions

Powered by AI

Random functions, when used for grade or sales data assignment, can lead to unrealistic results or skewed distributions that do not reflect real-world scenarios. In the examples, grades are assigned using `Rnd * 41 + 60`, ensuring grades fall between 60 and 100, a range that mimics typical grading systems with a realistic distribution focusing on average to high performance. Similarly, sales data is confined between 10000 and 60000 to simulate actual economic output limits realistically. These controlled uses of random functions help mitigate the problem of undue outliers and ensure the data remains within expected practical ranges .

Using multi-dimensional arrays to represent student grades across subjects provides a comprehensive and organized approach to data management. It facilitates efficient storage, retrieval, and processing of complex data sets, enabling easy access to individual students' performance metrics. In the example, the array structure `grades(4, 3)` with dimension for students and subjects is utilized to store and tabulate grades. This setup allows for quick calculations of averages and performance comparisons across different subjects, offering valuable insights into academic progress and helping educators tailor teaching strategies to meet individual needs .

Employing arrays for inventory management offers several benefits over traditional spreadsheet tools. Arrays provide faster data access and manipulation through direct indexing, enhancing performance for large-scale operations. They support programmatic operations, allowing for more complex calculations and automated alerts, such as reorder alerts directly integrated into the code logic. However, arrays may lack the user-friendly interface and advanced analytics features inherently available in spreadsheets, such as pivot tables or visual graphs. Another potential drawback is the fixed structure of arrays, which may not adapt easily to dynamic data requirements without significant reprogramming .

Adapting the chessboard setup for a checkers board would require altering the array initialization to reflect checkers' specific rules and setup. Key elements include using an 8x8 `chessBoard` array still but populating it so only certain squares, typically the 1st, 3rd, and 5th, 7th for black pieces and corresponding rows at the opposite end for white. Occupied squares could denote pieces with 'BP' for Black Piece and 'WP' for White Piece. Unlike chess, checkers only uses certain board rows for initial setup. This adaptation requires logical conditions to differentiate rows and columns, ensuring placement adheres to the game’s diagonal-movement restriction. Additionally, logic would need crafting to manage piece promotion, represented by possibly appending 'K' for king pieces when they reach the board’s opposite end .

The seating chart example effectively demonstrates the simultaneous use of dimensional arrays and boolean arrays to manage complex data structures. Here, a `seating` array, structured as `seating(5, 9)`, represents rows and seats with initial placeholder values '---'. Alongside this, a `seatStatus` boolean array tracks whether each seat is occupied (`True`) or not (`False`). This dual-array approach allows for versatile manipulation, where seat allocations can be visually represented and programmatically controlled. Occupied seats are denoted by specific codes (e.g., 'A01'), and checks against `seatStatus` ensure the correct display and availability status, providing a reliable system for managing seat reservations in a dynamic environment .

Utilizing a multi-dimensional array for theater seating arrangements offers distinct strengths and weaknesses. Strengths include organized storage and systematic seat tracking, enabling efficient seat reservations management, availability checks, and status updates within stipulated rows and columns. The array structure simplifies both the seating visualization and the implementation of booking logic. However, weaknesses manifest in increased complexity when managing larger theaters or evolving arrangements as arrays inherently require predefined sizing and lack flexibility in dynamic seat configuration. Scalability might become challenging if changes in row/seating numbers necessitate significant restructuring of underlying code .

Displaying a formatted regional sales report, as exemplified, significantly influences financial decision-making by offering clear and organized insights into performance across multiple regions and over a specified duration. The report tabulates total and average sales per region, allowing stakeholders to quickly identify trends, compare regions, and allocate resources effectively. This structured visualization highlights discrepancies or successes in various areas, supporting evidence-based decisions about scalability, market investments, or strategic initiatives to bolster underperforming zones. The added clarity from precise formatting aids in making accurate forecasts and refining business strategies .

The method for initializing student names and subject names (using arrays 'students' and 'subjects') can be extended to store additional details by expanding dimensions or linking related arrays. For student information, an additional array could incorporate attributes like student ID, age, or gender, set up similarly to a record-keeping array or using complex data types like objects or structs for better scalability. Subject data can correspondingly incorporate credit hours, instructor details, or room numbers. For seamless integration, the additional attributes need coordinated indexing, with expansion managed such that accessing additional info ties logically to each student or subject in the existing arrays, supporting a cohesive and scalable data management framework .

The initialization of a chessboard using a multi-dimensional array allows for a structured representation of the board, simulating an 8x8 grid used in actual chess games. The process begins with declaring a two-dimensional array of strings, `chessBoard(7, 7)`, to store the positions. The board is initially filled with placeholding values '--' to denote empty spaces. Row 7 is then set up with white pieces using specific notations like 'WR' for White Rook, 'WN' for White Knight, etc. Similarly, row 0 is configured for black pieces. This method provides a clear and organized structure for piece placement, supporting essential operations like piece movement and game state validation .

An inventory system using a multi-dimensional array determines the necessity of reordering based on the comparison of the current inventory quantity against a predefined reorder level. In the provided example, each product's information, including ID, quantity, price, and reorder level, is stored in an array `inventory(i, j)`. A condition checks if `inventory(i, 2)`, the current quantity, is less than or equal to `inventory(i, 4)`, the reorder level. If so, a notification `*** REORDER NEEDED ***` is triggered to signal the need for replenishment. This process ensures stock levels are maintained adequately to prevent shortages .

You might also like