Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Jan 3rd, 2008, 4:26 AM   #1
namsu
Newbie
 
Join Date: Jan 2008
Posts: 15
Rep Power: 0 namsu is on a distinguished road
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
namsu is offline   Reply With Quote
Old Jan 3rd, 2008, 5:14 AM   #2
Klipt
Hobbyist Programmer
 
Join Date: Dec 2005
Posts: 118
Rep Power: 0 Klipt is an unknown quantity at this point
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.
Klipt is offline   Reply With Quote
Old Jan 3rd, 2008, 5:22 AM   #3
namsu
Newbie
 
Join Date: Jan 2008
Posts: 15
Rep Power: 0 namsu is on a distinguished road
Re: Array with For Loop

Quote:
Originally Posted by Klipt View Post
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.
namsu is offline   Reply With Quote
Old Jan 3rd, 2008, 8:14 AM   #4
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 1,890
Rep Power: 5 Sane will become famous soon enough
Send a message via MSN to Sane
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?

Last edited by Sane; Jan 3rd, 2008 at 8:31 AM.
Sane is offline   Reply With Quote
Old Jan 3rd, 2008, 9:01 AM   #5
namsu
Newbie
 
Join Date: Jan 2008
Posts: 15
Rep Power: 0 namsu is on a distinguished road
Re: Array with For Loop

Quote:
Originally Posted by Sane View Post
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.
namsu is offline   Reply With Quote
Old Jan 3rd, 2008, 9:17 AM   #6
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 1,890
Rep Power: 5 Sane will become famous soon enough
Send a message via MSN to Sane
Re: Array with For Loop

Quote:
Originally Posted by namsu View Post
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:

Java Syntax (Toggle Plain Text)
  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.
Sane is offline   Reply With Quote
Old Jan 3rd, 2008, 9:55 AM   #7
namsu
Newbie
 
Join Date: Jan 2008
Posts: 15
Rep Power: 0 namsu is on a distinguished road
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
namsu is offline   Reply With Quote
Old Jan 3rd, 2008, 9:58 AM   #8
Jessehk
The Oblivious One
 
Jessehk's Avatar
 
Join Date: May 2005
Location: Ontario, Canada
Posts: 644
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
Old Jan 3rd, 2008, 10:32 AM   #9
namsu
Newbie
 
Join Date: Jan 2008
Posts: 15
Rep Power: 0 namsu is on a distinguished road
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.
namsu is offline   Reply With Quote
Old Jan 3rd, 2008, 5:56 PM   #10
mrynit
Hobbyist Programmer
 
mrynit's Avatar
 
Join Date: Mar 2006
Location: WA, USA
Posts: 332
Rep Power: 3 mrynit is on a distinguished road
Send a message via AIM to mrynit Send a message via MSN to mrynit Send a message via Yahoo to mrynit Send a message via Skype™ to mrynit
Re: Array with For Loop

Quote:
Originally Posted by Jessehk View Post
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. }
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.
__________________
i dont know much about programming but i try to help
mrynit is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
dynamic array help quickster12 C++ 4 Nov 29th, 2007 11:52 PM
problem processing file into a char array csrocker101 C++ 1 May 8th, 2007 11:50 PM
changing size of an array Eric the Red Java 3 Apr 3rd, 2006 8:19 PM
Installing IPB 2.03 bh4575 Other Web Development Languages 0 Apr 23rd, 2005 2:36 AM
Converting 1-dimensional array to 2-dimensional array Tazz_Mission_13 Java 6 Apr 8th, 2005 11:58 AM




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 3:26 PM.

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