📅  最后修改于: 2023-12-03 14:41:18.331000             🧑  作者: Mango
The for
loop is a crucial control flow statement that allows programmers to execute a block of code repeatedly. for
loops have been present in programming languages for over 50 years, and they continue to be widely used in F# and C++. In this article, we will explore how for
loops work in F# and C++ and provide some code examples to illustrate their usage.
In F#, there are two ways to implement for
loops: the for ... in ...
loop and the for ... to ... do ...
loop.
The for ... in ...
loop is used to iterate over a sequence of items. Here’s an example of how to use the for ... in ...
loop in F#:
let names = ["Alice"; "Bob"; "Charlie"]
for name in names do
printfn "Hello %s" name
In this example, we iterate over the sequence names
and print out each name with a greeting.
The for ... to ... do ...
loop is used to iterate over a range of values. Here’s an example of how to use the for ... to ... do ...
loop in F#:
for i in 1 .. 10 do
printfn "%d" i
In this example, we iterate over the range 1 .. 10
and print out each value.
In C++, there are three ways to implement for
loops: the for (init; cond; inc) { ... }
loop, the for (auto x : xs) { ... }
loop, and the for (;;) { ... }
loop.
The for (init; cond; inc) { ... }
loop is used to iterate over a range of values. Here’s an example of how to use the for (init; cond; inc) { ... }
loop in C++:
for (int i = 1; i <= 10; i++) {
std::cout << i << std::endl;
}
In this example, we iterate over the range 1 .. 10
and print out each value.
The for (auto x : xs) { ... }
loop is used to iterate over a range of values stored in a container. Here’s an example of how to use the for (auto x : xs) { ... }
loop in C++:
std::vector<std::string> names = {"Alice", "Bob", "Charlie"};
for (auto name : names) {
std::cout << "Hello " << name << std::endl;
}
In this example, we iterate over the sequence names
and print out each name with a greeting.
The for (;;) { ... }
loop is an infinite loop that executes the code within the loop indefinitely. Here’s an example of how to use the for (;;) { ... }
loop in C++:
for (;;) {
std::cout << "Hello, world!" << std::endl;
}
In this example, we print out the greeting "Hello, world!" over and over again.
In this article, we covered the basics of for
loops in F# and C++. We hope that you found these examples helpful and that you are now equipped to use for
loops in your own programs. Remember, the for
loop is a powerful tool that can help you write efficient and elegant code, so practice using it often!