Count to x amount of numbers then stop in Java? - java

I am doing a task in my Java class and I am stuck on one part for a week now. I have had all possible errors and infinite loops.
I am trying to display numbers in sequence of 4 and display only 500 numbers.
The code below shows what I have tried:
int add4 = 1;
int count500 = 1;
while (count500 <= 500)
{
if (count500 == 101)
{
System.out.print(add4);
}
else
{
System.out.print(add4 + "," + "");
}
add4 = add4 + 4;
}
Also I am stuck on the lucas sequence numbers.I dont even know where to start with that. I would appreciate your help with those questions.

The simplest way to print the sequence you want would be a for loop and print a function of the loop variable
System.out.print(1);
for (int i = 1; i < 500; ++i) {
System.out.print("," + (4*i+1));
}
This will also avoid trailing commas

Shortest way will be:
for(int i = 1, j = 1; i <= 500; i += 1, j += 4)
System.out.print("i = " + i + " j = " + j);

Refactor to while (count500++ <= 500). Then the loop will terminate correctly.
That said, I'd prefer something on the lines of
for (int i = 0; i < /*ToDo - limit*/; ++i){
System.out.print(i * 4); // ToDo - all your special whitespace.
}
since then you're operating on the iterating variable which will reduce the potential for bugs, such as the one that you have.

If you are not incrementing the value of count500 then how it will reach 500 ?
Add count500++ at the end of the loop

Your stuck in the loop because your precondition is count500 <= 500
The problem is you never change the value of count500.
I see two ways for you to get out of this infinte loop:
1.- Increment it in in your loop:
int add4 = 1;
int count500 = 1;
while (count500 <= 500)
{
if (count500 ==101)
{
System.out.print(add4);
}
else
{
System.out.print (add4 +"," +"");
}
add4 =add4 + 4;
count500++;
}
2.- Do it right in your while:
while (count500++ <= 500)
In bove cases he will run the loop 500 times.

Here ya go:
int add4 = 0;
for (int i = 0; i > 500; i += 1) {
System.out.println(add4);
add4 += 4;
}
Let's break that down.
First, we're initialising the variable add4 at zero, which later, in the for loop, increases by 4 directly after being printed.
Then, since you only want to print add4 out 500 times, you declare a for loop, which initialises integer i at zero (int i = 0), then tells the loop to continue while i is less than 500 (i > 500), and finally tells i to increase by one each time you go through the loop (i += 1).
Within the loop, add4 is being printed out, then being incremented by four. The last value printed out should be 2000, but the value of add4 at the end should actually be 2004.
Hope that helps.

I'm not exactly sure what you are trying to do but try this:
public class TestSequence {
static final int AMOUNT_NEEDED = 500;
static final int INCREMENT = 4;
static final int UPPER_LIMIT = AMOUNT_NEEDED * INCREMENT;
public static void main(String[] args) {
for( int numberMod4 =0; numberMod4< UPPER_LIMIT; numberMod4+=INCREMENT)
System.out.println(numberMod4);}
}

Related

I tried to reverse a string in a for loop, but it just isn't working

int num = 621126;
String secondHalfReverse = "";
String stringNum = "" + num;
String firstHalfProduct = stringNum.substring(0, 3);
String secondHalfProduct = stringNum.substring(3,6);
System.out.println("the first half is " + firstHalfProduct + " and the second half is: " + secondHalfProduct);
System.out.println(stringNum);
for(int i = 0; i < 3; i++)
{
int right = 1;
int left = 0;
String letter = secondHalfProduct.substring(left,right);
System.out.println(letter);
left++;
right++;
}
The output I get for letter is:
1
1
1
Instead of:
1
2
6
I just don't understand why letter won't move up the string and select the other letters.
because every time you loop, left and right get set back to 1. place them outside of your loop and it should work
You should move the declarations for int left and int right above the for loop.
Their values are reset every time the loop is executed. If you move them out of the loop, this will not be the case and they will increment as you expect.
Just change your loop like so, otherwise you right, and left variable will be set to 1 and 0 every loop.
int right = 1;
int left = 0;
for (int i = 0; i < 3; i++) {
String letter = secondHalfProduct.substring(left, right);
System.out.println(letter);
left++;
right++;
}
int right = 1;
int left = 0;
are declared inside the for loop so are reset every iteration. Declare them before the for loop
There is an easier way to do it if you are willing not to use a for loop:
StringBuffer a=new StringBuffer("java hungry");
System.out.println(a.reverse());

Recursion java - differently for loop does not understand how to work

I understand the principle of recursion and code but do not understand the loop for,Why variables are in the same line, we can explain how the loop works?
this line:
for (int i = digit, j = 1; i >= 1; i--, j++)
The code:
public static boolean hasSubSeries(int[] arr, int digit) {
return hasSubSeriesHelper(arr, arr.length, digit);
}
public static boolean hasSubSeriesHelper(int[] arr, int size, int digit) {
if (size == 0)
return false;
for (int i = digit, j = 1; i >= 1; i--, j++) {
if (arr[size - j] != i)
return hasSubSeriesHelper(arr, size - 1, digit);
}
return true;
}
thank's
The structure of the for loop is as follows:
for( starting conditions; verification at each loop; action at end of loop)
In your specific case:
for (int i = digit, j = 1; i >= 1; i--, j++)
Starting conditions:
A variable i which is equal to the value contained in the variable digits that is given at the start of the function hasSubSeriesHelper(int[] arr, int size, int digit).
A variable j which starts at 1.
Verification at each loop:
Once each loop is completed we will check this, if it is True, we keep on looping, if not we exit the loop.
We check to see if i declared at the start is greater than or equal to 1, if it is we keep on looping, if not we stop.
Action at end of loop:
We do two actions i-- which decreases the value of i by 1 and j++ which increases the value of j by 1.
To summarise you could translate it to a while loop if you prefer:
int i = digit;
int j = 1;
while ( i >= 1 ) {
// the code inside the for loop goes here
i--;
j++;
}
Note that the actions at the end happen inside the loop whilst the starting condditions go before the loop.
That should also clarify why you can have various declarations in the same line as long as they are of the same type.
You have three parts in a for loop
N°1 : Initialization of variable(s)
N°2 : Boolean expression evaluated to continue/stop looping
N°3 : Changes operated on variables
1
You may have multiple initialization in the first part, as long as the type stay the same, the following is entirely possible :
We declare and instantiate three variables within the first part of our for declaration.
for(int i = 2, j = 2*i, k = 4*j ; i < 3 ; i++) {
System.out.println(i + " " + j + " " + k); // 2 4 16
}

So I was wondering why it truns out to be a false about my junit test

here is my solution
public int count_chars_in_String(String s, String s1){
int count = 0;
for(int j = 0; j<s1.length(); j++){
for(int i = 0; i<s.length();i++){
if(s.charAt(i) == s1.charAt(j)){
count += 1;
}
}
}
and here is my rest code
#Test public void tests4(){
code.Solution s = new code.Solution();
String input = "hhhhhey ";
String input1 = "hhh";
int expected = 3;
int actual = s.count_chars_in_String(input, input1);
assertTrue("Expected was" +expected+"but the actual was" +actual , expected == actual);
}
every time i run the junit test it shows up that Expected was3 but actual was 15? How???I am so confusing.
Code which would give you result 3 would look probably like (note the break statement):
// the outer loop
for(int j = 0; j<s1.length(); j++){
// the inner loop
for(int i = 0; i<s.length();i++){
if(s.charAt(i) == s1.charAt(j)){
count += 1;
// Break the inner loop after finding
// the match.
break;
}
}
}
Without the break, for each h in hhh (the outer loop), you increase the counter 5 times (the inner loop; because h occurs 5 times in hhhhhey).
do not know if this answer is what you are looking for and excuse my poor English.
The for j will run 3 times and for each of the times the for i will run 5 times, that are equal to the time that the condition is met. Now 5x3=15, the result that you get.
if what you expect is to get the number characters that match each string (3), then just do the following:
for(int i = 0; i<s1.length();i++){
if(s.charAt(i) == s1.charAt(i)){
count += 1;
}
}
Regards.

How to print the following sequence, while satisfying these conditions

This was actually an interview question. I had to print the following using Java:
9
9 8 9
9 8 7 8 9
9 8 7 6 7 8 9
. . .
. . .
During the interview, I wrote an embarrassing piece of code, but it worked nonetheless - using an outer loop, two inner loops (one for the decrementing sequence and one for the incrementing sequence!) and a ton of variables. One of the variables was the length of each row.
The interviewer asked me to try and rewrite it using
just one outer and one inner loop
without the row length variable.
Note: After looking at the answers, I think the interviewer didn't really mean the second condition. He might have just wanted me to simplify my code and the second point just bumbled out of his mouth.
So, later back home, I arrived at this:
int rowCnt = 5;
for(int i = 1; i <= rowCnt; i++)
{
int val = 9;
int delta = -1;
int rowLen = i * 2 - 1;
for(int j = 1; j <= rowLen; j++)
{
System.out.print(val + " ");
val += delta;
if(j >= rowLen / 2) delta = 1;
}
System.out.println();
}
Here, I am using just one inner loop. I'm using a delta value to determine whether increment or decrement happens. For each row, I compare the current index to the midpoint of the row and change the delta.
I satisfied the first condition - just one inner loop. But I am not able to do it without using the row length.
How can we print this without finding out the row length?
Many answers were acceptable, But I had to choose one, and picked the one that was simplest to understand for me.
They probably wanted to hear the word 'recursion'.
Here's a recursive solution that doesn't need length:
countDownInMiddle("", 9, "");
private static void countDownInMiddle(String start, int n, String end) {
if (n < 0) {
return;
}
System.out.println(start + n + end);
countDownInMiddle(start + n, n - 1, n + end);
}
How about:
int start = 9;
for (int i = 0; i <= start; i++) {
StringBuilder sb = new StringBuilder((start - i) + " ");
for (int j = start - i; j < start; j++) {
sb.insert(0, (j + 1) + " ");
sb.append((j + 1) + " ");
}
System.out.println(sb.toString());
}
This is simple PHP, hope logic is clear and easily portable to Java:
$rowCount = 10;
$startNum = 9;
for ($idx =0; $idx <$rowCount; $idx ++) {
for ($jdx=0; $jdx < (2*$idx +1); $jdx++) {
if ($idx < $jdx)
echo $startNum -(2*$idx) + $jdx.' ';
else
echo $startNum - $jdx.' ';
}
echo '<br/>';
}
public class Pyramid {
public static void main(String[] args) {
int start = 9;
String left = "";
String right = "";
for (int i=start; i>=0; i--) {
System.out.println(left+i+right);
left = left+i;
right = i+right;
}
}
}
Sample output:
9
989
98789
9876789
987656789
98765456789
9876543456789
987654323456789
98765432123456789
9876543210123456789
This iterative solution is equivalent to the recursive solution. I would prefer to use iteration over recursion since the extra stack memory needed by the recursive solution could be huge when the number of rows grows big.
My non-recursive solution:
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 2*i+1; j++)
System.out.print((Math.abs(j - i) + 9 - i) + " ");
System.out.println();
}

Java for loop vs. while loop. Performance difference?

Assume i have the following code, there are three for loop to do something. Would it run fast if i change the most outer for loop to while loop? thanks~~
int length = 200;
int test = 0;
int[] input = new int[10];
for(int i = 1; i <= length; i++) {
for (int j = 0; j <=length - i; j++) {
for (int k = 0; k < length - 1; k++) {
test = test + input[j + k];
}
}
}
No, changing the type of loop wouldn't matter.
The only thing that can make it faster would be to have less nesting of loops, and looping over less values.
The only difference between a for loop and a while loop is the syntax for defining them. There is no performance difference at all.
int i = 0;
while (i < 20){
// do stuff
i++;
}
Is the same as:
for (int i = 0; i < 20; i++){
// do Stuff
}
(Actually the for-loop is a little better because the i will be out of scope after the loop while the i will stick around in the while loop case.)
A for loop is just a syntactically prettier way of looping.
This kind of micro-optimization is pointless.
A while-loop won’t be faster.
The loop structure is not your bottleneck.
Optimize your algorithm first.
Better yet, don’t optimize first. Only optimize after you have found out that you really have a bottleneck in your algorithm that is not I/O-dependant.
Someone suggested to test while vs for loops, so I created some code to test whether while loops or for loops were faster; on average, over 100,000 tests, while loop was faster ~95% of the time. I may have coded it incorrectly, I'm quite new to coding, also considering if I only ran 10,000 loops they ended up being quite even in run duration.
edit I didn't shift all the array values when I went to test for more trials. Fixed it so that it's easier to change how many trials you run.
import java.util.Arrays;
class WhilevsForLoops {
public static void main(String[] args) {
final int trials = 100; //change number of trials
final int trialsrun = trials - 1;
boolean[] fscount = new boolean[trials]; //faster / slower boolean
int p = 0; // while counter variable for for/while timers
while (p <= trialsrun) {
long[] forloop = new long[trials];
long[] whileloop = new long[trials];
long systimeaverage;
long systimenow = System.nanoTime();
long systimethen = System.nanoTime();
System.out.println("For loop time array : ");
for (int counter=0;counter <= trialsrun; counter++) {
systimenow = System.nanoTime();
System.out.print(" #" + counter + " #");
systimethen = System.nanoTime();
systimeaverage = (systimethen - systimenow);
System.out.print( systimeaverage + "ns |");
forloop[counter] = systimeaverage;
}
int count = 0;
System.out.println(" ");
System.out.println("While loop time array: ");
while (count <= trialsrun) {
systimenow = System.nanoTime();
System.out.print(" #" + count + " #");
systimethen = System.nanoTime();
systimeaverage = (systimethen - systimenow);
System.out.print( systimeaverage + "ns |");
whileloop[count] = systimeaverage;
count++;
}
System.out.println("===============================================");
int sum = 0;
for (int i = 0; i <= trialsrun; i++) {
sum += forloop[i];
}
System.out.println("for loop time average: " + (sum / trials) + "ns");
int sum1 = 0;
for (int i = 0; i <= trialsrun; i++) {
sum1 += whileloop[i];
}
System.out.println("while loop time average: " + (sum1 / trials) + "ns");
int longer = 0;
int shorter = 0;
int gap = 0;
sum = sum / trials;
sum1 = sum1 / trials;
if (sum1 > sum) {
longer = sum1;
shorter = sum;
}
else {
longer = sum;
shorter = sum1;
}
String longa;
if (sum1 > sum) {
longa = "~while loop~";
}
else {
longa = "~for loop~";
}
gap = longer - shorter;
System.out.println("The " + longa + " is the slower loop by: " + gap + "ns");
if (sum1 > sum) {
fscount[p] = true; }
else {
fscount[p] = false;
}
p++;
}
int forloopfc=0;
int whileloopfc=0;
System.out.println(Arrays.toString(fscount));
for(int k=0; k <= trialsrun; k++) {
if (fscount[k] == true) {
forloopfc++; }
else {
whileloopfc++;}
}
System.out.println("--------------------------------------------------");
System.out.println("The FOR loop was faster: " + forloopfc + " times.");
System.out.println("The WHILE loop was faster: " + whileloopfc + " times.");
}
}
you cant optimize it by changing it to while.
you can just increment speed very very very very little by changing the line
for (int k = 0; k < length - 1; k++) {
by
for (int k = 0; k < lengthMinusOne; k++) {
where lengthMinusOne is calculated before
this subtraction is just calculating almost (200x201/2) x (200-1) times and it is very little number for computer :)
here's a helpful link to an article on the matter
according to it, the While and For are almost twice as faster but both are the same.
BUT this article was written in 2009 and so i tried it on my machine and here are the results:
using java 1.7: the Iterator was about 20%-30% faster than For and While (which were still the same)
using java 1.6: the Iterator was about 5% faster than For and While (which were still the same)
so i guess the best thing is to just time it on your own version and machine and conclude from that
Even if the hypothesis of the while loop being faster than the for loop were true (and it's not), the loops you'd had to change/optimize wouldn't be the outer ones but the inner ones, because those are executed more times.
The difference between for and while is semantic :
In a while loop, you will loop as long as the condition is true, which can vary a lot, because you might, in your loop, modify variables using in evluating the while condition.
Usually, in a for loop, you loop N time. This N can be variable, but doesn't move until the end of your N loop, as usually developpers doesn't modify variables evaluated in the loop condition.
It is a way to help other to understand your code. You are not obliged not to modify for loop variables, but it is a common (and good) practice.
No, you're still looping the exact same number of times. Wouldn't matter at all.
Look at your algorithm! Do you know beforehand which values from your array are added more than one time?
If you know that you could reduce the number of loops and that would result in better performance.
There would be no performance difference. Try it out!
The JVM and further, the compiler, would make both loops into something like
label:
;code inside your for loop.
LOOP label
It would only matter if you are using multi-thread or multiple processor programming. Then it would also depends on how you assign the loops to the various processors/threads.
No, it's not going to make a big difference, the only thing is that if your nesting loops you might want to consider switching up for example for organizational purposes, you may want to use while loop in the outer and have for statements inside it. This wouldn't affect the performance but it would just make your code look cleaner/organized
You can calculate it yourself.
int length = 200;
int test = 0;
int[] input = new int[10];
long startTime = new Date().getTime();
for(int i = 1; i <= length; i++) {
for (int j = 0; j <=length - i; j++) {
for (int k = 0; k < length - 1; k++) {
test = test + input[j + k];
}
}
}
long endTime = new Date().getTime();
long difference = endTime - startTime;
System.out.println("For - Elapsed time in milliseconds: " + difference);
test = 0;
input = new int[10];
int i = 0, j = 0, k = 0;
startTime = new Date().getTime();
while(i < length) {
while(j <= length - i ) {
while(k < length - 1) {
test = test + input[j + k];
k++;
}
j++;
}
i++;
}
endTime = new Date().getTime();
difference = endTime - startTime;
System.out.println("While - Elapsed time in milliseconds: " + difference);
The for loop and while loop both are iteration statements, but both have their distinct feature.
Syntax
While Loop
//setup counter variable
int counter = 0;
while ( condition) {
//instructions
//update counter variable
counter++; //--> counter = counter + 1;
}
For Loop
for (initialization; condition; iteration){
//body of for loop
}
The for loop does have all its declaration (initialization, condition, iteration) at the top of the body of the loop. Adversely, in a while loop only initialization and condition are at the top of the body of the loop and iteration may be written anywhere in the body of the loop.
Key Differences Between for and while loop
In the for loop, initialization, condition checking, and increment or decrement of iteration variable are done explicitly in the syntax of a loop only. As against, in the While loop, we can only initialize and check conditions in the syntax of the loop.
When we are aware of the number of iterations that have to occur in the execution of a loop, then we use for loop. On the other hand, if we are not aware of the number of iteration that has to occur in a loop, then we use a while loop.
If you fail to put the condition statement in the for loop, it will lead to an infinite iteration of a loop. In contrast, if you fail to put a condition statement in the while loop it will lead to a compilation error.
The initialization statement in the syntax of the for loop executes only once at the start of the loop. Conversely, if the while loop is carrying an initialization statement in its syntax, then the initialization statement in the while loop will execute each time the loop iterates.
The iteration statement in the for loop will execute after the body for loop executes. On the contrary, the iteration statement can be written anywhere in the body of the while loop so, there can be some statements that execute after the execution of the iteration statement in the body of the `while loop.
Based on this: https://jsperf.com/loops-analyze (not created by me) the while loop is 22% slower than a for loop in general. At least in Javascript it is.

Categories