Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views7 pages

PF Lab 10

filing

Uploaded by

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

PF Lab 10

filing

Uploaded by

hirrah21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Enrollment Number: ____________________________

Programming Fundamentals
Lab 10
Topic Character Array, Jagged Array, and Recursion
 Understand the working of the character arrays
Objective  Understanding of Jagged Arrays
 Basic understanding of recursive approach

What is a Jagged Array?

 A jagged array is an array of arrays where each inner array can have a different
length.
 Unlike a regular 2D array (matrix) where each row has the same number of columns,
jagged arrays allow rows with varying sizes.
 Useful when you want to store data with irregular shapes, like different numbers of
elements per row.

Example of a Jagged Array in Java


public class JaggedArrayExample { import java.util.Scanner;
public static void main(String[]
args) { public class JaggedArrayDynamic {
// Declare a jagged array with 3 public static void main(String[] args) {
rows Scanner sc = new Scanner(System.in);
int[][] jagged = new int[3][];
System.out.print("Enter number of
// Initialize each row with rows: ");
different sizes int rows = sc.nextInt();
jagged[0] = new int[2]; // row 0
has 2 elements // Declare jagged array with given
jagged[1] = new int[4]; // row 1 number of rows
has 4 elements int[][] jagged = new int[rows][];
jagged[2] = new int[3]; // row 2
has 3 elements // For each row, ask size and
initialize
// Assign values for (int i = 0; i < rows; i++) {
jagged[0][0] = 1; System.out.print("Enter number of
jagged[0][1] = 2; elements in row " + (i + 1) + ": ");
int cols = sc.nextInt();
jagged[1][0] = 3; jagged[i] = new int[cols];
jagged[1][1] = 4;
jagged[1][2] = 5; System.out.println("Enter
jagged[1][3] = 6; elements for row " + (i + 1) + ":");
for (int j = 0; j < cols; j++) {
jagged[2][0] = 7; jagged[i][j] = sc.nextInt();
jagged[2][1] = 8; }
jagged[2][2] = 9; }

// Print jagged array System.out.println("\nJagged array


for (int i = 0; i < content:");
jagged.length; i++) { for (int i = 0; i < jagged.length; i+
for (int j = 0; j < +) {
jagged[i].length; j++) { for (int j = 0; j <
jagged[i].length; j++) {
System.out.print(jagged[i][j] + " "); System.out.print(jagged[i][j]
} + " ");

Page 1 of 7
Enrollment Number: ____________________________

System.out.println(); }
} System.out.println();
} }
}
sc.close();
}
}

What is Recursion?

Recursion is a programming technique where a method calls itself to solve a smaller


instance of the same problem. It usually has:

 Base case: The condition where recursion stops.


 Recursive case: The part where the method calls itself with a smaller problem.

Java Code: Print numbers from 1 to n using recursion


public class PrintNumbers {

public static void printNumbers(int n) {


if (n == 0) { // Base case: stop when n is 0
return;
}
printNumbers(n - 1); // Recursive call with n-1
System.out.print(n + " "); // Print after recursive call to
print in ascending order
}

public static void main(String[] args) {


int n = 10;
System.out.println("Numbers from 1 to " + n + ":");
printNumbers(n);
}
}

Sample Output:
Numbers from 1 to 10:
1 2 3 4 5 6 7 8 9 10

Page 2 of 7
Enrollment Number: ____________________________

Lab task
Task 1: Substring Frequency Finder
You are working on a basic plagiarism detection tool that operates on a low-resource
embedded system. This system only supports character arrays, so your program must
manually count how many times a given word (substring) appears in a larger sentence.

Task Requirements:
 Store a full sentence in a character array.
 Store the target word (substring) in a second character array.
 Count how many non-overlapping occurrences of the substring exist in the
sentence.
 Use no built-in string methods — only loops and conditional logic.

Sample Input:
Sentence: {'t','h','i','s',' ','i','s',' ','a',' ','t','e','s','t',' ','t','e','s','t',' ','t','e','s','t'}
Substring: {'t','e','s','t'}

Expected Output:
The substring 'test' was found 3 time(s).

Task 2: Convert Numbers into Roman Numerals


A historical data application needs to display year values in Roman numerals instead of
decimal numbers. You have been assigned to write a converter that accepts an integer input
and converts it to its Roman numeral equivalent using character arrays.
Task:
 Accept a positive integer (1 to 3999).
 Convert it to a Roman numeral using predefined rules.
 Store Roman symbols in a character array.
 Return the Roman numeral as a string or char array output.

Sample Input:
Enter a number: 1987

Sample Output:
Roman numeral: MCMLXXXVII

Roman Numeral Conversion Reference:


Value Symbol
1000 M
900 CM
500 D

Page 3 of 7
Enrollment Number: ____________________________

400 CD
100 C
90 XC
50 L
40 XL
10 X
9 IX
5 V
4 IV
1 I

Task 3: Count Vowels and Consonants Ratio


For linguistic analysis, you must evaluate the vowel-to-consonant ratio in a given word's
array.
Task:
 Count vowels and consonants in the character array row-wise and column-wise.
 Calculate and print the ratio.

Sample Input:
{{'S','o','f'},
{'t','w','a'},
{'r','e'}}

Sample Output:
Vowels: 3
Consonants: 5
Ratio (V:C) = 3:5

Task 4: Digit Spiral Game Scorer (Integer Jagged Array)


In a puzzle game, each player creates a digit spiral where each inner array is a ring of
numbers forming part of a spiral. Points are calculated based on the sum of edge elements
(first and last) in each row.
Task:
 Accept jagged array input for each player.
 For each row, sum the first and last digit.
 Total the score for the player.

Sample Input:
Player Matrix:
Row 1: [1, 2, 3] → 1 + 3
Row 2: [4, 5] → 4 + 5
Row 3: [9] → 9 + 9

Page 4 of 7
Enrollment Number: ____________________________

Output:
Total Score: 31

Task 5: Game Level Custom Map Parser (Character Jagged Array)


A game engine uses a jagged grid to load custom maps. Each character represents:
 'S' → Start point
 'E' → End point
 'O' → Obstacle
 ' ' → Open path
You are to:
 Validate each map.
 Ensure each map contains exactly one 'S' and one 'E'.
 Count total obstacles and open spaces.

Sample Input:
Map 1: S O E
Map 2: O O S O E
Map 3: E S O O

Sample Output:
Map 1: Valid | Obstacles: 1 | Open: 1
Map 2: Valid | Obstacles: 3 | Open: 0
Map 3: Invalid – Multiple S and E detected

Task 6: Hospital Shift Attendance Log


In a hospital, nurses work variable shifts across departments. Each row represents a nurse’s
weekly shift log: 'M' for morning, 'E' for evening, 'N' for night, and 'O’ for off.
Instructions:
 Accept a number of nurses and their shift logs (lengths may vary).
 Display each nurse’s weekly pattern.
 Identify:
o Nurse with the most night shifts.
o Any nurse who had 3 or more consecutive same shifts (excluding 'O').

Sample Input:
Nurse 1: M M E N O N
Nurse 2: N N N M O E
Nurse 3: M M M M M

Sample Output:
Nurse 2 has most night shifts: 3
Nurse 3 had 5 consecutive same shifts → Flagged for burnout alert.

Page 5 of 7
Enrollment Number: ____________________________

Task 7: GPA Calculator


In a university, each student takes a different number of courses with varying credit hours.
You are assigned the task of calculating the GPA for each student using their grade points
and course credits. Store the grades and credits in two jagged arrays: one for grade points,
one for course credits.
Instructions:
 Use two jagged arrays:
o grades[i][j] → Grade points for student i in course j
o credits[i][j] → Credit hours for corresponding course
 Compute weighted GPA using:
GPA = (sum of grade[i][j] * credit[i][j]) / (sum of credit[i][j])
 Display GPA of each student.

Sample Input:
Student 1: Grades = [3, 4, 3], Credits = [2, 3, 2]
Student 2: Grades = [2, 3], Credits = [4, 1]

Sample Output:
Student 1 GPA: 3.33
Student 2 GPA: 2.17

Task 8: Find factorial (Recursion)


Write a recursive function factorial(int n) that calculates the factorial of a given positive
integer N. The factorial of N (denoted as N!) is the product of all positive integers less than
or equal to N.
Explanation:
The factorial can be defined recursively as:
factorial(n)=n×factorial(n−1)
with the base case:
factorial(0)=1

Task:
 Implement the recursive function factorial(int n) to compute the factorial of n.
 In the main method, prompt the user to enter a non-negative integer N.
 Call the recursive function and print the factorial value.

Sample Input:
Enter a non-negative integer: 4

Sample Output:
Factorial of 4 is 24

Page 6 of 7
Enrollment Number: ____________________________

Home Task
Task: Implement Binary Search with a Recursive Approach
Implement a recursive binary search to find an element in a sorted array. Use bubble sort
recursive method to sort the array.
Explanation:
 Compare the middle element with the target.
 If match, return index.
 If the target is smaller, search in the left half; if greater, in the right half.
 Base case: if low > high, element not found.

Iterative Sample Code:


public class BinarySearchIterative {
// Function to perform binary search iteratively
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

// Check if target is at mid


if (arr[mid] == target) {
return mid; // found
}

// If target is smaller, ignore right half


if (target < arr[mid]) {
right = mid - 1;
}
// If target is larger, ignore left half
else {
left = mid + 1;
}
}

return -1; // not found


}

public static void main(String[] args) {


int[] data = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}; // sorted array
int target = 23;

int result = binarySearch(data, target);

if (result != -1) {
System.out.println("Element found at index: " + result);
} else {
System.out.println("Element not found.");
}
}
}

Page 7 of 7

You might also like