Posted by: ahmedashfaque | March 8, 2015

Why Java is so popular? Part 8


So far in part 1, part 2, part 3, part 4, part 5, part 6 and part 7 we have covered many topics on Java. In this post we will see arrays.

Arrays are a special variable to hold a list of values. For example if you want to hold price list of goods which are selling at the local grocery shop then you can put the price list in an array. The benefit is that if you want to do a central processing of these values then you can do it without defining further variables for computation. Like if you want to know how many items are there in the list or what is the total value of all items in the list or what is the minimum value in the list then you can simply count the number of items in the list.

Let us see one piece of code.

public class myArray {

public static void main(String[] args) {
double[] groceryList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements
for (int i = 0; i < groceryList.length; i++) {
System.out.println(groceryList[i] + ” “);
}
// Summing all elements
double total = 0;
for (int i = 0; i < groceryList.length; i++) {
total += groceryList[i];
}
System.out.println(“Total is ” + total);
// Finding the largest element
double max = groceryList[0];
for (int i = 1; i < groceryList.length; i++) {
if (groceryList[i] > max) max = groceryList[i];
}
System.out.println(“Max is ” + max);
}
}

 

Let us analyze the code. We have declared an array groceryArray of length 4. So there are 4 item values stored in the Array 1.9, 2.9, 3.4, 3.5. Using a loop we print all values in the list by iterating each element in the array and printing the element value. In the next operation, we added all values of array elements using a loop and adding each element in each iteration of the loop. The final operation we did was to find out which array element has the highest value. Again we used a loop and iterating through the loop to find out if any element has higher value than value of previous element.

Advertisements

Responses

  1. […] far in part 1, part 2, part 3, part 4, part 5, part 6, part 7 and part 8 we have covered many topics on Java. In this post we will see loop […]

  2. […] far in part 1, part 2, part 3, part 4, part 5, part 6, part 7, part 8 and part 9 we have covered many topics on Java. In this post we will see nested if […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: