Monday, July 22, 2024

Array in Java

 

Array:   

int a1 = 10; // Only one value at a time

 int a2 = 20;

 // To store 100 values, you would need to declare 100 variables,

e.g., a1, a2, a3, ..., a100               

An array is a collection of values of the same data type   

It can be used to store a collection of values that are homogeneous (i.e., of the same type).              

                            homogeneous             =  same type

// Instead, you can use an array to store multiple values

                              //       10, 20, 30  

                              //     1.1f, 2.1f, 4.3f

//                         'A','B', 'C'

//                       "Ram", "Sita","Raju"

Declaring an Array:

Arrays can be declared in two ways:

Syntax:

datatype varname[] = new datatype[size];

(or)

datatype[] varname = new datatype[size];

size represents how many values we can store in the array.                     

Declare int array:

// Declare an int array with the name 'arr' and size of 3

int arr[] = new int[3];

(or)

 int[] arr = new int[3];

Declare float array:

//  declare a float array with name i.e ‘farr’ and size of array = 3

float farr[] =  new float[3];

 (or)

 float [] farr  = new float [3];

Declare char array:

//  declare a char array with name i.e ‘charr’ and size of array = 2

char charr [] =  new char[2]; 

(or)

 char [] charr = new char [2];

Declare String array:

// Declare a String array with the name 'sarr' and size of array = 4

String sarr []  = new String [4];

(or)

 String [] sarr   = new String [4];

in array, it stores the values in index no.

The index number starts with 0 and ends with size of array -1 i.e 2 (3-1)

the first element of the array is stored at the indexno = 0,

2nd element is stored at the indexno = 1

............................... and so on.

                             

Store/assign values in array:

To store or assign values to an array, you specify the index position where the value should be stored.

// Declare an int array with the name 'arr' and size of 3

int arr[] = new int[3];

                              // Store the value 10 at index 0

                              arr[0]  =10;

                          //  10 value is stored at index no =0 in array

                             

                              //  store 20 value at index no =1

                              arr[1]  = 20;

                                //  20 value is stored at index no =1 in array

              

                             

                              // Access  values from array  based on index no = 0,1,2...etc

// Access the value stored at index 0      

arr[0]   -->  10

// Access the value stored at index 1

               arr[1] -->  20

                              ...

                              ....                        

package ArrayBasics;

public class intArrayBasics {

               public static void main(String[] args) {

                              //   create array of int val's  and size =3

                              int arr [] = new int[3];

                              //  store max 3 values only

                              //  store 10 val index no =0

                              arr[0] =10;

                              //  10 value is stored at index no =0 in array

                              //  store 20 val index no =1

                              arr [1] =20;

                              //  20 val is stored at indexno =1 in array

                              //  store 30 val at index no =2

                              arr [2] =30;

                              // 30  val is stored at index no =2

                              // store 40 val at index no  =3  --> ???     

                              //   4  th val  size  =3  max

//                                                                        arr[4]  = 40 ; // error :  we dont have index no = 4 ..

                              //here arr size = 3 index from 0 to size-1 i.e 3-1 = 2 (0-2)

                              // Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 3

                              //                                          at ArraysBasics.intArray.main(intArray.java:62)

                              //  arr [5]  index no = 0 to 4

                              //  arr [100]           0 to 99

                              // display / Access  values from array

                              // display arr val at index no =0

                              System.out.println(arr[0]);

                              System.out.println("Array value at indexno =0 --> "+ arr[0]);                       

                              //                   10

                             

                              // display arr val at index no =1

                              System.out.println(arr[1]);// 20

                              System.out.println("Array value at indexno =1 --> "+ arr[1]);                       

                              //// display arr val at index no =2

                              System.out.println(arr[2]);//  30

                              System.out.println("Array value at indexno =2  -->"+ arr[2]);        

               }

}

o/p:

10

Array value at indexno =0 --> 10

20

Array value at indexno =1 --> 20

30

Array value at indexno =2  -->30

Float array :

package ArrayBasics;

public class floatArray {

               public static void main(String[] args) {

                              //                           int arr[] =  new int[3];

                              // Declare float array of size =3

                              float farr[] = new float[3];                          

                              //   array name  - fArr

                              // size of array =  3  - we can store max of 3 float values 

                              // index no -always starts from 0  and ends with size of arr -1. i.e  3-1 =2

                              //    index no varies from 0 to 2  -  0,1,2

                              // store some float values in array

                              // store 1.2f values in float array at indexno =0

                              farr[0] = 1.2f;

                              // store 2.2f values in float array at indexno =1

                              farr[1] = 2.2f;

                              // store 3.2f values in float array at indexno =2

                              farr[2] =  3.2f;

                              //  display values from float array

                              System.out.println("val from float array at index no =0 -->" + farr[0]);

                              //                                                              1.2

                              System.out.println("val from float array at index no =1 -->" + farr[1]);//2.2

                              System.out.println("val from float array at index no =2 -->" + farr[2]);//3.2

               }

}

o/p:

val from float array at index no =0 -->1.2

val from float array at index no =1 -->2.2

val from float array at index no =2 -->3.2

HW define char array  and store char values  and display it

HW Define  double array and store double values  and display it

HW Define long array  and store some values  and display it

HW  Define boolean array  and store boolean values  and display it

Note:

When working with arrays, it's important to ensure that the type of values being assigned matches the type of the array.

Example of Type Mismatch:

Ex1:

int iarr[] = new int[3];

iarr[0] = 3.2f; // Type mismatch: cannot convert from float to int

                                             //  int array - can be used store int values only

Ex2:

float farr[] = new float[3];

farr[0] = 25;    // 25 gets converted to 25.0

farr[0] = 'A';   // 'A' gets converted to its ASCII value, 65, and then to 65.0

                              //   float array - can be used store decimal numbers usually (or) it will convert int to float value  (or)  else it throws error

Ex3:

farr[0] = true;  // Error: cannot convert boolean to float

Assigning a boolean value to a float array results in a type mismatch error.

2.  int array - We cannot store 1 float val + 1 double val +  1 char val +  1 boolean  value

int iarr[] = new int[3];

iarr[0] = 1.23f; // Error: cannot convert from float to int

iarr[0] = 3.2;   // Error: cannot convert from double to int

iarr[0] = 'C';   // 'C' is converted to its ASCII value, 67, which is valid for int

iarr[0] = true;  // Error: cannot convert from boolean to int

iarr[0] = "Ram"; // Error: cannot convert from String to int

 Always ensure the values being assigned to an array match the array's data type to avoid compilation errors.

Note:

In array, we can store same data type of values

                        homogeneous values

               int arr   -->   store only int vaues

               float arr -->   store only float values

In General array, we can not store  1 int val  + 1 float + 1 double  +  1 char

      + 1 boolean  +  1  String

Display values from array using 'for' loop:

              

package ArrayBasics;

public class intArrayBasics2 {

               public static void main(String[] args) {

                              // int array :  and store 3 values

                              int arr []  = new int[3];//  0 - 3-1 i.e 2

                              arr[0] =10;

                              arr[1] =20;

                              arr [2] =30;

                             

                              //Display each values from array using index no

//                           System.out.println("val at index no =0 -->"+ arr[0]);

//                           System.out.println("val at index no =1 -->"+ arr[1]);

//                           System.out.println("val at index no =2 -->"+ arr[2]);

                             

                              ///  99

//                           System.out.println("val at index no =2"+ arr[99]);

                             

                              //Display values from array using 'for' loop:

//                           for(int i=0;i<=3;i++)// i=0, 0+1= 1, 1+1 =2, 2+1 =3

                                             for(int i=0;i<=2;i++)// i=0, 0+1= 1, 1+1 =2, 2+1 =3

                              {//         0<=3  true, enters for loop

                                             //      1<=3  true , enters for loop

                                             //      2<=3  true, for loop

                                             //      3<=3 true, enters for loop

                                             System.out.println("values from array="+ arr[i]);

                                             //                                     arr[0] // 10

                                             //                                     arr[1]  //20

                                             //                                     arr[2] // 30

                                             //                                     arr[3]//  no index no =3 in array.

                                             //so it throws exception- java.lang.ArrayIndexOutOfBoundsException:

                                            

                              }

                                                           

               }

}

Array length:

In Java, the length of an array can be accessed using the length property.

This property returns the number of elements the array can hold, which is determined when the array is created.

package ArrayBasics;

public class intArrayBasics2 {

               public static void main(String[] args) {

                              // int array :  and store 3 values

                              int arr []  = new int[3];//  0 - 3-1 i.e 2

                              arr[0] =10;

                              arr[1] =20;

                              arr [2] =30;

                             

                              // length of array i.e 3

                              int le =  arr.length;

                              //         3

                              //  le  = 3

                              System.out.println("Length of array ="+ le);// 3

                             

                              //  dispay all values  from array  using for loop  and lenhth of array

                             

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

// use length of array

//              for(int i=0;i<=le-1;i++)

                                for(int i=0;i<=arr.length-1;i++)

                              {             //    3-1=2

                                             System.out.println(arr[i]);

                              }

                             

                             

//                                                         Values from array =10

//                                                         Values from array =20

//                                                         Values from array =30

              

                                                           

               }

}

o/p:

Length of array =3

10

20

30

Display values using 'for' loop in float array:

package ArrayBasics;

public class floatArray {

               public static void main(String[] args) {

                              //                           int arr[] =  new int[3];

                              // Declare float array of size =4

                              float farr[] = new float[4];                          

                              // index no always starts from 0  and ends with size of arr -1. i.e  4-1 =3

                              //    index no varies from 0 to 3  -  0,1,2,3

                              // store some float values in array 1.2f,2.2f,3.2f,4.2f in indexno = 0,1,2,3

                              farr[0] = 1.2f;

                              farr[1] = 2.2f;

                              farr[2] = 3.2f;

                              farr[3] = 4.2f;

                             

                              // length of float array

                              int arrLength = farr.length;

                              System.out.println("arrLength="+arrLength);// 4

                             

                                                            //  display all values from float arr using 'for' loop  and use length of array

                              // length of arr

//                           for(int i=0;i<=3;i++)

                                             for(int i=0;i<=farr.length-1;i++)

                              {  //                 4-1

                                             System.out.println("values from floar array="+ farr[i]);

                              }

 

                              //                                                         length of array =4

                              //                                                                                       values from float array =1.2

                              //                                                                                       values from float array =2.2

                              //                                                                                       values from float array =3.2

                              //                                                                                       values from float array =4.2

 

               }

}

HW Define char array and store 2 char values and display all values using for loop

HW Define double array and store 4 double values and display all values using for loop

HW Define long array and store some 3 values and display all values using for loop

HW Define Boolean array  and store boolean  2 values  and display all values using for loop

Default Values in an int Array

In Java, when you create an array of a specific data type, the array elements are automatically initialized with default values.

 For an int array, the default value for each element is 0.

If We don’t store any values in array,  it will store 0 value based on array type ie. int

package ArrayBasics;

public class DefaultValsForIntArray {

               public static void main(String[] args) {

                             

                              int arr []  =  new int [3];

                              //                           if We dont store any values in array,  it will store 0 val based on array type ie. int

                              // Display values from array

                              System.out.println("default val for int array ="+ arr[0]);

                              //                                                   0

                              System.out.println("default val for int array ="+ arr[1]);

                              //                                                  0

                             

                              //Display values from array  using for loop

                              System.out.println("Display values from array  using for loop");

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

                              for(int i=0;i<=arr.length-1;i++)// i =0-2

                              {

                                             System.out.println("default values from int arr ="+ arr[i]);

                              }

                             

                              //                           values from arr =0

                              //                                                         values from arr =0

                              //                                                         values from arr =0

                              // store some values 11,21 into arr[0] ,arr[1]

                              // Display values from array

                              System.out.println("ends here");                             

               }

}

o/p:

default val for int array =0

default val for int array =0

Display values from array  using for loop

default values from int arr =0

default values from int arr =0

default values from int arr =0

ends here

Default Values in a float Array

In Java, when you create an array of a specific data type, the array elements are automatically initialized with default values.

For a float array, the default value for each element is 0.0f.

package ArrayBasics;

public class DefaultValsForFloatArray {

               public static void main(String[] args) {

                              float fArr[]  =  new float [4];

                              // if we dont store any values in float arr,  it stores 0.0   by default

                              // Display values from float array using for loop 

                              //                           for(int i=0;i<=3;i++)// i =0  - 3

                              for(int i=0;i<=fArr.length-1;i++)// i =0  - 3

                              {                   // 4-1=3

                                             System.out.println("default values from float array ="+ fArr[i]);

                                             //                                                      0.0

                              }

               }

}

o/p:

default values from float array =0.0

default values from float array =0.0

default values from float array =0.0

default values from float array =0.0

HW  What is the default value in a char array?

HW  What is the default value in a boolean array?

HW  What is the default value in a String array?

Way2 : Initialize values in integer array (or) Store Values in integer Array at Declaration:

You can initialize an array at the time of declaration using an array initializer. This is a straightforward way to define and assign values to an array.

Syntax:

datatype[] arrayName = {value1, value2, value3, ...};

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

In this example, the arr array is created with 5 elements, and each element is initialized to the values specified in the curly braces.

package ArrayBasics;

public class InitialiseValsInArr {

               public static void main(String[] args) {

//                way 1:  Declare int array and store 3 values

//                                          int arr []  =  new int [3];

//                                         

//                                          arr [0] =10;

//                                          arr [1] =20 ;

                              //  way 2: 10,20,30

                              // We can store values in arary in single line

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

                                            

                //           values at index=0  1   2   3  4

                             

                              // length of array

                              int  l =  arr.length;

                              System.out.println("length of array ="+ l);

                              //                                                                                                                              5

                             

                                             // display all values from array using for loop

                              for(int i=0;i<=l-1;i++)// index no =   0 - 4

                              {     //    5<=4 false,

                                             System.out.println("values from array using for loop="+ arr[i]);

                              }

                             

               }

}

o/p:

length of array =5

values from array using for loop=10

values from array using for loop=20

values from array using for loop=30

values from array using for loop=40

values from array using for loop=50

Way2 : Initialize values in float array (or) Store Values in float Array at Declaration:

package ArrayBasics;

public class InitialiseValsInFloatArr2 {

               public static void main(String[] args) {

                              //  Intialise values in float array (or) Store Values in float Array:1.2f , 2.2f, 3.3f

                              float farr [] = {1.2f,2.2f,3.3f,4.25f};          

                              //                0    1    2     3

                              // length of array

                              int  l =  farr.length;

                              System.out.println("length of array ="+ l);//4

                             

                              // display values from float array using length of array

//                           for(int i=0;i<=3;i++)// i=0 -3

                              for(int i=0;i<=l-1;i++)// i=0 -3

                              {

                                             System.out.println("values from array using for loop="+ farr[i]);

                              }

              

               }

}

o/p:

length of array =4

values from array using for loop=1.2

values from array using for loop=2.2

values from array using for loop=3.3

values from array using for loop=4.25

HW    define long array and store values using 2nd way {120,12313,24214} and display values from arr

HW    define double array and store values using 2nd way and display values from arr

HW    define Boolean array and store values using 2nd way and display values from arr

HW    define char array and store values using 2nd way and display values from arr

 Way2 : Intialise values in String array (or) Store Values in String Array at declaration:

package ArrayBasics;

public class StringArray {

               public static void main(String[] args) {

                              // "ram" , "sita", "abc123"

                              String sarr [] =  {"ram" , "sita", "abc123"};

                              //                   0       1          2  - index no

                              System.out.println("1st val =" + sarr[0]); // ram

                              // HW get all values from string array using 'for' loop

               }

}

For loop without condition:

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

{

}

2.  syntax :

  for(;;) //  if there is no condition  in for loop, condi-is always true

{

}

If there is no condition specified in the for loop, the condition is always considered true.

- it goes to infinite loop

package ArrayBasics;

public class ForLoopwithoutcondi {

               public static void main(String[] args) {

                             

                              for(;;)

                              { //  no cond-  condi is always true

                                             //  no cond-  condi is always true

                                             System.out.println("stmt-1");

                                             System.out.println("stmt-2");

                              }

               }

}

o/p:

stmt-2

stmt-1

stmt-2

stmt-1

stmt-2

stmt-1

stmt-2

....

.....  infinite loop

For-Each Loop:

The for-each loop is used to iterate over arrays or collections in Java.

It can be used to get/ retrieve values from array / collection obj

It provides a simpler way to traverse through elements without using an index.

syntax :

               for(datatype  eachVal : arrVariableName)

               {

                             

               }

·  datatype: The type of elements in the array or collection.

·  eachVal: A variable that represents each element of the array or collection during iteration.

·  arrVariableName: The array or collection being traversed.

Display Values from int Array using 'for each' loop:

package ArrayBasics;

public class DisplayValsFromIntArray {

               public static void main(String[] args) {

                              //  define int array

                              int iarr [] =  {11,22,33,44};

                              //               0  1  2  3

                              //  display all values using 'for each' loop

                             

                              for(int x :iarr)

                              {// //   gets each val from iarr  and store each val in to variable i.e x

                                             System.out.println("values from array using for each loop="+ x );

                              }

                             

               }

}

o/p:

values from array using for each loop=11

values from array using for each loop=22

values from array using for each loop=33

values from array using for each loop=44

 

Display Values from float  Array using for each loop:?

package ArrayBasics;

public class DisplayValsFromFloatArrayUsingForEachLoop {

               public static void main(String[] args) {

                             

                               float farr []  =  {1.1f, 2.1f, 3.1f, 4.1f};

                               //                  0      1     2     3

                               

                              // display all values  "for each" loop

                               

                               for(float x  :farr)

                               {//  gets each values from float array and store into variable i.e x

                                              System.out.println("values from float array using for each loop="+ x);

                               }

               }

}

                

                             

o/p:      

values from float array using for each loop=1.1

values from float array using for each loop=2.1

values from float array using for each loop=3.1

values from float array using for each loop=4.1

                             

HW  store some values in long array and  gets all values using 'for each' loop?

HW  store some values in double array and  gets all values using 'for each' loop?

HW  store some values in char array and  gets all values using 'for each' loop?

HW  store some values in boolean array and  gets all values using 'for each' loop?

Display Values from String Array using for each loop:

package ArrayBasics;

public class StringgArrUsingForEachLoop {

               public static void main(String[] args) {

                              String sarr []  = {"Ram", "Sita", "Raju"};

                              //                  0       1       2

                              //Display Values from String Array using 'for each' loop:

                              for(String  eachVal  : sarr )

                              {

                                            

                                             System.out.println("values  from String array using for each loop="+  eachVal);

                              }

                              System.out.println("After for each loop");

               }

}

o/p:

values  from String array using for each loop=Ram

values  from String array using for each loop=Sita

values  from String array using for each loop=Raju

After for each loop

Note:

·  No Condition Required: In a for-each loop, there is no need to specify any condition. The loop automatically iterates through all elements.

·  No Index Required: You do not need to use an index number to access elements. The loop handles this internally.

·  Forward Direction: The loop retrieves values in a forward direction through the array or collection. It does not support iterating in reverse direction.

 

For Loop with Index:

·  Condition Required: You must specify a condition in a for loop to control the iteration.

·  Index Usage: To access values from an array, you need to use the index number, e.g., arr[0], arr[1].

·  Direction Flexibility: You can iterate through values in both forward and reverse directions using a for loop with index numbers.

 

Here’s a tabular comparison between the for loop with index and the for-each loop:

Feature

For Loop with Index

For Each Loop

Syntax

for(initialization; condition; increment/decrement) { ... }

for(datatype eachVal : arrVariableName) { ... }

Condition

Requires a condition to control the loop.

No condition is needed.

Index Usage

Uses an index to access array elements (e.g., arr[i]).

Does not use indices; directly accesses elements.

Direction

Can iterate in both forward and reverse directions.

Always iterates in forward direction.

Access to Index

Provides access to the current index of the array.

Does not provide access to the index.

Complexity

More complex; requires explicit handling of indices and conditions.

Simpler and more concise.

Use Case

Useful when the index is needed for calculations or operations.

Best used when you only need to access each element in sequence.

Modification of Array

Can modify elements of the array using index.

Cannot modify the array directly; used for read-only access.

Performance

Slightly more overhead due to index calculations.

Generally faster for simple iterations.

 

package ArrayBasics;

public class StringgArrUsingForEachLoop2 {

               public static void main(String[] args) {

                              String sArr []  = {"Ram", "Sita", "Raju"};

                              //                  0       1        2       

                              //Display Values from String Array using for each loop:

                              for(String x  :sArr)

                              {

                                             System.out.println("gets values from String array using for each loop:"+  x);

                              }

                              System.out.println("After for each loop");

                             

                              // display values in reverse order - for loop  but not for each loop

                              //   Raju  Sita Ram

                             

//                           for(int i=2;i>=0;i--)

                              for(int i=sArr.length-1;i>=0;i--)

                              {//       i=3-1            4>=0  true, enterd forloop

                                             //  arr[2]

                                             // arr [1]

                                             //  arr [0]

                                             System.out.println("get values from array in reverse direction ="+  sArr[i]);

                                             //                                                                 sArr[4]

                              }

               }

}

o/p:

gets values from String array using for each loop:Ram

gets values from String array using for each loop:Sita

gets values from String array using for each loop:Raju

After for each loop

get values from array in reverse direction =Raju

get values from array in reverse direction =Sita

get values from array in reverse direction =Ram

types of array:

1. single dimensional array

 

2. Multi dimensional array

 

1.single dimensional array  :

                               int arr[] =  new int[3];

           ( or) int [] arr = new int [3];

 

2.Two-Dimensional Arrays:

·        Represents a table with rows and columns

·        Each element can be accessed using two indices: row and column.

 

                              // Declare 2 dim array

                              data can be stored in the form of rows, columns m,n

                             

Syntax :  

datatype [] [] arrName = new dataType [m][n];

 (or) 

datatype  arrName [] [] = new dataType [m][n];

                              // m = no of rows  - Rowno no  varies from 0 - (m-1)

                              // n -no of columns- columms no varies  from 0 to (n-1)

 

 

package ArrayBasics;

public class TwoDimArr {

               public static void main(String[] args) {

                              // Declare 2 dim int -array  and store 2 rows and 3 columns

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

                               //  4   index no varies from  0- 3

                              // m = no of rows  - 2 respresents rows no  varies from 0 -1 (0 - 2-1=1)

                              // n -no of columns- 3  --  columms  varies from 0 to 2(0- 3-1=2)

                              //  store some value in 2 dim array

                             

                              //  0,0 , 0,1, 0.2

                              arr [0][0] = 00;

                              //  00 will be stored in arr at row no= 0  colno =0

                              arr [0] [1] = 01;

                              //                               row no =0  colno= 1

                             

                              arr [0] [2] =  02;

                             

                              // 1, 0    1,1   1,2

                              arr [1] [0] =  10;

                              arr [1] [1] =  11;

                              arr [1] [2] =  12;

                              // display val at index  0,0

                              System.out.println("display val at 0,0 cell =" + arr[0] [0]);

                              //                                                                                                                                                                                00 ---> 0

                              //display val at index  0,1

                              System.out.println("display val at 0,1 cell =" + arr[0] [1]);

                              //                                                                                                                                                                                 01 --> 1

                              //                                                         display val at index  10

                              System.out.println("display val at 1,0 cell =" + arr[1] [0]);

                              //                                                                                                                                                                                                               10

                             

                              //                                                         display val at index  11

                              System.out.println("display val at 1,1 cell =" + arr[1] [1]);

                              //                                                                                                                                                                                                11

                              // Hw display values 0,2

                             

                              //HW  display values 1,2

               }

}

o/p:

display val at 0,0 cell =0

display val at 0,1 cell =1

display val at 1,0 cell =10

display val at 1,1 cell =11

ex2: get all values from 2 dimensional array  using for loops

//                           00  01  02

//                           10  11  12

 

package ArrayBasics;

public class GetAllValsFrom2DimArrayUsingForLoops {

               public static void main(String[] args) {

                              // Declare 2 dim int- array of 2 rows and 2 columns

                              int arr[] []  = new int [2] [3];  //  4   index no varies from  0- 3

                                             // m = no of rows  - 2 respresents rows, index no  varies from 0 -1

                                             // n -no of columns- 3  --  columms , index -  0 to 2

                                             //  store some value       

                                             arr [0] [0] = 00;

                                             arr [0] [1] = 01;

                                             arr [0] [2]  = 02;

                                            

                                             // 10   1 1 ,  12

                                             arr [1] [0] = 10;

                                             arr [1] [1] = 11;

                                             arr [1] [2]  = 12;

                                                                          

                                                            // get all values from 2 dimensional array using  for loop

//                                          00  01  02

//                                          10  11  12

                                            

                                             for(int i=0;i<=1;i++) //  vary no of rows i=0, 0+1 =1, 1+1=2

                                             {//         0<=1, true,  it enters outer for loop

                                                            //      1<=1  true,  it enters outer for loop

                                                            //      2<=1 , false, ctrls goes after outer for loop

                                                           

                                                            for(int j =0;j<=2;j++) // to vary no of columns// j =0, 0+1=1, 1+1 =2, 2+1 =3

                                                            {//          0<=2, true ,it enters  inner for loop

                                                                           //       1<=2, true  ,it enters  inner for loop

                                                                           //       2<=2 , true ,,it enters  inner for loop

                                                                           //       3 <=2 , false ,  ctrl goes after inner for loop

                                                                           // arr [0][0] ,   arr [0] [1], arr [0] [2]

                                                                           System.out.println("values from 2 dim arr="+ arr[i][j]);

                                                                           //                                         arr[1][0] --> 10

                                                                           //                                          arr [1] [1]   -->11

                                                                           //                                              [1] [2] -->  12

                                                                          

                                                                           //  ctrl goes for increment

                                                            }// end of inner for loop

                                                           

                                                            //  ctrl will go to outer for loop

                                             }// end of outer for loop

               }

}

o/p:

values from 2 dim arr=0

values from 2 dim arr=1

values from 2 dim arr=2

values from 2 dim arr=10

values from 2 dim arr=11

values from 2 dim arr=12

 

// HW  Define  2 Dim float array of size 1 , 2   and store some values and display all values using for loop

// HW  Define  2 Dim String aray of size 3 , 4   and store some values and display all values using for loop

              

 

Getting Rows and Columns Count in a Two-Dimensional Array:

 

package ArrayBasics;

public class GetRowsColumnsCntFrom2DimArray {

               public static void main(String[] args) {

                              // Declare 2 dim  int array with 2 rows  cols= 3

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

//  1 dim arr-  int []  arr = new int [3];  length of array  -- > arr.length  = 3

 //  0 , 1 ,2

                              //  rows cnt  -- form 2 dim array

                              System.out.println("rows cnt  -- form 2 dim array  ="+  arr.length);

                                                                                                         //          rowsCnt =       2

                              // Columns cnt  form 2 dim array

                              System.out.println("Columns cnt  form 2 dim array ="+ arr[0].length);

                                                                                                                                                                                                                                 // 3

               }

}

                             

HW  use  rows cnt and columns cnt in for loop to display all values from 2 dim array ?

HW define int array of 3 rows and 2 columns, store some values, displays all values from 2 dim array using for loop?

HW define String array of 2 rows and 3 columns, store some values, displays all values from 2 dim array using for loop?

HW define char array of 1 row and 2 columns, store some values, displays all values from 2 dim array using for loop?

FAQ SearchForGivenNoInArray :

                              // check given no is exist in array or not

 

package ArrayBasics;

public class SearchForGivenNoInArray {

               public static void main(String[] args) {

                              // // check given no is exist in array or not

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

                              //            0   1  2  3

                              //check array contains 20 or not -->  display msg 'arr contains 20'

                              //  else  display msg "arr does not contain 20"

                              boolean flag = false;

                             

//                           int expectedNo =20;

                              int expectedNo =25;

                             

                              for(int i=0;i<=arr.length-1;i++) // i= 0, 0+1 =1, 1+1 =2, 2+1 =3, 3+1 =4

                              { //        0<=3 true, for loop

                                             //     1<=3 true , for loop

                                             //     2<=3 true, for loop

                                             //     3<=3 true , for loop

                                             //     4<=3 false,out of for loop

                                             //                                          System.out.println(arr[i]);

                                                                                          if(arr[i] == expectedNo )

//                                          if(arr[i] == 25 )

                                             {//  arr[0]  10 ==25 false,

                                                            //arr[1] 20 ==25 false

                                                            // arr[2] 30 == 25  false

                                                            // arr[3]  40 == 25  false

//                                                         System.out.println("arr contains "+expectedNo);//  displays

//                                                         System.out.println("I found"+expectedNo+"  value. so coming out of for loop");

                                                            flag = true;

                                                            break;

                                             }

                                             else

                                             {

//                                                         System.out.println("arr does not contain 20");

                                             }

                                             // ctrl - will go for increment

                              }// end of  for loop

                              if(flag == true)

                              {// false  true

                                             System.out.println("arr contains "+expectedNo);

                              }

                              else

                              {

                                             System.out.println("arr does not contains "+expectedNo);

                              }

                             

                              System.out.println("end of program");

               }

}

  

 

FAQ: WAP to Count Occurrences of a Given Character in a Char Array 

 char chArr []  = { 'r' , 'a', 'm','a'}

  'a'  char count - 2  times 

  'r'             -1   time

// Given char is not found ,   cnt =0

 

package ArrayBasics;

public class CharacterCntInArray {

               public static void main(String[] args) {

                             

                               char chArr []  = { 'r' , 'a', 'm','a'};

                               ///                 0     1    2   3

                               

//                           'a'  char count - 2  times 

//                             'r'             -1   time

                                                             // Given char is not found ,   cnt =0

//                           'Z' - cnt =0

                               

//                           char expectedChar = 'a';

//                           char expectedChar = 'r';

                               char expectedChar = 'Z';

                               int cnt =0;

                               

                               for(int i=0;i<=chArr.length-1;i++)// i=0, 0+1 =1, 1+1 =2, 2+1=3, 3+1 =4

                               {         // 0<=3 , true , for loop

                                              //       1<=3 , true . forloop

                                              //      2<=3 , true ,forloop

                                              //   3<=3 , true , for loop

                                              //    4<=3 , false., after for loop

                                             // System.out.println("values from array="+ chArr[i]);

                                              

                                              if(chArr[i] == expectedChar)

                                              { // charr[0] r == 'a',   false,ctrl goes after if block

                                                            // charr[1] a == 'a' , true , enters if block, increase the cnt by1

                                                             // charr[2] m == a,  false

                                                             // charr[3] a == a, true , enters if block

                                                            // increase the cnt by 1

                                                             cnt  = cnt +1;

                                                             //     1 + 1 = 2

                                                             //  cnt  =2

                                              }            

                                              //    ctrl goes for increment

                               }// end of for  loop

                               

                               // Display the cnt of given char

                               System.out.println("Expected char ="+ expectedChar + " count ="+ cnt);

                               //                                        a                        2

               }

}

FAQ // WAP  to get vowels count from char array ?

                              //  Vowels :  a e i o u

                             

                              char chArr []  = { 'r' ,'a', 'm','a','e','i'};

                              //  vowels cnt  = 4  -  cnt = 0 +1= 1 +1=2 +1=3 +1 =4

 

package ArrayBasics;

public class VowelCntInArray2 {

               public static void main(String[] args) {

                              char chArr []  = { 'r' ,'a', 'm','a','e'};

                              //                  0     1   2   3   4

                              //  vowels cnt  = 3  -  cnt = 0 +1= 1 +1=2 +1=3      

                             

                              int vowelsCnt = 0;

                             

                              for(int i=0;i<=chArr.length-1;i++)// i=0. 0+1=1, 1+1 =2, 2+1 =3, 3+1 =4, 4+1 =5

                              {         // 0<=4 , true , for loop

                                             //       1<=4 true, for loop

                                             //       2<=4 , true , for loop

                                             //      3<=4 , true for loop

                                             //      4<=4, true for loop

                                             //   5<=4  falsse, after forloop

//                                          System.out.println(chArr[i]);

                                            

                                             // check each char == vowel or not

                                             //     a ,e i , o ,u

                                             if(chArr[i]== 'a' || chArr[i] == 'e' || chArr[i] == 'i' || chArr[i] == 'o' || chArr[i] == 'u')

                                             {//  charr[4]          charr[1]

                                             //    e == a           e== e            e == i               e == o               e==u

                                                            // f     ||        tr        ||           f      ||     f       ||        f

                                                            //         true

                                                            vowelsCnt = vowelsCnt +1;

                                                            //            2+1 =

                                                            //  vowelsCnt =        3

                                             }             

                                            

                                             //   ctrl goes for increment

                              }

                             

                              // display the cnt after for loop

                              System.out.println("vowelsCnt ="+vowelsCnt);

                              //                                  3

                              //                                 

               }

}

HW Same program use 'for  each' loop and multiple if conditions

hint:      

                                             if(eachVal== 'a' )

                                             {

                                                            vowelsCnt =  vowelsCnt + 1 ;

                                             }

                                             if(eachVal== 'e'  )

                                             {

                                                            vowelsCnt =  vowelsCnt + 1 ;

                                             }

----------------

HW FAQ  WAP to get consonants count from char array ?

      r a m a

consonants cnt  = 2

HW  same program use 'for each' loop ?

No comments:

Post a Comment

git commands MCQ

 Here are some multiple-choice questions (MCQs) on Git commands relevant for Selenium: 1. Which Git command is used to clone a remote reposi...