LEARNING C++ English Tutorial
Hello EPVP,
Today I am posting a Tutorial about C++ This is where I learned it from and hopefully you will to. I put it in spoilers so it will not be so messy. Hopefully this tutorial gets approved cause I really put alot of time into getting it up on here but, I hope you guys learn it well. Peace.
Today I am posting a Tutorial about C++ This is where I learned it from and hopefully you will to. I put it in spoilers so it will not be so messy. Hopefully this tutorial gets approved cause I really put alot of time into getting it up on here but, I hope you guys learn it well. Peace.
INTRO TO C++
What's with all these variable types?
If statements in C++
Switch Case in C++
A C++ program is a collection of commands, which tell the computer to do "something". This collection of commands is usually called C++ source code, source code or just code. Commands are either "functions" or "keywords". Keywords are a basic building block of the language, while functions are, in fact, usually written in terms of simpler functions--you'll see this in our very first program, below.
Every program in C++ has one function, always named main, that is always called when your program first executes. From main, you can also call other functions whether they are written by us or, as mentioned earlier, provided by the compiler.
To access those standard functions that comes with the compiler, you include a header with the #include directive. What this does is effectively take everything in the header and paste it into your program. Let's look at a working program:
1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;
int main()
{
cout<<"HEY, you, I'm alive! Oh, and Hello World!\n";
cin.get();
}
The next important line is int main(). This line tells the compiler that there is a function named main, and that the function returns an integer, hence int. The "curly braces" ({ and }) signal the beginning and end of functions and other code blocks. You can think of them as meaning BEGIN and END.
The next command is cin.get(). This is another function call: it reads in input and expects the user to hit the return key. Many compiler environments will open a new console window, run the program, and then close the window. This command keeps that window from closing because the program is not done yet because it waits for you to hit enter. Including that line gives you time to see the program run.
Every program in C++ has one function, always named main, that is always called when your program first executes. From main, you can also call other functions whether they are written by us or, as mentioned earlier, provided by the compiler.
To access those standard functions that comes with the compiler, you include a header with the #include directive. What this does is effectively take everything in the header and paste it into your program. Let's look at a working program:
1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;
int main()
{
cout<<"HEY, you, I'm alive! Oh, and Hello World!\n";
cin.get();
}
The next important line is int main(). This line tells the compiler that there is a function named main, and that the function returns an integer, hence int. The "curly braces" ({ and }) signal the beginning and end of functions and other code blocks. You can think of them as meaning BEGIN and END.
The next command is cin.get(). This is another function call: it reads in input and expects the user to hit the return key. Many compiler environments will open a new console window, run the program, and then close the window. This command keeps that window from closing because the program is not done yet because it waits for you to hit enter. Including that line gives you time to see the program run.
What's with all these variable types?
Sometimes it can be confusing to have multiple variable types when it seems like some variable types are redundant (why have integer numbers when you have floats?). Using the right variable type can be important for making your code readable and for efficiency--some variables require more memory than others. Moreover, because of the way the numbers are actually stored in memory, a float is "inexact", and should not be used when you need to store an "exact" integer value.
Declaring Variables in C++
To declare a variable you use the syntax "type <name>;". Here are some variable declaration examples:
1
2
3
int x;
char letter;
float the_float;
It is permissible to declare multiple variables of the same type on the same line; each one should be separated by a comma.
1
int a, b, c, d;
If you were watching closely, you might have seen that declaration of a variable is always followed by a semicolon (note that this is the same procedure used when you call a function).
Common Errors when Declaring Variables in C++
If you attempt to use a variable that you have not declared, your program will not be compiled or run, and you will receive an error message informing you that you have made a mistake. Usually, this is called an undeclared variable.
Using Variables
Here is a sample program demonstrating the use of a variable:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
int main()
{
int thisisanumber;
cout<<"Please enter a number: ";
cin>> thisisanumber;
cin.ignore();
cout<<"You entered: "<< thisisanumber <<"\n";
cin.get();
}
Let's break apart this program and examine it line by line. The keyword int declares thisisanumber to be an integer. The function cin>> reads a value into thisisanumber; the user must press enter before the number is read by the program. cin.ignore() is another function that reads and discards a character. Remember that when you type input into a program, it takes the enter key too. We don't need this, so we throw it away. Keep in mind that the variable was declared an integer; if the user attempts to type in a decimal number, it will be truncated (that is, the decimal component of the number will be ignored). Try typing in a sequence of characters or a decimal number when you run the example program; the response will vary from input to input, but in no case is it particularly pretty. Notice that when printing out a variable quotation marks are not used. Were there quotation marks, the output would be "You Entered: thisisanumber." The lack of quotation marks informs the compiler that there is a variable, and therefore that the program should check the value of the variable in order to replace the variable name with the variable when executing the output function. Do not be confused by the inclusion of two separate insertion operators on one line. Including multiple insertion operators on one line is perfectly acceptable and all of the output will go to the same place. In fact, you must separate string literals (strings enclosed in quotation marks) and variables by giving each its own insertion operators (<<). Trying to put two variables together with only one << will give you an error message, do not try it. Do not forget to end functions and declarations with a semicolon. If you forget the semicolon, the compiler will give you an error message when you attempt to compile the program.
Changing and Comparing Variables
Of course, no matter what type you use, variables are uninteresting without the ability to modify them. Several operators used with variables include the following: *, -, +, /, =, ==, >, <. The * multiplies, the - subtracts, and the + adds. It is of course important to realize that to modify the value of a variable inside the program it is rather important to use the equal sign. In some languages, the equal sign compares the value of the left and right values, but in C++ == is used for that task. The equal sign is still extremely useful. It sets the left input to the equal sign, which must be one, and only one, variable equal to the value on the right side of the equal sign. The operators that perform mathematical functions should be used on the right side of an equal sign in order to assign the result to a variable on the left side.
Here are a few examples:
1
2
3
a = 4 * 6; // (Note use of comments and of semicolon) a is 24
a = a + 5; // a equals the original value of a with five added to it
a == 5 // Does NOT assign five to a. Rather, it checks to see if a equals 5.
The other form of equal, ==, is not a way to assign a value to a variable. Rather, it checks to see if the variables are equal. It is useful in other areas of C++; for example, you will often use == in such constructions as conditional statements and loops. You can probably guess how < and > function. They are greater than and less than operators.
For example:
1
2
3
a < 5 // Checks to see if a is less than five
a > 5 // Checks to see if a is greater than five
a == 5 // Checks to see if a equals five, for good measure
Comparing variables isn't really useful until you have some way of using the results.
Declaring Variables in C++
To declare a variable you use the syntax "type <name>;". Here are some variable declaration examples:
1
2
3
int x;
char letter;
float the_float;
It is permissible to declare multiple variables of the same type on the same line; each one should be separated by a comma.
1
int a, b, c, d;
If you were watching closely, you might have seen that declaration of a variable is always followed by a semicolon (note that this is the same procedure used when you call a function).
Common Errors when Declaring Variables in C++
If you attempt to use a variable that you have not declared, your program will not be compiled or run, and you will receive an error message informing you that you have made a mistake. Usually, this is called an undeclared variable.
Using Variables
Here is a sample program demonstrating the use of a variable:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
int main()
{
int thisisanumber;
cout<<"Please enter a number: ";
cin>> thisisanumber;
cin.ignore();
cout<<"You entered: "<< thisisanumber <<"\n";
cin.get();
}
Let's break apart this program and examine it line by line. The keyword int declares thisisanumber to be an integer. The function cin>> reads a value into thisisanumber; the user must press enter before the number is read by the program. cin.ignore() is another function that reads and discards a character. Remember that when you type input into a program, it takes the enter key too. We don't need this, so we throw it away. Keep in mind that the variable was declared an integer; if the user attempts to type in a decimal number, it will be truncated (that is, the decimal component of the number will be ignored). Try typing in a sequence of characters or a decimal number when you run the example program; the response will vary from input to input, but in no case is it particularly pretty. Notice that when printing out a variable quotation marks are not used. Were there quotation marks, the output would be "You Entered: thisisanumber." The lack of quotation marks informs the compiler that there is a variable, and therefore that the program should check the value of the variable in order to replace the variable name with the variable when executing the output function. Do not be confused by the inclusion of two separate insertion operators on one line. Including multiple insertion operators on one line is perfectly acceptable and all of the output will go to the same place. In fact, you must separate string literals (strings enclosed in quotation marks) and variables by giving each its own insertion operators (<<). Trying to put two variables together with only one << will give you an error message, do not try it. Do not forget to end functions and declarations with a semicolon. If you forget the semicolon, the compiler will give you an error message when you attempt to compile the program.
Changing and Comparing Variables
Of course, no matter what type you use, variables are uninteresting without the ability to modify them. Several operators used with variables include the following: *, -, +, /, =, ==, >, <. The * multiplies, the - subtracts, and the + adds. It is of course important to realize that to modify the value of a variable inside the program it is rather important to use the equal sign. In some languages, the equal sign compares the value of the left and right values, but in C++ == is used for that task. The equal sign is still extremely useful. It sets the left input to the equal sign, which must be one, and only one, variable equal to the value on the right side of the equal sign. The operators that perform mathematical functions should be used on the right side of an equal sign in order to assign the result to a variable on the left side.
Here are a few examples:
1
2
3
a = 4 * 6; // (Note use of comments and of semicolon) a is 24
a = a + 5; // a equals the original value of a with five added to it
a == 5 // Does NOT assign five to a. Rather, it checks to see if a equals 5.
The other form of equal, ==, is not a way to assign a value to a variable. Rather, it checks to see if the variables are equal. It is useful in other areas of C++; for example, you will often use == in such constructions as conditional statements and loops. You can probably guess how < and > function. They are greater than and less than operators.
For example:
1
2
3
a < 5 // Checks to see if a is less than five
a > 5 // Checks to see if a is greater than five
a == 5 // Checks to see if a equals five, for good measure
Comparing variables isn't really useful until you have some way of using the results.
If statements in C++
Without a conditional statement such as the if statement, programs would run almost the exact same way every time. If statements allow the flow of the program to be changed, and so they allow algorithms and more interesting code.
A true statement is one that evaluates to a nonzero number. A false statement evaluates to zero. When you perform comparison with the relational operators, the operator will return 1 if the comparison is true, or 0 if the comparison is false. For example, the check 0 == 2 evaluates to 0. The check 2 == 2 evaluates to a 1.
When programming, the aim of the program will often require the checking of one value stored by a variable against another value to determine whether one is larger, smaller, or equal to the other.
There are a number of operators that allow these checks.
ELSE
Sometimes when the condition in an if statement evaluates to false, it would be nice to execute some code instead of the code executed when the statement evaluates to true. The "else" statement effectively says that whatever code after it (whether a single line or code between brackets) is executed if the if statement is FALSE.
Else If
Another use of else is when there are multiple conditional statements that may all evaluate to true, yet you want only one if statement's body to execute. You can use an "else if" statement following an if statement and its body; that way, if the first statement is true, the "else if" will be ignored, but if the if statement is false, it will then check the condition for the else if statement. If the if statement was true the else statement will not be checked. It is possible to use numerous else if statements to ensure that only one block of code is executed.
A true statement is one that evaluates to a nonzero number. A false statement evaluates to zero. When you perform comparison with the relational operators, the operator will return 1 if the comparison is true, or 0 if the comparison is false. For example, the check 0 == 2 evaluates to 0. The check 2 == 2 evaluates to a 1.
When programming, the aim of the program will often require the checking of one value stored by a variable against another value to determine whether one is larger, smaller, or equal to the other.
There are a number of operators that allow these checks.
ELSE
Sometimes when the condition in an if statement evaluates to false, it would be nice to execute some code instead of the code executed when the statement evaluates to true. The "else" statement effectively says that whatever code after it (whether a single line or code between brackets) is executed if the if statement is FALSE.
Else If
Another use of else is when there are multiple conditional statements that may all evaluate to true, yet you want only one if statement's body to execute. You can use an "else if" statement following an if statement and its body; that way, if the first statement is true, the "else if" will be ignored, but if the if statement is false, it will then check the condition for the else if statement. If the if statement was true the else statement will not be checked. It is possible to use numerous else if statements to ensure that only one block of code is executed.
Loops
Loops are used to repeat a block of code. Being able to have your program repeatedly execute a block of code is one of the most basic but useful tasks in programming -- many programs or websites that produce extremely complex output (such as a message board) are really only executing a single task many times. (They may be executing a small number of tasks, but in principle, to produce a list of messages only requires repeating the operation of reading in some data and displaying it.) Now, think about what this means: a loop lets you write a very simple statement to produce a significantly greater result simply by repetition.
The variable initialization allows you to either declare a variable and give it a value or give a value to an already existing variable. Second, the condition tells the program that while the conditional expression is true the loop should continue to repeat itself. The variable update section is the easiest way for a for loop to handle changing of the variable. It is possible to do things like x++, x = x + 10, or even x = random ( 5 ), and if you really wanted to, you could call other functions that do nothing to the variable but still have a useful effect on the code. Notice that a semicolon separates each of these sections, that is important. Also note that every single one of the sections may be empty, though the semicolons still have to be there. If the condition is empty, it is evaluated as true and the loop will repeat until something else stops it.
Example:
#include <iostream>
using namespace std; // So the program can see cout and endl
int main()
{
// The loop goes while x < 10, and x increases by one every loop
for ( int x = 0; x < 10; x++ ) {
// Keep in mind that the loop condition checks
// the conditional statement before it loops again.
// consequently, when x equals 10 the loop breaks.
// x is updated before the condition is checked.
cout<< x <<endl;
}
cin.get();
}
WHILE - WHILE loops are very simple. The basic structure is
while ( condition ) { Code to execute while the condition is true } The true represents a boolean expression which could be x == 1 or while ( x != 7 ) (x does not equal 7). It can be any combination of boolean statements that are legal. Even, (while x ==5 || v == 7) which says execute the code while x equals five or while v equals 7. Notice that a while loop is the same as a for loop without the initialization and update sections. However, an empty condition is not legal for a while loop as it is with a for loop.
Example:
#include <iostream>
using namespace std; // So we can see cout and endl
int main()
{
int x = 0; // Don't forget to declare variables
while ( x < 10 ) { // While x is less than 10
cout<< x <<endl;
x++; // Update x so the condition can be met eventually
}
cin.get();
}
The easiest way to think of the loop is that when it reaches the brace at the end it jumps back up to the beginning of the loop, which checks the condition again and decides whether to repeat the block another time, or stop and move to the next statement after the block.
Notice that the condition is tested at the end of the block instead of the beginning, so the block will be executed at least once. If the condition is true, we jump back to the beginning of the block and execute it again. A do..while loop is basically a reversed while loop. A while loop says "Loop while the condition is true, and execute this block of code", a do..while loop says "Execute this block of code, and loop while the condition is true".
Example:
#include <iostream>
using namespace std;
int main()
{
int x;
x = 0;
do {
// "Hello, world!" is printed at least one time
// even though the condition is false
cout<<"Hello, world!\n";
} while ( x != 0 );
cin.get();
}
Keep in mind that you must include a trailing semi-colon after the while in the above example. A common error is to forget that a do..while loop must be terminated with a semicolon (the other loops should not be terminated with a semicolon, adding to the confusion). Notice that this loop will execute once, because it automatically executes before checking the condition.
The variable initialization allows you to either declare a variable and give it a value or give a value to an already existing variable. Second, the condition tells the program that while the conditional expression is true the loop should continue to repeat itself. The variable update section is the easiest way for a for loop to handle changing of the variable. It is possible to do things like x++, x = x + 10, or even x = random ( 5 ), and if you really wanted to, you could call other functions that do nothing to the variable but still have a useful effect on the code. Notice that a semicolon separates each of these sections, that is important. Also note that every single one of the sections may be empty, though the semicolons still have to be there. If the condition is empty, it is evaluated as true and the loop will repeat until something else stops it.
Example:
#include <iostream>
using namespace std; // So the program can see cout and endl
int main()
{
// The loop goes while x < 10, and x increases by one every loop
for ( int x = 0; x < 10; x++ ) {
// Keep in mind that the loop condition checks
// the conditional statement before it loops again.
// consequently, when x equals 10 the loop breaks.
// x is updated before the condition is checked.
cout<< x <<endl;
}
cin.get();
}
WHILE - WHILE loops are very simple. The basic structure is
while ( condition ) { Code to execute while the condition is true } The true represents a boolean expression which could be x == 1 or while ( x != 7 ) (x does not equal 7). It can be any combination of boolean statements that are legal. Even, (while x ==5 || v == 7) which says execute the code while x equals five or while v equals 7. Notice that a while loop is the same as a for loop without the initialization and update sections. However, an empty condition is not legal for a while loop as it is with a for loop.
Example:
#include <iostream>
using namespace std; // So we can see cout and endl
int main()
{
int x = 0; // Don't forget to declare variables
while ( x < 10 ) { // While x is less than 10
cout<< x <<endl;
x++; // Update x so the condition can be met eventually
}
cin.get();
}
The easiest way to think of the loop is that when it reaches the brace at the end it jumps back up to the beginning of the loop, which checks the condition again and decides whether to repeat the block another time, or stop and move to the next statement after the block.
Notice that the condition is tested at the end of the block instead of the beginning, so the block will be executed at least once. If the condition is true, we jump back to the beginning of the block and execute it again. A do..while loop is basically a reversed while loop. A while loop says "Loop while the condition is true, and execute this block of code", a do..while loop says "Execute this block of code, and loop while the condition is true".
Example:
#include <iostream>
using namespace std;
int main()
{
int x;
x = 0;
do {
// "Hello, world!" is printed at least one time
// even though the condition is false
cout<<"Hello, world!\n";
} while ( x != 0 );
cin.get();
}
Keep in mind that you must include a trailing semi-colon after the while in the above example. A common error is to forget that a do..while loop must be terminated with a semicolon (the other loops should not be terminated with a semicolon, adding to the confusion). Notice that this loop will execute once, because it automatically executes before checking the condition.
Switch Case in C++
Switch case statements are a substitute for long if statements that compare a variable to several "integral" values ("integral" values are simply values that can be expressed as an integer, such as the value of a char). The basic format for using switch case is outlined below. The value of the variable given into switch is compared to the value following each of the cases, and when one value matches the value of the variable, the computer continues executing the program from that point.
switch ( <variable> ) {
case this-value:
Code to execute if <variable> == this-value
break;
case that-value:
Code to execute if <variable> == that-value
break;
...
default:
Code to execute if <variable> does not equal the value following any of the cases
break;
}
The condition of a switch statement is a value. The case says that if it has the value of whatever is after that case then do whatever follows the colon. The break is used to break out of the case statements. Break is a keyword that breaks out of the code block, usually surrounded by braces, which it is in. In this case, break prevents the program from falling through and executing the code in all the other case statements. An important thing to note about the switch statement is that the case values may only be constant integral expressions. Sadly, it isn't legal to use case like this:
The default case is optional, but it is wise to include it as it handles any unexpected cases. Switch statements serves as a simple way to write long if statements when the requirements are met. Often it can be used to process input from a user.
int a = 10;
int b = 10;
int c = 20;
switch ( a ) {
case b:
// Code
break;
case c:
// Code
break;
default:
// Code
break;
}
Below is a sample program, in which not all of the proper functions are actually declared, but which shows how one would use switch in a program.
#include <iostream>
using namespace std;
void playgame()
{
cout << "Play game called";
}
void loadgame()
{
cout << "Load game called";
}
void playmultiplayer()
{
cout << "Play multiplayer game called";
}
int main()
{
int input;
cout<<"1. Play game\n";
cout<<"2. Load game\n";
cout<<"3. Play multiplayer\n";
cout<<"4. Exit\n";
cout<<"Selection: ";
cin>> input;
switch ( input ) {
case 1: // Note the colon, not a semicolon
playgame();
break;
case 2: // Note the colon, not a semicolon
loadgame();
break;
case 3: // Note the colon, not a semicolon
playmultiplayer();
break;
case 4: // Note the colon, not a semicolon
cout<<"Thank you for playing!\n";
break;
default: // Note the colon, not a semicolon
cout<<"Error, bad input, quitting\n";
break;
}
cin.get();
}
This program will compile, but cannot be run until the undefined functions are given bodies, but it serves as a model (albeit simple) for processing input. If you do not understand this then try mentally putting in if statements for the case statements. Default simply skips out of the switch case construction and allows the program to terminate naturally. If you do not like that, then you can make a loop around the whole thing to have it wait for valid input. You could easily make a few small functions if you wish to test the code.
switch ( <variable> ) {
case this-value:
Code to execute if <variable> == this-value
break;
case that-value:
Code to execute if <variable> == that-value
break;
...
default:
Code to execute if <variable> does not equal the value following any of the cases
break;
}
The condition of a switch statement is a value. The case says that if it has the value of whatever is after that case then do whatever follows the colon. The break is used to break out of the case statements. Break is a keyword that breaks out of the code block, usually surrounded by braces, which it is in. In this case, break prevents the program from falling through and executing the code in all the other case statements. An important thing to note about the switch statement is that the case values may only be constant integral expressions. Sadly, it isn't legal to use case like this:
The default case is optional, but it is wise to include it as it handles any unexpected cases. Switch statements serves as a simple way to write long if statements when the requirements are met. Often it can be used to process input from a user.
int a = 10;
int b = 10;
int c = 20;
switch ( a ) {
case b:
// Code
break;
case c:
// Code
break;
default:
// Code
break;
}
Below is a sample program, in which not all of the proper functions are actually declared, but which shows how one would use switch in a program.
#include <iostream>
using namespace std;
void playgame()
{
cout << "Play game called";
}
void loadgame()
{
cout << "Load game called";
}
void playmultiplayer()
{
cout << "Play multiplayer game called";
}
int main()
{
int input;
cout<<"1. Play game\n";
cout<<"2. Load game\n";
cout<<"3. Play multiplayer\n";
cout<<"4. Exit\n";
cout<<"Selection: ";
cin>> input;
switch ( input ) {
case 1: // Note the colon, not a semicolon
playgame();
break;
case 2: // Note the colon, not a semicolon
loadgame();
break;
case 3: // Note the colon, not a semicolon
playmultiplayer();
break;
case 4: // Note the colon, not a semicolon
cout<<"Thank you for playing!\n";
break;
default: // Note the colon, not a semicolon
cout<<"Error, bad input, quitting\n";
break;
}
cin.get();
}
This program will compile, but cannot be run until the undefined functions are given bodies, but it serves as a model (albeit simple) for processing input. If you do not understand this then try mentally putting in if statements for the case statements. Default simply skips out of the switch case construction and allows the program to terminate naturally. If you do not like that, then you can make a loop around the whole thing to have it wait for valid input. You could easily make a few small functions if you wish to test the code.
GERMAN C++ TUTORIAL
Hallo EPVP,
Heute bin ich Ihr einen Tutorial zu C++ Dies ist, wo ich lernte es von und hoffentlich werden Sie zu. Ich habe es in Spoiler, damit es nicht so chaotisch. Hoffentlich Tutorial genehmigt bekommt, weil ich wirklich setzen viel Zeit in immer es auf hier, aber ich hoffe, euch lernen es gut. Frieden.
Heute bin ich Ihr einen Tutorial zu C++ Dies ist, wo ich lernte es von und hoffentlich werden Sie zu. Ich habe es in Spoiler, damit es nicht so chaotisch. Hoffentlich Tutorial genehmigt bekommt, weil ich wirklich setzen viel Zeit in immer es auf hier, aber ich hoffe, euch lernen es gut. Frieden.
LERNEN C++
INTRO TO C++
Was ist mit all diesen Variablen-Typen?
If-Anweisungen in C++
-Schalter-Kasten in C++
INTRO TO C++
Ein C++-Programm ist eine Sammlung von Befehlen, die den Computer zu sagen, "etwas" zu tun. Diese Sammlung von Befehlen wird normalerweise als C++-Quellcode, Source-Code oder einfach nur Code. Befehle sind entweder "Funktionen" oder "keywords". Keywords sind ein Grundbaustein der Sprache, während Funktionen werden in der Tat, in der Regel in Bezug auf einfachere Funktionen geschrieben - du wirst sehen dies in unserem ersten Programm, unten.
*Jedes Programm in C++ eine Funktion hat, immer den Namen main, dass immer aufgerufen, wenn das Programm führt zuerst. Von Haupt, können Sie auch andere Funktionen aufrufen, ob sie von uns schriftlich oder, wie bereits erwähnt, durch den Compiler zur Verfügung gestellt.
Um diese Standard-Funktionen, die mit dem Compiler kommt zuzugreifen, einen Header mit der # include-Direktive sind Sie. Was das bedeutet ist alles effektiv zu nehmen in der Kopfzeile und fügen Sie ihn in Ihrem Programm. Lassen Sie uns an einem Arbeitsprogramm:
1
2
3
4
5
6
7
8
9
# Include <iostream>
*
using namespace std;
*
int main ()
{
**cout << "! Hey, du, ich bin am Leben Oh, und Hallo Welt \ n";
**cin.get ();
}
Der nächste wichtige Zeile ist int main (). Diese Zeile sagt dem Compiler, dass es eine Funktion namens main, und dass die Funktion einen Integer zurückgibt, also int. Die "geschweiften Klammern" ({und}) signalisieren den Beginn und das Ende von Funktionen und anderen Code-Blöcke. Sie können von ihnen denken, dahin beginnen und enden.
Der nächste Befehl wird cin.get (). Dies ist ein weiterer Funktionsaufruf: Sie liest in der Eingangs und erwartet, dass der Benutzer die Enter-Taste drücken. Viele Compiler-Umgebungen wird ein neues Konsolenfenster öffnen, starten Sie das Programm, und schließen Sie das Fenster. Dieser Befehl hält das Fenster schließt, weil das Programm noch nicht getan, weil es wartet, bis Sie die Eingabetaste drücken. Inklusive dieser Linie gibt Ihnen Zeit, um das Programm laufen zu sehen.
*Jedes Programm in C++ eine Funktion hat, immer den Namen main, dass immer aufgerufen, wenn das Programm führt zuerst. Von Haupt, können Sie auch andere Funktionen aufrufen, ob sie von uns schriftlich oder, wie bereits erwähnt, durch den Compiler zur Verfügung gestellt.
Um diese Standard-Funktionen, die mit dem Compiler kommt zuzugreifen, einen Header mit der # include-Direktive sind Sie. Was das bedeutet ist alles effektiv zu nehmen in der Kopfzeile und fügen Sie ihn in Ihrem Programm. Lassen Sie uns an einem Arbeitsprogramm:
1
2
3
4
5
6
7
8
9
# Include <iostream>
*
using namespace std;
*
int main ()
{
**cout << "! Hey, du, ich bin am Leben Oh, und Hallo Welt \ n";
**cin.get ();
}
Der nächste wichtige Zeile ist int main (). Diese Zeile sagt dem Compiler, dass es eine Funktion namens main, und dass die Funktion einen Integer zurückgibt, also int. Die "geschweiften Klammern" ({und}) signalisieren den Beginn und das Ende von Funktionen und anderen Code-Blöcke. Sie können von ihnen denken, dahin beginnen und enden.
Der nächste Befehl wird cin.get (). Dies ist ein weiterer Funktionsaufruf: Sie liest in der Eingangs und erwartet, dass der Benutzer die Enter-Taste drücken. Viele Compiler-Umgebungen wird ein neues Konsolenfenster öffnen, starten Sie das Programm, und schließen Sie das Fenster. Dieser Befehl hält das Fenster schließt, weil das Programm noch nicht getan, weil es wartet, bis Sie die Eingabetaste drücken. Inklusive dieser Linie gibt Ihnen Zeit, um das Programm laufen zu sehen.
Was ist mit all diesen Variablen-Typen?
Manchmal kann es verwirrend sein, um mehrere Variablen-Typen haben, wenn es scheint, wie einige Variablentypen sind redundant (warum haben ganze Zahlen, wenn Sie schwebt haben?). Mit der richtigen Variablentyp kann für die Herstellung Ihrer Code lesbar und Effizienz wichtig sein - einige Variablen mehr Speicher benötigen als andere. Außerdem wegen der Art, die Zahlen sind tatsächlich im Speicher gespeichert werden, ist ein Schwimmer "ungenau", und sollte nicht verwendet werden, wenn Sie eine "exakte" Integer-Wert speichern müssen.
Deklarieren von Variablen in C++
Um eine Variable verwenden Sie die Syntax erklären "Typ <name>,". Hier sind einige Beispiele Variablendeklaration:
1
2
3
int x;
char Brief;
the_float schweben;
Es ist zulässig, mehrere Variablen des gleichen Typs auf der gleichen Linie zu erklären; jeder sollte von einem Komma getrennt werden.
1
int a, b, c, d;
Wenn du genau beobachten, könnten Sie gesehen haben, dass die Deklaration einer Variablen wird immer durch ein Semikolon (dies ist das gleiche Verfahren verwendet, wenn Sie eine Funktion aufrufen).
Häufige Fehler bei der Deklaration von Variablen in C++
Wenn Sie versuchen, eine Variable, die Sie nicht erklärt haben, zu verwenden, wird Ihr Programm nicht kompiliert werden oder laufen, und Sie erhalten eine Fehlermeldung darüber informiert, dass Sie einen Fehler gemacht haben, erhalten. In der Regel wird dies als eine nicht deklarierte Variable.
Verwenden von Variablen
Hier ist ein Beispielprogramm demonstriert die Verwendung einer Variablen:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Include <iostream>
*
using namespace std;
*
int main ()
{
**int thisisanumber;
*
**cout << "Bitte geben Sie eine Zahl ein:";
**cin >> thisisanumber;
**cin.ignore ();
**cout << "Sie haben:" << thisisanumber << "\ n";
**cin.get ();
}
Lassen Sie uns auseinanderbrechen dieses Programm und untersuchen es Zeile für Zeile. Das Schlüsselwort int erklärt thisisanumber auf eine ganze Zahl sein. Die Funktion cin >> liest einen Wert in thisisanumber; muss der Benutzer die Eingabetaste drücken, bevor die Anzahl wird von dem Programm zu lesen. cin.ignore () ist eine weitere Funktion, die liest und verwirft ein Zeichen. Denken Sie daran, dass, wenn Sie in ein Programm eingeben Eingang, nimmt es die Enter-Taste zu. Wir tun dies nicht brauchen, so dass wir werfen es weg. Beachten Sie, dass die Variable eine ganze Zahl deklariert; Wenn der Benutzer eine Dezimalzahl in versucht, wird er gekürzt (das heißt, die Komponente des dezimalen Zahl wird ignoriert). Versuchen Sie, in einer Sequenz von Zeichen oder eine Dezimalzahl, wenn Sie das Beispiel-Programm ausführen; die Antwort wird von Eingang zu Eingang variieren, aber in keinem Fall ist es besonders schön. Beachten Sie, dass beim Ausdruck eine Variable Anführungszeichen werden nicht verwendet. Gab es in Anführungszeichen, der Ausgang wäre "Du Eingetragen von:. Thisisanumber" Das Fehlen von Anführungszeichen informiert den Compiler, dass es eine Variable ist, und daher, dass das Programm den Wert der Variablen, um die Variablennamen mit der Variablen bei der Ausführung der Ausgangsfunktion ersetzen überprüfen. Lassen Sie sich durch die Aufnahme von zwei separaten Einschub Operatoren in einer Zeile verwechselt werden. Inklusive Facheingabe Betreiber auf einer Linie ist durchaus akzeptabel und die gesamte Ausgabe wird an den gleichen Ort zu gehen. In der Tat, müssen Sie Stringliterale (Strings in Anführungszeichen) und Variablen, indem jeder seinen eigenen Einführungs Operatoren (<<) zu trennen. Der Versuch, zwei Variablen zusammen mit nur einer legte << erhalten Sie eine Fehlermeldung, versuchen Sie es nicht. Vergessen Sie nicht, Funktionen und Erklärungen mit einem Semikolon. Wenn Sie das Semikolon vergessen, wird der Compiler geben Sie eine Fehlermeldung, wenn Sie versuchen, das Programm zu kompilieren.
ändern und Vergleichen von Variablen
Natürlich, egal, welche Art Sie verwenden, sind Variablen, ohne die Möglichkeit, sie zu ändern uninteressant. Mehrere Betreiber mit Variablen verwendet werden, gehören die folgenden: *, -, +, /, =, ==,>, <. Die * multipliziert, die - subtrahiert und die + erstellt. Natürlich ist es wichtig zu erkennen, dass der Wert einer Variablen innerhalb des Programms ist es eher wichtig, das Gleichheitszeichen ändern. In einigen Sprachen, vergleicht das Gleichheitszeichen den Wert der linken und rechten Werte, aber in C + + == ist für diese Aufgabe verwendet. Das Gleichheitszeichen ist immer noch äußerst nützlich. Sie setzt den linken Eingang des Gleichheitszeichen, die eine, und nur eine Variable gleich dem Wert auf der rechten Seite des Gleichheitszeichens sein müssen. Die Betreiber, die mathematische Funktionen ausführen sollte auf der rechten Seite von einem Gleichheitszeichen, um das Ergebnis einer Variablen auf der linken Seite zugewiesen werden.
Hier sind ein paar Beispiele:
1
2
3
a = 4 * 6; / / (Hinweis Verwendung von Kommentaren und von Semikolon) ist ein 24
a = a + 5; / / A gleich dem ursprünglichen Wert von a mit fünf hinzugefügt, um es
a == 5 / / Funktioniert NICHT zuordnen fünf ein. Vielmehr prüft er, ob eine gleich 5.
Die andere Form der gleich, == ist nicht ein Weg, um einen Wert einer Variablen zuweisen. Vielmehr prüft er, ob die Variablen gleich sind. Es ist nützlich in anderen Bereichen der C + +; zum Beispiel, werden Sie oft verwenden == in solchen Konstruktionen wie bedingte Anweisungen und Schleifen. Sie können sich wahrscheinlich vorstellen, wie <und>-Funktion. Sie sind größer als und kleiner als Operatoren.
Zum Beispiel:
1
2
3
a <5 / / Prüft, ob ein weniger als fünf
a> 5 / / Prüft, ob a größer als fünf ist
a == 5 / / Prüft, ob a gleich fünf, für eine gute Maßnahme
Vergleich von Variablen ist nicht wirklich sinnvoll, bis Sie einen Weg, über die Ergebnisse zu haben.
Deklarieren von Variablen in C++
Um eine Variable verwenden Sie die Syntax erklären "Typ <name>,". Hier sind einige Beispiele Variablendeklaration:
1
2
3
int x;
char Brief;
the_float schweben;
Es ist zulässig, mehrere Variablen des gleichen Typs auf der gleichen Linie zu erklären; jeder sollte von einem Komma getrennt werden.
1
int a, b, c, d;
Wenn du genau beobachten, könnten Sie gesehen haben, dass die Deklaration einer Variablen wird immer durch ein Semikolon (dies ist das gleiche Verfahren verwendet, wenn Sie eine Funktion aufrufen).
Häufige Fehler bei der Deklaration von Variablen in C++
Wenn Sie versuchen, eine Variable, die Sie nicht erklärt haben, zu verwenden, wird Ihr Programm nicht kompiliert werden oder laufen, und Sie erhalten eine Fehlermeldung darüber informiert, dass Sie einen Fehler gemacht haben, erhalten. In der Regel wird dies als eine nicht deklarierte Variable.
Verwenden von Variablen
Hier ist ein Beispielprogramm demonstriert die Verwendung einer Variablen:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Include <iostream>
*
using namespace std;
*
int main ()
{
**int thisisanumber;
*
**cout << "Bitte geben Sie eine Zahl ein:";
**cin >> thisisanumber;
**cin.ignore ();
**cout << "Sie haben:" << thisisanumber << "\ n";
**cin.get ();
}
Lassen Sie uns auseinanderbrechen dieses Programm und untersuchen es Zeile für Zeile. Das Schlüsselwort int erklärt thisisanumber auf eine ganze Zahl sein. Die Funktion cin >> liest einen Wert in thisisanumber; muss der Benutzer die Eingabetaste drücken, bevor die Anzahl wird von dem Programm zu lesen. cin.ignore () ist eine weitere Funktion, die liest und verwirft ein Zeichen. Denken Sie daran, dass, wenn Sie in ein Programm eingeben Eingang, nimmt es die Enter-Taste zu. Wir tun dies nicht brauchen, so dass wir werfen es weg. Beachten Sie, dass die Variable eine ganze Zahl deklariert; Wenn der Benutzer eine Dezimalzahl in versucht, wird er gekürzt (das heißt, die Komponente des dezimalen Zahl wird ignoriert). Versuchen Sie, in einer Sequenz von Zeichen oder eine Dezimalzahl, wenn Sie das Beispiel-Programm ausführen; die Antwort wird von Eingang zu Eingang variieren, aber in keinem Fall ist es besonders schön. Beachten Sie, dass beim Ausdruck eine Variable Anführungszeichen werden nicht verwendet. Gab es in Anführungszeichen, der Ausgang wäre "Du Eingetragen von:. Thisisanumber" Das Fehlen von Anführungszeichen informiert den Compiler, dass es eine Variable ist, und daher, dass das Programm den Wert der Variablen, um die Variablennamen mit der Variablen bei der Ausführung der Ausgangsfunktion ersetzen überprüfen. Lassen Sie sich durch die Aufnahme von zwei separaten Einschub Operatoren in einer Zeile verwechselt werden. Inklusive Facheingabe Betreiber auf einer Linie ist durchaus akzeptabel und die gesamte Ausgabe wird an den gleichen Ort zu gehen. In der Tat, müssen Sie Stringliterale (Strings in Anführungszeichen) und Variablen, indem jeder seinen eigenen Einführungs Operatoren (<<) zu trennen. Der Versuch, zwei Variablen zusammen mit nur einer legte << erhalten Sie eine Fehlermeldung, versuchen Sie es nicht. Vergessen Sie nicht, Funktionen und Erklärungen mit einem Semikolon. Wenn Sie das Semikolon vergessen, wird der Compiler geben Sie eine Fehlermeldung, wenn Sie versuchen, das Programm zu kompilieren.
ändern und Vergleichen von Variablen
Natürlich, egal, welche Art Sie verwenden, sind Variablen, ohne die Möglichkeit, sie zu ändern uninteressant. Mehrere Betreiber mit Variablen verwendet werden, gehören die folgenden: *, -, +, /, =, ==,>, <. Die * multipliziert, die - subtrahiert und die + erstellt. Natürlich ist es wichtig zu erkennen, dass der Wert einer Variablen innerhalb des Programms ist es eher wichtig, das Gleichheitszeichen ändern. In einigen Sprachen, vergleicht das Gleichheitszeichen den Wert der linken und rechten Werte, aber in C + + == ist für diese Aufgabe verwendet. Das Gleichheitszeichen ist immer noch äußerst nützlich. Sie setzt den linken Eingang des Gleichheitszeichen, die eine, und nur eine Variable gleich dem Wert auf der rechten Seite des Gleichheitszeichens sein müssen. Die Betreiber, die mathematische Funktionen ausführen sollte auf der rechten Seite von einem Gleichheitszeichen, um das Ergebnis einer Variablen auf der linken Seite zugewiesen werden.
Hier sind ein paar Beispiele:
1
2
3
a = 4 * 6; / / (Hinweis Verwendung von Kommentaren und von Semikolon) ist ein 24
a = a + 5; / / A gleich dem ursprünglichen Wert von a mit fünf hinzugefügt, um es
a == 5 / / Funktioniert NICHT zuordnen fünf ein. Vielmehr prüft er, ob eine gleich 5.
Die andere Form der gleich, == ist nicht ein Weg, um einen Wert einer Variablen zuweisen. Vielmehr prüft er, ob die Variablen gleich sind. Es ist nützlich in anderen Bereichen der C + +; zum Beispiel, werden Sie oft verwenden == in solchen Konstruktionen wie bedingte Anweisungen und Schleifen. Sie können sich wahrscheinlich vorstellen, wie <und>-Funktion. Sie sind größer als und kleiner als Operatoren.
Zum Beispiel:
1
2
3
a <5 / / Prüft, ob ein weniger als fünf
a> 5 / / Prüft, ob a größer als fünf ist
a == 5 / / Prüft, ob a gleich fünf, für eine gute Maßnahme
Vergleich von Variablen ist nicht wirklich sinnvoll, bis Sie einen Weg, über die Ergebnisse zu haben.
If-Anweisungen in C++
Ohne eine bedingte Anweisung wie die if-Anweisung, würden Programme fast genau die gleiche Weise jedes Mal ausgeführt. Wenn Aussagen erlauben dem Ablauf des Programms geändert werden, und so sind sie Algorithmen und interessanter Code ermöglichen.
*Eine wahre Aussage ist eine, die auf eine von Null verschiedene Zahl ergibt. Eine falsche Anweisung wertet Null. Wenn Sie Vergleich mit den relationalen Operatoren durchzuführen, wird der Betreiber 1 zurück, wenn der Vergleich wahr ist, oder 0, wenn der Vergleich falsch ist. Zum Beispiel die Kontroll 0 == 2 für 0.. Das Rückschlag 2 == 2 wertet auf 1.
Bei der Programmierung wird das Ziel des Programms erfordern häufig die Kontrolle eines durch einen variablen Wert an einem anderen gespeicherten Wert, um zu bestimmen, ob eine größer, kleiner oder gleich dem anderen.
Es gibt eine Reihe von Operatoren, die diese Kontrollen zu ermöglichen.
ELSE
Manchmal, wenn die Bedingung in einer if-Anweisung false ergibt, wäre es schön, einige Code statt den Code ausgeführt werden, wenn die Aussage wahr ausgewertet auszuführen. Das "else"-Anweisung wirksam sagt, dass was auch immer Code, nachdem es (ob eine einzelne Linie oder Code zwischen Klammern), wenn die ausgeführt werden, wenn Aussage ist falsch.
Else If
Eine weitere Verwendung der andere ist, wenn es mehrere bedingte Anweisungen, die alle evaluieren kann, um wahre, aber wenn Sie nur eine Körper-Anweisung ausführen wollen. Sie können folgende Anweisung verwenden ein ", wenn sonst" eine if-Anweisung und ihre Körper; so, wenn die erste Aussage ist richtig, die "else if" wird ignoriert, aber wenn die Aussage falsch ist, wenn es überprüft dann die Bedingung für die else if-Anweisung. Wenn die if-Anweisung wahr war die else-Anweisung wird nicht überprüft. Es ist möglich, verwenden viele else if-Anweisungen, um sicherzustellen, dass nur ein Code-Block wird ausgeführt.
*Eine wahre Aussage ist eine, die auf eine von Null verschiedene Zahl ergibt. Eine falsche Anweisung wertet Null. Wenn Sie Vergleich mit den relationalen Operatoren durchzuführen, wird der Betreiber 1 zurück, wenn der Vergleich wahr ist, oder 0, wenn der Vergleich falsch ist. Zum Beispiel die Kontroll 0 == 2 für 0.. Das Rückschlag 2 == 2 wertet auf 1.
Bei der Programmierung wird das Ziel des Programms erfordern häufig die Kontrolle eines durch einen variablen Wert an einem anderen gespeicherten Wert, um zu bestimmen, ob eine größer, kleiner oder gleich dem anderen.
Es gibt eine Reihe von Operatoren, die diese Kontrollen zu ermöglichen.
ELSE
Manchmal, wenn die Bedingung in einer if-Anweisung false ergibt, wäre es schön, einige Code statt den Code ausgeführt werden, wenn die Aussage wahr ausgewertet auszuführen. Das "else"-Anweisung wirksam sagt, dass was auch immer Code, nachdem es (ob eine einzelne Linie oder Code zwischen Klammern), wenn die ausgeführt werden, wenn Aussage ist falsch.
Else If
Eine weitere Verwendung der andere ist, wenn es mehrere bedingte Anweisungen, die alle evaluieren kann, um wahre, aber wenn Sie nur eine Körper-Anweisung ausführen wollen. Sie können folgende Anweisung verwenden ein ", wenn sonst" eine if-Anweisung und ihre Körper; so, wenn die erste Aussage ist richtig, die "else if" wird ignoriert, aber wenn die Aussage falsch ist, wenn es überprüft dann die Bedingung für die else if-Anweisung. Wenn die if-Anweisung wahr war die else-Anweisung wird nicht überprüft. Es ist möglich, verwenden viele else if-Anweisungen, um sicherzustellen, dass nur ein Code-Block wird ausgeführt.
Loops
Loops werden verwendet, um einen Code-Block zu wiederholen. Die Möglichkeit, Ihr Programm wiederholt einen Block von Code auszuführen ist eine der grundlegendsten, aber nützliche Aufgaben in der Programmierung - viele Programme oder Websites, die extrem komplexe Ausgangs (wie ein Message Board) erzeugen, sind eigentlich nur eine einzige Aufgabe, die Ausführung oft . (Sie können die Ausführung werden eine kleine Anzahl von Aufgaben, aber im Prinzip, um eine Liste der Nachrichten nur erfordert Wiederholung der Vorgang des Lesens in einigen Daten und Anzeigen es zu produzieren.) Nun, was das bedeutet, dass: eine Schleife können Sie schreiben ein sehr einfache Anweisung, um eine deutlich höhere Ergebnis einfach durch Wiederholung zu produzieren.
Die Initialisierung von Variablen können Sie entweder eine Variable deklarieren und geben ihm einen Wert oder geben Sie einen Wert in einer bereits vorhandenen Variablen. Zweitens sagt die Bedingung, dass das Programm während der bedingte Ausdruck ist wahr, die Schleife weiter, sich zu wiederholen. Die variable Updateabschnitt ist der einfachste Weg für eine for-Schleife zu hand Änderung der Variablen. Es ist möglich, Dinge wie x + +, x = x + 10, oder sogar x = random (5) Sie, und wenn Sie wirklich wollten, könnten Sie andere Funktionen, die nichts auf die Variable tun nennen, aber immer noch eine nützliche Wirkung auf die haben Code. Beachten Sie, dass ein Semikolon trennt jeden dieser Abschnitte, das ist wichtig. Beachten Sie auch, dass jeder einzelne der Abschnitte kann leer sein, obwohl die Semikolons müssen noch da sein. Wenn die Bedingung leer ist, wird es als wahr bewertet, und die Schleife wird wiederholt, bis etwas anderes hört es.
Beispiel:
# Include <iostream>
using namespace std; //So kann das Programm cout und endl sehen
int main ()
{
**/ / Die Schleife geht, während x <10 und x um eins erhöht jede Schleife
**for (int x = 0, x <10 und x + +) {
****/ / Beachten Sie, dass die Schleifenbedingung überprüft
****/ / Die bedingte Anweisung, bevor es wieder Schlaufen.
****/ / Damit, wenn x = 10 die Schleife bricht.
****/ / X wird aktualisiert, bevor die Bedingung geprüft wird.
****cout << x << endl;
**}
**cin.get ();
}
WÄHREND - WHILE-Schleifen sind sehr einfach. Die Grundstruktur ist
while (Bedingung) {-Code auszuführen, solange die Bedingung true} Die wahre stellt einen Booleschen Ausdruck, der x == 1 sein könnte oder während (x! = 7) (x ist nicht gleich 7). Es kann eine beliebige Kombination von Booleschen Aussagen, die legal sind, sein. Selbst, (während x == 5 | | v == 7)., Die besagt, führen Sie den Code während x gleich fünf oder gleich 7, während v Beachten Sie, dass eine while-Schleife ist die gleiche wie eine for-Schleife, ohne die Initialisierung und Update-Abschnitte. Allerdings ist eine Leerzustand Rechtslage nicht, nicht für eine while-Schleife, wie es mit einer for-Schleife.
Beispiel:
# Include <iostream>
using namespace std; / / So können wir cout und endl sehen
int main ()
{
**int x = 0; / / Vergessen Sie nicht, Variablen zu deklarieren
**
**while (x <10) {/ / Wenn x kleiner als 10
****cout << x << endl;
****x + +; / / Update x so kann der Zustand irgendwann erfüllt werden
**}
**cin.get ();
}
Der einfachste Weg, um die Schleife zu denken ist, dass, wenn es die Klammer am Ende erreicht er springt wieder an den Anfang der Schleife, die den Zustand wieder überprüft und entscheidet, ob der Block ein anderes Mal zu wiederholen oder zu stoppen und zu bewegen, um die nächsten Anweisung nach dem Block.
Beachten Sie, dass der Zustand am Ende des Blocks statt am Anfang geprüft, so dass der Block, der mindestens einmal ausgeführt werden. Wenn die Bedingung erfüllt ist, springen wir zurück an den Anfang des Blockes und führen Sie es noch einmal. A do .. while-Schleife ist im Grunde eine while-Schleife umgekehrt. Eine while-Schleife sagt "Loop, während die Bedingung erfüllt ist, und diesen Block von Code ausführen", einer do .. while-Schleife sagt: "Führen Sie diesen Code-Block, und Schleife, während die Bedingung wahr ist."
Beispiel:
# Include <iostream>
using namespace std;
int main ()
{
**int x;
**x = 0;
**do {
****/ / "Hallo, Welt!" mindestens ein Mal gedruckt
****/ / Auch wenn die Bedingung falsch ist
****cout << "Hallo, Welt \ n";
**} While (x = 0!);
**cin.get ();
}
Denken Sie daran, dass Sie eine Hinter Semikolon nach dem während im obigen Beispiel enthalten. Ein häufiger Fehler ist, zu vergessen, dass eine do .. while-Schleife muss mit einem Semikolon (die anderen Schleifen sollte nicht mit einem Semikolon abgeschlossen werden, was zur Verwirrung) beendet werden. Beachten Sie, dass diese Schleife wird einmal ausgeführt, weil es wird automatisch ausgeführt, bevor Sie die Bedingung.
Die Initialisierung von Variablen können Sie entweder eine Variable deklarieren und geben ihm einen Wert oder geben Sie einen Wert in einer bereits vorhandenen Variablen. Zweitens sagt die Bedingung, dass das Programm während der bedingte Ausdruck ist wahr, die Schleife weiter, sich zu wiederholen. Die variable Updateabschnitt ist der einfachste Weg für eine for-Schleife zu hand Änderung der Variablen. Es ist möglich, Dinge wie x + +, x = x + 10, oder sogar x = random (5) Sie, und wenn Sie wirklich wollten, könnten Sie andere Funktionen, die nichts auf die Variable tun nennen, aber immer noch eine nützliche Wirkung auf die haben Code. Beachten Sie, dass ein Semikolon trennt jeden dieser Abschnitte, das ist wichtig. Beachten Sie auch, dass jeder einzelne der Abschnitte kann leer sein, obwohl die Semikolons müssen noch da sein. Wenn die Bedingung leer ist, wird es als wahr bewertet, und die Schleife wird wiederholt, bis etwas anderes hört es.
Beispiel:
# Include <iostream>
using namespace std; //So kann das Programm cout und endl sehen
int main ()
{
**/ / Die Schleife geht, während x <10 und x um eins erhöht jede Schleife
**for (int x = 0, x <10 und x + +) {
****/ / Beachten Sie, dass die Schleifenbedingung überprüft
****/ / Die bedingte Anweisung, bevor es wieder Schlaufen.
****/ / Damit, wenn x = 10 die Schleife bricht.
****/ / X wird aktualisiert, bevor die Bedingung geprüft wird.
****cout << x << endl;
**}
**cin.get ();
}
WÄHREND - WHILE-Schleifen sind sehr einfach. Die Grundstruktur ist
while (Bedingung) {-Code auszuführen, solange die Bedingung true} Die wahre stellt einen Booleschen Ausdruck, der x == 1 sein könnte oder während (x! = 7) (x ist nicht gleich 7). Es kann eine beliebige Kombination von Booleschen Aussagen, die legal sind, sein. Selbst, (während x == 5 | | v == 7)., Die besagt, führen Sie den Code während x gleich fünf oder gleich 7, während v Beachten Sie, dass eine while-Schleife ist die gleiche wie eine for-Schleife, ohne die Initialisierung und Update-Abschnitte. Allerdings ist eine Leerzustand Rechtslage nicht, nicht für eine while-Schleife, wie es mit einer for-Schleife.
Beispiel:
# Include <iostream>
using namespace std; / / So können wir cout und endl sehen
int main ()
{
**int x = 0; / / Vergessen Sie nicht, Variablen zu deklarieren
**
**while (x <10) {/ / Wenn x kleiner als 10
****cout << x << endl;
****x + +; / / Update x so kann der Zustand irgendwann erfüllt werden
**}
**cin.get ();
}
Der einfachste Weg, um die Schleife zu denken ist, dass, wenn es die Klammer am Ende erreicht er springt wieder an den Anfang der Schleife, die den Zustand wieder überprüft und entscheidet, ob der Block ein anderes Mal zu wiederholen oder zu stoppen und zu bewegen, um die nächsten Anweisung nach dem Block.
Beachten Sie, dass der Zustand am Ende des Blocks statt am Anfang geprüft, so dass der Block, der mindestens einmal ausgeführt werden. Wenn die Bedingung erfüllt ist, springen wir zurück an den Anfang des Blockes und führen Sie es noch einmal. A do .. while-Schleife ist im Grunde eine while-Schleife umgekehrt. Eine while-Schleife sagt "Loop, während die Bedingung erfüllt ist, und diesen Block von Code ausführen", einer do .. while-Schleife sagt: "Führen Sie diesen Code-Block, und Schleife, während die Bedingung wahr ist."
Beispiel:
# Include <iostream>
using namespace std;
int main ()
{
**int x;
**x = 0;
**do {
****/ / "Hallo, Welt!" mindestens ein Mal gedruckt
****/ / Auch wenn die Bedingung falsch ist
****cout << "Hallo, Welt \ n";
**} While (x = 0!);
**cin.get ();
}
Denken Sie daran, dass Sie eine Hinter Semikolon nach dem während im obigen Beispiel enthalten. Ein häufiger Fehler ist, zu vergessen, dass eine do .. while-Schleife muss mit einem Semikolon (die anderen Schleifen sollte nicht mit einem Semikolon abgeschlossen werden, was zur Verwirrung) beendet werden. Beachten Sie, dass diese Schleife wird einmal ausgeführt, weil es wird automatisch ausgeführt, bevor Sie die Bedingung.
-Schalter-Kasten in C++
Umschalten Case-Anweisungen sind ein Ersatz für lange, wenn Aussagen, die eine Variable auf mehrere "integral" Werte zu vergleichen ("integral" Werte sind nur Werte, die als ganze Zahl ausgedrückt werden kann, wie der Wert einer char). Das Grundformat für die Verwendung Schaltergehäuse wird im Folgenden erläutert. Der Wert der Variablen in Schalter gegeben wird, um den Wert nach jedem der Fälle verglichen, und wenn ein Wert der Wert der Variablen entspricht, wird der Computer die Ausführung des Programms an dieser Stelle.
Schalter (<variable>) {
Falls dies-Wert:
**Code ausführen, wenn <variable> == this-Wert
**break;
Fall, dass-Wert:
**Code ausführen, wenn <variable> == dass Wert
**break;
...
Standard:
**Code ausführen, wenn <variable> nicht den Wert nach jedem der Fälle gleich
**break;
}
Der Zustand einer Switch-Anweisung ist ein Wert. Der Fall sagt, dass, wenn sie den Wert, was auch immer nach diesem Fall hat dann tun, was auch immer den Doppelpunkt folgt. Die Pause wird verwendet, um aus den Case-Anweisungen zu brechen. Break ist ein Stichwort, das aus dem Code-Block, in der Regel von geschweiften Klammern umgeben ist, die es sich in diesem Fall verhindert Pause das Programm fallen durch und Ausführung des Codes in allen anderen Aussagen Fall bricht. Eine wichtige Sache, über die Switch-Anweisung beachten ist, dass die Fallwerte können nur konstante integralen Ausdrücke sein. Leider ist es nicht zulässig, Fall wie folgt verwenden:
Der Standardfall ist optional, aber es ist ratsam, sie aufzunehmen, da sie unerwartete Fälle behandelt. Switch-Anweisungen dient als einfache Möglichkeit, lange zu schreiben, wenn Aussagen, wenn die Voraussetzungen erfüllt sind. Oft kann es verwendet werden, um Eingaben von einem Benutzer zu verarbeiten.
int a = 10;
int b = 10;
int c = 20;
Schalter (a) {
Fall b:
**/ / Code
**break;
Fall c:
**/ / Code
**break;
Standard:
**/ / Code
**break;
}
Unten ist ein Beispielprogramm, in denen nicht alle die richtigen Funktionen tatsächlich erklärt, aber das zeigt, wie man Schalter in einem Programm zu verwenden.
# Include <iostream>
using namespace std;
Leere Playgame ()
{
****cout << "Play Spiel";
}
Leere loadgame ()
{
****cout << "Load Spiel";
}
Leere playmultiplayer ()
{
****cout << "Play-Multiplayer-Spiel";
}
int main ()
{
**int input;
**
**cout << ". ein Spiel starten \ n";
**cout << ". 2 Spiel laden \ n";
**cout << ". 3 Spielen Multiplayer \ n";
**cout << ". 4 Beenden \ n";
**cout << "Auswahl:";
**cin >> input;
**Schalter (Eingang) {
**Fall 1: / / Beachten Sie den Doppelpunkt, nicht ein Semikolon
****Playgame ();
****break;
**Fall 2: / / Beachten Sie den Doppelpunkt, nicht ein Semikolon
****loadgame ();
****break;
**Fall 3: / / Beachten Sie den Doppelpunkt, nicht ein Semikolon
****playmultiplayer ();
****break;
**Fall 4: / / Beachten Sie den Doppelpunkt, nicht ein Semikolon
****cout << "Danke, dass Sie für die Wiedergabe von \ n";
****break;
**Standard: / / Beachten Sie den Doppelpunkt, nicht ein Semikolon
****cout << "Fehler, schlechte Eingang, beenden \ n";
****break;
**}
**cin.get ();
}
Dieses Programm wird kompiliert, kann aber nicht laufen, bis die undefinierte Funktionen Gremien gegeben werden, aber es als Modell (wenn auch einfach) zur Verarbeitung von Eingangs dient. Wenn Sie das nicht verstehen, dann versuchen geistig setzen in if-Anweisungen für den Fall Aussagen. Standard springt einfach aus dem Schaltergehäuse Konstruktion und kann das Programm natürlich kündigen. Wenn Sie es nicht mögen, dass, dann können Sie eine Schleife um die ganze Sache zu machen, um es für gültige Eingabe. Sie könnte leicht machen ein paar kleine Funktionen, wenn Sie den Code testen möchten.
Schalter (<variable>) {
Falls dies-Wert:
**Code ausführen, wenn <variable> == this-Wert
**break;
Fall, dass-Wert:
**Code ausführen, wenn <variable> == dass Wert
**break;
...
Standard:
**Code ausführen, wenn <variable> nicht den Wert nach jedem der Fälle gleich
**break;
}
Der Zustand einer Switch-Anweisung ist ein Wert. Der Fall sagt, dass, wenn sie den Wert, was auch immer nach diesem Fall hat dann tun, was auch immer den Doppelpunkt folgt. Die Pause wird verwendet, um aus den Case-Anweisungen zu brechen. Break ist ein Stichwort, das aus dem Code-Block, in der Regel von geschweiften Klammern umgeben ist, die es sich in diesem Fall verhindert Pause das Programm fallen durch und Ausführung des Codes in allen anderen Aussagen Fall bricht. Eine wichtige Sache, über die Switch-Anweisung beachten ist, dass die Fallwerte können nur konstante integralen Ausdrücke sein. Leider ist es nicht zulässig, Fall wie folgt verwenden:
Der Standardfall ist optional, aber es ist ratsam, sie aufzunehmen, da sie unerwartete Fälle behandelt. Switch-Anweisungen dient als einfache Möglichkeit, lange zu schreiben, wenn Aussagen, wenn die Voraussetzungen erfüllt sind. Oft kann es verwendet werden, um Eingaben von einem Benutzer zu verarbeiten.
int a = 10;
int b = 10;
int c = 20;
Schalter (a) {
Fall b:
**/ / Code
**break;
Fall c:
**/ / Code
**break;
Standard:
**/ / Code
**break;
}
Unten ist ein Beispielprogramm, in denen nicht alle die richtigen Funktionen tatsächlich erklärt, aber das zeigt, wie man Schalter in einem Programm zu verwenden.
# Include <iostream>
using namespace std;
Leere Playgame ()
{
****cout << "Play Spiel";
}
Leere loadgame ()
{
****cout << "Load Spiel";
}
Leere playmultiplayer ()
{
****cout << "Play-Multiplayer-Spiel";
}
int main ()
{
**int input;
**
**cout << ". ein Spiel starten \ n";
**cout << ". 2 Spiel laden \ n";
**cout << ". 3 Spielen Multiplayer \ n";
**cout << ". 4 Beenden \ n";
**cout << "Auswahl:";
**cin >> input;
**Schalter (Eingang) {
**Fall 1: / / Beachten Sie den Doppelpunkt, nicht ein Semikolon
****Playgame ();
****break;
**Fall 2: / / Beachten Sie den Doppelpunkt, nicht ein Semikolon
****loadgame ();
****break;
**Fall 3: / / Beachten Sie den Doppelpunkt, nicht ein Semikolon
****playmultiplayer ();
****break;
**Fall 4: / / Beachten Sie den Doppelpunkt, nicht ein Semikolon
****cout << "Danke, dass Sie für die Wiedergabe von \ n";
****break;
**Standard: / / Beachten Sie den Doppelpunkt, nicht ein Semikolon
****cout << "Fehler, schlechte Eingang, beenden \ n";
****break;
**}
**cin.get ();
}
Dieses Programm wird kompiliert, kann aber nicht laufen, bis die undefinierte Funktionen Gremien gegeben werden, aber es als Modell (wenn auch einfach) zur Verarbeitung von Eingangs dient. Wenn Sie das nicht verstehen, dann versuchen geistig setzen in if-Anweisungen für den Fall Aussagen. Standard springt einfach aus dem Schaltergehäuse Konstruktion und kann das Programm natürlich kündigen. Wenn Sie es nicht mögen, dass, dann können Sie eine Schleife um die ganze Sache zu machen, um es für gültige Eingabe. Sie könnte leicht machen ein paar kleine Funktionen, wenn Sie den Code testen möchten.
Drop A Thanks If I helped anyone at all.








