for Loops to Count 

Use a for loop if your program needs to count from one specific number to another.  For example, use for loops to count through the items in an array.

Be careful to use the correct comparison for stopping the loop, and remember that this must fit sensibly with the increment (counting) command.

Trace these loops and state what will be printed.

   int[]  ages = (15, 10, 20, 5, 8);

   int sum = 0;
   for(int c=0; c < 4; c = c+1)
   {   sum = sum + ages[c]; }
   output(sum);

   for(int x=10; x <= 100; x = x+20)
   {  output( x ); }

   for(int n=10; n > 0;  n = n/2)
   {  output( n ); }

Solution

   50 , because it only adds up #0 + #1 + #2 + #3 ... it stops at c = 3

   10 , 30 , 50 , 70 , 90   ...  it doesn't print 100 because it misses 100

    10 , 5 , 2 , 1  ==>  10 .... 10/2 = 5 ....  5/2 = 2 (truncates) ...  2/2 = 1
                                 ...  1/2 = 0 (truncates) but does not print because not > 0