NOTE TO SELF FOR INTRODUCTION: The way I picture these being used by a new programmer is that information will be given very briefly as to background and structure and does not have to be memorized. Just stick it in the back of your mind as you read. It will be kept to only a page or two, so rereading it will never be a pain as you learn more. Then, commands and short samples will be given to quickly get you writing code. These notes IDEALLY will quickly become a reference, rather than something you have to memorize. As you write programs, you’ll be able to quickly find any command you need by seeing it used in the short sample problems given at a glance (no searching through massive text), then read a simplified explanation adjacent to that sample of each command. Memorization of all the annoying nomenclature of any new language will come AFTER and naturally as you have FUN using the language. Also, write a “what is programming” to just acquaint those who don’t even know what it is with what it is. Background: In C++, you type instructions of what you’d like the computer to do into a text file. This is called writing code. In order for the computer to understand what your instructions mean, it must translate them into “machine code,” which is a code made of ones and zeros that it can understand. Therefore, after you have all your instructions typed in, you tell the computer to “compile” the instructions; which means to change them into the machine code it understands. The computer then runs a “preprocessor” which looks at what you’ve typed and decides how to best compile it. Some statements in your code (called preprocessor directives) tell the preprocessor what libraries of information it will need in order to understand your commands. For example, the statement “# include ” (shown below) tells the preprocessor that you will be doing input and output within your program, and to include the library of input and output commands for that. After the preprocessor runs, then the compiler runs; which transforms your code that you typed in into machine code that the computer understands. Last, this code is saved as an executable file, which can be run with a click! The computer does all these things for you. So, it’s really simple huh? The computer creates quite a few files on your hard drive during this process, but they’ll be in the same directory, so they are easy to keep track of. Basically, after clicking on “compile” you’ll have your code, and then the computer will create “object code” (which is a step between your code and machine code), and then “linker files,” and finally an “executable” which will be your program ready to run! Almost ALL commands in C++ end with a semicolon. Except preprocessor directives or comment statements. The semicolon simply tells the computer where your command ends, just like a period would in a sentence. This all becomes simple and clear after doing a few sample problems Program Structure Here is a quick sample program to visualize the structure of a C++ program. // A simple program to output a sentence to the screen #include using namespace std; int main() { cout << "Hello."; return 0; } Statements and fun! // This is a Comment statement. Any time two slashes precede a line of text; the compiler ignores the text. This allows you to leave comments in your program to remind yourself what things in the program do. This is very important for figuring out what the code you wrote meant when you look at it in the future! If your comment is long, you can also use this method: /* Here is a comment that spans a few lines. */ Here is the last line. The “/*” and “*/” characters are used to signify the beginning and end of the comment over any length. # include The # include command shown above tells the preprocessor that your program will include input and output, and to include the needed files for that when it compiles your code. Using namespace; This command is needed to tell the computer to reserve some space in memory for holding your input and output info. Special note: Although it seems silly to have to NAME an area of memory to retain your information, it can actually be quite useful. For example, if you were merging two programs written by different people, you could use a different namespace for variables (info on this later) so that both programs could run without conflicting with each other’s data! This would save a huge amount of time and possible bugs. Int main () All C++ programs start with this. It’s a way of saying that everything that follows will be part of a routine called “Int main ()” { } These two brackets enclose the routine (function) called int main (), so that the computer knows where the beginning and ending of the routine are. cout << "Hello."; This line simply tells the computer to print “Hello.” to the screen. Note: Don’t forget that all these lines end with a semicolon. Only comments, preprocessor instructions, and functions like “main (0)” do not have semicolons. The reason is these things are not dealt with by the compiler. Return 0; This line simply tells the computer that it is at the end of the function (set of commands) that you wrote. It usually indicates the program has executed successfully. Text formatting Now that you know how to print something to the screen, you’ll want to be able to format that text to look attractive, or line up properly with things you put on the screen. cout << “Let’s start a new line “ << endl; The above statement uses the “endl” command to end the line. This is just like you hitting enter or return when typing. Otherwise, everything you told the computer to print to the screen would just print in one long line! The “<<” marks can be inserted within a cout command to allow you to print or do things consecutively. For example, cout << “Hey dog! << endl << “dog”; Will print “Hey dog!” on one line, then space down and print the word “dog” on the next line. There is a shortcut that can often be used instead of typing “endl” which is to add “\n” as shown below: cout << “Let’s start a new line \n“ The above line types out “Let’s start a new line” and then spaces down one space as if you hit enter or return. There are several other switches just like this to make formatting print easy. \n newline \t tab \a beep \r return \ \ prints a backslash \’ prints a quote \” prints quotes Variables Variables are just names or letters that carry a value. Just like in algebra. So, in programming you can have numeric values that change, kept in a variable. You could say in your program: X=1; and the computer would do any math you gave it with the idea that X=1. Another type of variable is a string variable. Strings are just text. So, you could say X= “Bob the dog.”; Then, you could tell the program to print X, and it would print, “Bob the dog.” Because these values are “variables” it lets your program take input (like entering your name) and then remember it, to address you by name later. In C++, you have to tell the computer what a variable will be used for in your program. This is called “declaring” the variable. This gets a LITTLE complicated, but not bad…. Let’s say we have a variable that we want to represent a number. We can call it anything we want, so, we’ll call it “number.” Int number; The above command declares to the computer that we’ll have a variable called “number” and that that number will be an integer. Here are other things you can declare your variable to be, other than an integer, and what they mean. When you declare a variable for use in a C++ math problem, here is a handy chart which shows the ranking and ranges of each type of variable (from largest to smallest): long double …………………….. +/- 1.7e +/- 308 (~15 digits) double ………………………….. +/- 1.7e +/- 308 (~15 digits) float …………………………….. +/- 3.4e +/- 38 (~7 digits) unsigned long …………………… 0 to 4294967295 long ……………………………... -2147483648 to 2147483647 unsigned int ….………………… 0 to 4294967295 int ……………………………… -2147483648 to 2147483647 Note: Unsigned simply means no negative numbers are included. I.e. “-“ sign. Two additional data types (not yet mentioned in our book): short ………………………… -32,768 to +32767 unsigned short ………………. 0 to 65535 Example: //This sample shows how a numeric variable is declared #include using namespace std; int main () { float distance; double math; distance = 1.76587587765E11; mass = 1.989E30; cout << “Distance = “ << distance << “ Mass = “< (Value) Example: Int (b) static_cast (b); Or, you can even use this method to print out a TEXT character (called an ASCII character) which is represented by the value stored in the variable. (Check the ASCII chart for the numeric value of each,) Example: Static_cast (65); Output will be an “A” as that is the ASCII character represented by the number 65. Note: The ASCII table has many interesting characters other than letters which can be useful for dressing up console (text only) programs. Note to self: See page 45, ask teacher where these go above. If you want your variable to contain string information (text rather than numbers), you define it as characters using this command: char(12) number; The above definition tells the computer to make space to remember 11 text characters, and to call those characters “number.” Why 11 and not 12? C++ always needs one extra character reserved so it can put in a marker to know when it’s reached the end of the text it’s remembering. (The marker is invisible and does not show up to the user.) You can change the number 12 to any number of characters you want the computer to be able to remember as your variable. It is possible to store a single character in memory, without adding an extra space for the marker. To do this, you simply use a single quotation mark around your variable. Example: letter = ‘A’; In order to have the computer stop and ask the user for information, you can use the “cin >>” command. Sample program: // This shows how to have a user input a number into your program. #include using namespace std; int main () { int number; cin >> number; cout << “You typed “ << number <<; return 0; } Note: “cin >>” can also be used for multiple values If you’d like to input a single value without having to press “enter,” you can use the getch() command . #include #include int main() { int c; // create an infinite loop for(;;) { // get a key from the keyboard c = getch(); // exit loop if Q hit if( c == 'Q') break; } return 0; } Note: Because the getch command just looks to see if a key is pressed, then continues on it’s way, it is placed in a loop, which will be covered later. Boolean Values Boolean values let you store a value of “true” or “false” in the boolValue variable. Example: bool boolValue; boolValue = true; cout << boolValue << endl; boolValue = false; cout << boolValue << endl; This example would print the value “true” then “false.” Math Functions Most math functions are written out just as they would be in algebra, and normal math rules apply as to what order the computer will solve an equation. I.e. expressions inside of parenthesis are solved first, multiplication and division has precedence over addition and subtraction etc. Associativity: Normally problems will be solved left to right. The exception being “unary negation” which is to say simply, if you have a single number with an operand (such as –5) the computer will read right to left. Note: To prevent problems in some C++ compilers, it is a good practice to put parentheses around expressions. Example: Cout << (A/B) << endl; There is no symbol for exponents used in C++ programming. If you wish to raise a number by a power, you can use the “pow” command. Example: area = pow(4.0, 2.0); This simply means the same as four to the power of two. Note: When using “pow” in a program, you must include the statement: #include Large numeric values can be displayed by the computer using scientific notation. Example: 47,281.97 = 4.728197E4 Numbers after “E” are to the power of 10. Note: Page 131 shows many additional mathematical functions like “pow” which can be called upon. Literals A literal is simply a value that does not change. A named constant is a variable that can’t be changed after it is defined. Example: Const double WALT = 5; Trick: Make constants all caps so you can identify them easily when reading your code later. Text (output) Formatting In order to line things up on the screen in a readable manner, C++ offers many handy text-formatting options. To specify a certain number of spaces be printed, regardless of the number of characters in your answer. Use the command “set.” Example: cout << setw (5) << value; To set the maximum number of digits before and after a decimal point, use the set precision command. Example: Cout << setprecision(2) << fixed; Note: The “fixed” statement above forces the output to be regular, and NOT scientific notation. Note: The set command, and the setprecision command require the #include statement. If you want to fill any output space with trailing zeros (rather than leave it empty), use the command “showpoint.” Example: Y= 456.0; cout << setprecision(6) << showpoint << Y Output will be: 456.000 To left or right justify, use left or right as shown below. Example: cout << left << setw(10) << x << endl; Note: There is a table on pg. 124 for this. Input text can also be formatted which is very important to prevent a user from typing in more characters than you want allowed by your program. Example: size=12; cin >> setw(size) >> variable; In the above, the computer will only read up to 12 letters typed by the user. Note: cin can not read spaces, enter, key, or tab. To read a whole line of input from the user with spaces included and only stop reading if the user hits “enter,” use the getline command. Example: Cin.getline(sentence,20); Will read up to 20 characters, or stop reading when the user presses enter. You can also use this command to get single characters that include space, tab, etc. Example: Cin.get(ch); Note to self (this is on page 128). You can also have C++ ignore certain characters. Example: cin.ignore (20, ‘\n’); The above line will ignore up to 20 characters until a newline is encountered. The ‘\n’ can also be any letter or number. Random Numbers Generating random numbers is very useful for many programs. To generate a random number, use the rand(_) command. Example: Y = rand(); Note: You must use the #include statement when using the random command. Because the computer uses a mathematical algorithm to generate a random number, the same numbers will be generated every time you use the random statement. In order to make sure the same numbers don’t show up every time, the computer will mix in a numeric value from the computers clock. Since the clock is constantly changing, this makes the computers pseudorandom numbers much more random seeming. This is called “seeding” and is done as follows. Example: unsigned seed = time(0); // gets clock value srand (seed); // seeds value cout << rand() << endl; // prints value You can use the following method to limit the range of your random numbers. Y = 1 + rand () % 100; The above example would make the variable Y equal to a random value between 1 and 100. Reading and Writing to Disk Note to self: Covered on page 142. Just as we have now printed information to the screen, and read from the keyboard, we can do the same thing from disk. Note: Input and output from disk requires the #include preprocessor command. The following commands are used: Inputfile.open (“filename with extension here”); Opens a file on disk for input or output. Then: ofstream ……………………. Output to a file ifstream …………………….. Input from a file fstream ……………………... input and output from a file Example: #include inputfile.open (“customer.dat”); char filename[20]; cout << Enter a filename: “; cin >> filename; outputFile << “hello /n”; Or, this can also be done in one statement as follows: Ifstream inputfile (“customer.dat); Note to self: Something is wrong with the above. Write the program to test it. Exiting the program automatically closes all files, BUT, it’s good programming practice to close files that are not needed whenever possible. To do this, use the following command: OutputFile.close(); Note: You can use variables to open and close your files as well. Walt’s Crib Notes on C++ 12