___ __ __ / _ \/ / _______ ___ _/ /_____ / ___/ _ \/ __/ -_) _ `/ '_(_-< /_/ /_//_/_/ \__/\_,_/_/\_Y___/ ___ ____ ___/ / / _ `/ _ Y _ / _\_,_/_//_|_,_/ / ___/__ ___ / /_____ / (_ / -_) -_) '_(_-< \___/\__/\__/_/\_Y___/ C++ Review Chap 1 By. Vile_Bafou ----------------- - all c++ programs have a main function the main funcation is where the program begins running. - A computer talks in machine language/Binary - Interperter - Translate the source code of a high level language - Compiler - Makes transation once and saves it - C++ - Comments - Compiler directives - i.e. #include - Main function - Braces - Statements - instructions that make the program work - Braces mark the beginning and end of blocks of code - statements are the lines of code the computer excutes - each statement ends with a simicolon - C++ is case senstive and it ignores extra space. ----------------- Cheats ----------------------- - (syntax) void main() "no need for return :)" - (syntax) endl " instead of yucky \n" ------------------------------------------------ Chap 2 Variables and constanst ------------------------------ - variable - data structure whose contents can change while a program is running - integer - is a whole number - c++ integers are char,unsigned char, short, unsigned short, int, unsigned int , long, unsigned long datatype min range of values min number -------- ------------------- ---------- | char -128 to 127 1| | unsigned char 0 to 255 1| | short -32.768 to 32.767 2| | unsigned short 0 to 65.535 2| | int -2.147.483.648 to 2.147.483.647 4| | unsigned int 0 to 4.294.967.295 4| | long -2.147.483.648 to 2.147.483.647 4| | unsigned long 0 to 4.294.967.295 4| -------------------------------------------- Declaring --------- - (syntax) int i; // declare i as integer - !Must intilize first in c++ - (syntax) = // Used to inilitize - identifers - names of variables Rules for identifers 1. can use letters, numericals or underscores in rest of identifer 2. use name that makes purpose clear 3. no spaces in identifers 4. keywords must NOT be used as identifers Characters ---------- - characters - symbols or letters - ASCII - American standard code for inforamtion interchange Floating-points --------------- - Used with taskes using money - Can store fractional numbers - datatypes: float, double, long double - can also use exponential notation - i.e. e56.9 Boolean variables ----------------- - Can have only 2 possible values - One value usually represent true and other false - some c++ compilers do not support boolean variables Constants --------- - constants hold data that does not change as the program runs - must be given a data type and a name - (syntax) const double PI = 3.14159; - traditontal Upper case letters are used in constants ----------------------Tips------------------------ - CAN NOT DIVIDE A FLOAT TIMES A DOUBLE :) - Boolean can have one of two possible values true or false -------------------------------------------------- Chapter 3 Math Operators ------------------------ - Assignment Operator - changes value to the left of variable operators in c++ ---------------- | + Addition | | - Subtraction | | * Multiplication | | / Division | | % Modulus(Remainder) | ------------------------ - Arithmethic operators are used with two operands - Modulus Operator(%) - Returns the remainder rather than the result of division - cin - console input(>>) - cout - console output(<<) ------------ Cheats ---------- - (syntax) /* */ to comment block of code - Check out the header files really useful :) - a\ ------------------------------ Incrementing(Counting up) Decerementing(Counting Down) ------------------------------------------------------ - You increment with the ++ operator - (syntax) k = j++; OR - (syntax) k = ++j; "math first then assign k to j - You decrement with the -- operator - (syntax) k = j--; OR - (syntax) k = --j; "math first then assign k to j Order of operations ------------------- 1. Minus sign used to change sign(-) 2. Mulitplication and Division and Mod(*/%) 3. Addition and Subtraction (+-) - Can use parentheses to override the Order of Operations Mixing Data Types ----------------- - C++ allows you to mix data types in calculations - C++ can automatically handle the mixing of datatypes (called promotion) or you can direct the complier on how to handle the data (called Typecasting) - Promotion - Mixing of datatypes (in your calculation) - Typecasting - Directing the compiler on how to handle the data - (syntax) x = (int)a + x; - (syntax) c = PI * (long double)(diameter) - Truncated - The digits after the decimal point are dropped Overflow & Underflow -------------------- - Overflow - When a value becomes too large for its datatype - Underflow - Occurs with a floating-point number, When a number is too small for the datatype Floating Point Rounding Errors ------------------------------ - Using floating-point numbers can produce incorrect results if you fail to take the precision of floating-point datatypes into account - "E" notation - this makes it possible to represent very large and very small floating-point numbers - (example) Mass_of_Electrons = 9.109e-31; // 9.109 x 10-31 kilograms - Signifant Digits - states the accuracy of the result of a calculation is only as good as the accuracy of your least accurate value ------------------------------Tips------------------------------ - The assingnment operator changes the value of the variable to the left of the operator to the result of the expression to the right of the operator - You can intialize multiple variables to the same value ina single statement - The arithmetic operators are used to create expressions - The modulus operator returns the remainder of integer division ---------------------------------------------------------------- Chapter 4 Strings and Screen I/O -------------------------------- - NO string datatype in c++ - There is a string header file that allows string use - Literals - Hard coded values or strings - (Example) Name = " My Name"; (String) - (Example) Initial = 'm'; (Character) - Literals can be numeric literals, string literals, or character literals Classes and Objects ------------------- - String Class - An object-oriented string datatype is referred to as this - A string class is actually a definition used to create a string object - Class - a generic definition from which an object is created - An object is said to be an instance of a class Using the string class ---------------------- - Made up of two files apstring.h(include folder) and apstring.cpp(project folder) - (Syntax) apstring(Object datatype) Mystring(Declares and initlizes it); (Syntax) apstring Mystring2("ABCDEF"); - Method - Action of string object or other - Can assign contents of one string object to another string object - (Syntax) Mystring1 = Mystring2; - Can assign string literal to a string object Messages -------- - Encapsulation - Containment Only the actions the object is supposed to do it will do - An object hides the details of how data is stores and how operations work - To make an object do what we want, we send the object a message Obtaining the length of a string -------------------------------- - Dot operator - Seperates the name from the method - Method - code inside object that perfoms length operation - (Example) 1 = Mystring2.Length(); String Concatention ------------------- - Concatention - Adding one string onto the end of another string - The + operator can be used to conconate strings - (Example) Mystring1 = Mystring1 + ' ' + Mystring2; - The += operator can also be used Using cin and cout ------------------ - Cin - stream that brings data from your keyboard - Cout - stream that takes data to your screen - >> Operator is also known as the Extraction Operator, Because it extracts data from the screen - << Operator Refered to as the Insertion Operator New line and other special characters ------------------------------------- - \n - called new line character or end-of-line character - \t - Tab - \' - Single Quote - \" - Double Quote - \\ - Backslash Using setf and unsetf --------------------- - The cout object has format options that can be changed by using setf and unsetf methods - (Example) cout.setf(ios::right); - Formatting options include: Left,Right,Showpoint,Uppercase,Showpos,Scientific Option Description ------ ----------- |Left Left-justifies the output | |Right Right-justifies the output | |Showpoint Displays decimal point and trailing zeros for all floating points,| | even if the decimal points are not needed | |Uppercase Displays the "e" in E notation as "E" rather than "e" | |Showpos Displays a leading plus sign before positive values | |Scientific Displays floating-point numbers in scientific("E") Notation | |Fixed Displays floating-point numbers in normal notation | ---------------------------------------------------------------------------------- I/O Manipulators ---------------- - need this header iomanip.h to use i/o manipulators - The most common I/O manipulators in c++ are setpercision and setw Inputing strings ---------------- - The getline method is used to input strings entered by user - (Example) getline(cin, Mystring); Flushing the input stream ------------------------- - After you have input a number using a cin statement, the new line character that is generated when you press enter stays in the input stream - You must remove the extra characters from the input stream before the getline method is executed - (Example) cin.ingnore(80, '\n'); --------------------Tips------------------- - Hard-coded numerical values are called numerical literals - Hard-coded text is called a string literal - A class is a definition used to create an object - An object is said to be an instance of a class - !Getline to get a input string! ------------------------------------------- Chapter 5 Decision Making ------------------------- - Flowchart - maps the decision a program is to make and the path down which each decision leads. True and False in C++ --------------------- - False = 0 - True = 1 -----------Relational Operators---------------- Operator Meaning -------- ------- == Equal to (Equality) > Greater than < Less than >= Greater then or equal to <= Less than or equal to != not equal to (Equality) ----------------------------------------------- (Tip - x=y Will ALWAYS be true) ( use == for comparisons and = for assignments) (Parenthesis overides all of this) -------------Logical Operators----------------- Operator Meaning Example -------- ------- ------- && and (j==1 && k==2) || or (j==1 || k==2) ! not result = !(j==1 && k==2) ----------------------------------------------- Order of Logical Operators -------------------------- 1. ! (not) 2. && (and) 3. || (or) - Can use logical operators to combine more then two comparsions Short circuit Evaluation ------------------------ - (&&) First is false (Two need to be true or false) - (||) First is True (Only need one to be true or false) Selection structures -------------------- - These execute statements one after another without changing the flow of the program - Selection Strucures - structures that make decisions in C++ - Selection structure controls the flow of the program based on the decision Using if -------- - The if structure is in most if not all programming languages - Control Expression - The expression that makes the decision - One-way selection structure Using if/else ------------- - Two-way selection structure - One block of code is executed if the control expression is true and another block is executed if the control expresson is false - Nested if statements - Placing if statements inside other if statements Switch Structure ---------------- - Switch Structure - a method for handling multiple comparsion options - Useful when working with menu choices that are presented to the user (syntax) switch (method) { case 1: cost = 5.00; break; } OR switch (method) { case 1: case 2: case 3: cost = 5.00; break; } It falls through case'(s) -----------------Tips------------------------ - default: is like the else in a case statement in VB.NET - Place more common choices at top and less common choices at bottom - ONLY integer datatype in switch --------------------------------------------- Chapter 6 Loops --------------- - For Loop - The loop repeats one or more satatements a specfic number of times - An loops uses parenthesis - Parameters - the three items needed to make a loop work - First parameter - Called INITIALIZING EXPRESSION, initializes the counter variable - Second parameter - the expression that will end the loop, called the CONTROL EXPRESSION it is tested BEFORE the loop - Third parameter(optional) - the STEP EXPRESSION, it changes the counter variable usually by adding to it - Placing a semicolon after the closing parenthesis of a loop will prevent any lines from being iterated (Step Expression) Counting by ten for( i += 10; i <= 300;) { cout << i << endl; } - += For lazy people OR i=i + 10 While Loops ----------- - A while loop is similar to a for loop, but in a while loop, something inside the loop triggers the loop to stop - There are two kinds of while loops: the standard while loops and the do while loop - The difference between the two is where the control expression is tested - The while loop repeats a statement or group of statements as long as a control/expression is true - a while loop does not use a counter loop (syntax) while (num > 1.0) { cout << num << endl; num = num / 2; } - as long as the value of num is greater then 1.0,the loop will continue Do While Loop ------------- - a do while loop repeats a statement or group of statements as long as a control expression is true at the end of the loop Stoping in the middle of a loop ------------------------------- - The keywork break, also utilized with switch statements, can be used to end the loop before the conditions of the control expression are met (syntax) { break} OR { break } - The continue statement skips the remainder of a loop and starts the next iteration of the loop - You should allow the control expression to end an iteration structure whenever practical - Continue - causes the statements in the loop to be skipped when counter variable is what you want it to be Nesing Loops ------------ - Using nested loops is possible and very common - We typically refer to the loops as the inner loop and outer loop - Make sure to trace the steps of the program carefully to understand how nested loops behave ----------------Tips------------------------ - Dont use breaks, find a differnt way to do the program - may cause spagetti code.... yucky -------------------------------------------- chapter 7 Functions ------------------- - Most programs use functions that perform specfic tasks - Main Function - This will call other functions as the program needs their functionality - VTOC - Visual Table Of Contents ---------------------------Guidelines Using Functions-------------------------------------- |- Organization - a program consisting of multiple functions is easier to read and debug | |- Autonomy - does not depend on code outside the function more than necessary | |- Encapsulation - hideing details from the user,the user does not need to know | |- Resuability - so it can be reused in the same or other programs | ------------------------------------------------------------------------------------------- Program Design -------------- - Top down Design - Begins with the functions at the top of the VTOC and works its way down - Bottom up Design - Involves beginning with the bottom of the VTOC and working your way up - Drivers - Program - Stubs - Function,sends back the right value (example) user defined function void print_title() { cout << "Soccer Scheduler Program\n"; cout << "By Ben And Conrad McCue\n"; } (example) calling function print_title(); // call to print title Function Prototypes ------------------- - Prototype - defines the function for the compiler (example) prototype // 1st funct.cpp #include void print_title(parameters); OR int print_title (parameters) // function Functions and Program Flow -------------------------- - When a function is called, the computer executes the statements in the function beginning with the first statement - When the end of the function is reached, program execution resumes with the statement that follows the call to the function Scope Of Variables ------------------ - Scope - the "availabilty" of a variable... i.e. who can see it - Local variable - declared within a function and is accessable only within that function - Global variable - This is declared before the MAIN function, they are accessable by any function - Automatic variable - Local variables - External variable - Global variables Data and Functions ------------------ - The parenthesis after a functions name can be used to pass data to a function and in some cases to return data from a function - When a function is called, the data in the parenthesis (called argument) is passes into the receiving function - Argument - data in the parenthesis - Passing by value - a copy of the value in the variable is given to the function for it to use - if the variable is changed within the function,the original copy of the variable in the calling function remains the same - Passing by reference - it passes any changes you make to the variable back to the calling function - To pass a variable by reference, simply precede the variable name with an ampersand(&) in the function definition Example of libary function -------------------------- - (example) z = pow(x,y) // z equals x raised to the y power - You need to include the math.h header file first Header Files ------------ - Header file - a text file that provides the prototype of a group of library functions - The Linker uses the information in the header file to properly link your program with the function you want to use - need ctype.h header file for "is" functions - ctype.h manipuates char - math.h mannipulates math Chapter 8 Data File Basics -------------------------- - RAM holds only as long as the computer is on - Data in RAM is lost as soon as your program ends - There is more HD sapce than RAM - Data must be saved to a file to prevent loss Sequential-Access ---------------- - A sequencial-access file works like a cassette tape - You have to move through the file sequencially to get to where you want - (Examples) word processor,spreadsheets,graphic files Random-Access ------------- - A random-access file works like a cd - You can move directly to any data in the file - (Example) Hard Drive,CD - The file is made of equal-sized blocks, a program can predict how far to move forward in the file in order to get the desired data Declaring File Streams ---------------------- - file stream - Getting data to and from files involves streams - When declaring a file stream, you select a stream type and name for the stream - (Syntax)Use ofstream outfile; For Writing - (Syntax)Use ifstream infile; For Reading Opening a File -------------- - When you open a file, a physical disk is associated with the file stream you declared - You must provide the name of the file you want to open, and whether you need to read or write data - After the file name you need to specify the stream operation mode - (Syntax)Use ios::out when creating an output file - (Syntax)Use ios::in when opening a file for input Open file examples ------------------ Ex.1 writing to a file ofstream high_scores; //stream for writing high_scores.open ("scores.dat", ios::out); // creates the output file Ex.2 reading to a file ifstream infile; // stream for reading infile.open("mydata.dat", ios::in); // open the file for input ------------------Tip----------------- - Use instead of - Because it has everything iostream.h has and more -------------------------------------- Closing a file -------------- - After a file has been opened, you can begin writing to it or reading from it - When you complete your work with it you must close it - (Syntax) infile.close OR outfile.close Writing data to files --------------------- - Writing data to a sequencial-access data file employs the insertion operator (<<) that you use when printing data to the screen - (Example) outfile << user_name << endl; - all formating stuff will work on this that worked on cout Reading data from a file ------------------------ - Before you can read data from a file you must open the file for input using a file stream - When you open a file using ios::in it must exist Reading numeric data -------------------- - When reading strictly numeric data, you can use the extraction opertator(>>) as if you were getting input from the keyboard - Instead of using cin as the input stream, use your file stream name Adding data to the end of a file -------------------------------- - Appending - Adding data to the end of a existing file - To append data to an existing file using ios::app stream operation mode - If the file does not exist, the OS creates it for you Detecting the end of a file --------------------------- - When reading strings from a file, the getline method returns a value of true as long as it finda valid data to read - If the end of a file is reached, the getline method will return a value of false - When reading numeric values, you must detect whether the operation has failed Ex.Loop to end data file while(getline(infile,instring)) { cout << instring << endl; } Ex. Loop to end numeric data file do { infile >> x; if(!infile.fail()) { cout << x << endl; } } while(!infile.fail()); - In some compliers you can use the EOF instead Using multiple files -------------------- - Reading and writing to multiple files at the same time is possible - Simply declare a seperate filestream for each file that needs to be manipulated - In this way, you could add data to the middle of an existing file -----------------------Tips------------------------ - Relational database systems - because they are linked by the field they are used in - infile.unsetf(ios::skipws); // Prevents space from being skipped --------------------------------------------------- Chapter 9 Arrays ---------------- - Row/Column - Vector - one dimentional array, of any datatype, when declared must specfify datatype - Matrix - Two dimentional array - Parallel Vector - two, one dimentional arrays - Array - a list of variables or other data structures that are accessed using a single identifier,also an array is an object Template Class -------------- - The vector class is an example of a template class, its a base class - Template Class - This is designed to customize the datatype at the time the program is compiled Ways to declare vectors -------------------------------------- |- Empty Vectors | | apvector Myvalues; | |- Specifying the number of elements | | apvector Myvalues(100); | |- Initializing the vector(all to 0) | | apvector Myvalues(100,0); | -------------------------------------- Compilying a program using the vector class ------------------------------------------- - Because the vector class is a template class, the entire class is contained in the file apvector.h - Must include apvector.h header file to use vectors class, not really used in bussiness and industry Indexing elements in a vector ----------------------------- - To set an element of the vector, indicate the element to which you want to assign a value using square brackets - Subscript - Value in the square bracket Ex. MyValues[2] = 2.5; - In c++ the first element in a vector is referred to by the subscript of 0 Using loops to work with vectors -------------------------------- - Loops are often used when working with vectors, since the counter in the loop can be used as the subscript in a vector Ex. for(i = 0; i <= (num_values - 1); i++) { cout << my_grades[i] << endl; } Other vector features ------------------------------------ |- Obtaining the length of a vector | | num_elements = Myvector.length();| |- Resizing a Vector | | Myvector.resize(50); | |- Assinging one vector to another | | Myvector1 = Myvector2; | ------------------------------------- Parallel Vectors ---------------- - Vectors can be used together to store data the would be best stored in a tow-dimentional table form. - The vectors are referred to as parallel because a common subscript represnts related information in two different vectors. - Parallel vectors can consist of differnt data types. Two-Dimensional Array(Matrix) ----------------------------- - A two-dimentions array can be visualized as a table or spreadsheet with row and columns Declaring a Matrix ------------------ - To use the matrix class, the apmatrix header must be included in your code, can only be two not more or less - There are 3 ways to declare a matrix apmatrix Mymatrix; apmatrix Mymatrix(4,2); apmatrix Mymatrix(3,2,0); Chap. 11 sec.3 Structuring -------------------------- Structuring Basics ------------------ - Structure = RAF - C++ allows variables to be grouped to form a new datatype - The data elements in a structure are arranged in a manner that is similar to the way database programs arrange data - c++ allows you to create a record by grouping the variables and arrays necessary for the fields into a single structure Declaring a structure --------------------- Ex.struct inventory_item { apstring item_id; apstring description; int quanity_on_hand; int reorder_point; double cost; double retail_cost; }; - Once youve declared a structure, you must declare an identifier called a structure variable, that is of the structure's type Accessing members of a structure -------------------------------- - To access a member of the structure, use the name of the variable ,the dot operator, then the name of the member you need to access Ex. todays_special.cost=47.80; Nested Structures ----------------- - A structure can include other structures as members - accessing the nested structure requires that two periods be used - Ex. current_donor.bp.diastolic = 74; Summary ------- - Pointers are variables and constants that hold memory addresses - the dereferrencing operator(*) is used to declare pointers and to access the value in the variable to which the pointer points - The address of operator(&) returns the address of a variable, rather than the value in the variable .............................................................. Chapter 10 Object-Oriented Programming -------------------------------------- Procedural Programming ---------------------- - The procedural paradigam focuses on the idea that all algroithims in a program are performed with functions and data that a programmer can see, understand and change. - To successfully write procedural programs, the programmer must understand how all data is stored and how the algorithms of the program work. Object-Oriented Programming --------------------------- - The object-oriented paradigm centers on the idea that all programs can be made up of seperate entities called objects. - Each of the objects used to build the program has a specific responsibility or purpose. - Communictaion among objects is similar to communication among people - In OOP, data is transfered through messages that are exchanged that are exchanged among objects Resuability ----------- - After an object is designed and coded into a class, that class can be used in any program - This means producttivity may be increased because less code has to be made - Although procedural code can be reused, object-oriented code is easer to use, especially when using more advanced techniques of data handling. - In addition, less code means fewer errors Containment ----------- - Objects can contain other objects and implement them into other objects - If you have a wheel object your car object can use the wheel to declare four wheel objects - Matrix object, vector of vectors - Has-a relationship - the relationship referred to because, i.e. a car has a wheel(four wheels) Inheritance ----------- - Inhertance is the ability of one object to inherit the properties of another object - Is-a relationship - the house object and the building object have this relationship because the house is a building - When one class inherits the properties of another, the class from which the properties are inherited is known as the PARENT CLASS - The class that inherits the properties of another is the CHILD CLASS or DERIVED CLASS Using a simple circle class --------------------------- - Class - defintion/blueprint for an object - The class circle tells the compliler how to create each object of type circle - Makes circle circle my_circle - Use circle header file #include "circle.h" - #define - instructs compiler to define a symbol and to remember that the symbol exists - #ifndef - checks the compilers symbol table for a specified entry Designing a class ----------------- - To design a class, you must define the purpose of the object that you will use - The purpose will determine how an object is coded, what data it will hold, and how it is implemented - You then decide what functions you want it to peform Class Definition ---------------- - Members - functions and variables that are prototyped and declared in a class definition - private keyword - using private keyword allows you to protect your data - public keyword - tells compiler to let the programmer using the class have direct access to all the variables and functions between public and private keywords - Constructors - tell compiler how to create the object in memory and what initial values of its data will be - Default Constructor - intilizes your member variables - Copy Constructor - recieves a reference to another object as an argument and is used when the object is declared - Member Functions - allow programmers using object to send information to it and recieve information from it - Scope-Resolution Operator(::) - precede function name, used to implement function