While loop statement study case

learning target

  1. Understand the meaning of loop structure.

  2. Familiar with the format and function of while and do-while statements.

  3. Initially apply the while statement to solve some practical problems.
    [Knowledge Landing]
    The format of the while statement is as follows:
    while (expression)
    {
    loop body
    }

    Insert picture description here

    Its meaning is: first calculate the value of the expression (generally called the loop condition), when the value of the expression is true (the loop condition is established), execute the loop body once. The difference with the if statement is that after the loop body is executed once, the while statement returns to the beginning, continues to calculate and judge the true or false of the expression, and decides whether to execute the loop body again. That is, "when the expression is established, the loop body is executed repeatedly", so it is also called "the current loop".

Example 1. Find the value of 1+2+3+…+100.
[Question analysis]
Set sum to store the answer, and initialize it to 0. Let i be the loop control variable and initialize it to 1. When the loop condition (i<=100) is established, the following loop body is executed repeatedly:
(1) Add i to the sum;
(2) Set i as the next number, i.e. i++.
Finally, output the value of ans.

#include<iostream>
using namespace std;
int main(){
    
    
    int i = 1,sum = 0;
    while(i <= 100) sum += i++;
    cout << sum << endl;
    return 0;
} 

[Practical exercise]
Try to use the while loop to write a program to output 100 "Hello World!" in a loop.
[Learning to think]
1. A cycle is a computer that does things repeatedly, so to write a cycle, you must first think about two questions: one is to do what the computer does repeatedly (the body of the loop); the other is when to start and when to end ( Loop control)
Thinking about these two issues clearly, the loop program is easy to write!
2. Video learning: Andy WeChat 13734582485
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_32431299/article/details/110682933