I have just started learning Java and pretty much programming and saw the following for loop expression:
for (int i = 1; i < 100; i += i)
System.out.print(i + " ");
My understanding is that "i += i" is short for "i = i + i". The output of the loop is "1, 2, 4, 8, 16, 32, 64". Cannot get my head around the iteration when "i" is 3 and higher. How can it become 8 etc.?
Because it's
Iteration 1 => 1+1
Iteration 2 => 2+2
Iteration 3 => 4+4
Iteration 4 => 8+8
etc.
With this particular for loop, the print statement is not being executed when i is 3 because i increments from 2 to 4. Let's take a closer look:
for (int i = 1; i < 100; i += i)
// iteration 1
System.out.print(i + " ");// prints 1 increment (1 += 1) == 2
------------------------------------------------------------------
// iteration 2
System.out.print(i + " ");// prints 2 increment (2 += 2) == 4
------------------------------------------------------------------
// iteration 3
System.out.print(i + " ");// prints 4 increment (4 += 4) == 8
------------------------------------------------------------------
// iteration 4
System.out.print(i + " ");// prints 8 increment (8 += 8) == 16
------------------------------------------------------------------
As you can see, i becomes 8 because on the third iteration of the loop, i is 4 and increments by itself to become 8.
Hope it helps :-)
first increment time : 1 + 1 = 2
second time : 2 + 2 = 4
third time : 4 + 4 = 8
forth time : 8 + 8 = 16 ... and so on 32,64,128,256....
Hope this helps you to clear your doubt.
In expression x+=y means really that you are writing x=x+y. In your expression i+=i really means that you are writing i = i+i which is equivalent to i = 2*i.
Now how for is working...It's calculating int i = 1 only once. Then it's checking your loop condition i < 100. The next step is to calculate next iteration value which will be i = 1 + 1 =2.
The 3rd iteration will calculate value for i in such way - i = 2 + 2 =4.
The 4rd iteration will be i = 4 +4 =8
....
If you want just to add by one, then please change i +=i by ++i.
for (int i = 1; i < 100; i += i)
System.out.print(i + " ");
Equivalent to:
int i = 1;
while(i<100){
System.out.print(i + " ");
i +=i;
}
Just to for completeness: i += K; is not exactly i = i + K; It is i = (TypeOf i ) (i + k)
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
enter code hereI have this number "811218-3476"as string,I want to multiply 8 by 2,1 by 1, 1 by2, 2 by1 and so on as following:
8 1 1 2 1 8 3 4 7 6
2 1 2 1 2 1 2 1 2 1 *
16 1 2 2 2 8 6 4 14 7 ----> Result
My question is how I kan do sum for the result, I did sum one number with another number like
16 + 1+2+2+2+8+6+4+14+7 = 62,
but I want to do sum as following:
1+6+1+2+2+2+8+6+4+1+4+7 = 47.
I do not need you to write a code I have wrote it, but I want to know how I kan sum 1+6 instead of 16 as example. my code is here and it works fine.
I hope help know.
Thanks.
enter code here
public static boolean checknumber(String s) {
if(checkPersonNummer(s)== true) {
char [] charray = s.toCharArray();
int newch = 0 ;
int j = 0;
int i = 0;
String sum= "";
int x = 0;
for( j = 2; j < 8 ; j++) {
System.out.print(" "+ charray[j] + " ");}
for( j = 9; j < charray.length ; j++) {
System.out.print(" "+ charray[j] + " ");}
System.out.println(" ");
for( j = 2; j < 8 ; j++) {
if(j%2 == 0) {
System.out.print(" "+ 2 + " ");
} else {
System.out.print(" "+ 1 + " ");
}
}
// System.out.println(" ");
for( j = 9; j < charray.length; j++) {
if(j%2 == 0) {
System.out.print(" "+ 2 + " ");
} else {
System.out.print(" "+ 1 + " ");
}
}
System.out.print("\n--------------------------------------------");
System.out.println("");
for( i = 2;i < 8;i++) {
if(i% 2 == 0) {
newch = Character.getNumericValue(charray[i] )* 2;
sum += newch;
}
else {
newch = Character.getNumericValue(charray[i]) * 1;
sum += newch;
}
System.out.print(newch + " " );
}
for( i = 9;i < charray.length;i++) {
if(i% 2 == 0) {
newch = Character.getNumericValue(charray[i] )* 1;
sum += newch;
}
else {
newch = Character.getNumericValue(charray[i]) * 2;
sum += newch;
}
System.out.print(newch + " " );
}
System.out.println();
System.out.print("Total = " + sum);
}
return true;
}
}
This sounds like a homework assignment, and we're not a homework writing team. But I'll give you some basic advice.
First, I had one person tell me, "programming is the art of editing the null program until it does what you want". By that he meant that we start with a program that does nothing and slowly built it up.
That's a good way to start.
So... Start your program. You need to get your data in. Do that, and figure out how to print it.
After that, think about printing out each number times either 1 or 2 as your problem requires, and print each calculation as you go.
Then all you have to do is keep a variable outside of this loop to store the sum, and add each mini-calculation to it, then print it at the end.
Start small. Work up to the final answer. Lots of debug output while working on it.
Lets say I have an array of numbers [2,3,4,5,6], Think of this question as you are multiplying the numbers with 1 those are at odd position in the array and multiplying the numbers with 2 those are at even position in the array.
Answer to How to add 1 + 6 instead of 16
Check if the number is less than 10, if it is than you don't have to
worry about it But,
If the number is greater than 10 you can use the % operator.
For instance
15 % 10 gives you 5 and 15 / 10 gives you 1 that way you can separate two individual digits.
Basically what my title says. Here's a piece of code
for (int i = 9; i >= 2; i--) {
system.out.println(i + " ");
}
this prints all values until 2, hence suggesting that starting from 9 and provided it doesn't go lower than 2, i should be printed. which it does.
now this one doesn't
for (int i = 9; i <= 2; i--) {
system.out.println(i + " ");
}
what i figure is it should count down to 2 without printing anything, then print 2 and 1, since the criteria is for all values equal or under 2, print i. However nothing shows on the console.
my understanding of the FOR loop might be wrong and i'm really trying to perfect my knowledge of basic concepts so id appreciate your help.
The basic concept is :
first loop => i=9, check if 9 >=2 = true , print 9 , i = i - 1
second loop => i=8, check if 8 >=2 = true , print 8 , i = i - 1
.
.
.
last loop=> i=1, check if 1 >=2 = false , end
in your second example
first loop => i=9, check if 9 <=2 = false , end
Hope i help you understand the for loop
Loop is only executed if the condition is true. If it is false, then loop will never be executed.
If you wanted to count down from 9 and only print 2 and 1, you'd have to write something like this:
for (int i = 9; i >= 1; --i) {
if (i <= 2) {
System.out.print(i + " ");
}
}
Of course, if all you wanted was to print 2 and 1, you'd normally just write:
for (int i = 2; i >= 2; --i) {
System.out.print(i + " ");
}
You wouldn't typically start the count at 9 unless you wanted to do something with the numbers 9 to 3 (other than ignore them, that is) as well as 2 and 1:
for (int i = 9; i >= 1; --i) {
if (i <= 2) {
System.out.print(i + " ");
} else {
System.out.println("We're not going to print " + i);
}
}
I'm a Java beginner, please bear with me. :) I haven't learned anything like if statements and such yet, I've only learned about loops, variables, and classes. I need to write a single loop which produces the following output:
10 0 9 1 8 2 7 3 6 4 5 5
I can see from the segment, that the difference between the numbers is reduced by one, so from 10 to 0 it is subtracted 10, then from 0 to 9 it is added by 9, and it goes on alternating between adding and subtracting.
My idea was to create the loop where my variable i = 10 decreases by 1 in the loop (i--) but I'm not quite sure how to alternate between adding and subtracting in the loop?
public class Exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 0; i--) {
System.out.print(i + " ");
}
}
}
Why not have two extra variables and the increment one and decremented the other:
int y = 0;
int z = 10;
for(int i = 10; i >= 5; i--) {
System.out.print(z + " " + y + " ");
y++;
z--;
}
Output:
10 0 9 1 8 2 7 3 6 4 5 5
However we can also do this without extra variables:
for(int i = 10; i >= 5; i--) {
System.out.print(i + " " + 10-i + " ");
}
I don't think the OP actually wanted somebody to do their homework for them, so I'm gonna stick to answering the question they actually asked: how to alternate between two operations within a loop (so they can keep the algorithm they came up with :)).
There's a nifty "trick" that's very often used when we want to do something every other iteration in most programming languages. You'll most definitely come across it in your life, and it could be perplexing if you've got no clue what's going on, so here it goes!
The modulo (%) operator will yield the remainder of the division between its operands.
For instance, consider the following: 7 ÷ 2 = 3.5
When working for integers, you'd say that 7 ÷ 2 = 3, then you're left with 1.
In this case, when all variables are ints, in Java, 7 / 2 would be 3 and 7 % 2 is 1.
That's modulo for you!
What's interesting about this operator is inherent to what's interesting about division in general, and one case in particular: the remainder of a division by 2 is always either 0 or 1... and it alternates! That's the key word here.
Here comes the "trick" (not really a trick, it's basically a pattern considering how widely used it is) to alternating operations over iterations:
take any variable that is incremented every iteration in a loop
test for the remainder of the division of that variable by 2
if it's 0, do something, otherwise (it'll be 1), take the alternate path!
In your case, to answer your actual question (although others do have good points, I"m not trying to take that away from anybody), you could consider using something like that:
if( i % 2 == 0 ) {
// i is even, subtract
} else {
// i is odd, add
}
That'd allow you to keep going with the algorithm you initially thought of!
public class exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 5; i--) {
System.out.print(i + " " + (10-i) + " ");
}
}
}
Or you can do it this way, if you want to be a wiseass ;)
for(int i = 0, arr[] = {10,0,9,1,8,2,7,3,6,4,5,5}; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
This looks a bit like a homework assignment, so I won't give you working code.
But remember that you can put multiple print statements inside the for loop. You don't necessarily have to iterate 10 times to get your output. 5 times is totally enough. And as already stated in a comment above: the numbers alternate between i and 10-i, for the right range of i.
replace i >= 0 with i >= 5
add this : System.out.print((10-i--) + " ");
starting from what you did
public class Exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 5; ) {
System.out.print(i + " " + (10-i--) + " ");
}
}
}
Somethings don't need overthinking:
public class Answer2 {
public static void main(String[] args) {
for (int i = 0; i <= 5; i++){
System.out.println(i);
System.out.println(10 - i);
}
}
}
edit
You CAN and should generalize your task. Here is an example how you could do it (I won't write the method, since it's your job - instead I'll alter my answer just to show you the possibilities)
public class Answer2 {
private static final Random RANDOM = new Random();
public static void main(String[] args) {
//You can use any upper bound for 'someLength'
int someLength = 1 + RANDOM.nextInt(20);
for (int i = 0; i <= someLength / 2; i++) {
System.out.println(someLength - i);
System.out.println(i);
}
}
}
Who said that you can only use one System.out.print in the loop?
for (int i=0; i < 5; i++) {
System.out.print((10 - i) + " " + (i + 1) + " ");
}
You should think about generalizing the series. As you have observed, the series alternates between addition and subtraction. Also, the difference goes down by one at each step. You can define variables for these two and adjust them in the loop.
public static void main(String[] args) {
int term = 10;
int sign = 1;
for(int delta = 10; delta >= -1; delta--) {
System.out.print(term + " ");
sign = -1 * sign;
term = term + sign * delta;
}
}
Simply run a loop either starting from 0 or starting from 10.
1.
If you start from 10
for(int i=10;i>=5;i--){
System.out.print(i + " " + (10-i) + " ");
}
2.
If you start from 0
for(int i=0;i<=5;i++){
System.out.print((10-i) + " " + i + " ");
}
The output will be:
10 0 9 1 8 2 7 3 6 4 5 5
I tried this code. It worked for me.
for(int i = 10; i >= 5; i--) {
System.out.print(i + " ");
System.out.print(10-i + " ");
}
This is here. The output list is a list of combinations to make 10;
10 0 9 1 8 2 7 3 6 4 5 5
10 + 0 = 10
9 + 1 = 10
8 + 2 = 10
7 + 3 = 10
6 + 4 = 10
5 + 5 = 10
int n = 10;
int half = n / 2;
if(n % 2 == 1){
half++;
}
for(int x = n; x >= half;x--){
int remainder = n % x;
if(remainder == 0){
remainder = n - x;
}
System.out.print(x);
System.out.print(" ");
System.out.println(remainder);
}
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:
int count = 0, result = 0;
while(count <= 10)
{
if(count % 2 ==0)
{
result = result + count;
}
else
{
result = 0;
}
count = count + 2;
}
System.out.println("Result: " + result);
Can someone explain why the answer is 30?
count starts at 0 and number 2 is added to it at each iteration. The loop stops when count is equal or higher than 10. Therefore the values of count will be :
0, 2, 4, 6, 8, 10
These are all even numbers so count % 2 == 0 will be true.
result starts at 0 and at each iteration count is added to it. Therefore the final result will be the sum of all the above numbers. And
0 + 2 + 4 + 6 + 8 + 10 = 30
To start with, count is 0. 0 % 2 == 0, so the if block is executed (and not the else block). result + count evaluates to 0, so result is set to 0. Repeat with 2 (count + 2) and this is added to result, as 2 % 2 == 0.
For every value of count, count % 2 == 0 evaluates to true. This is because you are incrementing it by 2 each time, so it will always remain even. Because of this, the else block is completely redundant and should be removed. Anyhow, what you are doing is summing all even numbers up to 10 (inclusive, as you use <=). This is 2 + 4 + 6 + 8 + 10 = 30, which is printed.
Side note: assignments which look like this (where v is a variable , o is an operator and e is an expression) may be simplified:
v = v o e;
is essentially (can anyone link me that question explaining the difference involving casting?) equivalent to
v o= e;
for arithmetic operators.
I just added two lines of code into yours and the code is now self-explaining.
int count = 0, result = 0;
while(count <= 10)
{
if(count % 2 ==0)
{
result = result + count;
System.out.println("count%2 " + count%2 + " and Count is " + count + " and Result is " + result);
}
else
{
result = 0;
System.out.println("count%2 " + count%2 + " Count is " + count + " and Result is " + result);
}
count = count + 2;
}
System.out.println("Result: " + result);
and it prints to the console following output
count%2 0 and Count is 0 and Result is 0
count%2 0 and Count is 2 and Result is 2
count%2 0 and Count is 4 and Result is 6
count%2 0 and Count is 6 and Result is 12
count%2 0 and Count is 8 and Result is 20
count%2 0 and Count is 10 and Result is 30
Result: 30
I hope this helps.
It simply increments result by every even number from zero to 10. And by adding those numbers together, you get, well, 30.
Even numbers between 0 and 10 include:
0, 2, 4, 6, 8, 10
by adding them all up, you get:
0 + 2 + 4 + 8 + 10 = 30
You can even prove this by keeping track of result as you go along. See below.
int count = 0, result = 0;
do {
if (count % 2 == 0) {
System.out.println("Result went from " + result + " to " + (result += count));
continue;
}
result = 0;
System.out.println("Result is now " + 0);
} while ((count += 2) <= 10);
System.out.println("Result: " + result);