Translate

Uses A Simple While Loop With compound-statement Syntax For Variable Names

#include <iostream>
using namespace std;
int main() {
int x, y;
// Get number from the keyboard and initialize x.
cout << "Enter a number and press ENTER: ";
cin >> y;
x = 1;

while (x <= y) { // While i less than or equal y,
cout << x << " "; // Print x,
x = x + 1; // Add 1 to i.
}
system("PAUSE");
return 0;
}


As you know that omments can be on their own lines or to the right of the statements.
The program, when run, counts to the specified number. Now we see for the result of the example, if the user inputs 6 from the keyboard, then the program will prints the following result:
1 2 3 4 5 6

This syntax introduces a new operator 'less than or equal to'.
x <= y
The less-than-or-equal operator (<=) is one of several relational operators, all of which return true or false.

OPERATOR
MEANING
==
Test for equality
!=
Test for inequality (greater than or less than)
Greater than
Less than
>=
Greater than or equal to
<=
Less than or equal to
If you followed logic way in this section, you now know the loop itself is straightforward. The braces ({}) create a statement block so that the while loop executes two statements each time through, rather than one. Now if we think about, the we will see that the last number of the syntax above is to be printed to 'y' which is what we want. As soon as x becomes greater than y, then the loop ends, and the output statement never executes for this case. The loop adds 1 to x before continuing to the next cycle. This ensures that the loop eventually ends, because it will sooner or later become greater than y (at which point the loop condition will fail). 

x = x + 1; which it's mean: Add 1 to x.

It may be easier to see how a while loop works in the following diagram, which shows the flow of control in the loop.



The program like this (while - loop) can be made more efficient by combining a couple of the statements. We can do the combining by initialization, in which you assign a value that you
declare for it. You can use the equal sign (=) to give any numeric or string that will be as a variable for the syntax of your program. The value created by this logic: int variable = value;

Now you can try to practice by writing a program to print all the numbers from n1 to n2, where n1 and n2 are two numbers specified by the user. (Hint: You’ll need to prompt for two values n1 and n2; then initialize i to n1 and use n2 in the loop condition.)


No comments:

Post a Comment