0% found this document useful (0 votes)
241 views9 pages

Java Array Programming Practices

This document contains code snippets and explanations for practicing different array and function concepts in Java, including: 1) One-dimensional and multi-dimensional array examples with traversal and manipulation of array elements. 2) Function examples with various parameter types (no parameters, no return value; parameters but no return value; parameters and return value) and recursion. 3) Examples combining arrays and functions by passing arrays as parameters and returning/printing array values. The document covers arrays, functions, and their integration through examples to help learn and practice core Java concepts.

Uploaded by

Rhynia Impas
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)
241 views9 pages

Java Array Programming Practices

This document contains code snippets and explanations for practicing different array and function concepts in Java, including: 1) One-dimensional and multi-dimensional array examples with traversal and manipulation of array elements. 2) Function examples with various parameter types (no parameters, no return value; parameters but no return value; parameters and return value) and recursion. 3) Examples combining arrays and functions by passing arrays as parameters and returning/printing array values. The document covers arrays, functions, and their integration through examples to help learn and practice core Java concepts.

Uploaded by

Rhynia Impas
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
  • One Dimensional Arrays
  • Multi Dimensional Arrays
  • Array Traversal
  • Functions
  • Functions with Arrays
  • Recursive Functions

Review on Arrays

1. One Dimensional Arrays Practice I

import [Link];

class Main {
public static void main(String[] args) {
int[] nums = new int[]{
-2, 1, 1, 2, 3,
9, 10, -3, 100, 2,
4, -5, 1, 10, -100,
5, 2, 3, -1, 1,
-3, -4, -5, -6, -7,
9, 9, 9, 9, 9,
1, 2, 3, 4, 5,
100, 100, 100, 100, 100
};

for(int i = 0; i<40; i++){


if(nums[i]>0){
nums[i]=nums[i]*nums[i]*nums[i];
[Link](nums[i]);
} else if(nums[i]<0){
nums[i]=nums[i]*nums[i];
[Link](nums[i]);
}
}
}
}

2. One Dimensional Arrays Practice II

import [Link];

class Main {
public static void main(String[] args) {
double[] nums = new double[]{1.4, 1.2054, 2.2, 2.5, 3.66, 3.0, 4.024,
4.00001, 5.5, 5.10};

for(int i = 10-1; i>=0; i--){


[Link]("%.2f\n", nums[i]);
}
}
}

1. Multi Dimensional Arrays Practice l

import [Link];

class Main {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Enter # of rows: ");
int row = [Link]();
[Link]("Enter # of columns: ");
int col = [Link]();
int[][] arr = new int[row][col];
[Link]("Elements:");
for(int i = 0; i<row; i++){
for(int j=0; j<col; j++){
arr[i][j]=[Link]();
}
}
[Link]("Enter the boogeyman's value: ");
int bog = [Link]();

for(int i = 0; i<row; i++){


for(int j=0; j<col; j++){
if(arr[i][j]==bog){
int holderI = i+1, holderJ=j+1;
[Link]("BOOGEYMAN LOCATED AT ROW "+holderI+", COLUMN
"+holderJ+"!");
}
}
}

}
}

2. Multi Dimensional Arrays Practice Il


// NAAY SAYOP
import [Link];

class Main {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Enter # of rows: ");
int row = [Link]();
[Link]("Enter # of columns: ");
int col = [Link]();
int[][] arr = new int[row][col];
[Link]("Enter elements:");
for(int i = 0; i<row; i++){
for(int j=0; j<col; j++){
arr[i][j]=[Link]();
}
}
int count=0;
for(int i = 0; i<row; i++){
int sum=0;
for(int j=0; j<col; j++){
sum=sum+arr[i][j];
}
if(sum%2==0){
count++;
break;
}
}
[Link]("Even row: "+count);

}
}

1. Array Traversal Practice I


class Main {
public static void main(String[] args) {
int[] array = new int[]{1,2,3,4,5};

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


[Link]("%d",array[i]);
if(i!=4){
[Link](",");
}
}
}
}

2. Array Traversal Practice II


//NAAY SAYOP
import [Link];
class Main {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Enter size: ");
int size = [Link]();
int[] array = new int[size];
int minus=0, holdermin;
for(int i =0; i<size; i++){
[Link]("Enter element %d: ",i+1);
array[i]=[Link]();
if(array[i]<=0){
holdermin = size-minus;
size=size-holdermin;
break;
}else {
minus++;
continue;
}
}
for(int i =0; i<size; i++){
if (i==0){
[Link]("[%d,",array[i]);
} else if(i>0 &&i<size){
[Link]("%d",array[i]);
}
if(i!=size-1 && i!=0){
[Link](",");
} else if(i==size-1){
[Link]("]");
}

}
}
}

Functions

1. Functions With No Parameters and Return Values Practice ll


wala

2. Functions With No Parameters and Return Values Practice l


import [Link];
class Main {
static int called = 0;

public static void hello() {


called++;
[Link]("Call counter: " + called);
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Call count: ");
int n = [Link]();
for(int called = 1; called <= n; called++) {
hello();
}
}
}

1. Functions With No Parameters But With Return Values Practice I

import [Link];

class Main {
public static int askInput() {
Scanner scan = new Scanner([Link]);

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


int number = [Link]();

return number;
}

public static void main(String[] args) {


int total = askInput();
[Link](total);
}
}
2. Functions With No Parameters but With Return Values Practice II

import [Link];

class Main {
public static int askInput() {
Scanner scan = new Scanner([Link]);

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


int number = [Link]();
if(number % 2 == 0)
{
[Link]("Even");
}
else
{
[Link]("Odd");
}

return number;
}
public static void main(String[] args) {
askInput();

}
}

1. Functions With Parameters and No Return Values Practice l

import [Link];

class Main {
public static int palindrome(int number) {
Scanner scan = new Scanner([Link]);

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


int num = [Link]();
int r,sum=0;
int temp=num;
while(num>0)
{
r=num%10;
sum=(sum*10)+r;
num=num/10;
}
if(temp==sum)
[Link](temp+" is a palindrome!");
else
[Link](temp+" is not a palindrome!");
return num;
}

public static void main(String[] args) {

palindrome(0);
}
}

2. Functions With Parameters and No Return Values Practice ll

import [Link];

class Main {
public static void palindrome()
{
Scanner scan = new Scanner([Link]);
String reverseStr = "";
[Link]("Enter a string: ");
String str = [Link]();
int strLength = [Link]();

for (int i = (strLength - 1); i >=0; --i)


{
reverseStr = reverseStr + [Link](i);
}

if([Link]().equals([Link]()))

[Link](str + " is a palindrome!");


else
[Link](str + " is not a palindrome!");
}

public static void main(String[] args) {

palindrome();
}
}

1. Functions With Parameters and Return Values Practice l

import [Link];

class Main {
public static int compare(int a, int b){

if(a>b){
return a;
} else if (a<b){
return b;
}
return 0;
}

public static void main(String[] args) {


Scanner scan = new Scanner([Link]);

char a, b;

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


a = [Link]().charAt(0);

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


b = [Link]().charAt(0);

int ascii1 = a, ascii2 = b;


int result = compare(ascii1,ascii2);

[Link]("Result value = " + result);


}
}

2. Functions With Parameters and Return Values Practice ll

import [Link];

class Main {
public static int compare(int a, int b, int c){

if(a>=b && a>=c){


return a;
} else if (b>=c && b>=a){
return b;
}else {
return c;
}
//return 0;
}
public static void main(String[] args) {
Scanner scan = new Scanner([Link]);

int a, b, c;

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


a = [Link]();

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


b = [Link]();

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


c = [Link]();

int result = compare(a,b,c);


[Link]("Greatest: " + result);
}
}

1. Recursive Functions Practice l

class Main {
public static void fun(int n) {
if (n > 0) {
fun(n-1);
if(n%2==0){
[Link](n+" ");
}
}
}

public static void main(String[] args) {


fun(20);
}
}

2. Recursive Functions Practice ll

import [Link];
class Main{
public static void factorial(int num){
int i,fact=1;
for(i=1;i<=num;i++){
fact=fact*i;
}
[Link](fact);
}

public static void main(String args[]){


Scanner in = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
factorial(num);
}
}

Functions with Arrays

1. Functions with 1D Arrays Practice I


import [Link];

class Main {
public static void main(String[] args) {
char[] array = new char[]{
'x','s','q','a','y','i','u','o','p','a','w','q'
};
vowelCount(array);
}
static void vowelCount(char[] array){
int count=0;
for(int i=0; i<[Link]; i++){
if(array[i]=='a' || array[i]=='e' || array[i]=='i' || array[i]=='o' ||
array[i]=='u'){
count++;
}
}
[Link]("Number of vowels: "+ count);
}
}

2. Functions with 1D Arrays Practice II

import [Link];
class Main{
public static void main(String[] args){
Scanner in = new Scanner([Link]);

[Link]("Enter size of array: ");


int size = [Link]();
int[] arr= new int[size];
for(int i = 0; i<size; i++){
[Link]("Enter element %d: ", i+1);
arr[i] = [Link]();
}
int max = maxArray(arr, size);
[Link]("Maximum element: %d", max);
}
static int maxArray(int[] arr, int size){
int max=0;
for(int i = 0; i<size; i++){
if(max< arr[i]){
max=arr[i];

}
}
return max;
}
}

1. Functions with 2D Arrays Practice I

class Main {
public static void main(String[] args) {
int[][] array = new int[][]{
{1, 6, 4},
{7, 2, 8},
{5, 9, 3}
};
int row=[Link];
int col=array[0].length;
displayElements(array, row, col);
}
static void displayElements(int[][] arr, int rows, int cols) {
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
[Link]("%d ", arr[i][j]);
}
[Link]();
}
}
}

2. Functions with 2D Arrays Practice ll

import [Link].*;

class Main {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
int[][] arr = new int[3][3];
int rows=[Link];
int cols=arr[0].length;

for(int i = 0; i < rows; i++) {


for(int j = 0; j < cols; j++) {
[Link]("R%dC%d: ", i+1,j+1);
arr[i][j] = [Link]();
}
}
displayElements(arr, rows, cols);
}
static void displayElements(int[][] arr, int rows, int cols) {
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
[Link]("%d ", arr[i][j]);
}
[Link]();
}
}
}

Common questions

Powered by AI

To read a 2D array, the program uses nested loops: an outer loop for rows and an inner for columns, utilizing a `Scanner` to capture input. Once populated, another nested loop iterates through the array, printing elements row by row. Formatting retains readability, typically inserting spaces or newlines between numbers .

A function is invoked repeatedly in a loop determined by a user-defined `n` count. Input dictates repetitions with `for` loop handling execution, invoking the function on each iteration. An internal counter incrementation tracks function calls, exemplified by cumulative display messages indicating execution frequency .

The method involves defining a function that accepts two integer parameters, and uses simple conditional statements (`if-else`) to compare them, returning the larger of the two. If they are equal, an optional decision can be made to return either or a predetermined value such as zero .

In functions without parameters but with return values, input is typically handled within the function using a Scanner object. The function prompts the user with `System.out.print`, reads the input using `scan.nextInt()`, and returns the input value. The function encapsulates both input handling and returning the received data .

Recursion is implemented by a function `fun(n)` that calls itself with decremented values from `n` until `n` becomes less than or equal to zero. Within each call, if `n` is even, it is printed. This recursive invocation implicitly uses a stack where values pause until all recursions complete. Printed on backtracking, only even numbers appear due to the conditional check .

The algorithm involves iterating over each row of the 2D array and computing the sum of its elements. For each row, if the resultant sum is even, the row is marked as even and counted. This demonstrates using nested loops: an outer loop traverses rows and an inner loop sums elements .

The approach involves iterating through the array, tracking the maximum element seen so far. Initialize a variable `max` with the first element's value, then iterate through the array comparing each element to `max`. If an element is greater, update `max` with that element's value. This finds the maximum by the end of the array .

The error is addressed by ceasing input and resizing the array when an element is less than or equal to zero. During input, if such a condition is met, the program calculates the number of allowed elements by obtaining the difference between the total size and the discount count, adjusting the input size accordingly .

To check if a string is a palindrome, reverse the entire string and compare it to the original. Convert the original and reversed strings to lower case for case insensitive comparison. If they are equal, the string is a palindrome. This requires iterating over the string in reverse order to construct the reversed string, and then using string comparison operations .

In Java, you can traverse through an array using a loop, and for each element, check its sign. If the element is positive, calculate its cube by multiplying it three times by itself. If it is negative, square it by multiplying it by itself. This is achieved by a conditional statement where the cube is calculated using `nums[i]*nums[i]*nums[i]` for positive numbers and the square is calculated using `nums[i]*nums[i]` for negatives .

Review on Arrays
1. One Dimensional Arrays Practice I
import java.util.Scanner;
class Main {
    public static void main(Stri
for(int i = 0; i<row; i++){
            for(int j=0; j<col; j++){
                arr[i][j]=in.nextInt();
class Main {
    public static void main(String[] args) {
        int[] array = new int[]{1,2,3,4,5};
        for(int i =0; i
class Main {
    static int called = 0;
    
    public static void hello() {
        called++;
        System.out.println("C
public static void main(String[] args) {
        askInput(); 
        
    }
}
1. Functions With Parameters and No Return
System.out.println(str + " is not a palindrome!");       
    }
    
    public static void main(String[] args)
public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        
        int a, b, c;
import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        char[] array = new char[]{
};
        int row=array.length;
        int col=array[0].length; 
        displayElements(array, row, col);
    }

You might also like