Sequence For Loop - java

I'm trying to create a for loop to sequentially add 4 to a random value (r) as many times as the value of (n).
I came up with this:
for (int counter = 1; counter <=n; counter++){
System.out.println(a = a + 4);
}
The thing is if the random value were to be 10 for example, it will start counting from 14, 18, 22.
I want it to start counting at the number itself so the results are 10, 14, 18 not to start +4 from the random number selected.

Change your loop body to:
System.println(a);
a += 4;
Or the whole loop to
for (int counter = 1; counter <=n; counter++, a += 4){
System.out.println(a);
}

Then do not increase a before printing it.
a = a + 4 will first increment a by 4 store the result in a and only then print it.
What you need is :
for (int counter = 1; counter <=n; counter++){
System.out.println(a);
a += 4;
}

Print the current number before adding 4 to it, then.
System.out.println(a); // print the number
a = a + 4; // THEN add 4

for (int counter = 1; counter <=n; counter++){
System.out.println(a+4*(counter-1));
}

Related

how many times will this loop execute

I was just wondering how many times a nested loop like this would run
int sum = 0;
for(int i = 0; i < total; i++) {
for(int j = i + 1; j < total; j++) {
for(int k = j; k < total; k++) {
sum++;
}
}
}
System.out.println(sum);
I can easily see the output of sum, but I would like to be able to mathematically calculate the total of sum with any number for total.
TL;DR
The loop will be executed for ((total ^ 3) - total) / 6 times and hence that will be the value of sum at the end of the loop.
int sum = 0;
for(int i = 0; i < total; i++) {
for(int j = i + 1; j < total; j++) {
for(int k = j; k < total; k++) {
sum++;
}
}
}
It is easy to see that the outer loop runs for a total times. The second loop is the trickier one
Let's try to work this out
i = 0, j runs from 1..total - 1
i = 1, j runs from 2..total - 1
i = 2, j runs from 3..total - 1
...
i = total - 2, j runs from total - 1 ..total - 1 (will only run once)
i = total - 1, inner loop does not execute as the loop termination condition is true.
The third loop is dependent on the second inner loop - k runs from j..total - 1
Let us take total as 6
j runs from 1..5 -> k runs for 5 times (j = 1) + 4 times(j = 2) + 3 times(j = 3)+ 2 times(j = 4) + 1 time(j = 4)
(Showing a minified version for others)
2..5 -> 4+3+2+1
3..5 3+2+1
4..5 2+1
5..5 1
Which is
1 + 2 + 3 + 4 + 5+
1 + 2 + 3 + 4 +
1 + 2 + 3 +
1 + 2 +
1
Generally,
1 + 2 + 3 + .. n +
1 + 2 + 3 +..n - 1+
1 + 2 + 3 +..n - 2+
1 + 2 + 3 +
1 + 2 +
1
This boils down to the sum
n * (n - 1)) / 2
For all values of n ranging from 1 to total
This can be verified with the below
int res = 0;
for (int i = 1; i <= total; i++) {
res += (i * (i - 1))/2;
}
res will be equal to your sum.
Mathematically, the above is
((total ^ 3) - total) / 6
Derivation:
References:
Sums of the First n Natural Numbers
Sum of the Squares of the First n Natural Numbers
The first iteration of the middle loop adds
total-1 + total-2 + ... + 1
to the sum.
The second iteration of the middle loop adds
total-2 + total - 3 + ... + 1
to the sum
The last iteration of the middle loop adds
1
to the sum.
If you sum all of these terms, you get
(total - 1) * 1 + (total - 2) * 2 + (total - 3) * 3 + ... + 2 * (total - 2) + 1 * (total - 1)
It's been a while since I studied math, so I don't remember if there's a simpler formula for this expression.
For example, if total is 10, you get:
9 * 1 + 8 * 2 + 7 * 3 + 6 * 4 + 5 * 5 + 4 * 6 + 3 * 7 + 2 * 8 + 1 * 9 =
9 + 16 + 21 + 24 + 25 + 24 + 21 + 16 + 9 =
165
It needs only a little bit knowledge of programming.Actually logic that is running behind is only computational kind of thing.
let's say:
total=10,sum=0
- when i is 0:
That time j is initialised with 1(i+1) and k as well. So k will lead us to execute the loop 9 times and and as j is incremented ,it will lead us to execute sum statement 8 times and 7 times and further 6 times till 1 time. (9+8+7+6+5+4+3+2+1=45 times.)
- when i is 1:
That time j is initialised with 2 and k as well.So sum statement is going to execute 8 times and then 7 times and then 6 times till 1.
(8+7+6+5+4+3+2+1=36 times).
- when i is 2:
Same thing happens repeatedly but starting with difference number ,so this time (7+6+5+4+3+2+1=28)
So this sequence continues until there is significance of occuring the condition with trueness.
This happens till i is 9.
So the final answer is 1+3+6+10+15+21+28+36+45=165.
The equation is like below
and the k is equal to total :
outermost loop runs 'total' number of times.
for each outer loop , middle loop runs 'total-i' times.
i.e total * total+total * (total-1)+total * (total-2)....total * 1
= total*(total+total-1+total-2...1)
= total*(1+2+3....total)
= total*(sum of first 'total' natural numbers)
= total*(total*(total+1)/2)
now the innermost loop also runs 'total-j' times for each middle loop
i.e
total*(total*(total+1)/2)*(total+(total-1)+(total-2)....+1)
= total*(total*(total+1)/2)*(1+2+3....+total)
= total*(total*(total+1)/2)* (sum of first 'total' natural numbers)
= total*(total*(total+1)/2) * (total*(total+1)/2)..
So finally you will get something close to
total * (total*(total+1)/2) * (total*(total+1)/2).
Sorry there's a correction as #andreas mentioned innermost and middle loops run only till total-i-1 times
in which case it will be the sum of first (total-1) no.s which should be (total-1)*total/2 so the final output should be
total * (total*(total-1)/2) * (total*(total-1)/2) .
As we know, the sum of an arithmetic progression is:
The inner-most loop will loop for
times, which is a function to j.
You sum it up and get a function to i, aka:
You sum it up again and get a function to total, aka:
For Mathematica users, the result is:
f[x_]:=Sum[Sum[x-j,{j,i+1,x-1}],{i,0,x-1}]
From here, we can see it more clearly, and the FINAL result is:
where x is total.
That function will loop (total/6)*(total*total - 1) times
The snippet bellow just verifies that
var total = 100
var sum = 0;
for(var i = 0; i < total; i++) {
for(var j = i + 1; j < total; j++) {
for(var k = j; k < total; k++) {
sum++;
}
}
}
function calc(n) {
return n*(n-1)*(n+1)/6
}
console.log("sum: "+sum)
console.log("calc: "+calc(total))
If we run this loop 100 times and generate a data set, then graph it, we get this:
Now, this graph is clearly a cubic. So we can do a solve using the cubic equation of ax^3+bx^2+cx+d.
Using 4 points, the values of them all are:
So the full equation is
y=x^3/6-x/6
y=x(x^2/6-1/6)
y=(x/6)(x^2-1)
Interactive Graph:
<iframe src="https://www.desmos.com/calculator/61whd83djd?embed" width="500px" height="500px" style="border: 1px solid #ccc" frameborder=0></iframe>
A simple loop like this:
for (i = a; i < b; i ++) {
....
}
runs b-a iterations (i takes the values: a, a+1, a+2... b-2, b-1) if a < b and 0 iterations otherwise. We will assume below that a < b always.
Its number of iterations can be compute using the simple maths formula:
Applying the formula to your code
We start with the innermost loop:
for(int k = j; k < t; k++) {
sum++;
}
Its number of iterations is:
Using the formula above, the value of U is (t-1)-j+1 which means:
U = t - j
Adding the middle loop
Adding the middle loop, the number of iterations becomes:
The terms of the second sum are t-(i+1), t-(i+2), ... t-(t-2), t-(t-1).
By solving the parentheses and putting them in the reverse order they can be written as:
1, 2, ... t-i-2, t-i-1.
Let p = t - j. The second sum now becomes:
It is the sum of the first t-i-1 natural numbers and its value is:
Adding the outer loop
Adding the outer loop the sum becomes:
On the last sum, the expression (t - i) starts with t (when i = 0), continues with t-1 (when i = 1) and it keeps decreasing until it reaches 1 (when i = t - 1). By replacing q = t - i, the last sum becomes:
The last expression subtracts the sum of the first n natural numbers from the sum of the first n square numbers. Its value is:
Now it's easy to simplify the expression:
The final answer
The number of iterations of the posted code is:

Java For-Loop Number Series

I'm trying to print a number series that divides by 2 which would result in an output of 128, 64, 32, 16, 8, 4, 2, 1
int num = 128;
for (int i = 1; i <= 8; i++)
{
int prevNum = 0;
prevNum = num / 2;
System.out.print(prevNum);
System.out.print(", ");
}
Clearly my current code isn't working as it is only outputting the number 64 eight times. I'm not sure how I can throw away the initial number after printing it and only use the stored number after the division
From the code that you have posted, I feel that you have initialised num as 128 somewhere in your code.
Now in your loop you are storing prevNum as num/2 in other words 128/2 each time in the loop. So you are getting 64 as output 8 times as your loop loops 8 times.
The correction I would suggest in this code is you do not require the second variable prevNum. Simply use num = num/2 and print the value of num variable. This will solve your problem.
A better code for this loop would be :
int num = 128;
while (num > 1) // This takes care of the loop.
//Also if you write num = 256, then also this loop would work.
{
num = num / 2;
System.out.print(num);
System.out.print(", ");
}
int num = 128;
int prevNum = num;
for (int i = 1; i <= 8; i++)
{
prevNum = prevNum / 2;
System.out.print(prevNum);
System.out.print(", ");
}
This is in logic to the way you are working with. But, there are more efficient ways to get the same result.
OP, you initialized prevNum=0 inside the for-loop and doing so, for each iteration, it was getting assigned to the value 0. What you actually wanted was to carry over the quotient of the previous division to the next iteration. So in order to do that, the prevNum was intilaized outside the loop with value set to num(i.e; 128). And in each iteration, prevNum is getting divided by 2, and the result is assigned back to prevNum.
Try to replace prevNum to num, this will change the value of num, but it works.
Or declare prevNum outside the loop this way: int preNum = num;, and replace line 4 to prevNum = prevNum / 2;
Without local variables outside of the loop:
for (int i = 128; i > 0; i = i / 2) System.out.print(i + (i > 1 ? ", " : ""));
We loop over i starting with the initial value 128 and dividing by 2 each iteration (i = i / 2).
Then the current value of i is printed and appended with , if i > 1 is satisfied.
Output:
128, 64, 32, 16, 8, 4, 2, 1
int num = 128;
int prevNum = num; // modify here.
for (int i = 1; i <= 8; i++)
{
prevNum = prevNum / 2;
System.out.print(prevNum);
System.out.print(", ");
}
Edit:
You are not reducing the actual number. On each iteration you are dividing same number again. But you should divide this prevNum by 2 on each iteration.
Hope this help.

Array value post-increment

I've been working on a few array examples. with some success along alone the way. I've been working on this code for the pass few days and just cant understand the purpose of this increment in the loop body. it usually makes since when it is isolated but this time i have no idea what it does.
Count the occurrences of integers between 1 and 10
Scanner input = new Scanner(System.in);
int[] count = new int[10];
System.out.println("Enter the integers between 1 and 10: ");
// Read all numbers
// 2 5 6 5 4 3 9 7 2 0
for (int i = 0; i < count.length; i++)
{
int number = input.nextInt();
count[number]++; //this is the one that perplexes me the most
}
//Display result
for (int i = 0; i < 10; i++)
{
if (count[i] > 0)
{
System.out.println(i + " occurs " + count[i]
+ ((count[i] == 1) ? " time" : " times"));
}
}
count[number]++; //this is the one that perplexes me the most
It increments the value in the array count at index number. Perhaps, splitting it may help understand:
int tmp = count[number];
tmp = tmp + 1;
count[number] = tmp;
i.e. The value of count[number] will be incremented after the execution of the the statement count[number]++;.
Also a note on how post-increment works.
If it were used as:
int value = count[number]++;
then value will have the old value at count[number] and the increment will be done after the execution of the statement.

Need explanation for the output of the following java code

public class Test {
public static void main (String args[]) {
int i = 0;
for (i = 0; i < 10; i++);
System.out.println(i + 4);
}
}
The output of the following code is 14.Why it is not 4?
And how can it be 14? Need some explanation
Thank you in advance...
for (i = 0; i < 10; i++);
This loop does nothing but incrementing i by one, 10 times .
Then
System.out.println(i + 4);
evaluates to
System.out.println(10 + 4);
// output
14
If you drop the semi colon at the end of for (i = 0; i < 10; i++);, you shall get
4
5
6
7
8
9
10
11
12
13
as an output.
Simple.
The loop increments i by 10 without doing anything else (notice the ; after the for loop definition)
The System.out statement prints i + 4 outside the loop (only once), i.e. 14
See description in comments:
// Declare variable 'i' of type int and initiate it to 0
// 'i' value at this point 0;
int i = 0;
// Take variable 'i' and while it's less then 10 increment it by 1
// 'i' value after this point 10;
for (i = 0; i < 10; i++);
// Output to console the result of the above computation
// 'i' value after this point 14;
System.out.println(i + 4);
System.out.println(i + 4); will get evaluated and executed after for (i = 0; i < 10; i++); statement is evaluated.
Result of for (i = 0; i < 10; i++); will be 10. The condition i < 10 will be true till i=9 which is the 10th iteration and in the 11th iteration i will be 10 as i++ will be computed and here the i<10 condition fails. Now final value of i will be 10.
The next statement System.out.println(i + 4); is evaluated which is i(=10)+4 = 14

Counting by factors of two with a while loop?

I want this while loop to print every multiple of two below the number submitted(ex. if 100 was submitted it would print 2 4 8 16 32 64). Here's what I have(I'm only going to include a portion of the class because there was other things in it that don't pertain to this part)
i = 1;
Scanner myScanner = new Scanner(System.in);
System.out.print("Would thoughst be inclined to enter a number fair sir/madam: ");
String answer = myScanner.nextLine();
int number = Integer.parseInt(answer);
System.out.print("Your number set is: ");
while(i <= number)
{
i = 2*i;
System.out.print(" " + i + " ");
}
What this prints if I enter 100 is: 2 4 8 16 32 64 128
How do I get rid of that last number?
You would get rid of that number by modifying your logic to match. Your code is doing precisely what it says. One option is to start at 2, and increase i at the end of the loop instead of just before printing it. You could also use a for loop:
for (int i = 2; i < 100; i *= 2)
...
If you want to save the last power, you have a few options, e.g.:
int k = 2;
for (int i = k; i < 100; i *= 2) {
k = i;
...
}
Or undo the last operation:
int i;
for (i = 2; i < 100; i *= 2)
...;
i /= 2;
Or check the next one:
int i;
for (i = 2; i * 2 < 100; i *= 2)
...;
Checking the next one, in your original form:
while (i * 2 <= number)
...;
Etc.
By the way, your title says "factors", your description says "multiples", and your code says "powers"...
In your code
while(i <= number)
{
i = 2*i;
System.out.print(" " + i + " ");
}
the problem is that i, when it is equal to 64, is indeed less than 100, so the loop continues.
If you change it to
i = 2*i;
while(i <= number)
{
System.out.print(" " + i + " ");
i = 2*i;
}
it does as you wish, because it pre-computes the value before being analyzed as the while-loop terminator.
Try
while( i <= number / 2)
Those are powers of 2, not factors of 2.
"thoughst" is not a word. It should be "thou".
Update the value of i after you print it.

Categories

Resources