iteration through a loop - java

Lets assume n=20
so after every 6 iterations I will do some processing
int i=0
for (t=6;t<20;t=t+6){
while(i<=t){
will do some processing
i++;
}
}
In the above code it will terminate when t=18, but I want to continue until 20.
How to do that ?

You are increasing the t variable 6 units... the last condition that satisfies the t<20 is when t = 18.
instead of doing t+=6 do a normal t++ and play with the modulo %6
example:
public static void main(String[] args) {
int n = 20;
for (int i = 0; i < n; i++) {
//TODDY
insert your while in here depending on when that must be executed
if (i % 6 == 0) {
System.out.println("am on a 6 modulo step..." + i);
} else {
System.out.println("foo#" + i);
}
}
System.out.println("done");
}

The behaviour is correct only.. Still if you want to perform any operation, do it after the condition is met, try below snippet:
int i = 0, n = 20;
do{
i += 6;
System.out.println(i);
} while (i < n);
System.out.println(i);

your code is not doing something every 6th iteration, but instead you are doing (n - n%6) times. your "will do some processing" is inside the while. If you add a print (or debug) there you will notice it; on the n=20 example the while will be executed 18 times; it will do something 18 times.
if you want to execute every 6th iterations, and include one extra for the cases that are not exactly divisible by 6, then you could do:
if (n == 0) {
return;
}
int number_iterations = n/6 + (n%6!=0 ? 1:0);
for (int i=0; i<number_iterations; i++) {
// do something
}
That covers what you requested; if not, pls edit question to be more clear on your exact needs.

Related

Looping through a list - when index reaches end, start from 0

I want to understand the logic of looping through a list. When I reach the end of list, I want the index to start from 0 again. The list is running in a loop and termination will happen, so it will not be an infinite loop.
I have seen solution using % operator but I don't understand it. Something like below but with % instead. I want to understand how that will work.
for(int i = 0; i < n; i++) {
if(i == n - 1) { i = 0; }
}
The modulo operator % is the remainder after a division.
Given two positive numbers, a and n, a % n is the remainder of the Euclidean division of a by n, where a is the dividend and n is the divisor.
You said you have a list, if you use % list.length() this will give you values from 0 to list.length().
See the following code:
List<String> list = new ArrayList<String>();
list.add("first");
list.add("second");
list.add("third");
for (int i = 0; i < 10; i++) {
System.out.println("element: " + list.get(i % list.size()));
}
this outputs:
element: first
element: second
element: third
element: first
element: second
element: third
element: first
element: second
element: third
element: first
You can check it working here.
You can increment the counter by 1 and take the remainder of that divided by the size of the list. The % operator in Java takes the remainder after dividing by a number i.e., a % b returns the remainder when a is divided by b. Ergo, when the counter reaches the list's size, the remainder will be zero and it will be reset to 0; when the counter is less than the list's size, the remainder when divided by the size will be the counter itself.
for(int i = 0, size = list.size(); ; i = (i + 1) % size){
//do something; add terminating condition
}
See also: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
You can do something like this:
// Will be an infinite loop
for(int i = 0; i < n; i++) {
if(i == n - 1) { i = 0; }
}
% gives you the remainder of a division.
10%2 == 0 // 10/2 = 5
10%3 == 1 // 10/3 = 3 and remainder 1
With % you can do something like this:
// Will be an infinite loop
for(int i = 0; i < n; i++) {
if(i == n - 1) { i = i%(n-1); }
}
package testproj;
import java.util.ArrayList;
import java.util.List;
public class ListLoop {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("string1");list.add("string2");list.add("string3");
int j=0; //loop braking.
for (int i=0;i<=list.size();i++) {
if (i == list.size()) {
i=0;
}
//This will go infinite loop. need a way to break the loop.
//Below is just demonstration.
j++;
if (j==10) break;
System.out.println("Do something with " + list.get(i));
}
}
}

Algorithm output to length starts new line

I am trying to format the output from what I have written to display a list of primes (Eratosthenes) to a certain number results per line. Do they need to placed into an Array to accomplish this? I have not come across a way to implement their division besides .split("");, which would render a single line for each and the Oracle site's System.out.format(); argument index to specify length. Yet, these require the characters to be known. I am printing it with the following, which of course creates an infinite line.
for (int count = 2; count <= limit; count++) {
if (!match[count]) {
System.out.print(count + ", ");
}
}
Is there a way to simply call System.out.print("\n"); with an if(...>[10] condition when System.out.print() has run for instance 10 times? Perhaps I am overlooking something, relatively new to Java. Thanks in advance for any advice or input.
By using a tracker variable, you can keep track of how many items have been displayed already so you know when to insert a new line. In this case, I chose 10 items. The exact limit is flexible to your needs.
...
int num = 0;
//loop
for(int count = 2; count <= limit; count++)
{
if(!match[count])
{
if (num == 10) { System.out.print("\n"); num = 0; }//alternatively, System.out.println();
System.out.print(count + ",");
num++;
}
}
...
You can just simply create some int value e.g.
int i = 1;
...and increment it's value everytime Sysout is running.
Something like this:
int i = 1;
for (int count = 2; count <= limit; count++) {
if (!match[count]) {
if (i%10 == 0)
System.out.print(count+ "\n");
else
System.out.print(count + ", ");
i++;
}
}
Try this:
int idx=1;
int itemsOnEachLine=10;
for(int count = 2; count <= limit; count++)
{
if(!match[count])
{
System.out.print(count+(idx%itemsOnEachLine==0?"\n":","));
idx++;
}
}
you go increasing a counter (idx) along with every write, every 10 increments (idx modulus 10 == 0), you will be printing a new line character, else, a "," character.

Numbers from 1 to 30 indivisible by 3

So I started learning Java only a few days ago and I'm doing really well except for this one exercise that boggles my mind. So the exercise is to "Write a program which displays all numbers from 1 to 30 indivisible by 3". So this is easy:
class numbers {
public static void main (String args[]) {
for (int i = 0; i <=30; i++){
switch(i % 3){
case 0 :
break;
default :
System.out.println(i);
break;
}
}
}
}
Except one of the variants says "use break after divisibility by 3 is detected. Now I'm not sure if hte break used in the code above is correct, as it is a part of switch. I was wondering if there was an other way to do it.
Some fixes:
class names should start with Upper letter, name class Numbers, not numbers
start iterating from 1, not from 0, because you are displaying numbers in range [1..30].
Because here you have only 2 possibilities (is or is not indivisible), replace switch with if statement. Switch is more suited for a large range of conditions.
Most important. Using break will make you get out of the loop. Using continue will skip this loop and go to next iteration.
So now your code should look shorted and cleaner:)
class Numbers {
public static void main (String args[]) {
for (int i = 1; i <=30; i++){
if(i % 3 == 0){
continue;
}
System.out.println(i);
}
}
}
}
Or you could go with shorter version:
for (int i = 1; i <=30; i++){
if(i % 3 != 0){
System.out.println(i);
}
}
Another short solution.
As we know that from 1 to 30 there are only 10 numbers divisible by 3, we make ten loops to print them all.
for (int i = 1; i <= 30; ++i) {
System.out.printf("%d%n%d%n", i++, i++);
}
The idea is to print the two numbers before the one which is divisible by 3 and skip the one which is divisible.
the counter i starts at 1
the first %din System.out.printf prints current i (i=1) and increase it by 1 (i=2)
the second %din System.out.printf prints current i (i=2) and increase it by 1 (i=3)
the end condition of the for-loop increase i by 1 (i=4)
repeat till the end condition i <= 30 is false
edit A more readable version (as proposed by ajb)
for (int i = 1; i <= 30; i += 3) {
System.out.printf("%d%n%d%n", i, i + 1);
}
The code is OK - if i % 3 results in 0, nothing is printed. Since there are only two possiblities I would rewrite as if-statement:
if( ( i % 3 ) != 0 )
{
System.out.println( i );
}
Is in my opinion better readable and conveys the intent more clearly.
More on the actual statement:
switch( i % 3 )
{
case 0:
//do nothing
break; // leave switch - statement
...
}
The break is needed to leave the switch statement. So yes, it is necessary.

Choose to loop infinitely if a number equals 0 or loop until some number if that number is greater than 0 - Java

I want to loop infinitely using a for loop if a number equals 0, and loop until that number number if the number is greater than 0. Here's the code to help visual what I'm getting at.
for (int i = 0; i < this.getNumRounds(); i++) {
// 30 some lines of code
}
or
for ( ; ; ) {
// 30 some lines of code
}
if getNumRounds() is greater than 0, do the first loop, if it equals 0, do the second. I would prefer to do this without copying and pasting my 30 some lines of code twice and using an if statement seeing as the code is redundant, though I could use a function to take out that redundancy, but I'm looking to see if there's another option.
Use the powerful ternary operator:
for (int i = 0; this.getNumRounds() == 0 ? true : i < this.getNumRounds(); i++) {
// 30 some lines of code
}
As noted in the comments by yshavit, there is a shorter, cleaner way of expressing this:
for (int i = 0; this.getNumRounds() == 0 || i < this.getNumRounds(); i++) {
// 30 some lines of code
}
Have you thought about using a while loop instead?
int i = 0;
while(i < this.getNumRounds() || this.getNumRounds() == 0) {
//some 30 lines code
i++
}
So you want something like this:
int num = //whatever your number equals
if (num == 0) {
boolean running = true;
while (running) {
doLoop();
}
} else {
for (int i = 0; i < num; i++) {
doLoop();
}
}
private void doLoop() {
//some 30 lines of code
}
This code puts the contents of the loop in a separate method and checks if the number is equal to 0. If it is, the program runs the doLoop() method forever. Otherwise, it runs until i equals the number.
While it would be better to just create a method and use an if-statement you could add an if statement inside the for-loop to decrease i every iteration. It would look like:
for (int i = 0; i <= this.getNumRounds(); i++) {
if(this.getNumRounds() == 0){
i--;
}
// 30 some lines of code
}
Notice I changed i < this.getNumRounds() to i <= this.getNumRounds. This way if the number of rounds is zero then the loop will be called.
You could do the following.
for (int i = 0; i < this.getNumRounds() || i == 0; ++i) {
do {
// 30 lines of code
} while (this.getNumRounds() == 0);
}
If getNumRounds is non-trivial to compute, consider pulling it out of the loop and calling it only once.

Increment int variable every 5 iterations of loop (JAVA)

i want to Increment int variable every 5 iterations of loop. so the current int is 009. I want to change it to an infinite loop wherein the value add + 1 every 5 loops. so after that the value of 009 will change to 010, then after 5 loops. again it will change into 011.
String itemID = "2014-009";
for (int i = 0; i <= 5; i++) {
String sdf = new SimpleDateFormat("yyyy").format(new java.util.Date());
String[] parts = itemID.split("-");
String part2 = parts[1];
int result = Integer.parseInt(part2);
String second = sdf + "-" + String.format("%03d", result + 1);
JOptionPane.showMessageDialog(null, second);
System.out.println(second);
}
Something like this should work:
int value = 0;
for (int i = 0; ; i++) {
if (i%5 == 0) {
value++;
}
}
Explanation:
The loop has no end, because it doesn't have a condition
The value variable is incremented only every 5 iterations
We enforce that restriction by asking whether i is exactly divided by 5
Be aware that I'm not taking into account the fact that ints are finite and at some point they will overflow. For truly "infinite" values (limited only by the memory available in your machine), we would have to use arbitrary precision values, BigInteger will come in handy for that.
Well, you should initialize result outside the loop.
Then you can do an infinite loop with a counter that checks if the iteration is divisable by 5 :
....
int result = Integer.parseInt(part2);
int i = 0;
while (true) {
i++;
if (i%5 == 0)
result++;
....
}
for(float i=0; i<10; i=i+0.2f){
System.out.println((int) i);
}
You can adapt the rest
In my case all above works on first iteration because 0%5 == 0 in my case is true and I suggest to write code like this:
if(i%5 == 0 && i != 0) {//6 threads per one operation
lq1.join();
lq2.join();
}

Categories

Resources