Tutorial by Examples

C++11 for loops can be used to iterate over the elements of a iterator-based range, without using a numeric index or directly accessing the iterators: vector<float> v = {0.4f, 12.5f, 16.234f}; for(auto val: v) { std::cout << val << " "; } std::cout <<...
A for loop executes statements in the loop body, while the loop condition is true. Before the loop initialization statement is executed exactly once. After each cycle, the iteration execution part is executed. A for loop is defined as follows: for (/*initialization statement*/; /*condition*/; /*it...
A while loop executes statements repeatedly until the given condition evaluates to false. This control statement is used when it is not known, in advance, how many times a block of code is to be executed. For example, to print all the numbers from 0 up to 9, the following code can be used: int i =...
In the condition of the for and while loops, it's also permitted to declare an object. This object will be considered to be in scope until the end of the loop, and will persist through each iteration of the loop: for (int i = 0; i < 5; ++i) { do_something(i); } // i is no longer in scope...
A do-while loop is very similar to a while loop, except that the condition is checked at the end of each cycle, not at the start. The loop is therefore guaranteed to execute at least once. The following code will print 0, as the condition will evaluate to false at the end of the first iteration: i...
Loop control statements are used to change the flow of execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. The break and continue are loop control statements. The break statement terminates a loop without any furthe...
Using range-base loops, you can loop over a sub-part of a given container or other range by generating a proxy object that qualifies for range-based for loops. template<class Iterator, class Sentinel=Iterator> struct range_t { Iterator b; Sentinel e; Iterator begin() const { return ...

Page 1 of 1