Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Java (http://www.programmingforums.org/forum17.html)
-   -   Array with For Loop (http://www.programmingforums.org/showthread.php?t=14857)

namsu Jan 3rd, 2008 4:26 AM

Array with For Loop
 
I have a problem understanding how arrays are working when using the for loop. I am confused as to how lines 23-24 are working, how the stars are being printed. Because the statement says if the stars are less than the value of the one in the index using the counter variable, then increment (stars++). Does that not increment stars by one every time, how does the star get printed when a number like 4 gets read out of the index in the array. I just cant seem to get my head round on what variable it is applying it to. If someone is kind of enough to help me out in understanding please help. Thank you very much.

:

Figure 7.6. Bar chart printing program.
 1  // Fig. 7.6: BarChart.java
 2  // Bar chart printing program.
 3
 4  public class BarChart
 5  {
 6    public static void main( String args[] )
 7    {
 8        int array[] = { 0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1 };
 9
10        System.out.println( "Grade distribution:" );
11
12        // for each array element, output a bar of the chart
13        for ( int counter = 0; counter < array.length; counter++ )
14        {
15          // output bar label ( "00-09: ", ..., "90-99: ", "100: " )
16          if ( counter == 10 )
17              System.out.printf( "%5d: ", 100 );
18          else
19              System.out.printf( "%02d-%02d: ",
20                counter * 10, counter * 10 + 9 );
21
22          // print bar of asterisks                             
23          for ( int stars = 0; stars < array[ counter ]; stars++ )
24              System.out.print( "*" );                           
25
26          System.out.println(); // start a new line of output
27        } // end outer for
28    } // end main
29  } // end class BarChart


Klipt Jan 3rd, 2008 5:14 AM

Re: Array with For Loop
 
:

for (int stars = 0; stars < array[counter]; stars++)
        System.out.print("*");

is equivalent to
:

int stars = 0;
while (stars < array[counter])
{
        System.out.print("*");
        stars++;
};


(except that the scope of 'stars' is limited to the inside of the for loop in the first case).

'stars' is just a counter that keeps track of how many stars you've printed. Once it reaches array[counter], you print a newline and move to the next index in the array.

namsu Jan 3rd, 2008 5:22 AM

Re: Array with For Loop
 
Quote:

Originally Posted by Klipt (Post 139045)
:

for (int stars = 0; stars < array[counter]; stars++)
        System.out.print("*");

is equivalent to
:

int stars = 0;
while (stars < array[counter])
{
        System.out.print("*");
        stars++;
};


(except that the scope of 'stars' is limited to the inside of the for loop in the first case).

'stars' is just a counter that keeps track of how many stars you've printed. Once it reaches array[counter], you print a newline and move to the next index in the array.

The output of the program is:


Grade distribution:
00-09:
10-19:
20-29:
30-39:
40-49:
50-59:
60-69: *
70-79: **
80-89: ****
90-99: **
100: *

I understand the counter part of the for loop. But I do not understand how the stars are being calculated from the array in order to be printed. It seems weird that the stars increments by 1 every time, how does the star for loop pick up that the numbers in the index of an array and print the star for that. Thanks for the help. This is very confusing.

Sane Jan 3rd, 2008 8:14 AM

Re: Array with For Loop
 
I see where your difficulty lies. I had to blink a couple times before seeing what was happening. I'll try to explain.

:

int array[] = { 0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1 };

As you know, that's the input of the grade distribution.

In the first for loop, the variable "counter" starts at 0, and loops until it's through to the end of array[].

:

for ( int counter = 0; counter < array.length; counter++ )

So let's try to calculate the grade distribution of the 9th item. That means we're on the for loop's 9th iteration... also known as the 8th index. Which contains the value, 4.

The counter will equal 8 at this point.

So what happens when we get to this code?

:

for (int stars = 0; stars < array[counter]; stars++)
        System.out.print("*");


If you go back to the first line I posted:

:

array[counter] = array[8] = 4

So array[counter] = 4 at this point in time, and the code becomes interpreted as:

:

for (int stars = 0; stars < 4; stars++)
        System.out.print("*");


The variable "stars", starts at 0, and iterates as long as its less than 4. Therefore, the second for loop will iterate 4 times, printing out a star each time.

:

****

Voila.

Does that helps you understand what's happening?

namsu Jan 3rd, 2008 9:01 AM

Re: Array with For Loop
 
Quote:

Originally Posted by Sane (Post 139050)
I see where your difficulty lies. I had to blink a couple times before seeing what was happening. I'll try to explain.

:

int array[] = { 0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1 };

As you know, that's the input of the grade distribution.

In the first for loop, the variable "counter" starts at 0, and loops until it's through to the end of array[].

:

for ( int counter = 0; counter < array.length; counter++ )

So let's try to calculate the grade distribution of the 9th item. That means we're on the for loop's 9th iteration... also known as the 8th index. Which contains the value, 4.

The counter will equal 8 at this point.

So what happens when we get to this code?

:

for (int stars = 0; stars < array[counter]; stars++)
        System.out.print("*");


If you go back to the first line I posted:

:

array[counter] = array[8] = 4

So array[counter] = 4 at this point in time, and the code becomes interpreted as:

:

for (int stars = 0; stars < 4; stars++)
        System.out.print("*");


The variable "stars", starts at 0, and iterates as long as its less than 4. Therefore, the second for loop will iterate 4 times, printing out a star each time.

:

****

Voila.

Does that helps you understand what's happening?

Thanks alot that was a very good way to explain the code. I got one more question. When we have a nested for loop, does that loop keep track of the variable during each iteration or does it reset again? Thanks ever so much everyone.

Sane Jan 3rd, 2008 9:17 AM

Re: Array with For Loop
 
Quote:

Originally Posted by namsu (Post 139053)
Thanks alot that was a very good way to explain the code. I got one more question. When we have a nested for loop, does that loop keep track of the variable during each iteration or does it reset again? Thanks ever so much everyone.

It would work as it should if you were to follow through step by step. For example, you could try running this code:

:

  1. for ( int counter = 0; counter < 5; counter++ )
  2. {
  3.     for ( int stars = 0; stars < 2; stars++ )
  4.     {
  5.         System.out.printf( "%d %d", counter, stars );           
  6.         System.out.println();
  7.     }
  8. }


That should output:
:

0 0
0 1
1 0
1 1
2 0
2 1
3 0
3 1
4 0
4 1


That should hopefully answer your question.

Edit: I apologize if any of my syntax or anything is wrong. I've never used Java before. I'm only rearranging pieces from your post based intuitively on how things work in other languages.

namsu Jan 3rd, 2008 9:55 AM

Re: Array with For Loop
 
I have one quick question, when the prefix increment operator is used before accessing the index of that array, what is it supposed to do, shift the index by one? Thanks for the help.

:

3  import java.util.Random;
 4
 5  public class RollDie
 6  {
 7    public static void main( String args[] )
 8    {
 9        Random randomNumbers = new Random(); // random number generator
10        int frequency[] = new int[ 7 ]; // array of frequency counters
11
12        // roll die 6000 times; use die value as frequency index
13        for ( int roll = 1; roll <= 6000; roll++ )
14          ++frequency[ 1 + randomNumbers.nextInt( 6 ) ];
15
16        System.out.printf( "%s%10s\n", "Face", "Frequency" );
17
18        // output each array element's value
19        for ( int face = 1; face < frequency.length; face++ )
20          System.out.printf( "%4d%10d\n", face, frequency[ face ] );
21    } // end main
22  } // end class RollDie


Jessehk Jan 3rd, 2008 9:58 AM

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. :)

:

  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:
:

  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:
:

  1. int array[] = { 1, 1, 1 };


Doing this:
:

  1. ++array[0];


Will result in an array that looks like this:
:

  1. { 2, 1, 1 }


namsu Jan 3rd, 2008 10:32 AM

Re: Array with For Loop
 
I wasn't even looking at the inner for loops properly. Thanks everyone that really helped alot for my understanding in arrays.

mrynit Jan 3rd, 2008 5:56 PM

Re: Array with For Loop
 
Quote:

Originally Posted by Jessehk (Post 139057)
Alternatively, depending on the version of Java you have installed, you can iterate through an array like this:
:

  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. }


That is called an enhanced for loop or for each loop. It is new to Java 5 and is not reverse compatible with older versions of java.


All times are GMT -5. The time now is 12:32 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC