View Single Post
Old Jan 3rd, 2008, 10:58 AM   #8
Jessehk
The Oblivious One
 
Jessehk's Avatar
 
Join Date: May 2005
Location: Ontario, Canada
Posts: 648
Rep Power: 4 Jessehk is on a distinguished road
Re: Array with For Loop

I've annotated the source. I don't know if will be helpful at all (Sane seems to have covered it fine), but it couldn't hurt.

java Syntax (Toggle Plain Text)
  1. public class BarChart {
  2. public static void main( String[] args ) {
  3. int array[] = { 0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1 };
  4.  
  5. System.out.println( "Grade distribution: " );
  6.  
  7. // For every element in the array...
  8. for ( int counter = 0; counter < array.length; counter++ ) {
  9. if ( counter == 10 )
  10. System.out.printf( "%5d: ", 100 );
  11. else
  12. System.out.printf( "%02d-%02d: ", counter * 10, counter * 10 + 9 );
  13.  
  14. // A helper variable to make things easier to understand.
  15. int gradeFreq = array[counter];
  16.  
  17. // print a star "gradeFreq" times
  18. for ( int i = 0; i < gradeFreq; i++ )
  19. System.out.print( "*" );
  20.  
  21. // Print a new line to seperate the bars
  22. System.out.println();
  23. }
  24. }
  25. }

Alternatively, depending on the version of Java you have installed, you can iterate through an array like this:
java Syntax (Toggle Plain Text)
  1. public class Foreach {
  2. public static void main( String[] args ) {
  3. int[] array = { 1, 2, 3, 4, 5 };
  4.  
  5. // Print out every element of the array
  6. for ( int element : array ) {
  7. System.out.println( element );
  8. }
  9. }
  10. }

EDIT: In reply to your second question, given:
java Syntax (Toggle Plain Text)
  1. int array[] = { 1, 1, 1 };

Doing this:
java Syntax (Toggle Plain Text)
  1. ++array[0];

Will result in an array that looks like this:
java Syntax (Toggle Plain Text)
  1. { 2, 1, 1 }
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS!
Jessehk is offline   Reply With Quote