Sie sind auf Seite 1von 28

C++

1An Example#include <cstdlib> #include <iostream> // The two slashes are comments // this text will not be compiled // the above 2 #include statements // are to bring in 2 standard // libraries from the C++ libraries // the first one is for system() // which is a function. // The second one is for cout, cin // which is output to the screen // and input from the user keyboard using namespace std; // if we don't put up the above // using statement. Then we would // be forced to write cout and cin // like this: std::cout or std::cin // so we're just saying we want to // always use std for cout/cin.

// int main is simply the standard // function for all beginning // C++ programs. // the int means integer, because // when function main is finished // it will return an integer type. int main(int argc, char *argv[]) { int guess(0); // we just initialized a // local variable called // guess. C++ is case sensitive. // guess is initialized as 0. // this is the same as // int guess = 0; // this will be our guessing number. int MyGuess(0); // this is another integer at zero. srand(time(NULL)); // srand is a function that

http://www.infernodevelopment.com

Page 1

// seeds the rand() function // with a time(0) (UNIX time), // basically it will // generate an almost random // starting point for rand(). guess = rand()%10+1; // this will be the number we have to guess // The %10 means 10 is maximum random number. // The +1 means 1 is the minimum random // number. // Now guess contains our random number. // % is actually modulus (divide by 10, get // remainder). cout << "Guess our random number (1-100)\n"; // cout will output text to our console. // pay attention to the arrows facing cout. // We add our string that we want to print. // \n means a new line should appear there. // it's like pressing return/enter on keyboard. cin >> MyGuess; // This will wait for the user to type // a number to the screen. It will save it // as MyGuess. A space or return/enter // will make the code continue. cout << "You guessed " << MyGuess << ", the answer"; cout << " was " << guess << "\n"; // We tell the user the results. if(MyGuess == guess){ // check if MyGuess is guess cout << "You guessed it!\n"; } else { // otherwise cout << "You failed this extremely simple game.\n"; }

system("PAUSE"); // This will pause the program. // displaying a message like // "Press any key to continue". // which will end program. return EXIT_SUCCESS; // exit success is just a // representation for integer zero. }

http://www.infernodevelopment.com

Page 2

2Basic C++ programmingBasics of C++ Programming Programs are first sent through the process of compiling by a compiler, allowing all the syntax to be translated to code, then it is linked with libraries and other cpp/h files to create the program itself using a linker. They are turned into an EXE file in windows. EXE files are actually encrypted Assembly code. The Assembly code is fed to your processor which actually allows you to execute all your commands. This is why exe files cannot be decompiled, they can only be disassembled, (turned into Assembly code). Many programmers use Microsoft Visual Studio 2003/2005 .NET, some use DevC++, CodeBlocks, or C++ Builder for their C++ purposes, but these are IDE and Compilers (So they are programs where you type in the code and you compile & link to create EXE files). The process of compiling is very similar in all program, but let's talk about DevC++ an IDE that can also compile and link using the mingw compiler. You can download DevC++ for free from DevC++ 4.9.9.2 Binary Release. Now, after you install DevC++, try and start an empty project. Click your project in the tree view on the left, and then press Ctrl+N (or just create a new file). Now save this as main.cpp, and then add this code to your file: // First Program #include <stdio.h> #include <stdlib.h> int main(){ printf("My First Program!\n"); system("PAUSE"); return 0; }

//not necessary in visual environment // it is a SHELL DOS COMMAND

This is your first program. We used // to indicate a comment, a comment is NEVER used in your code, it is just there for human programmers to read. The compiler ignores the line with //. Other comments include encasing text with /* some comment */. We included the STD IO library (stdio.h) to use our printf function. printf is used to print out information onto your console window. The STD IO library, is not a C++ library, it is a C library. C and C++ are not the same but C can be used in C++ and as you advance you will understand the hundreds of differences between them, such as Object Oriented Programming capabilities in C++, which help organize your code better. int main(), is how we declare our main function, which is a special function for console programs. it starts with int, because it will return an integer type. You could have written void main(), and then instead of return 0; you would just return;. Printf is used to print out information to the console program, it will show up in the black screen. In contrast you can use scanf, in the sense of something like (This code must be inside your main() function):

http://www.infernodevelopment.com

Page 3

printf("Enter a name: \n"); char myCharString[50]; scanf("%s", myCharString); printf("You entered %s", myCharString); These 4 lines would be a very simple approach to input and output between the user and your program. A char is a type in memory that allows you to store keyboard characters. The maximum you can enter in this example is 50 letters. Entering any more than that will crash your program, and therefore you should take precautions for this, which we will discuss in the future. Scanf is used to take in the input and store it in myCharString or any other series of chars. The %s symbol means a series of chars or another string type that has multiple characters, which you can use in both printf and scanf. We used "\n" to indicate a new line in the console, so that the PAUSE will appear below it rather than on the same line. If we used "Hey\n how are you?", it would put "Hey" and "how are you", in different lines. system("PAUSE"); is a shell command for DOS. It displays a pause statement and waits for you to press enter. If you remove this piece of code your program will end so fast you will not even see the message. The Pause allows you to see your result and then press enter to exit your console program. return 0; is used in main() function to return to end the program. This was the basic structure of a C/C++ program. We hope you enjoyed this tutorial and hope it explains to you how to learn programming and perhaps will allow you to actually practice this field without all the confusion surrounding programming. If you continue to have any questions, or if you want to help improve this tutorial please come to our forums, register there, and feel free to post a topic somewhere.

http://www.infernodevelopment.com

Page 4

3C++ Variables and Data TypesFirst off, a data type tells a variable what kind of data it will be holding. The whole point of data types, is so that the computer can store just the right amount of bytes for a variable, instead of too much or too little. You must know the different data types to pick the one that best fits your needs. toc_collapse=0; Contents [hide] Data Types Declaring variables Scope Global Variables Typedef Variables Function Variables(Parameters) Classes Downside to variables Here or the most common types you will encounter when programming: bool = true or false int = integer -signed: -2147483648 to 2147483647 -unsigned: 0 to 4294967295 char = character -signed: -128 to 127 -unsigned: 0 to 255 string = string (when #include <string>) short int = short integer -signed: -32768 to 32767 -unsigned: 0 to 65535 long int = long integer -signed: -2147483648 to 2147483647 -unsigned: 0 to 4294967295 float = Floating point number double = Double precision floating point number long double = Long double precision floating point number

Declaring variables
Read about constants. Since we have a data type, pick a name for your variable. Try to link it with what the variable will be holding and what type of data it's holding. For example, I have a integer that tells me how many coins I have. I would name it intCoins. The whole point of this is so that the code can be easily

http://www.infernodevelopment.com

Page 5

read, and you don't have to keep looking to see what you named that variable. To declare a variable, you type the data type, the name, and then (if you wish) you can set it a value. Here are two examples: int intNUM = 1; //variable declared with starting value 1 int intNUM2; //variable declared with undeclared value But, why have that take up two lines when we can make it one? You can declare multiple variables of the same type by separating them with commas. Like so: int Num1, Num2, Num3 //creates 3 integers with names Num1, Num2, and Num3.

Scope
Scope is the visibility of a variable. For example, local scope means a variable declared inside a function, and outside of this function it is invisible. A global variable has global scope, meaning the whole program can see the variable.

Global Variables
Global variables are variables that are usable and editable through your whole program. Because they're not linked to a specific function, they are usable anywhere. To make your variable global, simply place it outside any type of function. An example is #include , is outside a function.

Typedef Variables
Typedef is a c++ keyword that allows you to use alias' within your application. These are not complicated. Typedef makes a variable with a data type, then you can later make an alias to that variable. Here's example code: #include <string> #include <iostream> using namespace std; //typedef placed after std typedef string Stringer; //Creates string Stringer typedef unsigned int Inter; //Creates integer Inter [unsigned part is optional] int main(int argc, char *argv[]) { Stringer irString = "Hello World"; //Stringer makes alias irString to equal hello world Inter x = 5; //Inter makes alias x to equal 5 cout << irString << " " << x; //displays the values of the alias' getchar(); return 0; }

Think of it as if a new (using code above) string is created called irString, with the attributes of Stringer.

http://www.infernodevelopment.com

Page 6

Function Variables(Parameters)
Functions can also have variables called parameters. To learn more about these I suggest you look Here for more information.

Classes
Another type is also a class. To make a class you add class before your desired variable. Like so: class MyClass { //class code here void MyClass(){ cout << "MyClass Constructor"; } };

I will not explain everything you can do in/with a class, but for further information go here.

Downside to variables
The big downside to variables is that they take up memory. In simple applications this isn't a big deal, but in applications where how much memory your application is taking up is a big deal, variables are a big deal and should be avoided whenever possible. They take up so much memory because the application reserves the amount of memory needed for the given data type. Example is that a double takes up 8 bytes of memory whether or not it has a value.

http://www.infernodevelopment.com

Page 7

4C++ Operators
First of all, what is an operator? There are multiple types of operators, but in this tutorial we'll only talk about 2 types. The first type includes arithmetic operators such as addition, subtraction, multiplication, and division. The second type includes equals, greater than, and other comparison testing operators. First, lets talk about arithmetic operators, simply put the operator between two variables you want to operate on: + is addition - is subtraction * is multiplication / is division ++ increase number by 1 -- decrease number by 1

These operators can be used in different ways. Sometimes other data types such as string can use the addition operation, because it overloads it as a "concatenation" (combining) operation (you cannot do addition with strings). Here's an example of using all the operators: #include <iostream> #include <string> using namespace std; int main(){ int number = 5 + 5 / (3 * 2) - 2; // a math equation number = number % 2; // modulus, gets the remainder of number divided by 2. number %= 2; // Same operation as above. string thee("The"); string tee("Fox"); number++; // save and then increment by 1. ++number; // increment by 1 and save. thee += " " + tee; thee += " ran incredibly fast through the forest."; cout << thee << endl; // "Fox ran incredibly fast through the forest."; return 0; } You will most likely only ever use these in if, while, do, and for statements, or in loops. The operators look like this: == is equal to != is not equal to (equivalent to <>) > is greater than < is less than >= is greater than or equal to <= is less than or equal to

http://www.infernodevelopment.com

Page 8

Here is an example of using comparison operators in an if statement. if(((5 + 5) / 2) >= 3){ cout << "10/2 = 5, and five IS greater than or equal to ten, so this text will display."; }

http://www.infernodevelopment.com

Page 9

5C++ ConstantsA constant is a variable type which cannot be changed during run-time of a program. Once it has a set value, it stays that way until you change your code. There isn't much to constants, but they can cause errors that aren't explained well in your IDE. toc_collapse=0; Contents [hide] Declaration Compiling Errors Statics

Declaration
To declare a constant all you do is put const before the data type, like this: const int intNUM = 5; // makes intNUM a integer with a constant value. Also be sure to remember to set the variable to something within the declaration so it can have a value. There is also another way to declare constants, these are called definitions (the compiler takes the definition and literally replaces all instances of the definition in your code with the constant). Here's an example: #define hi "hello" // making hi a constant with the value hello. #define pie 3.14

#define is helpful because it doesn't take up as much memory as variables.

Compiling Errors
Now, what happens when you're trying to edit a constant value? In Dev-C++ (the IDE I use), it never really tells you that you're try to edit a constant value. For example, this code: const string magic = "World"; // sets magic as constant string cin >> magic; // tries to set the constant 'magic' to what the user types

produces this error: no match for 'operator>>' in 'std::cin >> magic' It will not tell you exactly that you are trying to edit a constant value, but it will tell you something is wrong with that part of the code. Also note that that is a compile error, so you will not even be able to compile when trying to edit a constant value (in Dev-C++).

Statics
http://www.infernodevelopment.com Page 10

Statics are not the same as constants, they can change. You declare a static by typing static before the data type or function. There are a couple good things about statics. The first is that statics are allocated when the program starts, and deallocated when the program ends. Another upside to statics is that when declared, they're declared with the value of 0 (Unless another value is set). You must set the class static variable inside the file to a value, otherwise it won't work. Inside a function, a static can retain its current value. Here's an example of a static variable inside a class and a function with a static variable inside of it. #include <iostream> using namespace std; class Counter { public: static int m_count; }; int Counter::m_count = 0; void IncrementDifferentCounter(){ static int different_counter = 0; cout << different_counter++ << endl; } int main(){ cout << Counter::m_count << endl; // outputs 0 cout << ++Counter::m_count << endl; // outputs 1 Counter::m_count = 5; cout << Counter::m_count << endl; // outputs 5 IncrementDifferentCounter(); // outputs 0 IncrementDifferentCounter(); // 1 IncrementDifferentCounter(); // 2 IncrementDifferentCounter(); // 3 IncrementDifferentCounter(); // 4 }

http://www.infernodevelopment.com

Page 11

6Beginner C++ Cout Cin Integer


The objective of this basic C++ tutorial is to provide beginners with a simple understanding of the cout and cin functions of C++, while simultaneously providing a guide to one of their first programs. This C++ tutorial will also show you how to set up your environment and your example programs. toc_collapse=0; Contents [hide] What You Will Need Working with Variables

What You Will Need


o A compiler and IDE (I'm using Bloodshed Dev-C++; this is a free IDE that comes with the MinGW compiler) o Some creativity Install DevC++ by going to their website, downloading their exe package with the mingw compiler. Most default options will be fine. To begin, create a project, right click your project on the left side and add new source files. Press F9 to compile. To start the program off, we need to include the "preprocessor." A preprocessor will run as soon as the program opens, before any additional data is entered. #include <iostream> "iostream" is a header that gives you access to many predefined functions such as cout and cin which is what will be the focus of this tutorial. Now hit enter twice and type "using namespace std;". The statement we just used is to alert the compiler we will be using functions inside the "std" library - "std" is abbreviated for standard. Make sure you include the semicolon (;) or your program will not have the proper syntax. In C++ (and C) programming, you need to include a semicolon to tell the compiler that you have ended the command. #include <iostream> using namespace std; Now for one of the most important parts of the code! Hit enter twice again, and type: int main() { There is no semicolon at the end of int main() because that is where you will be telling the program what to do. If you were to type int main(); your program would not do anything because you've informed the compiler that you are at the end of the command. However, we're at the beginning! The reason for typing int before main is because the function will return an integer.

http://www.infernodevelopment.com

Page 12

#include <iostream> using namespace std; int main() { OK we've reached an exciting part! We're actually going to do something that we can see a result for! Hit enter once (your compiler should automatically indent for you) and type: "cout<<"Sup world!\n"; cin.get(); }" Cout is similar to print, it displays text in the program. << are insertion operators that indicate what to output. The quotes make the compiler output the literal string, and /n moves the cursor down to the next line. Notice there is a semicolon at the end of the command. Cin.get(); tells the program to expect the user to hit the enter key. Try the running the program without this line. The program flashes for a very brief moment. The aforementioned function keeps the program open until you hit enter. The } ends the main function. #include <iostream> using namespace std; int main() { cout<<"Sup world!\n"; cin.get(); } Now comment out the code you just wrote in main. You have two options here. Option 1: Use "//" at the start of the line. This will cause the compiler to ignore the line of code. However, you have to do this at the start of each line you want to comment out. If you are trying to comment out a massive section of code this practice will consume a large amount of time. Thus, we have Option: Use /* at the beginning of the area to be commented out, and */ at the very end. Say you want to test a program you've written without a section of code. Just enclose that section of code with /* at the beginning and */ at the end. This option works for a single line, or a vast number of lines. #include <iostream> using namespace std; int main() { /* cout<<"Sup world!\n"; cin.get(); */ }

Working with Variables


Variables allow you to store data, different types of variables allow you to store different types of data. o int - Int allows you to store integers (whole numbers)

http://www.infernodevelopment.com

Page 13

o float - Float allows you to store numbers with decimals o char - Char allows you to store a single character In this tutorial we will be using int, but I strongly encourage you to test the different types of variables on your own. This will help improve your understanding of variables. Be creative, try different things as you go! You don't have to follow along exactly with me. In the main section type: "int thisisanumber; cout<<"Please enter a number: "; cin>> thisisanumber; cin.ignore(); cout<<"You entered: "<< thisisanumber <<"\n"; cin.get();" You will notice a few new things here, the rest is knowledge we're adding onto. With int thisisanumber we are defining a variable and it is set as an integer. We ask the user to enter a number and with cin>> thisisanumber we store the number they enter. We use cin.ignore() to disregard the user hitting the enter key. Next, using cout we display the integer entered with << thisisanumber <<. The insertion operators allow us to enter the variable, but if we don't end it with them, we'll get an error, so make sure to enclose the variable inside of these. And finally, cin.get() keeps the program open until we hit enter. #include <iostream> using namespace std; int main() { /* cout << "Sup world!\n"; cin.get(); */ int thisisanumber; cout << "Please enter a number: "; cin >> thisisanumber; cin.ignore(); cout << "You entered: " << thisisanumber << "\n"; cin.get(); } As previously mentioned I encourage you to experiment with this tutorial and try to work out ideas that you come up with. I try my best to not be a hypocrite and had done this myself. I was aware of the basic math functions the included library provided me (+, -, x, and /) so I wanted to test out multiplying variables together. This is what I typed: "int thisisanumber, thisnumber2, a; cout<<"Please enter a number: "; cin>> thisisanumber; cin.ignore(); cout<<"Please enter another number: ";

http://www.infernodevelopment.com

Page 14

cin>> thisnumber2; cin.ignore(); cout<<"You entered: "<< thisisanumber <<" & "<< thisnumber2 <<"\n"; a = thisisanumber * thisnumber2; cout<<"a = "<< a << ""; cin.get(); return 0;" It is important to notice that I have added extra integers, doing so allows me to do the multiplication without overwriting values. The rest of the code is similar to what has already been covered. Record a variable, then record another - note that the variable name changed. Then we see the numbers the user has entered. The program then multiplies the two variables together and records the answer in variable a. The user does not notice this because there was no cout function. After multiplying the two together and getting the answer, then the program provides the output of the multiplication problem. At the bottom of the code you'll notice I have entered return 0; which informs your pc whether the program succeeded or not. #include <iostream> using namespace std; int main() { /* cout<<"Sup world!\n"; cin.get(); return 1; */ int thisisanumber, thisnumber2, a; cout << "Please enter a number: "; cin >> thisisanumber; cin.ignore(); cout << "Please enter another number: "; cin >> thisnumber2; cin.ignore(); cout << "You entered: " << thisisanumber << " & " << thisnumber2 << "\n"; a = thisisanumber * thisnumber2; cout << "a = " << a << ""; cin.get(); return 0; } The code posted below is how my code looked after completing the tutorial I followed. I took some imagination to help further my understand of basic functions taught in the tutorial. Take a look: #include <iostream> using namespace std; int main()

http://www.infernodevelopment.com

Page 15

{ /* cout<<"Sup world!\n"; cin.get(); return 1; */ int thisisanumber, thisnumber2, a; cout << "Please enter a number: "; cin >> thisisanumber; cin.ignore(); cout << "Please enter another number: "; cin >> thisnumber2; cin.ignore(); cout << "You entered: " << thisisanumber << " & " << thisnumber2 << "\n"; a = thisisanumber * thisnumber2; cout << "a = " << a << ""; cin.get(); return 0; }

http://www.infernodevelopment.com

Page 16

7-Using >>, cin.get, cin.getline, and cin.ignore


Using the >> operator (with cin)
The >> operator may be used when you simply want to read the next non-blankspace characters entered by the user into a character or character array. Any printable characters that follow the first space will be ignored and will not be stored in the variable. Do not use a statement like, cin >> UserExplanation; if, for example, you wish to obtain a whole sentence from the user that includes spaces. In that case, you would be better served by using the cin member functions get or getline. Question: Will a null-terminator automatically be stored at the end of the character array, UserExplanation?

Using cin.get
The unformatted get member function works like the >> operator with two exceptions. First, the get function includes white-space characters, whereas the extractor excludes white space when the ios::skipws flag is set (the default). Second, the get function is less likely to cause a tied output stream (cout, for example) to be flushed. A variation of the get function specifies a buffer address and the maximum number of characters to read. This is useful for limiting the number of characters sent to a specific variable, as this example shows:
#include <iostream.h> void main() { char line[25]; cout << " Type a line terminated by carriage return\n>"; cin.get( line, 25 ); cout << ' ' << line; }

In this example, you can type up to 24 characters and a terminating character. Any remaining characters can be extracted later.

http://www.infernodevelopment.com

Page 17

Using cin.getline
The getline member function is similar to the get function. Both functions allow a third argument that specifies the terminating character for input. The default value is the newline character. Both functions reserve one character for the required terminating character. However, get leaves the terminating character in the stream and getline removes the terminating character. The following example specifies a terminating character for the input stream:
#include <iostream.h> void main() { char line[100]; cout << " Type a line terminated by 't'" << endl; cin.getline( line, 100, 't' ); cout << line; }

Using cin.ignore
cin.ignore( int nCount = 1, int delim = EOF ); Parameters nCount - The maximum number of characters to extract. delim - The delimiter character (defaults to EOF). Remarks Extracts and discards up to nCount characters. Extraction stops if the delimiter delim is extracted or the end of file is reached. If delim = EOF (the default), then only the end of file condition causes termination. The delimiter character is extracted.

http://www.infernodevelopment.com

Page 18

8Control Structures (if else)Control structures like if...else and switch...case are what allow the computer to make decisions based on input and calculations. According to different conditions and circumstances your program can make different decisions or pathway of actions. The most important one is the if else structure. #include <iostream> using namespace std; int main(){ int inferno = 0; if(inferno > 100){ cout << "inferno IS greater than 100\n"; } return 0; } Of course in the above example, the text will never be displayed because inferno is always zero. if(condition){ // this is executed ONLY if condition is TRUE or 1 or non-zero }

Conditional Operators
Common conditional operators include: > Greater than (tests if left side is greater than right) < Less than (tests if left side is less than right) || Logical OR (tests if left side is true OR right is true) && Logical AND (tests if left side is true AND right is true) ! Logical NOT (tests if right side is false) == equivalence (tests if both left and right are equivalent) != Logical NOT and equal (tests if left and right are NOT equal) >= Greater than OR equal to <= Less than OR equal to #include <iostream> using namespace std; int main(){ int inferno = 0; cin >> inferno; // get input from user keyboard if(inferno >= 100){ cout << "inferno IS greater than OR equal to 100\n"; } else if(inferno <= 80){

http://www.infernodevelopment.com

Page 19

cout << "inferno IS less than OR equal to 80\n"; } else { cout << "inferno IS between 81 and 99.\n"; } return 0; } Yes, you can combine any number of if and else statements to create different paths of actions. The last else statement decides everything you didn't define.

Switch and Case


You can use switch case system, where you are testing for individual cases or integers. #include <iostream> using namespace std; int main(){ int inferno = 0; cin >> inferno; // get input from user keyboard switch(inferno){ case 0:{ cout << "Zero was entered."; break; } case 1:{ cout << "One was entered."; break; } case 2:{ cout << "Two was entered."; break; } case 3:{ cout << "Three was entered."; break; } default:{ break; } // in case of everything else, do nothing } return 0; } The above can be translated to if...else blocks: #include <iostream> using namespace std; int main(){ int inferno = 0; cin >> inferno; // get input from user keyboard if(inferno == 0){ cout << "Zero was entered."; } else if(inferno == 1){ cout << "One was entered."; } else if(inferno == 2){

http://www.infernodevelopment.com

Page 20

cout << "Two was entered."; } else if(inferno == 3){ cout << "Three was entered."; } else { // do nothing } return 0; } It is definitely more beneficial to use switch case whenever possible.

Short Hand If Else


Sometimes, there is too much code to type and it may be easier to use the following format for if else. However, if you use this, you should have an else clause. Only use it for small boolean or integer option testing, like "IsRed()" do this else do this. It's good for options or settings the user enters. Do not use it for large operations. (DidUserEnterRed)?MakeColorRed():MakeColorOrange(); If the boolean variable "diduserenterred" is true, then it will make the color red, otherwise, orange function will be called. Here's a good example to use the short hand for: #include <iostream> using namespace std; int main(){ int OpenInNewWindow; cout << "Enter 1 if you want to open it in a new window.\n"; cin >> OpenInNewWindow; OpenWebsite("http://www.infernodevelopment.com", "/forums", "Welcome Message", (OpenInNewWindow)?240:100); return 0; } The function above is pseudo code, but it expresses the best time to use shorthand for. Perhaps a function needs to give a parameter of 240, every time it wants to open a new window, and 100 if it does not. The condition tests if OpenInNewWindow is 1 or 0, if 1 then 240, otherwise 100.

http://www.infernodevelopment.com

Page 21

9LOOPThere are so many different methods of looping which is an essential building block of any game or complicated program. Knowing efficient looping skills will make you a better C++ programmer.

For Loop
The most common form of looping is using the for loop. #include <iostream> using namespace std; int main(){ for(int i = 0; i < 5; i++){ cout << i << endl; } return 0; } This will output: 1 2 3 4. In each line of course because of endl. A for loop is structured like so: for(initialization variable; condition to loop; update variable){ execute loop code } If you leave the inside empty, it becomes an infinite loop: for(;;){ // infinite loop } Some other for loop examples may be used with arrays and displaying a sequence of characters (a string): #include <iostream> using namespace std; int main(){ char string[] = "Just a string"; int maximum = (int)sizeof(string)/sizeof(char); // sizoeof(char) is 1 for(int i = 0; i < maximum; i++){ cout << string[i] << " "; }

http://www.infernodevelopment.com

Page 22

return 0; }

It's good to keep functions outside the loop code, which is why I created the maximum integer so that the sizeof functions are only executed once. We don't want to keep doing sizeof ten or twenty times. This will display the string as: Justastring

While loop
A while loop is also very common, usually used for true or false conditions. #include <iostream> using namespace std; int main(){ bool btest = true; int i = 0; while(btest){ i += 5; if(i == 50){ btest = false; // stop looping at 50 } } return 0; } Useful for infinite loops where only certain exit inputs can get out of the loop.

Do While Loop
Do While loops are loops that are executed at least once before testing the condition. Useful in situations where the first execution might determine whether we can keep looping. #include <iostream> using namespace std; int main(){ int memory(0); do { memory = CheckMemory(); Sleep(100); } while(!memory);

http://www.infernodevelopment.com

Page 23

return 0; } It's very useful in situations where you are waiting around until an event happens.

Foreach
There is no foreach loop in C++ or C; unless you install Qt library which has a foreach method.

Break
The break command allows you to exit a loop that you don't need to repeat depending on a condition. #include <iostream> using namespace std; int main(){ int memory(0); do { memory = CheckMemory(); if(memory > 0)break; Sleep(10000); } while(memory < 1); return 0; } In the above example, you may not want to go through the whole 10,000 second sleep again before exiting the loop because memory is now greater than 0. So you break out of the loop.

Continue
Continue is a skipping of the loop so that it can go to the next iteration. #include <iostream> using namespace std; int main(){ int memory(0); for(int i = 0; i < 10; i++){ memory = Check(); if(memory < 200 && memory > 100 && i == 2){ continue; }

http://www.infernodevelopment.com

Page 24

GetMoreMemory(); } return 0; } You may want to skip this iteration if we already reached 100 memory. Thus, depending on certain conditions you may want to go to the next loop step rather than continue in the current one.

http://www.infernodevelopment.com

Page 25

10C++ FunctionsA function (in programming) is a simple command used to do multiple or more complicated tasks. If you have ever programmed anything in your life, you used a function. Examples of functions are: cin, cout, printf, and getchar. Those are all functions. Now your probably thinking, big deal functions are helpful but why would I need to learn about them? Well functions are great for handling errors and organizing code. toc_collapse=0; Contents [hide] Declaring Functions Return Values/Function Types Function variables (parameters) Inlining Functions

There are four steps to making your own function. 1) The first step is type. You function needs a type, whether it be int, void, or BOOL, it needs one. 2) The second step is naming your function. It needs a name! Imagine calling a dog without a name, it won't go by you. It's the same with functions, in order to call them, you have to name them. Note: Stay away from naming functions something that sounds like it could be declared in header files. Optional 3)Variables. You can define any function specific variables here. Although this step isn't really needed it can be helpful in organization. 4) Code! Your function has to do something so it needs some code!

Declaring Functions
Declaring common functions: A defined function would be one like LockWindowUpdate. It exists out there as a common function, in a header file that you include (#include). An example is in order to use the function printf in your code, you just include the iostream header file. #include <iostream> Declared custom functions: A custom function is what you created. Now, to declare a custom function just look at the very first line of the function you created. Here's a function I'll use in example: void printMessage(char msgprint){ //this line printf(msgprint); }

To declare that, just take the first line (Minus the "{"), and place it up at the top of your file, by the #includes. The declaration for the function posted above looks like this: void printMessage(char msgprint); NOTE: You do not have copy the first line if the function code is ABOVE int main.

Return Values/Function Types


http://www.infernodevelopment.com Page 26

Now, remember when you picked the type for you function to be? Well the type depends one what the return value is. int - Return value is an integer. Example: return 9; BOOL - Return value is true or false. Example: return false;

Function variables (parameters)


Functions can also have variables. They're special variables, and are called parameters. These are used if you plan to use the function more than once but have a slightly different job. Or they could completely change what the function does, depending on how you use it. To make a function parameter, declare it in () after the function name. Example: void printmsg(char* message){ //char* message is the variable for the function printf("%c", message); //prints the value that you set message to } Now when calling the function just do this: printmsg("hi");//puts the word 'hi' in the console And now you can use that function to print whatever you want in the console.

Inlining Functions
Some functions, don't really need a function. These kinds of functions are usually only about 2 - 6 lines long and with minimal work. Since functions use up more memory than just using the lines in our code, we can inline them. Now what inlining does is the compiler finds every place you used that function and replaces it with the code inside that function. But it only does this inside the .exe. To inline a function just keep the decloration the same as before, and then go down to the function and add inline in front of the data type. Example: int main(){ inlinefunction();//calls the function inlinefunction getchar();//pauses the app } inline int inlinefunction(){ printf("inlined function");//prints the message 'inlined function' to console }

The compiler would turn that code into this: int main(){ printf("inlined function");//prints the message 'inlined function' to the console getchar();//pauses the app }

http://www.infernodevelopment.com

Page 27

http://www.infernodevelopment.com

Page 28

Das könnte Ihnen auch gefallen