Loop and relational expressions, cyclic relational expressions

Source: Internet
Author: User

Loop and relational expressions, cyclic relational expressions

For Loop

Fooloop. cpp

/* Forloop. cpp */# include <iostream> int main () {using namespace std; int I;/* this cycle first sets the integer variable I to 0: I = 0 this is the initialization part of the loop. Then, the loop test part checks whether I is less than 5: I <5 if it is indeed less than 5, the program will execute the following statement-loop body and then, the program uses the cyclic update part to add 1 until the cyclic update I is 5. In this case, the program fails to execute the loop statement. */For (/* initialize the loop part */I = 0;/* test the loop part */I <5;/* update the loop part */I ++) /* loop body */cout <"C ++ knows the loop. \ n "; cout <" C ++ knows when to stop. \ n "; cin. get (); cin. get (); return 0 ;}

Output

C ++ knows the cycle. C ++ knows when to stop.

 

Num_test.cpp

#include<iostream>int main(){    using namespace std;    cout << "Entet the starting coutdown value:";    int limit;    cin >> limit;    int i;    for (i = limit; i; i--)        cout << "i=" << i << "\n";    cout << "Done now that i=" << i << "\n";    cin.get();    cin.get();    return 0;}

Output

Entet the starting coutdown value:5i=5i=4i=3i=2i=1Done now that i=0

For Loop Design

 

Formore. cpp

# Include <iostream>
/* Use a symbolic constant where the length of the array is required. If the array is used multiple times, it is convenient to modify the length of the array */const int ArSize = 16; int main (){
Long factorials [ArSize]; factorials [1] = factorials [0] = 1LL; for (int I = 2; I <ArSize; I ++) factorials [I] = I * factorials [I-1];
/* The variables declared in fot-init-statement only exist in the for statement. That is to say, when the program leaves the loop, this variable will disappear */for (int I = 0; I <ArSize; I ++) std: cout <I <"! = "<Factorials [I] <std: endl; std: cin. get (); std: cin. get (); return 0 ;}

Output

0!=11!=12!=23!=64!=245!=1206!=7207!=50408!=403209!=36288010!=362880011!=3991680012!=47900160013!=622702080014!=8717829120015!=1307674368000

 

Forstr1

#include<iostream>#include<string>int main(){    using namespace std;    cout << "Enter a word:";    string word;    cin >> word;    for (int i = word.size()-1; i >= 0; i--)        cout << word[i];    cout << "\nBye.\n";    cin.get();    cin.get();    return 0;}

Output

Enter a word:nameemanBye.

 

Compound statement (statement block)

The format (or syntax) of the C ++ for statement may seem strict, because the loop body must be a statement. It is inconvenient for Zhejiang to include multiple statements in the loop body. Fortunately, C ++ provides a way to avoid this restriction. In this way, you can include any number of statements in the loop body.

Conforming statements also have an interesting feature. If a new variable is defined in the statement block, the variable exists only when the program executes the statements in the statement block. After the statement block is executed, the variable is released. This indicates that this variable is only available in this statement block.

Note: variables defined in the external statement block are also defined in the internal statement block.

What if a variable is declared in a statement block and an external statement block contains a variable with this name? Within the declared position to the end of the internal statement block, the new variable hides the old variable, and the old variable is visible again.

 

While Loop

A while LOOP is a for loop without initialization or update. It only has test conditions and body:

While (test-condition)

Body

First, the program calculates the test condition expression in parentheses. If the expression is true, the statement in the loop body is executed.

Obviously, if you want the loop to end, the code in the loop body must complete some operations that affect the test condition expression.

While Loop Structure

While. cpp

# Include <iostream> const int ArSize = 20; int main () {using namespace std; char name [ArSize]; cout <"Your first name, please :"; cin> name; cout <"Here is your name, varticalized and ASC Ⅱ ized: \ n"; int I = 0;/* The loop stops when a null character is encountered. This character-by-character traversal technique is a standard method for C ++ to process C-style strings. Because the string contains the end mark, therefore, the program usually does not need to know the length of the string * // *. You can modify the while row as follows: after the while (name [I]) is modified, the program will work in the same way. This is because name [I] is a regular character and its value is the encoding of this character-non-zero value or true. */While (name [I]! = '\ 0') {/* the ASC Ⅱ code of the character to be printed. name [I] must be converted to an integer by force type conversion. In this way, cout prints the value into an integer instead of interpreting it as a character encoding. */Cout <name [I] <":" <int (name [I]) <endl; /* Omitting this step will cause the loop to stay on the same array element, print the string and Its Encoding until the program is forcibly terminated. Leading to endless loops is one of the most common problems of loops. Usually */I ++;} cin. get (); cin. get (); return 0 ;}

Output

Your first name,please:MapleHere is your name,varticalized and ASCⅡized:M:77a:97p:112l:108e:101

 

For and while

Because the for loop is almost equivalent to the while loop, which one is just a matter of style. There are three differences between them. First, if the test condition is omitted in the for loop, the condition is considered to be true. Second, in the for loop, you can use the initialization statement to declare a local variable, however, you cannot do this in the while loop. Finally, if the loop body contains the continue statement, the situation will be slightly different.

Generally, programmers use a for loop to count a loop, because the for loop format allows all relevant information-the initial value, the termination value, and the method for updating the Counter-to be placed in the same place. When you cannot know the number of times the loop will be executed in advance, programmers often use the while loop.

 

Write a latency Loop

Waiting. cpp

#include<iostream>#include<ctime>int main(){    using namespace std;    cout << "Enter the delay time,in seconds:";    float secs;    cin >> secs;    clock_t delay = secs* CLOCKS_PER_SEC;    cout << "starting\a\n";    clock_t start = clock();    while (clock() - start < delay)        ;    cout << "done\a\n";    cin.get();    cin.get();    return 0;}

 

Do while LOOP

Do while loop is an exit condition loop. This means that this loop will first execute the loop body, then determine the test expression, and decide whether to continue executing the loop. If the condition is false, the loop ends. Otherwise, a new round of execution and testing will be conducted.

Syntax:

Do

Body

While (test-expression)

Structure of the do while LOOP

Sometimes the do while test is reasonable. For example, when requesting user input, the program must first obtain the input and then test it.

 

Range-based for loop (C ++ 11)

This loop simplifies a common loop task: to perform the same operation on each element of an array (or container class, such as vector and array.

Double prices [5] = {4.99, 10.99, 6.87, 7.99, 8.49 };

For (double x: prices)

Cout <x <std: endl;

X indicates the first element of the array prices. After the first element is displayed, the loop is continuously executed, and x indicates other elements of the array in turn.

 

Loop and text input

Cin objects support single-Character Input in three different modes, and their user interfaces are different. The following describes how to use these three modes in a while loop.

Input using the original cin

# Include <iostream> int main () {using namespace std; char ch; int count = 0; cout <"Enter characters; enter # to-quit; \ n "; cin> ch; // read the first character before the loop, so that the loop can test the first character. This is important because the first character may be # while (ch! = '#'/* Sentinel character, used as the stop mark */) {cout <ch; // echo read character + + count; // calculate the number of characters read. cin> ch;} cout <endl <count <"characters read"; // The total number of characters processed by the Report. cin. get (); cin. get (); return 0 ;}

 

Nested loops and two-dimensional arrays

C ++ does not provide a two-dimensional array, but you can create an array for each element.

for(int row=0;row<4;row++){    for(int col=0;col<5;++col)        cout<<maxtemps[row][col]<<"\t";    cout<<endl;}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.