0% found this document useful (0 votes)
8 views3 pages

Array Basics - 2

Uploaded by

bookit
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)
8 views3 pages

Array Basics - 2

Uploaded by

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

Array-Loop-if statement

Maximum Number in an Array:

Step 1: Initialize integer variable for storing maximum Element (int max;)

Step 2: Load max variable with the first element in array.

Step 3: Compare max with each and every array element, this can be achieved
using for loop and If statement .

int[] array={1,55,95,33,44,62};// Array


int max=array[0];//Max
for(int i=0;i<array.length;i++){
if(max<array[i]) //Comparing array elements with max
max=array[i]; // if its true max is loaded with array element
}
System.out.println(“Maximum Value in Array is:”+max);

Minimum Number in an Array:


Similarly ,
int[] array={1,55,95,33,44,62};// Array
int max=array[0];//Max
for(int i=0;i<array.length;i++){
if(max<array[i]) //Comparing array elements with max
max=array[i]; // if its true max is loaded with array element
}
System.out.println(“Maximum Value in Array is:”+max);
If Index is different then how to use the for loop:
[Note: This is possible solution .You can have different solution also]

For Example: Except the ‘5’ in the given Array is to be copied in the new array
with the reduced length.

Step 1: Count Number of ‘5’ in the given array.


Step 2: Create a new array with the length=given array length-count
Step 3: copy the elements from the given array to new array, initialize the
variable to point for the new array as follows.

int[] array={5,88,99,5,1,7}
int count=0;// for storing number of ‘5’ in given array
for(int i=0;i<array.length;i++){
if(array[i]==5)
count++;
}
int resultlength=array.length-count;// Result array length
int[] result=new int[resultlength];// initializing result array
int k=0;// pointer for result array
for(int i=0;i<array.length;i++){
if(array[i]!=5){
result[k]=array[i];
k++;}
System.out.println(result[k]+”,”);
}
Sorting:
Ascending order:
{5,6,1,3}
Sorting as follows
Each element should be compared with the other elements an interchange the
positions. So it can be achieved using two for loop as follows.
First element in the array is 5 is compared with all array elements as
If any array element is less then the array element are exchanged.

int[] array={5,6,1,3}
int temp=0;
for(int i=0;i<array.length;i++){// one element is taken
for(int k=i;k<array.length;k++) { //from that element the comparison is
started till the end length
if(array[i]>array[k]){
temp=array[i];
array[i]=array[k];
array[k]=temp;
}
}

You might also like