0% found this document useful (0 votes)
2 views61 pages

COSC211 Lab00 Solutions

Uploaded by

vicdavejuwon
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)
2 views61 pages

COSC211 Lab00 Solutions

Uploaded by

vicdavejuwon
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

Airforce Institute of Technology Kaduna Faculty of Sciences

Department of Mathematics and Statistics

CSC 202 Assignment by:

Name: Joseph Timothy

Matric No.: U25ST2002

COSC 211 - Lab 00 Solutions


Lab00 is the setup/introduction laboratory. It focuses on preparing the Java development
environment before writing programs.

Question/Task: Install and setup Java JDK


Concept:
JDK (Java Development Kit) contains the tools needed to create, compile and run Java
programs.

Steps:
1. Download and install the Java JDK.
2. Configure the system PATH so the computer can find Java commands.
3. Test the installation using:

java -version
and
javac -version
If versions appear, Java is correctly installed.

Question/Task: Understand Java program flow


A Java program normally follows this process:
1. Write source code (.java file)
2. Compile using javac
Example:
javac [Link]

3. Run the generated bytecode using:


java Program
The compiler converts human-readable Java code into bytecode that the JVM executes.

Question/Task: First Java Program


Example:

public class HelloWorld {


public static void main(String[] args) {
[Link]("Hello World");
}
}

Lab 01 Solutions
Lab 01 focuses on Java printing statements, escape sequences, formatted output, and
basic program output patterns.

Question 1: Printing using print()


Concept:
[Link]() displays output without moving to the next line.

Solution:

public class Printing{


public static void main(String[] args){
[Link]("Computer");
[Link]("Science");
[Link]("Department");
}
}

Output:
ComputerScienceDepartment

Question 2: Printing using println()


Concept:
[Link]() prints output and moves the cursor to a new line.
Solution:

public class PrintingLine{


public static void main(String[] args){
[Link]("Computer");
[Link]("Science");
[Link]("Department");
}
}

Output:
Computer
Science
Department

Question 3: Formatted printing using printf()


Concept:
printf() allows control over spacing, decimal places and number formatting.
Solution:

public class PrintingFormat{


public static void main(String[] args){
[Link]("%d",60);
[Link]();
[Link]("%03d%n",9);
[Link]("PI %.3f",3.141527);
[Link]();
[Link]("Total is: N%,.2f%n",84785.8978);
[Link]("%-10S%n",
"Department of Computer Science");
[Link]("% .2f",-67.8917);
[Link]();
[Link]("% .2f",67.8917);
}
}
Important:
%d = integer
%f = decimal number
%.3f = 3 decimal places
%n = new line
Question 4: Escape Sequence Program
Concept:
Escape sequences are special characters used inside strings.
Examples:
\n = new line
\t = tab space
\\ = backslash
\" = quotation mark
Solution:

public class EscapeSequence {


public static void main(String args[]) {
[Link]("ABU said \"To pass, you must work hard!\".\n");
[Link](
"Two Sided Triangles\n*\t*****\n**\t ****\n***\t ***\n****\t **\n*****\t *\
n");
[Link](
"A Diamond \n *\n ***\n*****\n ***\n *");
}
}

Question 5: Multiplication Pattern


Solution:
public class Multiplication {
public static void main(String args[]) {
[Link](
"\t1 2 3 4\n" +
"1\t1 2 3 4\n" +
"2\t2 4 6 8\n" +
"3\t3 6 9 12\n" +
"4\t4 8 12 16");
}
}
Concept:
This uses escape sequences to create table formatting.

Question 6: Pattern Printing


Solution:
public class Pattern {
public static void main(String args[]) {
[Link](" *\n * *\n* * *\n* *");
[Link]("* *\n* * *\n* *\n* * *\n* *");
[Link]("* *\n* *\n* *\n * *");
}
}

Concept:
Patterns are created by controlling spaces and line breaks.

LAB 02 SOLUTIONS

Question 1: Creating Objects


Example: Rectangle Object
Concept:
A Rectangle object can have properties like:
• length
• width
and methods like:
• calculate area
• display information
Solution:

class Rectangle {
double length;
double width;

double area() {
return length * width;
}
}

public class Main {

public static void main(String[] args) {


Rectangle rectangle1 = new Rectangle();

[Link] = 10;
[Link] = 5;

[Link]("Area = " + [Link]());


}
}
Output:
Area = 50.0

Assignment: MakePassword
Concept

A password can be created by combining different pieces of information.

Example:
Name + numbers + symbols

Solution:

import [Link];

public class MakePassword {

public static void main(String[] args) {

Scanner input = new Scanner([Link]);

[Link]("Enter your name: ");

String name = [Link]();

String password = name + "123";

[Link]("Password: " + password);

}
}

Assignment: MoveRectangle
Concept

Objects can change their values through methods.

A rectangle position can be moved by changing x and y coordinates.

Solution:

class Rectangle {

int x;
int y;

void move(int newX, int newY){


x = newX;
y = newY;
}

void display(){

[Link]("Position: " + x + "," + y);

}
}

public class MoveRectangle {

public static void main(String[] args){

Rectangle r = new Rectangle();

[Link](5,10);

[Link]();

Output:
Position: 5,10

LAB 03 SOLUTIONS

Question 1: Declaring Variables


public class Variables {

public static void main(String[] args) {

int number = 10;


double price = 50.5;
char letter = 'A';
boolean status = true;

[Link](number);
[Link](price);
[Link](letter);
[Link](status);

}
Output:
10
50.5
A
true

Question 2: Accepting User Input


import [Link];

public class UserInput {

public static void main(String[] args){

Scanner input = new Scanner([Link]);

[Link]("Enter your name: ");


String name = [Link]();

[Link]("Enter your age: ");


int age = [Link]();

[Link]("Name: " + name);


[Link]("Age: " + age);

Example Output:
Enter your name: John
Enter your age: 20

Name: John
Age: 20

Question 3: Simple Calculator


import [Link];

public class Calculator {

public static void main(String[] args){

Scanner input = new Scanner([Link]);

[Link]("Enter first number: ");


double num1 = [Link]();

[Link]("Enter second number: ");


double num2 = [Link]();

double sum = num1 + num2;


double product = num1 * num2;
double division = num1 / num2;

[Link]("Sum = " + sum);


[Link]("Product = " + product);
[Link]("Division = " + division);

Question 4: Rectangle Area Program


import [Link];

public class RectangleArea {

public static void main(String[] args){

Scanner input = new Scanner([Link]);

[Link]("Enter length: ");


double length = [Link]();

[Link]("Enter width: ");


double width = [Link]();

double area = length * width;

[Link]("Area = " + area);

Example:
Input:
Length = 5
Width = 4

Output:
Area = 20
LAB 04 SOLUTIONS

Question 1: Creating a Student Class


class Student {

String name;
int age;

void display(){

[Link]("Name: " + name);


[Link]("Age: " + age);

public class Main {

public static void main(String[] args){

Student student1 = new Student();

[Link] = "John";
[Link] = 20;

[Link]();

Output:
Name: John
Age: 20

Question 2: Using Constructor


class Student {

String name;

Student(String n){

name = n;

void display(){
[Link](name);

public class Main{

public static void main(String[] args){

Student s1 = new Student("Mary");

[Link]();

Output:
Mary

Question 3: Using this Keyword


class Student{

String name;
int age;

Student(String name, int age){

[Link] = name;
[Link] = age;

void display(){

[Link](name);
[Link](age);

public class Main{

public static void main(String[] args){


Student s = new Student("David",22);

[Link]();

Output:
David
22

Topic 4: Bank Account Class


Concept

A bank account object contains:

Properties:
• account number
• balance

Methods:
• deposit()
• withdraw()
• display balance

class BankAccount{

String accountNumber;
double balance;

BankAccount(String accountNumber, double balance){

[Link] = accountNumber;
[Link] = balance;

void deposit(double amount){

balance += amount;

void withdraw(double amount){

balance -= amount;
}

void display(){

[Link]("Account: " + accountNumber);


[Link]("Balance: " + balance);

public class Main{

public static void main(String[] args){

BankAccount account = new BankAccount("001",5000);

[Link](2000);
[Link](1000);

[Link]();

Output:
Account: 001
Balance: 6000

Topic 5: Method Overloading


Concept Explanation

Method overloading means:

Same method name but different parameters.

Example:

add(int a,int b)

add(double a,double b)

Java chooses the correct one depending on the values supplied.

class Calculator{

int add(int a,int b){


return a+b;

double add(double a,double b){

return a+b;

public class Main{

public static void main(String[] args){

Calculator c = new Calculator();

[Link]([Link](5,3));
[Link]([Link](5.5,2.5));

Output:
8
8.0

LAB 05 SOLUTIONS

Question 1: Check Positive Number

Solution:

import [Link];

public class PositiveCheck {

public static void main(String[] args){

Scanner input = new Scanner([Link]);

[Link]("Enter number: ");


int number = [Link]();

if(number > 0)
{

[Link]("Positive Number");

Question 2: Check Even or Odd

Solution:

import [Link];

public class EvenOdd{

public static void main(String[] args){

Scanner input = new Scanner([Link]);

[Link]("Enter number: ");

int num = [Link]();

if(num % 2 == 0)
{

[Link]("Even");

else
{

[Link]("Odd");

}
}

Explanation

The % operator gives remainder.

Example:

10 % 2 = 0

No remainder means even.

7%2=1

Remainder means odd.

Question 3: Simple Menu Program

Solution:

import [Link];

public class Menu {

public static void main(String[] args){

Scanner input = new Scanner([Link]);

[Link]("1. Add");

[Link]("2. Subtract");

[Link]("3. Multiply");

[Link]("Choose option: ");

int choice = [Link]();

switch(choice)
{
case 1:

[Link]("Addition selected");

break;

case 2:

[Link]("Subtraction selected");

break;

case 3:

[Link]("Multiplication selected");

break;

default:

[Link]("Invalid option");

Topic 7: Comparing Strings

Important:

Do NOT use:

==

for strings.

Use:

.equals()
Example:

Correct:

if([Link]("John"))
{

Question 4: Login Check

Solution:

import [Link];

public class Login{

public static void main(String[] args){

Scanner input = new Scanner([Link]);

[Link]("Enter username: ");

String username = [Link]();

if([Link]("admin"))
{

[Link]("Welcome Admin");

else
{

[Link]("Access Denied");

}
LAB 06 SOLUTIONS

Question 1: Print Numbers 1 - 10

Solution:
public class Numbers {

public static void main(String[] args){

for(int i=1; i<=10; i++)


{
[Link](i);
}

Explanation

The loop starts at i = 1, checks i <= 10, prints the value,


increments i, and repeats until i becomes 11.

Question 2: Countdown Program

Solution:
public class Countdown {

public static void main(String[] args){

int count = 5;

while(count >= 1)
{
[Link](count);
count--;
}

[Link]("Finished");

}
Output:
5
4
3
2
1
Finished

Topic 4: do...while Loop

Concept

A do...while loop executes at least once before checking the condition.

Syntax:
do
{

}
while(condition);

Example:
public class Test {

public static void main(String[] args){

int number = 1;

do
{
[Link](number);
number++;
}
while(number <= 5);

Output:
1
2
3
4
5

Topic 5: Finding Sum Using Loop

Concept

An accumulator stores a running total.

Example:
sum = sum + number;

Solution:
public class Sum {

public static void main(String[] args){

int sum = 0;

for(int i=1; i<=10; i++)


{
sum = sum + i;
}

[Link]("Total = " + sum);

Output:
Total = 55

Topic 6: Multiplication Table

Solution:
import [Link];

public class MultiplicationTable {

public static void main(String[] args){


Scanner input = new Scanner([Link]);

[Link]("Enter number: ");


int number = [Link]();

for(int i=1; i<=12; i++)


{
[Link](number + " x " + i + " = " + (number*i));
}

Example Input:
5

Example Output:
5x1=5
...
5 x 12 = 60

Topic 7: Nested Loops

Concept

A loop inside another loop.

Used for:
• Patterns
• Tables
• Matrices

Example:
public class Pattern {

public static void main(String[] args){

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
[Link]("*");
}

[Link]();
}

Output:
*
**
***
****
*****

Topic 8: Loop Control

break

Stops the loop immediately.

Example:
for(int i=1;i<=10;i++)
{
if(i==5)
break;

[Link](i);
}

Output:
1
2
3
4

continue

Skips current repetition.

Example:
for(int i=1;i<=5;i++)
{
if(i==3)
continue;

[Link](i);
}

Output:
1
2
4
5

LAB 07 SOLUTIONS

Topic 1: Arrays in Java

Concept Explanation

An array is a collection of values stored under one name.

Instead of:
int score1;
int score2;
int score3;

We use:
int[] scores = new int[3];

An array stores multiple values of the same data type.

Topic 2: Declaring an Array

Syntax:
dataType[] arrayName = new dataType[size];

Example:
int[] numbers = new int[5];

Meaning:
Create an integer array that can store 5 values.

Topic 3: Initializing an Array


Example:
int[] numbers = {10,20,30,40};

Stored as:

Index 0 = 10
Index 1 = 20
Index 2 = 30
Index 3 = 40

Important:
Array index starts from 0.

Question 1: Display Array Elements

Solution:

public class ArrayDisplay {

public static void main(String[] args){

int[] numbers = {10,20,30,40,50};

for(int i=0; i<[Link]; i++)


{
[Link](numbers[i]);
}

Output:
10
20
30
40
50

Explanation

[Link] gives the size of the array.


Example:
int[] a = new int[5];

Then:
[Link] = 5

Topic 4: Taking Array Input

Solution:

import [Link];

public class ArrayInput {

public static void main(String[] args){

Scanner input = new Scanner([Link]);

int[] numbers = new int[5];

for(int i=0; i<5; i++)


{
[Link]("Enter number: ");
numbers[i] = [Link]();
}

[Link]("Numbers entered:");

for(int i=0; i<5; i++)


{
[Link](numbers[i]);
}

Topic 5: Finding Sum of Array

Concept

Use a variable to store the total.


Example:
sum = sum + value;

Solution:

public class ArraySum {

public static void main(String[] args){

int[] numbers = {5,10,15,20};

int sum = 0;

for(int i=0;i<[Link];i++)
{
sum += numbers[i];
}

[Link]("Sum = " + sum);

Output:
Sum = 50

Topic 6: Finding Average

Formula:

Average = Total / Number of values

Solution:

public class Average {

public static void main(String[] args){

int[] marks = {70,80,90,60};

int total = 0;
for(int i=0;i<[Link];i++)
{
total += marks[i];
}

double average = total / [Link];

[Link]("Average = " + average);

Output:
Average = 75

Topic 7: Finding Maximum Value

Solution:

public class Maximum {

public static void main(String[] args){

int[] numbers = {10,50,30,90,20};

int max = numbers[0];

for(int i=1;i<[Link];i++)
{
if(numbers[i] > max)
{
max = numbers[i];
}
}

[Link]("Maximum = " + max);

}
Output:
Maximum = 90

Topic 8: Searching an Array

Concept

Searching checks whether a value exists.

Example:
Find if 20 exists.

Solution:

public class SearchArray {

public static void main(String[] args){

int[] numbers = {5,10,15,20};

int search = 20;

boolean found = false;

for(int i=0;i<[Link];i++)
{
if(numbers[i] == search)
{
found = true;
}
}

if(found)
{
[Link]("Found");
}
else
{
[Link]("Not Found");
}

}
}

Output:
Found

Topic 9: Enhanced for Loop

Java provides an easier way.

Normal:
for(int i=0;i<[Link];i++)

Enhanced:
for(int value : arr)

Example:

int[] numbers = {1,2,3};

for(int x : numbers)
{
[Link](x);
}

LAB 08 SOLUTIONS

Topic 1: Two Dimensional Arrays

Concept Explanation

A normal array stores data in one line.

Example:

int[] numbers = {1,2,3};

A 2D array stores data like a table.

Example:

1 2 3

4 5 6

7 8 9
It has:

• Rows

• Columns

Topic 2: Declaring a 2D Array

Syntax:

dataType[][] arrayName = new dataType[row][column];

Example:

int[][] matrix = new int[3][3];

Meaning:

Create a matrix with:

3 rows

3 columns

Topic 3: Initializing a Matrix

Example:

int[][] numbers =

{
{1,2,3},

{4,5,6},

{7,8,9}

};

Representation:

Row 0 → 1 2 3

Row 1 → 4 5 6

Row 2 → 7 8 9

Question 1: Display a Matrix

Solution:

public class MatrixDisplay {

public static void main(String[] args){

int[][] matrix =

{1,2,3},

{4,5,6},

{7,8,9}

};
for(int i=0;i<[Link];i++)

for(int j=0;j<matrix[i].length;j++)

[Link](matrix[i][j] + " ");

[Link]();

Output:

123

456

789

Explanation

The outer loop controls rows.

for(int i=0;i<[Link];i++)

The inner loop controls columns.

for(int j=0;j<matrix[i].length;j++)
Because every row contains multiple columns.

Topic 4: Taking Matrix Input

Solution:

import [Link];

public class MatrixInput {

public static void main(String[] args){

Scanner input = new Scanner([Link]);

int[][] matrix = new int[2][3];

for(int i=0;i<2;i++)

for(int j=0;j<3;j++)

[Link]("Enter value: ");

matrix[i][j] = [Link]();

}
[Link]("Matrix:");

for(int i=0;i<2;i++)

for(int j=0;j<3;j++)

[Link](matrix[i][j]+" ");

[Link]();

Topic 5: Adding Two Matrices

Concept

Matrix addition:

Each position is added together.

Example:

12 56

34 + 78

=
68

10 12

Solution:

public class MatrixAddition {

public static void main(String[] args){

int[][] A =

{1,2},

{3,4}

};

int[][] B =

{5,6},

{7,8}

};

int[][] C = new int[2][2];

for(int i=0;i<2;i++)

{
for(int j=0;j<2;j++)

C[i][j] = A[i][j] + B[i][j];

for(int i=0;i<2;i++)

for(int j=0;j<2;j++)

[Link](C[i][j]+" ");

[Link]();

Output:

68

10 12

Topic 6: Finding Sum of Matrix Elements

Solution:
public class MatrixSum {

public static void main(String[] args){

int[][] matrix =

{10,20},

{30,40}

};

int sum = 0;

for(int i=0;i<[Link];i++)

for(int j=0;j<matrix[i].length;j++)

sum += matrix[i][j];

[Link]("Total = " + sum);

Output:
Total = 100

Topic 7: Finding Largest Element in Matrix

Solution:

public class MatrixMaximum {

public static void main(String[] args){

int[][] matrix =

{5,20},

{15,30}

};

int max = matrix[0][0];

for(int i=0;i<[Link];i++)

for(int j=0;j<matrix[i].length;j++)

if(matrix[i][j] > max)

max = matrix[i][j];
}

[Link]("Maximum = " + max);

Output:

Maximum = 30

Topic 8: Matrix Multiplication Idea

Matrix multiplication uses:

Row × Column

It is different from normal addition.

Example:

A×B

requires:
Number of columns in A = Number of rows in B

LAB 09 SOLUTIONS

Topic 1: File Handling in Java

Concept Explanation

Normally, data stored in a program disappears when the program stops.

Files allow us to save data permanently.

Examples:

• Save student records

• Store reports

• Save user information

Java uses classes from:

[Link]

for file operations.

Topic 2: Writing to a File

Important Class:
FileWriter

Question 1: Create and Write File

Solution:

import [Link];

import [Link];

public class WriteFile {

public static void main(String[] args){

try{

FileWriter writer = new FileWriter("[Link]");

[Link]("Name: John\n");

[Link]("Department: Computer Science\n");

[Link]("Level: 200");

[Link]();

[Link]("File created successfully");

catch(IOException e){

[Link]("Error occurred");

Output:
File created successfully

Explanation

FileWriter writer = new FileWriter("[Link]");

creates a file.

[Link]();

puts information inside.

[Link]();

closes the file.

Topic 3: Reading From a File

Important Class:

Scanner

Question 2: Read File Content

Solution:

import [Link];

import [Link];

public class ReadFile {


public static void main(String[] args){

try{

File file = new File("[Link]");

Scanner reader = new Scanner(file);

while([Link]()){

String data = [Link]();

[Link](data);

[Link]();

catch(Exception e){

[Link]("File not found");

Example Output:

Name: John

Department: Computer Science

Level: 200

Topic 4: Exception Handling

Concept

Errors can happen during execution.


Examples:

• File does not exist

• Wrong input

• Invalid operation

Java handles errors using:

try-catch

Topic 5: String Processing

Strings are objects with built-in methods.

Example:

String name = "Java";

String Length:

[Link]()

Converting to Uppercase:

toUpperCase()

Converting to Lowercase:

toLowerCase()

Topic 6: String Comparison


Wrong:

if(name=="John")

Correct:

if([Link]("John"))

Question 3: Count Characters

Solution:

public class CountCharacters {

public static void main(String[] args){

String text = "Computer Science";

int count = [Link]();

[Link]("Number of characters: " + count);

Output:

Number of characters: 16

Topic 7: Extracting Characters

Use:

charAt(index)
Question 4: Display Each Character

Output:

Topic 8: Searching Inside Strings

Use:

contains()

Topic 9: Replacing Text

Use:

replace()

How To Solve File Questions

Writing:

1. Create writer

2. Write data

3. Close file
Reading:

1. Open file

2. Read line by line

3. Display/process data

How To Solve String Questions

Length → length()

Uppercase → toUpperCase()

Lowercase → toLowerCase()

Compare → equals()

Character → charAt()

Search → contains()

Replace → replace()

Common Mistakes

Wrong:

[Link]();

without closing.

Correct:

[Link]();

Wrong:

text=="Java"
Correct:

[Link]("Java")

END OF LAB 09

LAB 10 SOLUTIONS

Topic 1: Recursion in Java

Concept Explanation

Recursion is when a method calls itself.

A recursive method solves a problem by reducing it into smaller versions of the same
problem.

Example:

Parts of a Recursive Method

1. Base Case
The condition that stops the recursion.

Example:

if(number == 0)

2. Recursive Case

The part where the method calls itself.

Example:

method(number - 1);

Topic 2: Simple Recursion Example

Question 1: Print Numbers Using Recursion

public class RecursionExample {

static void printNumber(int n){

if(n == 0){

return;

[Link](n);

printNumber(n-1);
}

public static void main(String[] args){

printNumber(5);

Output:

Explanation

printNumber(5)

prints 5 and calls printNumber(4).

The process continues until printNumber(0), then it stops.

Topic 3: Factorial Using Recursion

Concept

5! = 5 × 4 × 3 × 2 × 1 = 120
Formula:

n! = n × (n-1)!

Solution:

public class Factorial {

static int factorial(int n){

if(n == 1){

return 1;

return n * factorial(n-1);

public static void main(String[] args){

[Link](factorial(5));

Output:

120

Topic 4: Fibonacci Sequence


Concept

Each number is the sum of the previous two.

0112358

Formula:

F(n)=F(n-1)+F(n-2)

Solution:

public class Fibonacci {

static int fibonacci(int n){

if(n <= 1){

return n;

return fibonacci(n-1) + fibonacci(n-2);

public static void main(String[] args){

for(int i=0;i<10;i++){
[Link](fibonacci(i)+" ");

Output:

0 1 1 2 3 5 8 13 21 34

Topic 5: Recursive String Reversal

Concept

JAVA becomes AVAJ

Solution:

public class ReverseString {

static String reverse(String text){

if([Link]()){

return text;

return reverse([Link](1))
+ [Link](0);

public static void main(String[] args){

String word="JAVA";

[Link](reverse(word));

Output:

AVAJ

Topic 6: Checking Palindrome

Concept

A palindrome reads the same forward and backward.

Examples:

level

madam

Solution:
public class Palindrome {

public static void main(String[] args){

String word="level";

String reverse="";

for(int i=[Link]()-1;i>=0;i--){

reverse += [Link](i);

if([Link](reverse)){

[Link]("Palindrome");

else{

[Link]("Not Palindrome");

Output:

Palindrome

Topic 7: Counting Words in a Sentence


Solution:

public class WordCount {

public static void main(String[] args){

String sentence = "Java is very powerful";

String words[] = [Link](" ");

[Link]("Number of words: " + [Link]);

Output:

Number of words: 4

Topic 8: Removing Spaces

Solution:

public class RemoveSpaces {

public static void main(String[] args){

String text = "Computer Science";


text = [Link](" ","");

[Link](text);

Output:

ComputerScience

Topic 9: Combining Recursion and Strings

Example: Count characters recursively.

Solution:

public class RecursiveLength {

static int length(String text){

if([Link]("")){

return 0;

return 1 + length([Link](1));

}
public static void main(String[] args){

[Link](length("Java"));

Output:

How To Solve Recursion Questions

Step 1:

Find the smallest possible case.

Example:

if(n==1)

return 1;

Step 2:

Make the problem smaller.

Example:

n-1

Step 3:

Write the recursive call.


Example:

factorial(n-1)

Common Mistakes

Wrong:

method(n-1);

without a base case.

Correct:

if(n==0)

return;

COSC211 COMPLETE LAB SERIES SUMMARY

Lab01 - Java output, formatting, escape sequences

Lab02 - Classes, objects, strings

Lab03 - Variables, Scanner, calculations

Lab04 - Constructors, methods, this keyword, OOP design

Lab05 - Decision making

Lab06 - Loops

Lab07 - Arrays

Lab08 - 2D Arrays and matrices

Lab09 - Files and String processing


Lab10 - Recursion

END OF LAB 10

You might also like