0% found this document useful (0 votes)
86 views17 pages

Module in CC 103 Second Sem AY 2023 24

Programming
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)
86 views17 pages

Module in CC 103 Second Sem AY 2023 24

Programming
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/ 17

CC 103: Computer Programming 2 Prof. Rene D.

Arduo
NISULC-BSIT Associate Professor I
Second Semester AY 2023-24

Module 1, Lesson 1
Multi-dimensional Arrays
Introduction

In this module, you shall be introduced to the multi-dimensional arrays. You


will test sample programs in multi-dimensional arrays. You will also answer
programming problems and create your own programs in multi-dimensional arrays.

Read the discussion and answer the programming problem exercises in this
manual.

Learning Outputs:
Upon completion of this Module, you shall be able to:
1. Test multi-dimensional arrays sample programs.
2. Answer and create multi-dimensional array programs as solutions to
programming problems.
Multidimensional Arrays

A multidimensional array or a 2D array is an array of arrays.

Multidimensional arrays are useful when you want to store data in a tabular form, like
a table with rows and columns.

To create a two-dimensional array, add each array within its own set of curly
braces:

Example

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers is now an array with two arrays as its elements.

Access Elements

To access the elements of the myNumbers array, specify two indexes: one for the
array, and one for the element inside that array. This example accesses the third
element (2) in the second array (1) of myNumbers:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
System.out.println(myNumbers[1][2]); // Outputs 7

Remember that: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.

Accessing values in a two-dimensional String array.


Example
public class Multi1
{
public static void main (String a[])
{
String[][] pet = { {"Dog","Cat"}, {"Black", "Brown", "White"} };
System.out.println(pet[1][2]+" "+ pet[0][1] ); // White Cat
}
}
Practice Activity
1. Using the program class Multi1, display the following outputs. Access the
elements in the array using the appropriate index numbers.
I have a Black Dog named brownie.
The big Brown Cat jump over the lazy White Dog.
Change Element Values

You can also change the value of an element:

Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers[1][2] = 9;
System.out.println(myNumbers[1][2]); // Outputs 9 instead of 7

String[][] pet = { {"Dog","Cat"}, {"Black", "Brown", "White"} };


pet[1][1]=”Yellow”;
System.out.println(pet[1][1]); // Outputs Yellow instead of Brown
Loop Through a Multi-Dimensional Array

We can also use a for loop inside another for loop to get the elements of a two-
dimensional array (we still have to point to the two indexes):

Example

public class Main {

public static void main(String[] args) {

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

for (int i = 0; i < myNumbers.length; ++i) {

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

System.out.println(myNumbers[i][j]);

}
}

Programming Exercises

1. Print the values 8, 3, 87, and 34 by accessing them from the given two-
dimensional array. Complete the program.

public class Test1


{
public static void main(String[] args)
{
int[][] arr = { {10,39,8},3,{35,87},22,{34} };

// ADD CODE HERE //

}
}

2. Create a program that displays all the possible products from the given values of
the two-dimensional array.
int[][] myNumbers = { {2, 5, 3}, {5, 6, 7} };
For example (2x5=10, 2x6=12, 2x7=14…)
3. From the sample array below, create a program that displays 3 friends in the two
sections.
String[][] friend = { {“Section A”,”Section B”}, {“Jen”, “Jill”, “Jake”,”Joy”,”Jerry”,”Jeff”} };

4. Create your 2D array using the materials/equipment/devices found at home.


Display the elements using a for-loop.
CC 103: Computer Programming 2 Prof. Rene D. Arduo
NISULC-BSIT Associate Professor I
Second Semester AY 2023-24

Module 1, Lesson 1
Java Methods
Introduction

In this module, you shall be introduced to Java Methods. You will test sample
programs in Java methods. You will be able to difference between a parameter and
an argument. You will also answer programming problems and create your programs
using different methods.

Read the discussion and answer the programming problem exercises in this
manual.

Learning Outputs:
Upon completion of this Module, you shall be able to:
1. Test sample programs that contain methods.
2. Describe the methods with different return types.
3. Explain the parameters and arguments.
4. Create methods with different return types.
Java Method

A method is a block of code that only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as functions.

Why use methods? To reuse code: define the code once, and use it many times.

Create a Method

A method must be declared within a class. It is defined with the name of the method,
followed by parentheses (). Java provides some pre-defined methods, such
as System.out.println(), but you can also create your own methods to perform certain
actions:

Example

Create a method inside Main:

public class Main {

static void myMethod() {

// code to be executed
}

Example Explained

 myMethod() is the name of the method


 static means that the method belongs to the Main class and not an object of
the Main class.
 void means that this method does not have a return value.

Call a Method

To call a method in Java, write the method's name followed by two


parentheses () and a semicolon;

In the following example, myMethod() is used to print a text (the action), when it is
called:

Example

Inside main, call the myMethod() method:

public class Main {

static void myMethod() {

System.out.println("I just got executed!");

public static void main(String[] args) {

myMethod();

// Outputs "I just got executed!"

A method can also be called multiple times:

Example

public class Main {

static void myMethod() {


System.out.println("I just got executed!");

public static void main(String[] args) {

myMethod();

myMethod();

myMethod();

// I just got executed!

// I just got executed!

// I just got executed!

Activity

Insert the missing part to call myMethod from main.

static void Output() {


System.out.println("I just got executed!");
}

public static void main(String[] args) {


;
}

Programming Exercises
1. Create a method that displays your name, age, and address. Call the method
in the program.
Java Method Parameters
Parameters and Arguments
Information can be passed to methods as a parameter. Parameters act as variables
inside the method.

Parameters are specified after the method name, inside the parentheses. You can
add as many parameters as you want, just separate them with a comma.

The following example has a method that takes a String called fname as parameter.
When the method is called, we pass along a first name, which is used inside the
method to print the full name:

Example

public class Main {

static void myMethod(String fname) {

System.out.println(fname + " Refsnes");

public static void main(String[] args) {

myMethod("Liam");

myMethod("Jenny");

myMethod("Anja");

// Liam Refsnes

// Jenny Refsnes

// Anja Refsnes

When a parameter is passed to the method, it is called an argument. So, from the
example above: fname is a parameter, while Liam, Jenny and Anja are arguments.
Multiple Parameters

You can have as many parameters as you like:

Example

public class Main {

static void myMethod(String fname, int age) {

System.out.println(fname + " is " + age);

public static void main(String[] args) {

myMethod("Liam", 5);

myMethod("Jenny", 8);

myMethod("Anja", 31);

// Liam is 5

// Jenny is 8

// Anja is 31

Note that when you are working with multiple parameters, the method call must have
the same number of arguments as there are parameters, and the arguments must be
passed in the same order.

Activity:
Add a fname parameter of type String to myMethod, and output "John Doe":

static void myMethod( ) {


System.out.println( + " Doe");
}
public static void main(String[] args) {
myMethod("John");
}

Return Values

The void keyword, used in the examples above, indicates that the method should not
return a value. If you want the method to return a value, you can use a primitive data
type (such as int, char, etc.) instead of void, and use the return keyword inside the
method:

Example

public class Main {

static int myMethod(int x) {

return 5 + x;

public static void main(String[] args) {

System.out.println(myMethod(3));

// Outputs 8 (5 + 3)

This example returns the sum of a method's two parameters:

Example

public class Main {

static int myMethod(int x, int y) {

return x + y;

public static void main(String[] args) {


System.out.println(myMethod(5, 3));

// Outputs 8 (5 + 3)

You can also store the result in a variable (recommended, as it is easier to


read and maintain):

Example
public class Main {

static int myMethod(int x, int y) {

return x + y;

public static void main(String[] args) {

int z = myMethod(5, 3);

System.out.println(z);

}// Outputs 8 (5 + 3)

A method that returns a double value


public class Method2{
static double ComputeInterest(double p, double r, double t) {
return p * r * t;
}
public static void main(String[] args) {
System.out.println(ComputeInterest(1000,.05,1));//outputs 50.0
}
}

A method that returns a boolean value


public class Method3{
static boolean Compare(String user, String password) {
if(user.equals("Guest") && password.equals("pass1234"))//outputs true
return true;
else
return false;
}
public static void main(String[] args) {
System.out.println(Compare("Guest","pass1234"));
}
}
Programming Exercises
1. Write a Java method to compute the average of three numbers.
2. Write a Java method to compute the area of a triangle.

A Method with If...Else


It is common to use if...else statements inside methods:

Example
public class Main {

// Create a checkAge() method with an integer variable called age

static void checkAge(int age) {

// If age is less than 18, print "access denied"

if (age < 18) {

System.out.println("Access denied - You are not old enough!");

// If age is greater than, or equal to, 18, print "access granted"

} else {

System.out.println("Access granted - You are old enough!");

public static void main(String[] args) {


checkAge(20);//Call the checkAge method and pass along an age of 20

// Outputs "Access granted - You are old enough!"

Programming Exercises
1. Write a Java method to find the smallest number among three numbers.
2. Write a Java method to check whether a year (integer) is a leap year or not.
CC 103: Computer Programming 2 Prof. Rene D. Arduo
NISULC-BSIT Associate Professor I
Second Semester AY 2023-24

Module 1, Lesson 1
String Methods
Introduction

In this module, you shall be introduced to Java String Methods. You will test
sample programs in Java String methods. You will also answer programming
problems and create your programs using different string methods.

Read the discussion and answer the programming problem exercises in this
manual.

Learning Outputs:
Upon completion of this Module, you shall be able to:
1. Test sample programs that contain String methods.
2. Apply String methods in answering programming exercises.

In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:

char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);

is same as:

String s="javatpoint";

Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.

All String Methods


The String class has a set of built-in methods that you can use on strings.

Method Description

charAt() Returns the character at the specified index (position)

codePointAt() Returns the Unicode of the character at the specified index

codePointBefore() Returns the Unicode of the character before the specified index
codePointCount() Returns the number of Unicode values found in a string.

compareTo() Compares two strings lexicographically

compareToIgnoreCase() Compares two strings lexicographically, ignoring case differences

concat() Appends a string to the end of another string

contains() Checks whether a string contains a sequence of characters

contentEquals() Checks whether a string contains the exact same sequence of characters
of the specified CharSequence or StringBuffer

copyValueOf() Returns a String that represents the characters of the character array

endsWith() Checks whether a string ends with the specified character(s)

equals() Compares two strings. Returns true if the strings are equal, and false if not

equalsIgnoreCase() Compares two strings, ignoring case considerations

format() Returns a formatted string using the specified locale, format string, and
arguments

getBytes() Encodes this String into a sequence of bytes using the named charset,
storing the result into a new byte array

getChars() Copies characters from a string to an array of chars

hashCode() Returns the hash code of a string

indexOf() Returns the position of the first found occurrence of specified characters
in a string

intern() Returns the canonical representation for the string object

isEmpty() Checks whether a string is empty or not

lastIndexOf() Returns the position of the last found occurrence of specified characters
in a string

length() Returns the length of a specified string

matches() Searches a string for a match against a regular expression, and returns
the matches

offsetByCodePoints() Returns the index within this String that is offset from the given index
by codePointOffset code points

regionMatches() Tests if two string regions are equal

replace() Searches a string for a specified value, and returns a new string where
the specified values are replaced

replaceFirst() Replaces the first occurrence of a substring that matches the given regular
expression with the given replacement

replaceAll() Replaces each substring of this string that matches the given regular expression
with the given replacement

split() Splits a string into an array of substrings

startsWith() Checks whether a string starts with specified characters

subSequence() Returns a new character sequence that is a subsequence of this sequence

substring() Returns a new string which is the substring of a specified string

toCharArray() Converts this string to a new character array

toLowerCase() Converts a string to lower case letters

toString() Returns the value of a String object

toUpperCase() Converts a string to upper case letters

trim() Removes whitespace from both ends of a string

valueOf() Returns the string representation of the specified value

Java String charAt()

The Java String class charAt() method returns a char value at the given index
number.

The index number starts from 0 and goes to n-1, where n is the length of the string. It
returns StringIndexOutOfBoundsException, if the given index number is greater
than or equal to this string length or a negative number.

Java String charAt() Method Example

Let's see Java program related to string in which we will use charAt() method that
perform some operation on the give string.

FileName: CharAtExample.java

public class CharAtExample{


public static void main(String args[]){
String name="javatpoint";
char ch=name.charAt(4);//returns the char value at the 4th index
System.out.println(ch);
}}

Activity

1. Using the string “Welcome to Computer Programming 2”, create a program


that display the first and last character.
Example to display All capital letters in a String.

public class CharAt{

public static void main(String[] args) {

String c= "Welcome to Computer Programming 2";

for (int x=0; x<c.length();x++)

if (Character.isUpperCase(c.charAt(x)))

System.out.println(c.charAt(x));

}//outputs WCP

Programming Exercises

1. Using the string “Welcome to Computer Programming 2”, display only the
numbers. Use for loop and if-statement.

2. Using the string “Welcome to Computer Programming 2”, count and


display the number of uppercase, lowercase and digit . Use for loop and if-
statement.

You might also like