12.07.2015 Views

C++ Tutorial Using Visual C++ (Console Applications)

C++ Tutorial Using Visual C++ (Console Applications)

C++ Tutorial Using Visual C++ (Console Applications)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

IntroductionIn the BeginningThe first concept you need to know is that the <strong>Visual</strong> <strong>C++</strong> package is a large and powerful IntegratedDevelopment Environment (IDE), which is designed primarily to create programs with graphic userinterfaces (GUI). That means that the user will key data into boxes presented on a screen (such as Name);then he will cause processing to occur by clicking on a button on the same screen (such as SearchDatabase). The results of the Search by that Name on a database may print the found record on anotherscreen with a different arrangement of display boxes. This process is very similar to the way you send andreceive data at a web site on the Internet. It is called Windows programming. Our programs do NOT usethis type of input and output. Our programs will be using read and write commands in the <strong>C++</strong> language toget data into and out of the computer. Consequently, we will not be using large segments of <strong>Visual</strong> <strong>C++</strong>. Ihave found that most books on <strong>Visual</strong> <strong>C++</strong> do not provide you the information you need to create non-Windows programs. That is the reason I have put this tutorial together.Three Basic AssumptionsThere are three basic assumptions that I have made with this <strong>C++</strong> tutorial. The first is that the reader hassome knowledge of programming and is familiar with basic programming structures in some otherlanguage, such as the decision and repetition statements. This tutorial will cover the beginning elements ofthe <strong>C++</strong> language, up to its object-oriented segments. The second assumption is that the reader will beusing <strong>Visual</strong> <strong>C++</strong> 6.0 installed in the SPSU Computer Science Projects lab (Room J263) or a similarpackage of <strong>Visual</strong> <strong>C++</strong> in a Windows 95, 98 or NT 4 environment. The tutorial will cover important stepson how to successfully enter, compile, run and debug a console application in the <strong>Visual</strong> <strong>C++</strong> environment.My third assumption is that the reader has a basic understanding of a Windows environment so that termssuch as click, drop-down menu, pop-up list, etc. are familiar.Notations UsedAny term encountered for the first time will be bold-faced and explained at that point. Also, manyelements that the user needs to click on are bold-faced. Important rules are underlined. Please email anycomments or suggestions for improving this tutorial to proth@spsu.edu.Part 1 - <strong>Visual</strong> <strong>C++</strong> EnvironmentGetting StartedHaving said all that, how do we use <strong>Visual</strong> <strong>C++</strong>? From the main screen of Windows, click on Start at thelower left of the screen, slide up to Programs , slide over to Microsoft, then Microsoft <strong>Visual</strong> Studio 6.0and finally click on Microsoft <strong>Visual</strong> <strong>C++</strong> 6.0. You may Close the Tip-of-the-Day screen. The firstscreen that you will see is the empty development window, called an IDE.4


What's an IDE?The almost blank screen that appears is the IDE (Integrated Development Environment) where allprograms are created, compiled, linked, and tested, both the Windows type programs and the non-Windowsprograms. The window to the left is the Project Workspace Window (where on-line documentation aboutyour program is displayed allowing you to navigate through the many sections of your program). Thewindow to the right is the Text Editor Window (where you enter and modify your source code). Thewindow at the bottom is the Output Window (where compiling and linking messages are displayed). TheOutput Window will appear the first time you compile your program – it is not visible yet. The toolbarsare along the top of the three windows. The top bar on the screen is main with drop-down menus for File,Edit, View, etc. The row of icons below the main menu bar are short cut methods for some of the methodsin File and Edit, such as Save, Copy, Cut Paste, etc. On the third row of toolbars, on the far right, is theBuild MiniBar toolbar. You will use this set of icons to compile (called build in <strong>Visual</strong> <strong>C++</strong>), execute,and debug your program. Other toolbars you should have at this time are Output, Workspace, Standard,and WizardBar. If these are not showing or if you want to alter the toolbars showing, right click with the5


Saving the Program and Adding It to the ProjectClick on File in the main menu, then Save and create a symbolic name if prompted to do so. All programnames should have the extension .cpp appended to them. Name this program Sample.cpp, if you didn’t doit earlier, and click on Save. If you neglected to check the Add to Project: box on the earlier screen, youcan do it now by right clicking in the Editor window and selecting the Insert File into Project item fromthe pop-up menu. Either way, the file has now been added to the project and it will appear in the ProjectWorkspace window under the FileView tab.Building a Project - Compiling and Linking the ProjectThere are four ways to compile the source files in a project to produce object code and then link these filestogether to produce the executable file. This is called building a project in <strong>Visual</strong> <strong>C++</strong>. (If you have anopen source file, it will be saved when a build is performed) You can:1. Click the Build button on the Build toolbar, which is shown here.2. Choose the Build item from the menu that appears when you right click the Sample files folder in theFileView in the Project Workspace window.3. Choose the Build Sample.exe item from the Build menu on the main menu bar.4. Press F7.The build operation is very efficient in that it only recompiles the files in which you have made changes,since the last build operation. If you choose, you can use the RebuildAll menu option in the Build menuinstead of Build Sample.exe, but it is not necessary unless you have made changes to multiple source files.The Output window will appear and provide you with status and error information during the buildoperation. For each error noted, click on the error number in the Output window and an arrow will appearin the Text Editor window next to the line of code where the error has been detected. For more help withcompile and link errors, click on the error line with the error number and press F1.Executing a ProgramYou can execute the program by selecting Execute Sample.exe from the Build menu or by clicking on theExecute button on the Build toolbar. The screen output of your program will appear overtop of the TextEditor window and will look like the output below. Notice the extra comment (“Press any key tocontinue”) you get automatically, which freezes the screen until you are ready to move on.8


Closing the ProjectIn the main menu bar, select File and then Close Workspace to close the project. Choosing File and Exitwill exit the <strong>Visual</strong> <strong>C++</strong> package and return to the main Windows screen. You can also select File, thenSaveAll, and exit the application to close the project. If you are starting a new project in the same worksession, be sure to create a new workspace with the new project so the new application is not placed in thecurrent workspace.Retrieving a ProjectWhen you return to the computer to work on a project that has been saved properly, you can retrieve it byclicking on File and then Open Workspace. Notice at the bottom of the pop-up window when you click onFile that you may chose to open the most recently saved workspace in one stroke, which will save you frombrowsing for a project if the most recent one is the one you need.Additional Information - Setting OptionsYou can set options in <strong>Visual</strong> <strong>C++</strong> that will apply to every project or a specific project. In the main menu,select Tools and then Options for options that apply to all projects, Project and then Settings for options fora particular project or Tools and then Customize to change the contents of the toolbars. On each tab youwill see a range of options that you can select or deselect by clicking the check boxes. If you wantinformation on one of the options, click on the ? (question mark) at the top right of the screen and thenclick on the check box of the option.ConclusionThis part of the tutorial has described the basic elements of <strong>Visual</strong> <strong>C++</strong> for non-windows (console)applications. Please check one of the books or web sites listed in Part Three if you need more detailedinformation.9


Structure and VariablesPart 2 - Basics of <strong>C++</strong>Structure of a <strong>C++</strong> ProgramAll <strong>C++</strong> programs are made up of one or more modules or functions, one of which must be main ().Execution will start with the main function. Main, or one of the other modules, will call the otherfunctions. All program modules will be coded one after another, usually with the main function beingcoded last. There is no nesting of functions (one inside the other) or differentiation of procedures andfunctions, as in Pascal and several other procedural languages. All modules begin with a heading linefollowed by an open brace ({) and ending with a closing brace (}). These curly braces collectively surroundthe body of the function. Each function begins its execution at the beginning (open brace) of the function.The return statement transfers control to the statement after the call of the function.Built-in FunctionsAll <strong>C++</strong> programs consist of at least one main function and one or more pre-coded files available from astandard library. For example, all <strong>C++</strong> programs that use any keyboard input or produce any screen outputmust include the standard library function called iostream. You have already seen an include statement inthe Sample program. A #include statement is a preprocessor directive which causes the compiler toinsert the named file into the program. I will introduce other directives and library functions, as theybecome necessary.More on NamespacesThe standard library is an extensive set of routines, which have been written to do many common tasks.Since there are a very large number of these routines, it is possible that you may use the same name as oneof the library routines for your own program segments. All of the standard library routines are contained10


within the namespace std, hence the entry using namespace std; - this command applies std:: as a domainname to all the library functions used in this module. When using other libraries, other than std, additionalnamespaces will be declared.CommentsAs explained before, comments begin with // and can appear at the beginning of a line of code (whole lineis a comment) or somewhere els e in the line of code (rest of line is a comment). Usually, a module beginswith a comment block that explains what the module does and includes other documentation as required bythe organization. These multi-line comments can begin with a /* and end with an */ rather than placingdouble slashes on every line. Either of the following documentation blocks could be used for a payrollapplication./***************************** //****************************This module calculates gross pay // This module calculates gross pay*****************************/ // ****************************Coding Conventions<strong>C++</strong> program statements are generally placed one per line and each ends with a semi-colon. Whitespace isthe term used to describe blanks, tabs, newline characters and comments in a statement. The compilerignores whitespace so where there is one space to separate two entries, multiple spaces are also allowed.<strong>C++</strong> source code is basically free form, but certain conventions are followed so the code can be more easilyunderstood. I have been pointing these out as we progress through the coding rules and have used them inall the examples. In the Sample program, notice that the code is indented and the curly braces are lined upone under another. Later you will see sections of code included in a decision or repetition structureindented for ease of reading and debugging.Variables/Identifiers Naming ConventionsVariables reserve a storage area for data coming into the program or results being calculated in theprogram, such as Hours or Rate_of_ Pay. The rules for creating variable names are the following:? Must begin with a letter or an underscore (usually reserved for first character of standard system names).? Can be any length, up to 255 characters but no embedded spaces.? Can consist of letters (upper or lower case), the digits 0-9, and the underscore character.? Cannot be a <strong>C++</strong> keyword (has a special meaning within the language), such as return or main.? Should be descriptive of the data stored in the variable, such as Price or Quantity_on_Hand.Defining Elementary Data TypesWhen variables are declared in the beginning lines of the source program, they must be assigned a type. Sixof the most basic types are int (integer data with no decimal positions), long (integer value with moreprecision than int), float (single precision values up to 6 digits of precision with a decimal point), double(double precision values with a decimal point), char (a location in storage for a single digit, letter, orspecial character), and bool (location for logical results of a test, setting, etc.). If you want the variable tobegin the program with an initial value, add an equal sign and the initial value to the variable definition. Ifyou want the variable to have a constant value, add const before the definition and give it a value using theequal sign as explained above with the initial values. Some valid examples are:int i, j, k=0;long m;float a, b=2.5, c=3.9;double x=0.456342, y, z;char flag='T'; //use only single quotes for a single character variablebool flag=true; //boolean data types can only take on the logical values of true or false; use no quotesconst float DISCOUNT=0.10; //setting up a constant DISCOUNT amount – compiler will not let11


Basic Input and Output Operations<strong>C++</strong> Output// program change the value of DISCOUNT, with const added// constant variable names are conventionally all capital letters<strong>C++</strong> input from the keyboard and output on the screen revolve around the idea of a data stream. <strong>C++</strong> usesoperators to separate the variables/constants we can extract from the input stream or put into the outputstream. In the cout statement in the Sample program above, cout is the output command, "Welcome toSPSU" and endl are the data items we needed to insert into the output stream, and


<strong>C++</strong> InputFor input, <strong>C++</strong> uses the >> operator to separate the items retrieved from an input stream. The followingexample inputs an integer into firstnumber and floating point data into secondnumber. These twonumbers would be keyed in with at least one blank separating the values, followed by the user pressing theEnter key to advance the program to the next statement. NOTE: To avoid input problems, always typeinput data that matches the data type of the variable where it will be stored and never include any specialcharacters like dollar signs, comma with values greater than 999 or embedded blanks with the values. Toexecute the following code, the first number should have no decimal point, but may have a leading sign.The secondnumber can be any value with a decimal point and may have an optional leading sign.int firstnumber; // type a number such as, 25, +100, 0, -99float secondnumber; // type a number such as 3.6, 0.789, -6.2345, +1025.66cin >> firstnumber >> secondnumber;If the user types in:25 3.6[Enter]the input statement shown above will store 25 into firstnumber in memory and 3.6 into secondnumber.Assignment Statement and Arithmetic OperationsThree Formats of AssignmentThe <strong>C++</strong> assignment statement is similar to assignment statements in many other programming languages.It has three basic formats with three basic uses. The assignment statement must be written with a variableon the left of the equal sign and either a constant, variable or expression on the right side.First format:variable = constant;This form is used to set a variable to an initial value, if it wasn't done in the declarations, or is used if thelogic requires that a variable be reset to a value. For example:total = 0;regular_hours = 40;flag = 'T';In <strong>C++</strong>, you can also write repeated statements such as,a = b = 1;which assigns the value 1 to b and then the value of b to a.Second format: variable = variable;This form is used to move data from one location in memory to another - the contents of the variablenamed on the right is moved to the storage location named on the left, destroying the original contents ofthat memory location on the left. For example:value = new_value;a = b;Remember that it takes three moves to flip-flop two memory positions because of memory's destructiveread-in characteristic. If a contains a 5 and b contains a 10, the coding to switch the two values is:temporary_location = a;a = b;b = temporary_location;Third format:// save the 5 in temporary_location// move the 10 to a, destroying the 5 that was in a// move the saved 5 to b, destroying the 10 that was in bvariable = arithmetic expression;13


This form of the assignment statement allows the user to calculate a value and store the results in memoryfor later use or for output. Normal algebraic hierarchy is followed as the compiler evaluates the expression.Nested parentheses are done first, followed by multiplication and division as they occur, left to right, thenaddition and subtraction as they occur, left to right. (Exponentiation is done with a library function calledpow(x,y) and, if used, the directive, #include would need to be included in the program.) The +operator is used for addition, - for subtraction, * for multiplication, and / for division. In the followingexample, the final grade is multiplied by its weight factor and the midterm grade is then multiplied by itsweight factor. Next, the quizzes are summed, then averaged, and multiplied by their weight factor. Thenthe weighted final is added to the weighted mid-term and average weighted quiz grade for the final grade inthe class, which is stored in class_grade.class_grade = final * final_weight + midterm * midterm_ weight + (quiz1 + quiz2) / 2 *quiz_weight;An example of exponentiation is,y = pow(x,3);// cubes xIn the assignment statement, normal algebraic equivalents do not hold. For example, you can codectr = ctr + 1;which directs the computer to add the value of 1 to the value of ctr and then store the result back in thelocation ctr. This is the conventional way to increment a variable in programming - it does not representan algebraic equality because ctr does NOT equal ctr + 1, algebraically. You may want to run thefollowing program in <strong>Visual</strong> <strong>C++</strong> to try out all you have learned so far.Integer ArithmeticIn many programming languages there is a facility to perform modulus arithmetic or integer divide. In<strong>C++</strong>, if you divide one integer value with a second integer value using the divide operator (as in a / b), theanswer developed will be an integer or the whole number of times b divides into a. No fractional part will14


e developed. The modulus operator (% ) can be used to calculate the remainder of an integer divide. Forexample:int a=5, b=3, c, d;float x;c = a / b; // the answer in c is 1 because 3 goes into 5 only 1 timed = a % b; // the answer in d is 2 because after 3 integer divides into 5, 2 remainsx = a / b; // NOTE: since a and b are integer, integer divide is performed and the answer is 1// However the answer is stored as 1.0 in the float variable xCombination OperatorsIn <strong>C++</strong>, if an operation is performed on one location of memory and the answer will be placed back in thatsame location, you can use a combination operator. The following examples are duplicate code:a = a + 1; // same as a += 1;a = a + b; // same as a += b;a = a + (b * c); // same as a += (b * c); // parens not necessary but add claritya = a - 1; // same as a -= 1;a = a - b; // same as a -= b;a = a - (x + y + z); // same as a -= (x + y + z); // parens not necessary but add claritya = a * b; // same as a *= b;a = a / b; // same as a /= b;a = a / (b + c); // same as a /= (b + c); // parens not necessary but add claritya = a % b; // same as a %= b;NOTE: the interpretation by the compiler is that the whole expression beyond the combination operator istreated as if it is included in parentheses and is done first before combining it with the implied variable.For example,a /= b + c;// interpreted as a = a / (b + c);// not as a = a / b + c;Increment/Decrement OperatorsIn the two examples above where the value 1 is added to or subtracted from a variable, a third format ispossible, using the increment or decrement operator (++ or - -). For example,a = a + 1; // all 4 formatsa += 1; // result ina ++;// the++ a; // same operationb = b - 1; // all 4 formatsb -= 1; // result inb --;// the-- b; // same operationint ctr=0;ctr++;// adds 1 to ctr - you could also use ++ctr;cout


NOTE: the only time you have to worry about which side of the variable you must place theincrement/decrement operator is when it is used inside an expression with other operators. For example,int a, b=2, c=3;a = ++b * c;// adds 1 to b and then multiples b(3) by ccout


DecisionsComparisonsBesides being able to calculate arithmetic operations at very high speeds, the power of the computer lies inits ability to compare two variables and take action on the results of that comparison. A logical expressionconsists of the following relationship:constant, or \ relational / constant, orvariable, or | operator | variable, orexpression / \ expressionThe relational operator can be (greater than), =(greater than orequal to), == (equal to), !=(not equal to). All logical expressions are resolved to true or false.Sample valid logical expressions are:total == 100 // be sure to use == to test for equal comparisons, NOT a single =a b + c // parens not necessary since arith. precedence is higher than logical (willa > (b + c) // be done first) - can use parens for clarityflag == true //can also test flag by itself since a boolean variable is true or false by definition// if (flag) and if (flag == true) produce the same testletter != ' ' // looking for non-blank character in char variable, letterA programmer can also combine several conditions into one logical expression using the and (&&), or (||),or not (!) logical operators. Several examples include:(age < 40) || single(letter >= 'A') && (letter 69)cout


if (hours = 20 && age < 35young_adult_ctr++;else if (age < 55) // tests that age is >=35 && age < 55adult_ctr++;elseseniors_ctr++; // counts if age is over 55NOTE: only the upper range needs to be tested in each new bracket.There are mu ltiple formats of nested if statements. For clarity, indent each new if section and line up eachelse under its companion if. Use curly braces if there are two or more statements to execute in a true orfalse section.if (condition1)if (condition2)statement(s)elsestatement(s)elseif (condition3)statements(s)elsestatement(s)// condition 1 and 2 true// condition 1 true and condition 2 false – if no action specified// on an inside else, use a single semi-colon (see note below)// condition1 false and condition 3 true// condition 1 and 3 falseIf there is no action specified for an internal else (as in cond1 true and cond 2 false above), create an actionwith a null statement to hold the space and preserve the logic. A null statement in <strong>C++</strong> is a single semicolon.Case LogicIn certain cases, a program must test for multiple codes, such as 1, 2, 3, 4, etc. or 'A', 'B', 'C', 'D', etc. Anested if can be used for this purpose, but a switch statement works better.int code;double amount, balance;.......cin >> code >> amount; // user types in a code and an amount of moneyswitch (code) {case 1: balance += amount;cout


double gift=10000;double interest;int year_ctr=0;do{ interest = gift * 0.08;gift += interest;year_ctr++;}while (gift < 1000000);cout


cout n;if (n > 1)for (int i=n; i > 1; i--)product *= i; // no braces needed for true path, just 1 for statementif (n >= 0)cout


cin >> grades[ctr];ctr++;cout finished;}The subsequent loop, which may calculate the average grade or print out the grades in the array, can becontrolled with a loop variable that runs from 0 to ctr-1. When you exit the loop above, ctr points to thenext location in the array to be filled, if there had been more data to enter, and is also the total number ofitems in the array. Therefore, the loop control variable to process the current number of items in the arrayshould be coded as for(i=0; i


......xyptr = &x;*xyptr += 10;xyptr = &y;*xyptr += 10;// xyptr takes on the value 5000, the address of x// the value 10 is added to the value of 1 in x since xyptr points to x// now xyptr takes on the value of 6000, the address of y// the value of 10 is added to the value of 5 in y since xyptr points to yPointers can be used to point to array elements rather than using an index variable or subscript. First, it isimportant to know that when an array is defined, such as int arrayx[100], the array name (arrayx) isautomatically a pointer variable with the address of the first element of the array (*arrayx points to the firstvalue of the array which is in arrayx[0]). So the second item of the table is arrayx[1] or *(arrayx + 1).NOTE: when you add 1 to a pointer in a line of code, the compiler actually adds 2, 4, or 8 to the address inthe pointer, knowing by the data type of the pointer that the next item of the array is 2, 4, or 8 bytes away.In other words, incrementing or decrementing a pointer works in terms of the type of the object pointed to.Therefore, the programmer can process an array in a for loop by incrementing the array name rather thanthe index (subscript) of the array. For example, the earlier problem of the sum of the sales array can bedone according to the following code:double sales[100];double sum=0;........ // read data into the arrayfor (int i = 0; i


double sales[100];double* arrayptr=&sales[0];double sum=0;........ // read data into the arrayfor (int i = 0; i


function to average 3 float values, returning a float result, and any other function that needs that calculationcan call calcavg to do it. NOTE: <strong>C++</strong> functions only return one value or none at all.Additional Information About FunctionsHere is some additional information about functions that you may find helpful:? If the function does not return a value, use void as the return-type as in void myfunction (int x)? The parameter list must be enclosed in parentheses; if there are no parameters, specify void as inint myfunction (void) or you can use int myfunction ( ) with an empty list? The function body is encased in curly braces as we used in main? All the variables declared in the function, as well as those in the parameter list, are local to thefunction, which means that they are separate memory locations from other like-named variables inother modules - be careful about creating global variables with the same name as local variables.? The value returned may be encased in parentheses. If you are returning an expression, use parentheses.The sample function above, calcavg , could have eliminated the variable answer and the assignmentstatement line of code by coding the return as: return ((a + b + c) / 3);. When returning an expressionmake sure the calculation ends up with the required return-type. If the function does not return a value,use a plain return;. In the main function, it is conventional to use return (0); and code main as intmain ( ). You can also use void main ( ) as the heading line and use a plain return; at the bottom ofmain.? If a function definition appears in the compile list before its call, you do not need a prototypedeclaration of each function called in a module. If the function definition is physically after thefunction call (when you code main first, followed by all the functions that main calls), you will need todeclare each function used in the calling function in the declarative section of the calling function. Aprototype declaration of a function is the complete heading, line including the parameter list,followed by a semi-colon. If the program example, used in the scope of variables example in thesection on Additional Issues on page 17 is rearranged so that main is encountered by the compilerbefore func1 and func2, two prototype declarations would be required in main, as shown below.const double PI=3.1416; // PI is 3.1416 in all modules- a global variable, as beforeint main ( ){int func1 ( );// function declarations - new requirement if definitionsint func2 ( );// of functions appear after their calls - notice semi-colonsconst int x=5;// x is 5 in this module..... // assuming call to func1 and func2 are here in main}int func1 ( )// function definition physically appears after call to it{const int x=10; // x is 10 in this module....}int func2( )// function definition physically appears after call to it{const int x=50; // x is 50 in this module.....}Pass-by-ValueThe discussion of functions, so far, is related to functions whose arguments (in the call of the function) arepassed-by-value to the parameter locations (in the actual function). Copies of the argument values aremade and transferred to the corresponding parameter locations in the called function. If the calcavgfunction, shown above, is called with calcage (70.0, 80.0, 90.0), values of 70.0, 80.0, and 90.0 are placed ina, b, and c and an average of 80.0 is calculated and sent back to average in main. A key consequence ofthe pass-by-value function is that the called function, such as calcavg , cannot change the values of thearguments (quiz1, quiz2, quiz3) in the calling function (main). Even if the code in calcavg added 1025


points to each of the variables a, b, and c, before calculating the average, resulting in a returned answer of90.0, the values of quiz1, quiz2, and quiz3 in main would still be 70, 80, and 90.Pass-by-ReferenceIf the programmer must "return" two or more variables from a function or if the user must have access tothe argument locations in the calling program, we use a different approach to functions, called pass-byreference.The pass-by-value mechanism still operates as before, but the arguments passed are addresses,or pointers to the locations which need to be referenced in the function. If we want to do the same calcavgfunction, but have the function directly address quiz1, quiz2, quiz3 and average in main, the code wouldlook like the following:void calcavg (float* a, float* b, float* c, float* d) // no value is returned since all calculations{ // are referenced in main, hence, void return-type// a, b, c, and d are all pointers, address variables*d = (*a + *b+ *c) / 3; // function calculates an average of any 3 float valuesreturn;// by referencing those variables in main; the result} // is also stored in the main memory location, referenced by *dint main (){float quiz1, quiz2, quiz3, average; // application variables set up in main....... // read data into quiz1, quiz2, quiz3calcavg (&quiz1, &quiz2, &quiz3, &average); // call to function passes addresses...... // for quiz1,quiz2,quiz3, and average to calcavgreturn (0);}Notice that the call to calcavg is different here because no data is returned from calcavg. All processingdone in calcavg, which references the variable locations in main .26


A second example of a function to sum and average three values may serve to better contrast pass-by-valueand pass-by-reference. The following function passes the three arguments to be summed and averaged inthe normal way, pass-by-value. The two answers, however, are pass-by-reference. The function does notreally "return two values"; it calculates the two answers and stores them directly in the main memorylocations.void calcavg (float a, float b, float c, float* ptrsum, float* ptravg){*ptrsum = (a + b + c);// sum is stored where ptrsum points in main*ptravg = *ptrsum / 3;//average is stored where ptravg points in mainreturn;}int main (){float quiz1, quiz2, quiz3, sum, average; // application variables set up in main....... // read data into quiz1, quiz2, quiz3calcavg (quiz1, quiz2, quiz3, &sum, &average); // call to function passes 3 arguments with...... // values for quiz1, quiz2, quiz3 to calcavg// and addresses for sum and averagereturn (0);// function "returns" both sum and average by} // placing the calculated results in those locationsPassing an Array to a FunctionOne last topic to cover is passing arrays to functions. The rule for passing arrays to functions is to give thearray name when passing an array as an argument and define the array in the parameter list as an array27


name, followed by empty brackets. Look at the following code to find the highest element in an integerarray:int findhigh (int arrayx[], int size) // use arrayname with [] in definition heading line{int highest=arrayx[0];// assume the first element is the highestfor (int i=1; i highest) // look for any higher valuehighest = arrayx[i];return (highest);}int main ( ){int height_in_inches[100]int biggest, n;...... // read in data for this run determining number of elements(n)biggest = findhigh(height_in_inches, n); // use name of array, no brackets.......return (0);}ConclusionThis part of the tutorial has described most of the basic elements of the <strong>C++</strong> language leading up to thetopics on its object-oriented features. Please check one of the books or web sites listed in Part Three if youneed more detailed information.Part 3 - Additional HelpDebugging Tips in <strong>Visual</strong> <strong>C++</strong>When you build your program, syntax errors are displayed in the Output window at the bottom of thescreen. You have already learned how to click on the error in the Output window and an arrow will appearin the program where the error was detected. Most of these errors are typographical or omissions ofdeclarations which you should be able to find quite easily. However, when the program compiles and runs,but does not produce the correct results, often times you have a logic bug in your code. <strong>Visual</strong> <strong>C++</strong>provides a large array of debugging tools to help you find and correct this type of error. Although thistutorial will cover the main debugging tools, the reader is encouraged to visit the web site related to <strong>Visual</strong><strong>C++</strong> provided by Microsoft (www.microsoft.com/visualc/) for the latest updates on bugs and fixes. Youshould also check the resource list in the next section and search on ‘debugging’ in the <strong>Visual</strong> <strong>C++</strong>documentation for a rich list of additional information.When you build a project in <strong>Visual</strong> <strong>C++</strong>, an automatic ‘debug’ configuration (unless you change it in theProject/Settings…) causes additional information to be included in your executable program so that thedebugging facilities can be used. This extra information is stored in the .pdb file in the Debug folder foryour project. You would omit this overhead in a fully tested, operational program. When the debuginformation is omitted, <strong>Visual</strong> <strong>C++</strong> will optimize the code for more efficient execution.Debug ToolbarRight click on the Build toolbar in the upper right hand corner and click on Debug. The Debug toolbarwill appear, which is shown below in the sample debug run. The debugger has two primary modes ofoperation – it works through the code by single stepping (one line at a time), or runs to a particular point(breakpoint) in the source code.28


Setting BreakpointsYou usually set a breakpoint at the place in the code where you think the error is, so you can execute theprogram to that point and then single step through a section, viewing the contents of variables.Place the cursor at the line of code where you want a breakpoint and click on the Insert/RemoveBreakpoint button, shaped like a hand, which is two icons to the right of the red exclamation mark(Execute button) in the Build toolbar. A breakpoint is indicated in the program by a large circle to the leftof the line of code you marked with a breakpoint (See sample below for the large dot behind an arrow.). Ifyou click on the hand again with the cursor on the breakpoint, it will be removed. To remove allbreakpoints at one time, click on Edit, then Breakpoints, then press RemoveAll. Be careful – this sequencewill remove breakpoints in all files, not just the ones that are open. When debugging, you would normallyset several breakpoints, each chosen to show when the variables that you think are causing the problem arechanging. In the sample debug program below, I have set one breakpoint inside the loop.Start DebuggingThere are several ways to begin execution in the debugging mode but the easiest seems to be to click on theGo icon (picture of a page with an arrow down the side) in the Build toolbar. (Go is also available on theDebug toolbar.) This will execute code up to the first breakpoint. You may then continue by clicking onGo again (to go to the next breakpoint) or one of four choices in the Debug toolbar:?? Step Over – braces with arrow over the top - to skip a function if there is a breakpoint on its callingline of code or line of code you are not interested in seeing, like a cout statement.?? Step Into – braces with arrow into the middle – to also step through the lines of code of a breakpointedfunction call, rather than skipping over it.?? Step Out – braces with arrow coming out of top – to get out of a function or segment of code that youdon’t want to be in?? Run to Cursor – arrow pointing to braces – to execute to cursor location, similar to a Go operationTo run the example below, I clicked on the Go icon, but for this simple example any of the four choicesabove would give almost the same result. Go and Run to Cursor (if cursor is on breakpoint) execute oneiteration of the loop with each click. Step Over and Step Into, in this simple example, single step througheach statement of the loop (test, process the sum, increment, test, etc.). For experience, type in this simpleexample and try Go and all four methods given above. The Variables window on the lower left section ofthe sample below, which appears automatically, shows the status of the variables i, arrayx[i], and sum. Byexamining the window, you can see that the first execution of the loop is adding the second value (20) ofthe array to sum, rather than the first element (10). Obviously, I’ve missed the first element, because Istarted the loop at 1, instead of 0! I clicked on Go again to see the variables switch to arrayx[2] = 30, i =2, and sum = 20 (sum is one step behind in adding the arrayx element to it).29


Inspecting Variable ValuesDefining a variable that you want to inspect is referred to as setting a watch for the variable. In theVariable window on the left, if the Variable window tab is on Auto, the variables named in the line withthe cursor and the line before the cursor will be displayed automatically. The Locals tab shows the valuesof the variables local to the current module/function and will phase in and out as you trace through aprogram. In this case, where we only have the main function, all the variables in main will be displayedconstantly. The this tab shows information about the current this pointer that contains the address of thecurrent object when a non-static class member function is executing (beyond the scope of this tutorial).If there is a plus sign next to a variable in the Variable window, there is additional information that can bedisplayed by clicking on the plus sign.Viewing Variables in the Edit WindowIf you need to look at a single variable and the variable is visible in the Text Editor window, position thecursor over the variable, wait one second, and the current value of the variable will be displayed. You canalso highlight a whole expression, rest the cursor over the highlighted area and the current value of theexpression will be displayed. You must be running in Debug mode for this to work.Watching Variables’ ValuesTo set a watch for a variable, position the cursor in the Text Editor window in the middle of the variablename and click on the Debug toolbar icon that looks like a pair of glasses(QuickWatch). This causes theQuickWatch window to appear with your selected variable listed. The QuickWatch window can onlyshow a single variable or expression, and since the dialog is modal, you can’t continue stepping through thecode while the QuickWatch window is displayed. Click on AddWatch to move the item from the30


QuickWatch window to the Watch window on the bottom right of the screen. Alternately, you canhighlight a variable or expression in the Text Editor window and drag it into the Watch window. TheQuickWatch and Watch windows are best suited to viewing the hierarchy of classes and other structures.It won’t show us any more detailed information than the Variable window in this simple example.Ending the Debugging ModeThe program will end as soon as the last line of code has been executed, but you can cancel the debuggingby clicking on the Stop Debugging icon (crossed out page with arrow) from the Debug toolbar.Books and Web SitesThe following list provides additional information on <strong>C++</strong> and console applications in <strong>Visual</strong> <strong>C++</strong>:Books1.) Davis, Stephen R. <strong>C++</strong> for Dummies, Third Edition. Chicago, Illinois: IDG Books Worldwide, 1998.This book covers all the central details of <strong>C++</strong> without addressing advanced topics, which are covered in asecond book by the author. Davis discusses each feature showing "how" it works and "why" it works thatway, a unique feature of this text. The book begins with a discussion of the basics of <strong>C++</strong> and then has asection on the non object-oriented features of the language The later sections of the book cover classes,inheritance and other object-oriented topics. There is a nice chapter in the book on the settings used in<strong>Visual</strong> <strong>C++</strong> that you may find helpful when trying to run your programs.2.) Friedman, Frank L. and Elliot B. Koffman. Problem Solving, Abstraction, and Design <strong>Using</strong> <strong>C++</strong> (2ndEdition). Reading, Massachusetts: Addison-Wesley, 1997.This textbook is designed to teach <strong>C++</strong> with a focus on the problem solving/software construction process.There are lots of problems with full development from designing the algorithm to completing the code.Object-oriented concepts are introduced early in Section 2.4 and 3.7 but they can be delayed until Chapter11, which is the real beginning of the object-oriented topics. There is no discussion of environment but thefirst ten chapters will be helpful with basic <strong>C++</strong> concepts.3.) Holzner, Steve. <strong>Visual</strong> <strong>C++</strong> in Record Time. San Francisco, California: Sybex, 1998.The first few pages of this book are really good on workspaces and project explanations, and I/O streamsfor console applications in <strong>Visual</strong> <strong>C++</strong>. Then the author turns his attention to object-oriented features ofthe language (classes, hierarchy, etc.) and finally full windows applications with boxes, buttons, menus, etc.There is a website available at Sybex to provide all the code to run the sample programs in the text so thereader does not have to type in the code.4.) Horton, Ivor. Beginning <strong>Visual</strong> <strong>C++</strong> 6. Birmingham, United Kingdom: Wrox, 1998.This book devotes the whole first third of a one thousand page text to console applications and the basics of<strong>C++</strong> programming. It has the most information on the topics in this tutorial in one place. The text costsabout $50.00 so hopefully you will appreciate the material summarized in this tutorial so that you can savea lot of money. But if you want to purchase a book to learn either console applications or windowsprogramming in <strong>Visual</strong> <strong>C++</strong>, this is a good and thorough book to get!5.) Hyman, Michael and Bob Arnson. <strong>Visual</strong> <strong>C++</strong> for Dummies. Chicago, Illinois: IDG BooksWorldwide, 1998.The text begins with a major section on simple windows applications. Then the author discusses <strong>C++</strong> frominput/output statements to arrays and functions, which would be helpful to the beginnings of <strong>C++</strong>. Thethird section is all object-oriented applications. Chapter 4 is particularly good because the author discussesprojects and workspaces, a concept which is missing from most texts.31


6.) Kurtz, Jeff and Jerry Kurtz. Teach Yourself <strong>Visual</strong> <strong>C++</strong> 6 Online in Web Time. Indianapolis, Indiana:SAMS, Division of Macmillan Computer Publishing, 1999.This book is one of a series of "Teach Yourself" books which give you full access to a web site to helpmaster the information in the book with interactive tests, exercises, a chat room with other students, andsearchable on-line references. The book, however, is designed for <strong>C++</strong> programmers who want to learn<strong>Visual</strong> <strong>C++</strong>. There is only one paragraph on "<strong>Console</strong> <strong>Applications</strong>".7.) Liberty, Jesse. Teach Yourself <strong>C++</strong> in 24 Hours. Indianapolis, Indiana: SAMS, Division of MacmillanComputer Publishing, 1999.This book is written like a textbook with 1-4 topics per chapter, which is rather a slow development, andlots of samples with review questions at the end of each chapter. The author claims the reader does nothave to have any programming knowledge to use this text but I feel that is inaccurate because concepts arenot explained, just language details. However it should be helpful for programmers trying to learn <strong>C++</strong>.There is no environment discussion in the book.8.) Lippman, Stanley B. and Josee Lajoie. <strong>C++</strong> Primer, Third Edition. Reading, Massachusetts: Addison-Wesley, 1998.Part I is a quick tour of the <strong>C++</strong> language, including some object-based and object-oriented designs. Part IIbegins again with the basic details of <strong>C++</strong> data types, statements, and container types. In Part II, theauthors devote a whole section to procedural programming (functions) and another section covers classesand overloaded operators. Object-oriented programming is the focus of the final section. No environmentdetails are discussed but parts of Part I, Part II, and functions would be helpfulto programmers trying tolearn <strong>C++</strong>.9.) Pohl, Ira. Object-Oriented Programming <strong>Using</strong> <strong>C++</strong>. Reading, Massachusetts: Addison-Wesley,1997.This is the text for CS5183 at SPSU which I took in the Fall, 1998. The book begins with an overviewchapter, which discusses 7 program examples demonstrating all the major topics to be covered in the text.It can be quite intimidating. The second and third chapters cover the basics of the <strong>C++</strong> language followedby the rest of the text (Chapters 4-12) which is focused on object-oriented topics. This tutorial will helpstudents in this class get through chapters 2 and 3 quickly. There is no discussion of the <strong>Visual</strong> <strong>C++</strong>environment.10.) Stroustrup, Bjarne. The <strong>C++</strong> Programming Language, 2nd Edition. Reading, Massachusetts:Addison-Wesley, 1997Stroustrup is the author of the <strong>C++</strong> language and this is one of his texts on the language.The book is divided into three parts: a tutorial introduction to <strong>C++</strong>, a discussion of design and softwaredevelopment issues, and a reference manual. There are exercises at the end of each chapter to encouragethe student to apply what he has learned. There is no discussion of the <strong>Visual</strong> <strong>C++</strong> environment.11.) Walter, Jan, Danny Kalev, Michael Tobler, Paul Snaith, Andrei Kossoroukov, and Scott Roberts. TheWaite Group's <strong>C++</strong> How-To. Indianapolis, Indiana: SAMS, Division of Macmillan Computer Publishing,1999.This book is written to teach <strong>C++</strong> programmers applications by showing them approaches to objectorientedproblems so most sections are very advanced. The authors try to answer specific programmingproblems in <strong>C++</strong>. The first chapter, however, covers the basics of the <strong>C++</strong> language for the beginning <strong>C++</strong>programmers. There is no coverage of compilers/environment.32


12.) Williams, Mickey. <strong>Visual</strong> <strong>C++</strong>6 in 24 Hours. Indianapolis, Indiana: SAMS, Division of MacmillanComputer Publishing,1998.This book is written for the beginning or experienced programmer who is new to <strong>Visual</strong> <strong>C++</strong>, according tothe author. He uses many, short concise examples without a lot of extra material or theory which I thinkwould be hard to follow for a brand new programmer. The code examples are usually limited to one pageof source code with a page or two of explanation. However, he begins the first chapter with a consoleapplication and continues with two more chapters on that topic which would be very helpful to a new <strong>C++</strong>programmer. The last two thirds of the book are devoted to windows applications in detail.Web Sites1.) Kevin Boone. C/<strong>C++</strong> <strong>Tutorial</strong>: General Information, 1996-8. Internet URL:http://www.cs.mdx.ac.uk/staffpages/kevin/ctut-general.htmlThis brief tutorial provides short code segments with text explanations. It is very easy to follow. I liked hisstraightforward explanations as he covered only the introductory parts of <strong>C++</strong>, such as input/output, loops,arrays, etc. He does not cover any object-oriented features of the language. His style is similar to theapproach of this tutorial. There is no environment discussion.2.) Marshall Brain. Understanding <strong>C++</strong>: An Accelerated Introduction, 1998. Internet URL:http://devcentral.iftech.com/learning/tutorials/c-cpp/cpp/2.aspThis 8-page article is designed to help C programmers make the transition into <strong>C++</strong>. The author explainsthe advantages of <strong>C++</strong> over C, the tools in <strong>C++</strong> to express object oriented ideas and how to design andimplement code using object oriented principles. There are some good explanations about the design of the<strong>C++</strong> language.3.) Vinit Carpenter. C/<strong>C++</strong> <strong>Tutorial</strong>s, 1995. Internet URL: http://www.up.ac.za/information/c-c++learn.htmlThis site provides a list of many C and <strong>C++</strong> language tutorials, code collections and books, developed as aservice for Internet users by the author. Although the site is quite dated, there are still a lot of referenceslisted, which may be useful to the new <strong>C++</strong> programmer.4.) Marshall Cline. FAQ on <strong>C++</strong>, 1991,92. Internet URL: http://osiris.sund.ac.uk/online/<strong>C++</strong>/cplus.htmlThis website has gathered the most frequently asked questions on <strong>C++</strong> in one place. There are over 140questions and answers grouped into specific areas from the basics, such as "What are the Advantages of<strong>C++</strong>" and "Input/Output..." to sections on the object-oriented features of <strong>C++</strong>, like "Constructors andDestructors", "Operator Overloading", and "Friends", among others. Some of the answers are quiteinformative and very straightforward.5.) Coronado Enterprises. <strong>C++</strong> <strong>Tutorial</strong>, 1985 (first tutorial). Internet URL:http://www.swcp.com/~dodrill/Coronado Enterprises had free tutorials on C, <strong>C++</strong>, Pascal and Ada. These tutorials were supposed to beshareware so the user was expected to pay a nominal fee after 30 days if the tutorial was helpful. The feeshave not been forthcoming so the group cannot handle the monthly expense of over $150.00 - they havedecided to discontinue this offering. I expect Coronado Enterprises to get sponsorship in due time so I amlisting the site in the tutorial hoping that it will again be available. I found many references to it on theInternet. It was quite popular so plan to check it again for extra information if it gets reinstated.6.) Gordon Dodrill. <strong>C++</strong> Language <strong>Tutorial</strong>, 1997. Internet URL:http://home.onestop.net//mr_orange/cpplist.html33


This web site is a shareware tutorial on <strong>C++</strong> developed in 1996 and 1997 for programmers who alreadyunderstand C. This tutorial is a very nice and clear development of the <strong>C++</strong> language, referencing samplesof C and <strong>C++</strong> together. The tutorial consists of text and code. The author recommends that the user printthe text of one or two chapters at a time, download the sample programs, and load them into the compiler'seditor for viewing while reading the text analyses. This site will be helpful if you already know C.7.) Peter Mueller. Introduction to Object-Oriented Programming <strong>Using</strong> <strong>C++</strong>, 1996. Internet URL:http://www.zib.de/mueller/Course/material.html.This tutorial was originally created in 1995 and updated in 1996 under the direction of Peter Mueller. It isa collection of lectures on <strong>C++</strong> which he had used at several universities. He invites his readers to makesuggestions and submit information for the topics covered. His examples are concise in both theelementary areas and in the object-oriented segments. He has a nice discussion of program developmentfrom unstructured, to procedural, to modular, to object-oriented which I think would benefit the <strong>C++</strong>student who is trying to understand all the different parts of <strong>C++</strong>.8.) North Carolina State University, Dept of Computer Science students and faculty. On Line InstructionSystem - <strong>C++</strong> <strong>Tutorial</strong>, 1995. Internet URL: http://www.csc.ncsu.edu:8080/This site provides very elementary instruction on arithmetic expressions, relational expressions, loops,functions, input/output commands, arrays and structures in 7 different lessons. You must log-on and createa user name to use the site so it can keep track of where you are in each lesson. The explanations areconcise and understandable. A student could learn the basics of <strong>C++</strong> programming from this site, althoughthere are no introductory lessons on the basic structure of the language (includes, braces, main, etc). Thereis no discussion of the <strong>Visual</strong> <strong>C++</strong> environment.9.) Neil C. Obremski. Neil's <strong>C++</strong> Stuff, 1998. Internet URL: http://www.cyclone7.com/cpp/A student created the site to supplement the <strong>C++</strong> information he was receiving in a <strong>C++</strong> class taught by avery poor instructor, according to him. It is a work in progress with a high level of dedication on his part tocomplete it for other students who may be having the same difficulties. He has some good sections onreference variables, pointers, structures, classes and arrays. There are other sparse or uncompleted sectionswhich he is still working on. The text is interspersed with humor, making it enjoyable to read and digest.10.) Douglas C. Schmidt. <strong>C++</strong> Programming Language <strong>Tutorial</strong>s, 1997. Internet URL:http://www.cs.wustl.edu/~schmidt/<strong>C++</strong>/index.htmlThe website contains parts of a series of lectures on <strong>C++</strong> taught by Dr. Schmidt at the University ofCalifornia, Urvine, and Washington University, St. Louis. The author assumes that the student knows Cand begins with an overview of the C portions of <strong>C++</strong>, much like the approach in the text for CS5183 atSPSU. The rest of the series concentrates on <strong>C++</strong> object-oriented topics.11.) (no name given). <strong>C++</strong> <strong>Tutorial</strong>, (no date given). Internet URL:http://www.cs.bsu.edu/homepages/peb/cplusplus/This web site is not too helpful and is quite suspect due to lack of name and date. It is very brief, hasincomplete areas, and repeats the information about FAQ found at Marshall Cline's site (Cline does allowcopying of his site). The good news is that there are some side-by-side listings of <strong>C++</strong> code and Pascalcode for some functionalities. It would be somewhat helpful for a Pascal programmer trying to learn <strong>C++</strong>.34

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!