Modify variable in for loop [closed] - swift

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
The code below would print abc 5 times and then print 1024. As far as I understand, in any for, the "iterator " is automatically declared (the equivalent of a C(++)/Java for(int i=1; i<=5; i++) ). Is it possible to actually not automatically create that variable and use the one declared before the for so that it would print abc 5 times and then print 5, thus modifying it?
var i = 1024
for i in 1...5 {
print("abc")
}
print(i)

#DrummerB's answer works, but if you want a for...in loop, this will also work. It's the same principle - declare your variable outside the loop and increment it inside it:
var i:Int = 0
for _ in 0...5 {
print("abc")
i += 1
}
print(i)
Since you aren't referencing a loop variable, Swift syntax recommends an underscore.

You could just rewrite the for loop as a while loop like this:
var i = 1024
i = 1
while i <= 5 {
print("abc")
i = i+1
}
print(i)

If you really want to change the value of the i using the loop in that way, you can do:
var i=1024
for j in 1...5 {
print("abc")
i = j
}
print(i)
The j would be used strictly in the loop, so once finished, it's value is dumped. But a variable declared before (i in your case), could take it's value and maintain it.

Related

How to check if the result of an operation equals an Integer? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm super new with Swift (and programming). I need to compare if the result of a Remainder Operator (modulo operator) equals an integer.
This is my code:
if Int.random(in: 1...1000) % 4 >= "This number" {
print ("OK")
} else {
print ("WRONG")
}
If "This number" is replaced by an actual number e.g. 100 it works fine.
But if replaced by Int it crashes displaying: Type 'Int.Type' cannot conform to 'BinaryInteger'; only struct/enum/class types can conform to protocols
You have to compare Int with Int, not String or Int type (Int.Type). If you want to declare a value that you will use for comparison you can declare it as variable. To compare if it is equal use == operator.
let thisNumber: Int = 3 // or any other value
if Int.random(in: 1...1000) % 4 == thisNumber {
print ("OK")
} else {
print ("WRONG")
}
now both Int.random(in: 1...1000) % 4 and thisNumber is Int so you can compare them without getting an error.

Passing by reference and assigning into a variable [closed]

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 3 years ago.
Improve this question
I was studying about passing by reference. It made me wonder what would happen in the following example (Written in pseudo-C which supports "by reference"):
int foo(int a) {
a = 5;
return a * 2;
}
int main() {
int a = 1;
a = foo(a);
printf("%d",a);
return 0;
}
What should be printed? if we only did foo(a); without assigning into a then we would get 5. but what would be printed when assigning? should it be 5 or 10?
Since you have a = foo(a); in your main() function, a will contain the result returned by foo(a). foo(a) will always return 10 no matter what a is.
C does not support pass by reference. Changing a = foo(a); to just foo(a); would mean a would retain the value it had before it was passed to foo(), so it would be 1.
One variation of C that supports pass by reference is C++. In C++, you could write foo() as:
int foo(int &a) {
a = 5;
return a * 2;
}
The int &a syntax is used to denote that the parameter will be passed by reference. Now, foo will assign 5 to the referenced variable, but still always return 10.
In this case a = foo(a); will result in a having the value 10, and foo(a); alone will result in a having the value 5.

How to while loops work in Scala? [closed]

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 5 years ago.
Improve this question
Would you please explain this code step by step, as I don't understand why there is a inner = 1 in the while loop. A general overview of this program and how it works would be deeply appreciated as I am currently learning loops in Scala!
import scala.io.StdIn._
object loops4 {
def main(args: Array[String]): Unit = {
var outer = 1;
var inner = 1;
print("How many units for the base of the triangle? ");
var base: Int = readInt();
while (outer <= base) {
inner = 1
while (inner <= outer) {
print ('*');
inner += 1;
}
println("\n");
outer += 1;
}
}
}
Don't "learn loops in scala", it's a waste of time. Learn scala.
This does the same thing (except for redundant empty lines between stars) as your snippet, except, I bet you don't have to ask people on internet how it works :)
(1 to base).foreach { n => println("*" * n) }
It might be helpful to debug the code as Carcigenicate suggested. Inner is set to 1 in the outer loop because it's changed to match the outer loop on the previous iteration of the outer loop. Debug and observe inner at the end of the outer loop. As far as what this code is doing, it's constructing a triangle in standard output and the outer loop is counting lines, and the inner loop is constructing the lines with '*' symbols. As Dima said there are more idiomatic ways to do this in Scala.

using for loop for fibonacci series to print values it will print up to 47 values above that it shows error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
var num = "100"
var num = text2.text.toInt()
var temp = 0
var temp2 = 1
if (nu == 1) {
println(1)
}
else {
for var valued = 2; valued<num;++valued {
var temp3 = temp + temp2
temp = temp2
temp2 = temp3
println("\(temp3)")
}
I want to print the fibonacci series of number. The number should be any one that should be choose by user. My code is above i have to choose num as 100 but it will print up to 47 values. The final value print here is 1836311903. It will not print up to 100. It shows an error. How i find the fibonacci series for number 100.
Fib(47) is 2,971,215,073.
2,971,215,073 is larger than 231 - 1 ... which is the largest 32 bit signed integer.
Hence your calculation is overflowing. (In a lot of programming languages, you wouldn't have gotten an error. You would have just gotten the wrong answer.)
How i find the fibonacci series for number 100.
You can't use simple integer arithmetic. You will need to use the Swift equivalent of Java's BigInteger class.
BigInteger equivalent in Swift?

What are my errors in the following code? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This is the function:
for (i = 0; i <= array.Length; i++) {
if (array[i].transform.position = 0)
array.RemoveAt(i);
print(“Removed element: “ + array[i].name);
else if (array[i].transform.position > 0)
array[i].transform.forward = Vector3(1,0,0);
}
I'm not sure if this is a valid question but there is for sure some logic errors :
First of all i'm not sure there is a RemoveAt(int index) for arrays
(but i'm not a big unityscript user) (there is for List though)
You should absolutely never (even if some weird languages maybe allow it to you) try to access an object you just deleted... which is what you try to do here :
array.RemoveAt(i);
print(“Removed element: “ + array[i].name);
Position is a Vector3 NOT a int or float so you cannot do : array[i].transform.position = 0
You should never use the = (assignment operator) in an if() you should use the == (comparison operator) (because = returns always true when assignment is possible)
That line is wrong for the same reason as before array[i].transform.position > 0
array[i].transform.forward = Vector3(1,0,0); Leaves me wondering because if it was C# i'd try the new keyword before Vector3() and i'd prefer floats that way :
array[i].transform.forward = new Vector3(1.0F,0,0); But even there Unity will throw you an error stating that you cannot modify components of Transform without making a copy first i believe...
But nice try :D
you can't compare a vector to 0 it needs to be like this
if(myObject.transform.position==Vector3.zero)
and for removing things I'd suggest to include System.Collections.generic lib
then use Listarray then you can use array.RemoveAt(index);