473,546 Members | 2,644 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Repetition or Iteration

1,510 Recognized Expert Top Contributor
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 5148

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

Similar topics

35
3703
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 ------------------------------------------------------------- PEP: 323
2
2066
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 useListIteration(): list = result = "" for item in list: result += item return result
1
1939
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 impossible, yet I ask anyway: Is it possible to eliminate the second (third, fourth, fifth, etc.) occurrence of any given word when its presence in...
75
5563
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 complexity as I go. Here's a simple one I tried out: #include<stdio.h> /* To compare the the time and space cost of iteration against
6
34221
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 (with nested For … Next statements) and minimize the number of output statements. * *** ***** ******* ********* ******* *****
4
2985
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 following output would be ok a,b,c,a,d,c or a,c,d,a,d,a but the following would not; a,b,c,c, or a,b,b,c, etc... I hope that makes sense. If it...
4
5393
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 worm is moving toward an apple. each time it moves, the worm cuts the distance between itself and the apple by its own body lenght until the worm is...
5
3049
by: NATHAN1511 | last post by:
How To Write A Program By Using Repetition Structure As Show Below: 1 12 123 1234 12345
15
3061
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 digit 1 time, 2nd digit 2 times, 3rd digit 3 times and so forth... I cannot get the last bit working, what bit of code can i use for the repetition...
3
1350
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 wierd..they r not same.. i used "for" repetition..
0
7504
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7435
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7694
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7461
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6026
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5080
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3470
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1046
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
747
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.