for : loop code example
Example 1: for loop
for (let i = 0; i < array.length; i++) {
}
Example 2: for loop
for(int i = 0; i < some_number; i++){
//inside loop do whatever you want
}
Example 3: for loop
// this is javascript, but can be used in any language
// with minor modifications of variable definitions
let array = ["foo", "bar"]
let low = 0; // the index to start at
let high = array.length; // can also be a number
/* high can be a direct access too
the first part will be executed when the loop starts
for the first time
the second part ("i < high") is the condition
for it to loop over again.
the third part will be executen every time the code
block in the loop is closed.
*/
for(let i = low; i < high; i++) {
// the variable i is the index, which is
// the amount of times the loop has looped already
console.log(i);
console.log(array[i]);
} // i will be incremented when this is hit.
// output:
/*
0
foo
1
bar
*/
Example 4: for loop
for i in range (some_number):
#code goes here
Example 5: for loop
fruits = ['apple', 'orange', 'peach']
for fruit in fruits:
print(fruit)
Example 6: for loop
// Unity for loop coroutine (repeat something every x seconds for x time)
Coroutine doThisCoroutine; // (Create a coroutine for stopping)
int duration = 5 // (Duration, whatever you want it to be)
float waitTime = 1 // Wait time to iterate in seconds, usually 1
void Awake(){
DoThisCoroutine = StartCoroutine(DoThis()); // Start the coroutine
}
IEnumerator DoThis(){
while (enabled){ // While the behavior is enabled,
for (int x = 0; x < Duration; x++){ // From zero until 5 incrementing by 1...
print("Doing This!"); // Do whatever...
yield return new WaitForSeconds(waitTime) // Every second.
}
}
}
Example 7: for loop
for (let i = 0; i < substr.length; ++i) {
// do something with `substr[i]`
}
Example 8: for loop
#!/bin/bash
for (( c=1; c<=5; c++ ))
do
echo "Welcome $c times"
done
Example 9: for loop
double serviceCharge = 0; if (cost >= 150)
{
serviceCharge = 0.15 * cost;
}