<jupyter_start><jupyter_text>Controlling Flow : Repetitively * One of important advantages of using computers is fast repetitive processing.* The **loop** clauses for such tasks. * `for` loops are usually to repeat finite times.* `while` loops are to reiterate indefinite times. * To avoid runaway codes, it is advisable to set limits of repetition in all loops at least initially.If possible, please use a `for` loop. When using a `while` loop, add a counter variable and `break` after it reaches a limit.  Iterating over elements of a list or an array  python<jupyter_code># s is a string
s = 'abcd'

# for each character of s
for c in s:
    # repeat the indented code block below
    # c would have each character of s
    print(c, end=' ')


# s is a string
s = 'abcd'

# for each character of s
for i, c in enumerate(s):
    # repeat the indented code block below
    # c would have each character of s
    # i would be the order of c in s
    print(f"s[{i}] = {c}")<jupyter_output><empty_output><jupyter_text>C/C++ ``` C++// int32_tinclude // strlen()include // coutinclude // declaring intention to use namespace stdusing namespace std;// program starting pointint32_t main(const int32_t argn, const char * argv[]){    // a zero terminated C string    const char s [] = "abcd";    // bound of n    const int32_t n = strlen(s);        // this for loop will go through each character of s    for(int32_t i = 0; n > i; ++i){        // present i'th element of s        cout << s[i] << ' ';    }    // change line    cout << '\n';            // indicate program success    return 0;}```  Example : Sum of an arithmatic sequence * Followings would calculate the sum of the first 100 natural numbers.  Python `for`<jupyter_code># initialize the sum
s = 0

# integer loop
# would start from 1 to 100
for i in range(1, 100+1):
    # accumulate to s
    s += i

# present the sum
print(f'sum = {s}')


# check result with an expected value
assert 5050 == s, "Sum incorrect"<jupyter_output><empty_output><jupyter_text>Python `while`<jupyter_code># set both i and s to zero
i, s = 0, 0

# while loop will maintain as long as i is smaller then 100
while 100 > i:
    # increase i by one
    i += 1
    # accumulate to s
    s += i

# present the sum
print(f'sum = {s}')

# check result with an expected value
assert 5050 == s, "Sum incorrect"<jupyter_output><empty_output><jupyter_text>C++ `for` ``` C++// assert()include // int32_tinclude // std::coutinclude // program starting pointint32_t main(int32_t argn, char *argv[]){    // initialize the sum    int32_t s = 0;    // integer loop    // would start from 1 to 100    // increment i by one at each iteration    for (int32_t i=1; i <= 100; ++i){        // accumulate to s        s += i;    }    // present result    std::cout << "sum = " << s << '\n';        // compare with an expected value    assert(5050 == s);        // indicate the program successful    return 0;}```  Compiling and running in `vi` * Please start by entering `vi cpp_for.cpp` at a shell prompt.* Press i to switch to *insert mode*.* Enter the source code.* When finished, press ESC to switch to *command mode*.* Enter `:w` to save the file.* Enter `:!g++ -Wall -g cpp_for.cpp -o cpp_for` to compile the file.If no error message, compile should have been successful.Press Enterto return to the `vi` editor.* Enter `:!./cpp_for` to run the program.Press Enterto return to the `vi` editor.* Above two steps in one line : `:!g++ -Wall -g cpp_for.cpp -o cpp_for && ./cpp_for`  Compiling and debugging using MS VS Code * See [C/C++ for Visual Studio Code](https://code.visualstudio.com/docs/languages/cpp) for details.* Please start by entering `code . &`* If not done yet, please install **Microsoft C/C++ extension**.Press Ctrl+Shift+x and search.* Open the Command Palate using Ctrl+Shift+p.* Select **Tasks: Configure Tasks...**.* Select **Create tasks.json file from template**.* Choose **Others**.* Change value of **command** to "`g++`" and add a comma at the end.* Add key "`args`" and its value as a bracket list as follows. [[ref0](https://stackoverflow.com/questions/45679035/build-currently-opened-file-in-visual-studio-code)],[[ref1](https://code.visualstudio.com/docs/editor/variables-reference)]`["-g", ${fileBasename}]`* To enable **Tasks: Run Build Task**, add "`group`" key-value pair.The `tasks.json` file would look as follows: ``` json {    "version": "2.0.0",    "tasks": [        {            "label": "build current file",            "type": "shell",            "command": "g++",            "args": [                "-Wall", "-g", "${fileBasename}",                 "-Wa,-adhln=${fileBasenameNoExtension}.s",            ],            "group": {                "kind": "build",                "isDefault": true            }        }    ]}```* To build, press Ctrl+Shift+b.* To debug, press F5.* When `launch.json` appears, change the value of `"program"` to something like `"${workspaceFolder}/a.out"`.* Click on the left side of the row `int32_t s = 0;` to set a break point.A red circle would appear.* Press F5.The debugger would wait for your command at the breakpoint.* Press F10.The debugger would move the highlight line to the next line.* Continue pressing F10.The debugger would update variables as the program executes.* To open console pane, press Ctrl+~.* Select `Debug Console` and enter a name of a variable to check its value.* If there is an iteration and you want to skip it, make another breakpoint after the loop and press F5.* To finish debugging press Shift+F5.* If you think it might be helpful, commit `tasks.json` and `launch.json` files into your repository.  C++ `while` ``` C++// assert()include // int32_tinclude // std::coutinclude // program starting pointint32_t main(int32_t argn, char *argv[]){    // initialize i and s    int32_t i = 0, s = 0;    // while loop will repeat as long as i is smaller than 100     while (i < 100){        // increment i and accumulate to s        s += (++i);        // What if "s += (i++);" ?        // https://stackoverflow.com/questions/24853/    }    // present the sum    std::cout << "sum = " << s << '\n';        // check with expected result    assert(5050 == s);        // program finished successfully    return 0;}```  Example: Smallest positive number in floating point? * Is $0<2^{-n}$ always true? Let's find out.  Python `for`<jupyter_code># Initialize with one
a = 1.0

# counter loop that will iterate seemingly sufficiently many times
for counter in range(1, 100000000):
    # divide a by half
    a *= 0.5

    # if unable to distinguish a from zero, break the loop
    # mathematically, would this be true ever?
    if not (0 < a):
        break

    # present the intermediate result
    print(f"{counter:9d} : {a}")<jupyter_output><empty_output><jupyter_text>Python `while`<jupyter_code># Initialize with one
a = 1.0

# initialize with zero
counter = 0

# the loop will stop when unable to distinghish zero and a
while 0 < a:
    # divide a by half
    a *= 0.5
    # increment the counter
    counter += 1

    # iteration limit
    if 1e10 < counter:
        break
    # present intermediate result
    print(f"{counter:9d} : {a}")<jupyter_output><empty_output><jupyter_text>C++ `for` ``` C++// int32_tinclude // setwinclude // std::coutinclude // program starting pointint32_t main(int32_t argn, char *argv[]){    // initialize    double a = 1.0;        for (int32_t counter=0;counter < 1e10; ++counter){        // divide by two        a *= 0.5;        std::cout << "(" << std::setw(9) << counter << ") " << a << '\n';        // break if unable to distinguish        if (!(0<a)){            break;        }    }    // indicate successful    return 0;}```  C++ `while` ``` C++// int32_tinclude // setwinclude // std::coutinclude // program starting pointint32_t main(int32_t argn, char *argv[]){    // initialize    double a = 1.0;    // initialize counter    int32_t counter = 0;    // loop would stop when a becomes zero    while (0<a){        // divide a by two        a *= 0.5;        std::cout << "(" << std::setw(9)                  << (++counter) << ") "                  << a                  << '\n';        // max iteration limit        if (10000<counter){                break;        }    }    // indicate program success    return 0;}```  Example : Largest Fibonacci number below 100  Python `for`<jupyter_code># first two of the Fibonacci sequence
a0, a1 = 0, 1
# iteration limit
max_iter = 10000
# upper bound of the Fibonacci sequence
upper_bound = 100

for i in range(max_iter):
    # next 
    a2 = a0 + a1
    # if a2 reaches the upper_bound, stop
    if a2 >= upper_bound:
        break
    # present intermediate result
    # with end=' ', print would append ' ' instead of '\n'
    print(a2, end=' ')
    # update previous values
    a0, a1 = a1, a2

# present result
print(f'\nLargest Fibo below {upper_bound} = {a1}')<jupyter_output><empty_output><jupyter_text>Python `while`<jupyter_code>a0, a1 = 0, 1
a2 = 0
max_iter = 10000
upper_bound = 100

i = 0
while (a2 < upper_bound) and (i < max_iter):
    i += 1
    a2 = a0 + a1
    print(a1, end=' ')
    a0, a1 = a1, a2
    if i > max_iter:
        break

print(f'\nLargest Fibo below {upper_bound} = {a0}')<jupyter_output><empty_output><jupyter_text>C/C++ `for` ``` C++// int32_tinclude // std::coutinclude // program starting pointint32_t main(int32_t argn, char *argv[]){    // maximum number of iterations    const int32_t max_iter = 10000;    const int32_t upper_bound = 100;    // current and two previous values of Fibonacci Sequence    int32_t a0 = 0, a1 = 1, a2 = 0;    // for loop    // i would start from 0    // loop will stop when max_iter <= i    // at every iteration increase i by one    for (int32_t i=0; (max_iter > i); ++i){        // next Fibonacci Sequence is sum of two previous values        a2 = a0 + a1;        // stop if a2 becomes larger than upper_bound        if (upper_bound < a2){            break;        }                // update previous values        a0 = a1;        a1 = a2;                // present the new value        std::cout << a2 << ' ';    }    // indicate a1 because a2 > upper_bound    std::cout << "\nLargest Fibo below " << upper_bound << " = " << a1 << "\n";        return 0;}```  C++ `while` ``` C++include using namespace std;int main(int argn, char *argv[]){    const int max_iter =10000;    const int upper_bound = 100;    int a0 = 0, a1 = 1, a2 = 0;    int i = 0;    while ((upper_bound > a2) && (max_iter > i)){        i ++;        a2 = a0 + a1;        a0 = a1;        a1 = a2;        cout << a0 << ' ';    }    cout << "\nLargest Fibo below " << upper_bound << " = " << a0 << '\n';        return 0;}``` * Please see if you could improve the code.  Exercise  00 Smallest $\Delta x$ for $x=10.0$ (python) * Add a cell below and write a python program that finds smallest number satisfying $x + \Delta x > x$ when $x=10$.  01 Smallest $\Delta x$ for $x=10.0$ (C/C++) * Create a new .cpp file and write a C/C++ program that finds smallest number satisfying $x + \Delta x > x$ when $x=10$.  02 Minimum value of a polynomial (python) * Complete the python program of the following cell.<jupyter_code># Random number generator
import random

# Initalize the random number generator
random.seed()

# Paramaters for the polynomial
a0 = random.random() + 0.1
a1 = random.random() - 0.5
a2 = random.random() - 0.5

x = 1

for counter in range(100000):
    fx = a0 * x * x + a1 * x + a2 + (random.random() - 0.5) * 1e-5

# Write a python program that would try to find x minimzing fx
# within -100 < x < 100 or an interval of your choice<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1285099052540913, 'fraction_numerical': 0.030318690783807063, 'mean_word_length': 2.771029555050341, 'pattern_counts': {'":': 9, '<': 119, '<?xml version=': 0, '>': 43, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '140658', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 3812, 'n_tokens_neox': 3538, 'n_words': 1438, 'path': '01.ipynb', 'repo_name': '2018pycpp/18pycpp-02', 'size': '11610'}