473,378 Members | 1,369 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,378 developers and data experts.

Repetition or Iteration

1,510 Expert 1GB
Repetition or Iteration

The third control structure allows us to repeat parts of a program. The first form is
Expand|Select|Wrap|Line Numbers
  1.   while (some condition) do something
Where the condition is written using comparison operators.

e.g. print a line of *
Expand|Select|Wrap|Line Numbers
  1.  
  2.   public class Line
  3.      {
  4.      public static void main(String argv[])
  5.        {
  6.        int i=5;
  7.        while (i>0)
  8.          {
  9.           System.out.print('*');
  10.           i--;
  11.          }
  12.        System.out.println();
  13.        }
  14.      }
  15.  
A loop may contain any code required, including another loop with each level of nesting is indented further so that the structure is immediately visible.

e.g. A nested loop that will print the pattern
****
***
**
*
Expand|Select|Wrap|Line Numbers
  1.     int linecount = 4;
  2.     while (linecount>0)
  3.     {
  4.       int starcount = linecount;
  5.       while (starcount>0)
  6.       {
  7.         System.out.print("*");
  8.         starcount--;
  9.       }
  10.       System.out.println();
  11.       linecount--;
  12.     }
  13.  
A loop has several distinct parts: initialisation (linecount = 4), condition (linecount>0), loop body and 'housekeeping' (linecount--).

A shorthand form exists: the for loop
Expand|Select|Wrap|Line Numbers
  1.   for(initialisation;condition;housekeeping)
(1) Initialisation is done before the loop starts, then the condition is tested.
(2) Following that the loop body is executed and then the housekeeping is done, followed by the test again.

e.g. to display a block of *'s
Expand|Select|Wrap|Line Numbers
  1.  
  2.   public class Block1
  3.     {
  4.      public static void main(String argv[])
  5.        {
  6.         for (int i=5;i>0;i--)
  7.           {
  8.            for (int j=4;j>0;j--)
  9.                System.out.print('*');
  10.            System.out.println();
  11.           }
  12.        }
  13.     }
  14.  
The do loop
The condition is tested at the end of the loop: a useful structure for the times when a loop body must always be done at least once.

For example, the value epsilon is specified thus:
Expand|Select|Wrap|Line Numbers
  1.     1.0 + epsilon != 1.0
  2.  
The value of epsilon is the smallest number which, when added to the value 1.0, changes the value, i.e. adding any smaller value to 1.0 still gives 1.0. A pseudo-code version of the algorithm often used to calculate the values of epsilon is:
Expand|Select|Wrap|Line Numbers
  1.     epsilon = 1.0
  2.     do
  3.         epsilon = epsilon / 2.0
  4.     while ( 1.0 + epsilon != 1.0 )
  5.     epsilon = 2.0 * epsilon
  6.  
which can be implemented in Java using a do loop
Expand|Select|Wrap|Line Numbers
  1. public class epsilon
  2. {
  3.   public static void main(String s[])
  4.    {
  5.     float epsilon = 1.0f;
  6.  
  7.     do
  8.         epsilon = epsilon / 2.0f; 
  9.     while ((1.0f + epsilon) != 1.0f);
  10.     System.out.println("  float epsilon calculated  = " + epsilon * 2.0f);
  11.    }
  12. }
Apr 11 '07 #1
0 5137

Sign in to post your reply or Sign up for a free account.

Similar topics

35
by: Raymond Hettinger | last post by:
Here is a discussion draft of a potential PEP. The ideas grew out of the discussion on pep-284. Comments are invited. Dart throwing is optional. Raymond Hettinger ...
2
by: Abdullah Khaidar | last post by:
Is there any iteration style we must use to get faster processing time? I've tried with some style to concat number in list. But I still don't know which one is the recommended style. >>> def...
1
by: Chris Gamache | last post by:
For my particular case, word repetition shouldn't be relevant in determining the rank of a document. If I strip() the vector, I loose what relevance proximity and weight add to the rank. It seems...
75
by: Sathyaish | last post by:
Can every problem that has an iterative solution also be expressed in terms of a recursive solution? I tried one example, and am in the process of trying out more examples, increasing their...
6
by: udhas | last post by:
Write a program that prints the following diamond shape. You may use output statements that print a single asterisk (*), a single space or a single carriage return. Maximize your use of repetition...
4
by: mj.clift | last post by:
Hi All, I need to be able to choose a random string from an array. That is easy enough, but I want to restrict the repetition of that string until one or two other choices have been made. So the...
4
by: XpatienceX | last post by:
Hi, Can someone help me with this assignment, I am confused of what is needed to be done here. I am suposed to design a program that models a worm's behavior in the following scenario: A...
5
by: NATHAN1511 | last post by:
How To Write A Program By Using Repetition Structure As Show Below: 1 12 123 1234 12345
15
by: Beany | last post by:
Hi All, i need help with the following: i need to write a simple program that asks the user to input a number (minimum of 3 digits), which i seperate into individual digits and print the 1st...
3
by: anizatie | last post by:
if i wanna do some programming lets say... i hv a=a+3*a*(1.0^-10) how to generate the answer if a=(1.0^-10) ive done but wen i compared the answer using calculator..the answer is...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.