A tutorial on C++ Programming


Published on

Published in: Education, Technology
1 Like
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

A tutorial on C++ Programming

  1. 1. Prof. Erwin M. Globio, MSIT Page 1 of 66 WORKTEXT for ITEC223 Advance Programming (With Laboratory Exercises on every chapter) By PROF. ERWIN M. GLOBIO, MSIT
  2. 2. Prof. Erwin M. Globio, MSIT Page 2 of 66 Chapter 1 Introduction to C programming language C is a general-purpose high-level programming language with features of economy of expression, modern flow control & data structures, and a rich set of operators. It is not specialized to any particular area of application, the absence of restrictions and its generality make it more convenient and effective for many tasks than any other powerful languages. It is not tied to any particular hardware or system, and therefore it is easy to write programs that will run without change on any machine that supports C. It is often called a middle-level computer language because it combines the best elements of high- level languages with the control and flexibility of assembly language. Structure of programming in C Let's start learning by writing a simple program.  Every C program starts execution form a user defined function called main(). This function must be present in every C program. Program can have only one main function. /* This is a simple C++ program. Call this file Sample.cpp. */ #include <iostream> #include <conio.h> using namespace std; // A C++ program begins at main(). int main() { cout << "C++ is power programming."; getch(); return 0; } Before beginning, let‘s review two terms: source code and object code. Source code is the human readable form of the program. It is stored in a text file. Object code is the executable form of the program created by the compiler. When run, the program displays the following output: C++ is power programming. Although Sample.cpp is quite short, it includes several key features that are common to all C++ programs. Let‘s closely examine each part of the program. The program begins with the lines. /*
  3. 3. Prof. Erwin M. Globio, MSIT Page 3 of 66 This is a simple C++ program. Call this file Sample.cpp. */ This is a comment. Like most other programming languages, C++ lets you enter a remark into a program‘s source code. The contents of a comment are ignored by the compiler. The purpose of a comment is to describe or explain the operation of a program to anyone reading its source code. In the case of this comment, it identifies the program. In more complex programs, you will use comments to help explain what each feature of the program is for and how it goes about doing its work. In the case of this comment, it identifies the program. In more complex programs, you will use comments to help explain what each feature of the program is for and how it goes about doing its work. In other words, you can use comments to provide a ―play-by- play‖ description of what your program does. The next line in the program is using namespace std; This tells the compiler to use the std namespace; namespaces are a relatively recent addition to C++. A namespace creates a declarative region in which various program elements can be placed. Elements declared in one namespace are separate from elements declared in another. Namespaces help in the organization of large programs. The using statement informs the compiler that you want to use the std namespace. This is the namespace in which the entire Standard C++ library is declared. By using the std namespace, you simplify access to the standard library. The next line, as the preceding comment indicates, is where program execution begins. int main() All C++ programs are composed of one or more functions. As explained earlier, a function is a subroutine. Every C++ function must have a name, and the only function that any C++ program must include is the one shown here, called main(). The main() function is where program execution begins and (most commonly) ends. (Technically speaking, a C++ program begins with a call to main() and, in most cases, ends when main() returns.) The opening curly brace on the line that follows main() marks the start of the main() function code. The next line in the program is cout << "C++ is power programming."; This is a console output statement. It causes the message C++ is power programming. to be displayed on the screen. It accomplishes this by using the output operator <<. The << operator causes whatever expression is on its right side to be output to the device specified on its left side. cout is a predefined identifier that stands for console output and generally refers to the computer‘s screen. Thus, this statement causes the message to be output to the screen. Notice that this statement ends with a semicolon. In fact, all C++ statements end with a semicolon.
  4. 4. Prof. Erwin M. Globio, MSIT Page 4 of 66 The message ―C++ is power programming.‖ is a string. In C++, a string is a sequence of characters enclosed between double quotes. Strings are used frequently in C++. The next line in the program is return 0; This line terminates main() and causes it to return the value 0 to the calling process (which is typically the operating system). For most operating systems, a return value of 0 signifies that the program is terminating normally. Other values indicate that the program is terminating because of some error. return is one of C++‘s keywords, and it is used to return a value from a function. All of your programs should return 0 when they terminate normally (that is, without error). Control Statements Inside a function, execution proceeds from one statement to the next, top to bottom. It is possible, however, to alter this flow through the use of the various program control statements supported by C++. The if Statement: if(condition) statement; where condition is an expression that is evaluated to be either true or false. In C++, true is nonzero and false is zero. If the condition is true, then the statement will execute. If it is false, then the statement will not execute. For example, the following fragment displays the phrase 10 is less than 11 on the screen because 10 is less than 11. if(10 < 11) cout << "10 is less than 11"; However, consider the following: if(10 > 11) cout << "this does not display"; In this case, 10 is not greater than 11, so the cout statement is not executed. Of course, the operands inside an if statement need not be constants. They can also be variables. C++ defines a full complement of relational operators that can be used in a conditional expression. They are shown here: Operator Meaning < Less than <= Less than equal to > Greater than >= Greater that equal to == Equal to != Not equal to
  5. 5. Prof. Erwin M. Globio, MSIT Page 5 of 66 Notice that the test for equality is the double equal sign. Here is a program that illustrates the if statement: #include <iostream> #include <conio.h> using namespace std; int main() { int a, b, c; a = 2; b = 3; if (a < b) cout << "a is less than bn"; // An if statement // this won't display anything if (a == b) cout << "you won't see thisn"; cout <<"n"; c = b - a; // c now contains 1 cout << "c contains 1n"; if (c>= 0) cout << "c is non-negative n"; if (c < 0) cout << "c is negative n"; getch(); return 0; } The output generated by this program is shown here: a is less than b c contains -1 c is negative c contains 1 c is non-negative The complete form of the if the statement is if(expression) statement; else statement; where the targets of the if and else are single statements. The else clause is optional. The targets of both the if and else can also be blocks of statement. The general forms of the if using blocks of statements is:
  6. 6. Prof. Erwin M. Globio, MSIT Page 6 of 66 if(expression) { statement sequence; } else { statement sequence; } If the conditional expression is true, the target of the if will be executed; otherwise, the target of the else, if it exists, will be executed. At no time will both be executed. The conditional expression controlling the if may be any type of valid C++ expression that produces a true or false result. The following demonstrates the if by playing a simple version of the ―guess the magic number‖ game. The program generates a random numbers, prompts for your guess, and prints the message ** Right ** if you guess the magic number. This program also introduces another C++ library function, called rand( ), which returns a randomly selected integer value. It requires the <stdlib> header. #include <iostream> #include <conio.h> using namespace std; main() { int magic, guess; magic = rand(); cout << "Enter your guess: "; cin >> guess; if (guess == magic) cout << "*** Right ***"; getch(); return 0; } This program uses the ‗if‘ statement to determine whether the user‘s guess matches the magic number. If it does, the message is printed on the screen. Modular Programming As programs grow in size, it becomes important to break them into separate parts (modules) that communicate with rest of the program through a few well defined interfaces. If we decompose the program into modules well is we can code each module independently. Also if change happens we can localize changes to a particular module without impacting the rest of the programs. For example, as is their habit, a LCD which we had used in a product went obsolete. We had a written the hardware abstraction layer for the LCD as a separate module. We
  7. 7. Prof. Erwin M. Globio, MSIT Page 7 of 66 substituted a different LCD, and modified the LCD hardware abstraction module while not impacting rest of the program. How to achieve a modular programming in C? C provides two keywords static and extern that facilitate this. Disciplined coding practice also aids modularization. The key is to have a header file for each module. This header file contains  a comment section about the module  definition of all constants publicly exposed by the module  definition of all structures publicly exposed by the module  all publicly exposed variables defined with extern  all publicly exposed functions defined with extern In the header file you should only put definitions of constants, structures, variables and functions that you want to expose. As a coding practice prefix all constant, structure, variable and function definitions with the name of the module. This makes it easy to identify the source of definition in a larger program with many modules. The implementation file(s) contains the actual definition of variables and implementations of the functions defined in the header file. The implementation file also contains definitions of those variables, structures and constants that are used only in the implementation file. It also contains definitions and implementations of helper functions. These should be declared as static to prevent access from outside. I all find it a good programming practice to prefix all internal names with "_". Example Header file for a module named node node.h /* Interface for node module node_var1 is a variable used inside the module node_do_something() is a function in the module */ extern int node_var1; extern int node_do_something(void); Implementation file for module named node node.c: #include "node.h" int node_var1;
  8. 8. Prof. Erwin M. Globio, MSIT Page 8 of 66 static int _node_var2; static void _node_helper_function(void){ } int node_do_something(void){ node_var1 = 2; _node_var2 =35; _node_helper_function(); } The main file which uses module node #include "node.h" int main(int argc, char *argv[]){ while(1){ node_do_something(); } }
  9. 9. Prof. Erwin M. Globio, MSIT Page 9 of 66 COURSE TITLE : ITEC223 – Advance Programming EXERCISE NUMBER : 1 COURSE TOPIC : Review of Introduction to C Programming language I. Objectives:  To learn and understand the basic syntax and script delimeters of C.  To understand and use C/C++ variables and operators. II. Part I. Basic Syntax of C++ 1. Where does the C++ program begin execution? _____________________________________________________________________________ _____________________________________________________________________________ 2. What is cout? _____________________________________________________________________________ _____________________________________________________________________________ 3. What does #include <iostream> do? _____________________________________________________________________________ _____________________________________________________________________________ 4. What does the if statement do? _____________________________________________________________________________ _____________________________________________________________________________ 5. How is block of code created? What does it do? _____________________________________________________________________________ _____________________________________________________________________________ 6. What is a namespace? _____________________________________________________________________________ _____________________________________________________________________________ Supplementary Programming (50 points) 1. Write a program that averages the absolute value of five values entered by the user. Display the result.
  10. 10. Prof. Erwin M. Globio, MSIT Page 10 of 66 Chapter 2 & 3 String Handling Functions The string handling functions in the standard C++ libraries incorporated from the standard C libraries do not have a single header file for a source. When declaring a character array that will hold a null-terminated string, you need to declare it one character longer than the largest string that it will hold. For example, if you want to declare an array str that could hold a 10-character string: char str[11]; Specifying the size as 11 makes room for the null at the end of the string. A string constant is a list of characters enclosed in double quotes. Here are some examples: ―hello there‖ ―I like C++‖ ―Mars‖ ―‖ It is not necessary to manually add the null terminator onto the end of string constants; the C++ compiler does this for you automatically. Therefore, the string ―Mars‖ will appear in memory like this: M a r s 0 The last string shown is "". This is called a null string. It contains only the null terminator and no other characters. Null strings are useful because they represent the empty string. The easiest way to read a string entered from the keyboard is to use a char array in a cin statement. For example, the following program reads a string entered by the user: // using cin to read a string from the keyboard #include <iostream> using namespace std; int main() { char str[80]; cout << ―Enter a string: ―; cin >> str; // read a string from keyboard <-- read a string using cin cout << ―Here is your string: ―; cout << str; return 0; } Here is a sample run: Enter a string: testing
  11. 11. Prof. Erwin M. Globio, MSIT Page 11 of 66 Here is your string: testing Although this program is technically correct, it will not always work the way you expect. To see why, run the program and try entering the string ―This is a test‖. Here is what you will see: Enter a string: This is a test Here is your string: This When the program redisplays your string, it shows only the word ―This‖, not the entire sentence. The reason for this is that the C++ I/O system stops reading a string when the first whitespace character is encountered. Whitespace characters include spaces, tabs, and newlines. One way to solve the whitespace problem is to use another of C++‘s library functions, gets( ). The general form of a call to gets( ) is gets(array-name); To read a string, call gets( ) with the name of the array, without any index, as its argument. Upon return from gets( ), the array will hold the string input from the keyboard. The gets( ) function will continue to read characters, including whitespace, until you enter a carriage return. The header used by gets( ) is <cstdio>. This version of the preceding program uses gets( ) to allow the entry of strings containing spaces: //Using gets() to read a string from the keyboard. #include <iostream> #include <cstdio> using namespace std; int main() { char str[80]; cout << ―Enter a string: ―; gets(str); // read a string using gets() //  Read a string using gets(). cout << ―Here is your string‖; cout << str; return 0; }
  12. 12. Prof. Erwin M. Globio, MSIT Page 12 of 66 Notice that in a cout statement, str can be used directly. In general, the name of a character array that holds a string can be used any place that a string constant can be used. Keep in mind that neither cin nor gets( ) performs any bounds checking on the array that receives input. Therefore, if the user enters a string longer than the size of the array, the array will be overwritten. Some string Library Functions: C++ supports a wide range of string manipulation functions. The most common are: strcpy() strcat() strcmp() srtlen() The string functions all use the same header, <string>. Let‘s take a look at these functions now. strcpy A call to strcpy( ) takes this general form: strcpy(to, from); The strcpy( ) function copies the contents of the string from into to. Remember, the array that forms to must be large enough to hold the string contained in from. If it isn‘t, the to array will be overrun, which will probably crash your program. strcat A call to strcat( ) takes this form: strcat(s1, s2); The strcat( ) function appends s2 to the end of s1; s2 is unchanged. You must ensure that s1 is large enough to hold its original contents and those of s2. strcmp A call to strcmp( ) takes this general form: strcmp(s1, s2); The strcmp( ) function compares two strings and returns 0 if they are equal. If s1 is greater than s2 lexicographically (that is, according to dictionary order), then a positive number is returned; if it is less than s2, a negative number is returned. The key to using strcmp( ) is to remember that it returns false when the strings match.
  13. 13. Prof. Erwin M. Globio, MSIT Page 13 of 66 Therefore, you will need to use the !operator if you want something to occur when the strings are equal. For example, the condition controlling the following if statement is true when str is equal to ―C++‖: if(!strcmp(str, "C++") cout << "str is C++"; strlen The general form of a call to strlen( ) is strlen(s); Example using strlen: #include <string.h> #include <iostream> #include <conio.h> using namespace std; int main() { char aString1[11] = "abcdefghij", aString2[11] = "tooShort", aString3[51]; unsigned int len1, len2, len3; cout << endl << endl; cout << "Please supply a third string: "; cin.getline(aString3, 11); // 'n' delimiter assumed len1 = strlen(aString1); len2 = strlen(aString2); len3 = strlen(aString3); cout << endl << "String #1: " << aString1 << ", length = " << len1 << endl << "String #2: " << aString2 << ", length = " << len2 << endl << "String #3: " << aString3 << ", length = " << len3; cout << endl << endl; getch(); return 0;
  14. 14. Prof. Erwin M. Globio, MSIT Page 14 of 66 } where s is a string. The strlen( ) function returns the length of the string pointed to by s. A String Function Example: The following program illustrates the use of all four string functions: // Demonstrate the string functions. #include <iostream> #include <stdio.h> #include <string.h> #include <windows.h> #include <conio.h> using namespace std; int main() { char s1[80],s2[80]; strcpy(s1, "C++"); strcpy(s2, " is power programming."); cout << "lengths: " << strlen(s1); cout << ' ' << strlen(s2) << 'n'; if(!strcmp(s1, s2)) cout << "The strings are equaln"; else cout << "not equaln"; strcat(s1, s2); cout << s1 << 'n'; strcpy(s2, s1); cout << s1 << " and " << s2 << "n"; if(!strcmp(s1, s2)) cout << "s1 and s2 are now the same.n"; getch(); return 0; } Here is the output: lengths: 3 22 not equal C++ is power programming. C++ is power programming. and C++ is power programming. s1 and s2 are now the same. Using the Null Terminator
  15. 15. Prof. Erwin M. Globio, MSIT Page 15 of 66 The fact that strings are null-terminated can often be used to simplify various operations. For example, the following program converts a string to uppercase: // Convert a string to uppercase #include <iostream> #include <string.h> #include <conio.h> #include <ctype.h> #include <windows.h> using namespace std; int main() { char str[80]; int i; strcpy (str, "this is a test"); for (i=0; str[1]; i++) str[i] = toupper(str[i]); cout << str; getch(); return 0; } The output from this program is shown here: THIS IS A TEST This program uses the library function toupper(), which returns the uppercase equivalent of its character argument, to convert each character in the string. The upper() function uses the header <ctype.h>. Notice that the test condition of the for loop is simply the array indexed by the condition variable. The reason this works is that a true value is any non-zero value. Remember, all character values are non-zero, but the null terminating the string is zero. Because the null terminator marks the end of the string, the loop stops precisely where it is supposed to.
  16. 16. Prof. Erwin M. Globio, MSIT Page 16 of 66 Table 1: Character functions in <ctype.h> Function Function Signature Description isalnum() int isalnum(int c) Returns a non-zero if c is alphabetic or numeric isalpha() int isalpha(int c) Returns a non-zero if c is alphabetic iscntrl() int iscntrl(int c) Returns a non-zero if c is a control character isdigit() int isdigit(int c) Returns a non-zero if c is a digit, 0 - 9 isgraph() int isgraph(int c) Returns a non-zero if c is a non-blank, but printing character islower() int islower(int c) Returns a non-zero if c is a lower case alphabetic character, i.e. a - z isprint() int isprint(intc) Returns a non-zero if c is printable, non-blanks and white space included ispunct() int ispunct(int c) Returns a non-zero if c is a printable character, but not alpha, numeric, or blank isspace() int isspace(int c) Returns a non-zero for blanks and these escape sequences: 'f', 'n', 'r', 't', and 'v' isupper() int isupper(int c) Returns a non-zero if c is an upper-case alphabetic character, i.e. A - Z isxdigit() int isxdigit(int c) Returns a non-zero if c is a hexadecimal character: 0 - 9, a - f, or A - F tolower() int tolower(int c) Returns the lower case version if c is an upper case character; otherwise returns c toupper() int toupper(int c) Returns the upper case version if c is a lower case character; otherwise returns c Table 2: Some String Handling Functions in <string.h> Functions Function Signature Description strcat() char* strcat(char* s1, const char* s2) Adds string s2 onto the end of s1 (conCATenation). strchr() char* strchr(const char* s, int c) Returns a pointer to the first occurrence of c in string s. Returns NULL if c is not found in s. strcmp() int strcmp(const char* s1, const char* s2) Compares s1 and s2 alphabetically. Returns a negative, zero, or positive number depending on whether s1 is before, the same as, or after s2 if you were alphabetizing s1 and s2. strcpy() char* strcpy(char* s1, const char* s2) Copies s2 into s1, and returns a point to s1. strlen() size_t strlen(const char* s) Returns the number of characters in the string s, starting at s[0] and ending before the first NULL. strncat() char* strncat(char* s1, const char* s2, size_t n) Tacks on the first n characters of s2 onto s1. A pointer to s1 is returned.
  17. 17. Prof. Erwin M. Globio, MSIT Page 17 of 66 strncmp() int strncmp(const char* s1, const char* s2, size_t n) Compares s1 with the first n characters of s2. Returns a negative, zero, or positive integer (just like strcmp). strncpy() char* strncpy(char* s1, const char*s2, size_t n) Copies the first n characters of s2 into the first n characters of s1. strrchr() char* strrchr(const char*s, int c) Returns a pointer to the last occurence of c in string s. (Compare with strchr().) strstr() char* strstr(const char* s1, const char* s2) Returns the address of the first occurence of string s2 that is also in string s1. Returns NULL if s2 is not found in s1.
  18. 18. Prof. Erwin M. Globio, MSIT Page 18 of 66 COURSE TITLE : ITEC223 – Advance Programming EXERCISE NUMBER : 2 COURSE TOPIC : String and Handling Function I. Objectives: To know the String handling function used Part II. String Handling Functions 1 & 2 1. What is a null-terminated string? _____________________________________________________________________________ _____________________________________________________________________________ 2. To hold a string that is 18 characters long, how must the character array be? _____________________________________________________________________________ _____________________________________________________________________________ 3. Show how to initialize a four-element array of int to the values 1,2,3 and 4. _____________________________________________________________________________ _____________________________________________________________________________ 4. How can this initialization be rewritten? char str[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘O’); _____________________________________________________________________________ _____________________________________________________________________________ 5. Rewrite the following as an unsized array: Int nums[4] = {44, 55, 66, 77} _____________________________________________________________________________ _____________________________________________________________________________ Supplementary Programming (50 points) 1. Write a program that prompts the user for two strings and then compares the strings for equality, but ignores case differences. Thus, “ok” and “OK” will compare as equal.
  19. 19. Prof. Erwin M. Globio, MSIT Page 19 of 66 Chapter 4 Introduction to Pointers A pointer is an object that contains a memory address. Very often this address is the location of another object, such as a variable. For example, if x contains the address of y, then x is said to ―point to‖ y. Pointer variables must be declared as such. The general form of a pointer variable declaration is type *var-name; Here, type is the pointer‘s base type. The base type determines what type of data the pointer will be pointing to. var-name is the name of the pointer variable. For example, to declare ip to be a pointer to an int, use this declaration: int *ip; Since the base type of ip is int, it can be used to point to int values. Here, a float pointer is declared: float *fp; In this case, the base type of fp is float, which means that it can be used to point to a float value. In general, in a declaration statement, preceding a variable name with an * causes that variable to become a pointer. The Pointer Operator There are two special operators that are used with pointers: * and &. The & is a unary operator that returns the memory address of its operand. For example, ptr = &total; puts into ptr the memory address of the variable total. This address is the location of total in the computer‘s internal memory. It has nothing to do with the value of total. The operation of & can be remembered as returning ―the address of‖ the variable it precedes. Therefore, the preceding assignment statement could be verbalized as ―ptr receives the address of total.‖ To better understand this assignment, assume that the variable total is located at address 100. Then, after the assignment takes place, ptr has the value 100. The second operator is *, and it is the complement of &. It is a unary operator that returns the value of the variable located at the address specified by its operand. Continuing with the same example, if ptr contains the memory address of the variable total, then
  20. 20. Prof. Erwin M. Globio, MSIT Page 20 of 66 val = *ptr; will place the value of total into val. For example, if total originally had the value 3,200, then val will have the value 3,200, because that is the value stored at location 100, the memory address that was assigned to ptr. The operation of * can be remembered as ―at address.‖ In this case, then, the statement could be read as ―val receives the value at address ptr.‖ The following program executes the sequence of the operations just described: #include <iostream> using namespace std; int main() { int total; int *ptr; int val; total = 3200; // assign 3,200 to total ptr = &total; // get address of total val = *ptr; // get value at that address cout << "Total is: " << val << 'n'; return 0; } It is unfortunate that the multiplication symbol and the ―at address‖ symbol are the same. This fact sometimes confuses newcomers to the C++ language. These operators have no relationship to each other. Keep in mind that both & and * have a higher precedence than any of the arithmetic operators except the unary minus, with which they have equal precedence. The act of using a pointer is often called indirection because you are accessing one variable indirectly through another variable. The Base Type of a Pointer In the preceding discussion, you saw that it was possible to assign val the value of total indirectly through a pointer. At this point, you may have thought of this important question: How does C++ know how many bytes to copy into val from the address pointed to by ptr? Or, more generally, how does the compiler transfer the proper number of bytes for any assignment involving a pointer? The answer is that the base type of the pointer determines the type of data upon which the pointer operates. In this case, because ptr is an int pointer, four bytes of information are copied into val (assuming a 32-bit int) from the address pointed to by ptr. However, if ptr had been a double pointer, for example, then eight bytes would have been copied. It is important to ensure that pointer variables always point to the correct type of data. For example, when you declare a pointer to be of type int, the compiler assumes that anything it points to will be an integer variable. If it doesn‘t point to an integer variable, then trouble is usually not far behind! For example, the following fragment is incorrect: int *p; double f; // ... p = &f; // ERROR
  21. 21. Prof. Erwin M. Globio, MSIT Page 21 of 66 This fragment is invalid because you cannot assign a double pointer to an integer pointer. That is, &f generates a pointer to a double, but p is a pointer to an int. These two types are not compatible. (In fact, the compiler would flag an error at this point and not compile your program.) Although two pointers must have compatible types in order for one to be assigned to another, you can override this restriction (at your own risk) using a cast. For example, the following fragment is now technically correct: int *p ; double f; // ... p = (int *) &f; // Now technically OK The cast to int * causes the double pointer to be converted to an integer pointer. However, to use a cast for this purpose is questionable practice. The reason is that the base type of a pointer determines how the compiler treats the data it points to. In this case, even though p is actually pointing to a floating-point value, the compiler still ―thinks‖ that p is pointing to an int (because p is an int pointer). To better understand why using a cast to assign one type of pointer to another is not usually a good idea, consider the following short program: //This program will not work right #include <iostream> using namespace std; int main() { double x,y; int *p; x = 123.23; p = (int *) &x; // use cast to assign double * to int *. y = *p; // what will this do? cout << y; // what will this print? return 0; Here is the output produced by the program. (You might see a different value.) 1.37439e+009 This value is clearly not 123.23! Here is why. In the program, p (which is an integer pointer) has been assigned the address of x (which is a double). Thus, when y is assigned the value pointed to by p, y receives only four bytes of data (and not the eight required for a double value), because p is an integer pointer. Therefore, the cout statement displays not 123.23, but a garbage value instead. Assigning value to pointers You can use a pointer on the left-hand side of an assignment statement to assign a value to the location pointed to by the pointer. Assuming that p is an int pointer, this assigns the value 101 to the location pointed to by p. *p = 101;
  22. 22. Prof. Erwin M. Globio, MSIT Page 22 of 66 You can verbalize this assignment like this: ―At the location pointed to by p, assign the value 101.‖ To increment or decrement the value at the location pointed to by a pointer, you can use a statement like this: (*p)++; The parentheses are necessary because the * operator has lower precedence than does the ++ operator. The following program demonstrates an assignment through a pointer: #include <iostream> using namespace std; int main() { int *p, num; p = &num; *p = 100; // assign num the value 100 through p. cout << num << ‗ ‗; (*p)++; // increment num through p. cout << num << ‗ ‗; (*p)--; // decrement num through p. cout << num << ‗/n‘; return 0; } The output from the program is shown here: 100 101 100 Pointer Expressions Pointers can be used in most C++ expressions. However, some special rules apply. Remember also that you may need to surround some parts of a pointer expression with parentheses in order to ensure that the outcome is what you desire. Pointer Arithmetic There are only four arithmetic operators that can be used on pointers: ++, – –, +, and –. To understand what occurs in pointer arithmetic, let p1 be an int pointer with a current value of 2,000 (that is, it contains the address 2,000). Assuming 32-bit integers, after the expression p1++; The contents of p1 will be 2,004, not 2,001. The reason for this is that each time p1 is incremented; it will point to the next int. The same is true of decrements. For example, again assuming that p1 has the value 2000, the expression
  23. 23. Prof. Erwin M. Globio, MSIT Page 23 of 66 p1--; causes p1 to have the value 1996. Generalizing from the preceding example, the following rules apply to pointer arithmetic. Each time that a pointer is incremented, it will point to the memory location of the next element of its base type. Each time it is decremented, it will point to the location of the previous element of its base type. In the case of character pointers, an increment or decrement will appear as ―normal‖ arithmetic because characters are one byte long. However, every other type of pointer will increase or decrease by the length of its base type. You are not limited to only increment and decrement operations. You can also add or subtract integers to or from pointers. The expression p1 = p1 + 9; makes p1 point to the ninth element of p1‘s base type, beyond the one to which it is currently pointing. Although you cannot add pointers, you can subtract one pointer from another (provided they are both of the same base type). The remainder will be the number of elements of the base type that separate the two pointers. Other than addition and subtraction of a pointer and an integer, or the subtraction of two pointers, no other arithmetic operations can be performed on pointers. For example, you cannot add or subtract float or double values to or from pointers. To graphically see the effects of pointer arithmetic, execute the next short program. It creates an int pointer (i) and a double pointer (f). It then adds the values 0 through 9 to these pointers and displays the results. Observe how each address changes, relative to its base type, each time the loop is repeated. (For most 32-bit compilers, i will increase by 4s and f will increase by 8s.) Notice that when using a pointer in a cout statement, its address is automatically displayed in the addressing format applicable to the CPU and environment. #include <iostream> using namespace std; int main() { int *I, j[10]; double *f, g[10]; int x; i = j; f = g; for (x=0; x<10; x++) cout << i+x << ‗ ‗ << f+x << ‗n‘; // display the addresses produced by adding x to each pointer Here is a sample run. (The precise values you see may differ from these.) 0012FE5C 09012FE84
  24. 24. Prof. Erwin M. Globio, MSIT Page 24 of 66 0012FE60 0012FE8C 0012FE64 0012FE94 0012FE68 0012FE9C 0012FE6C 0012FEA4 0012FE70 0012FEAC 0012FE74 0012FEB4 0012FE78 0012FEBC 0012FE7C 0012FEC4 0012FE80 0012FECC Pointer Comparisons Pointers may be compared using the relational operators, such as ==, <, and >. In general, for the outcome of a pointer comparison to be meaningful, the two pointers must have some relationship to each other. For example, both may point to elements within the same array. There is, however, one other type of pointer comparison: any pointer can be compared to the null pointer, which is zero.
  25. 25. Prof. Erwin M. Globio, MSIT Page 25 of 66 I. Objectives: To identify the use of Pointers in C and its use. II. Basic Information / Scenario: Answer the following, using Pointers. 1. What is a pointer? _____________________________________________________________________________ _____________________________________________________________________________ 2. Show how to declare a long int pointer called valPtr. _____________________________________________________________________________ _____________________________________________________________________________ 3. As they relate to pointers, what do the * and & operators do? _____________________________________________________________________________ _____________________________________________________________________________ 4. All pointer arithmetic is performed relative to the _____ of the pointer. _____________________________________________________________________________ _____________________________________________________________________________ 6. Assuming the double is 8 bytes long, when a double pointer is incremented, by how much is its value increased? _____________________________________________________________________________ _____________________________________________________________________________ 7. What are two pointer operators? _____________________________________________________________________________ _____________________________________________________________________________
  26. 26. Prof. Erwin M. Globio, MSIT Page 26 of 66 Chapter 5 Pointers and Arrays In C++, there is a close relationship between pointers and arrays. In fact, frequently a pointer and an array are interchangeable. Consider this fragment: char str[80]; char *p1; p1 = str; Here, str is an array of 80 characters and p1 is a character pointer. However, it is the third line that is of interest. In this line, p1 is assigned the address of the first element in the str array. (That is, after the assignment, p1 will point to str[0].) Here‘s why: In C++, using the name of an array without an index generates a pointer to the first element in the array. Thus, the assignment p1 = str; assigns the address of str[0] to p1. This is a crucial point to understand: When an unindexed array name is used in an expression, it yields a pointer to the first element in the array. Since, after the assignment, p1 points to the beginning of str, you can use p1 to access elements in the array. For example, if you want to access the fifth element in str, you can use str[4] or *(p1+4) Both statements obtain the fifth element. Remember, array indices start at zero, so when str is indexed, a 4 is used to access the fifth element. A 4 is also added to the pointer p1 to get the fifth element, because p1 currently points to the first element of str. The parentheses surrounding p1+4 are necessary because the * operation has a higher priority than the + operation. Without them, the expression would first find the value pointed to by p1 (the first location in the array) and then add 4 to it. In effect, C++ allows two methods of accessing array elements: pointer arithmetic and array indexing. This is important because pointer arithmetic can sometimes be faster than array indexing— especially when you are accessing an array in strictly sequential order. Since speed is often a consideration in programming, the use of pointers to access array elements is very common in C++ programs. Also, you can sometimes write tighter code by using pointers instead of array indexing. Here is an example that demonstrates the difference between using array indexing and pointer arithmetic to access the elements of an array. We will create two versions of a program that reverse the case of letters within a string. The first version uses array indexing. The second uses pointer arithmetic. The first version is shown here: // Reverse case using array indexing.
  27. 27. Prof. Erwin M. Globio, MSIT Page 27 of 66 #include <iostream> #include <ctype.h> using namespace std; int main() { int i; char str[80] = "This Is A Test"; cout << "Original string: " << str << "n"; for(i = 0; str[i]; i++) { if(isupper(str[i])) str[i] = tolower(str[i]); else if(islower(str[i])) str[i] = toupper(str[i]); } cout << "Inverted-case string: " << str; return 0; } The output from the program is shown here: Original string: This Is A Test Inverted-case string: tHIS iS a tEST Notice that the program uses the isupper( ) and islower( ) library functions to determine the case of a letter. The isupper( ) function returns true when its argument is an uppercase letter; islower( ) returns true when its argument is a lowercase letter. Inside the for loop, str is indexed, and the case of each letter is checked and changed. The loop iterates until the null terminating str is indexed. Since a null is zero (false), the loop stops. Here is the same program rewritten to use pointer arithmetic: // Reverse case using array indexing. #include <iostream> #include <ctype.h> using namespace std; int main() { int i; char str[80]; = ―This Is A Test‖; cout << ―Original string: ― << str << ―n‖; for i = 0; str[i]; i++) { if (iupper(str[i])) else if (islower(str[i])) str[i] = toupper(str[i]; } cout << ―Inverted-case string: ― << str; return 0; }
  28. 28. Prof. Erwin M. Globio, MSIT Page 28 of 66 In this version, p is set to the start of str. Then, inside the while loop, the letter at p is checked and changed, and then p is incremented. The loop stops when p points to the null terminator that ends str. Because of the way some C++ compilers generate code, these two programs may not be equivalent in performance. Generally, it takes more machine instructions to index an array than it does to perform arithmetic on a pointer. Consequently, in professionally written C++ code, it is common to see the pointer version used more frequently. However, as a beginning C++ programmer, feel free to use array indexing until you are comfortable with pointers. Indexing a Pointer As you have just seen, it is possible to access an array using pointer arithmetic. What you might find surprising is that the reverse is also true. In C++, it is possible to index a pointer as if it were an array. Here is an example. It is a third version of the case- changing program. //index a pointer as if it were an array. #include <iostream> #include <ctype.h> using namespace std; main() { char *p; int i; char str[80]=‖This is A Test‖; cout << ―Original string: ― << str << ―n‖; p = str; // assign the p address of the start of the array // now index p for (I = 0; p[i]; i++) if (isupper(p[i])) p[i] = tolower{p[i]); else if (islower(p[i]) p[i] = toupper(p[i]); } cout << ―Inverted – case string:‖ < str; return 0; } The program creates a char pointer called p and then assigns to that pointer the address of the first element in str. Inside the for loop, p is indexed using the normal array indexing syntax. This is perfectly valid because in C++, the statement p[i] is function functionally identical to *(p+i). This further illustrates the close relationship between pointers and arrays.
  29. 29. Prof. Erwin M. Globio, MSIT Page 29 of 66 COURSE TITLE : ITEC223 – Advance Programming EXERCISE NUMBER : 4 COURSE TOPIC : Pointers and Arrays I. Objectives: To identify the use of Pointers and Arrays using C. II. Tasks / Procedure / Instructions: Answer the following questions. 1. Can an array be accessed through a pointer? _____________________________________________________________________________ _____________________________________________________________________________ 2. Can a pointer be indexed as if it were an array? _____________________________________________________________________________ _____________________________________________________________________________ 3. An array name used by itself, with no index, yields what? _____________________________________________________________________________ _____________________________________________________________________________ 4. All pointer arithmetic is performed relative to the _____ of the pointer. _____________________________________________________________________________ _____________________________________________________________________________ 5. Assuming the double is 8 bytes long, when a double pointer is incremented, by how much is its value increased? _____________________________________________________________________________ _____________________________________________________________________________
  30. 30. Prof. Erwin M. Globio, MSIT Page 30 of 66 Chapter 6 Pointers and String Strings and Constants You might be wondering how string constants, like the one in the fragment shown here, are handled by C++: cout << strlen("Xanadu"); The answer is that when the compiler encounters a string constant, it stores it in the program‘s string table and generates a pointer to the string. Thus, ―Xanadu‖ yields a pointer to its entry in the string table. Therefore, the following program is perfectly valid and prints the phrase Pointers add power to C++.: #include <iostream> using namespace std; int main() { char *ptr; ptr = ―Pointers add power to C++. n‖; // ptr is assigned the address of this string constant cout << ptr; return 0; } In this program, the characters that make up a string constant are stored in the string table, and ptr is assigned a pointer to the string in that table. Since a pointer into your program‘s string table is generated automatically whenever a string constant is used, you might be tempted to use this fact to modify the contents of the string table. However, this is usually not a good idea because many C++ compilers create optimized tables in which one string constant may be used at two or more different places in your program. Thus, changing a string may cause undesired side effects. Reversing a String in Place Earlier it was mentioned that comparing one pointer to another is meaningful only if the two pointers point to a common object, such as an array. Now that you understand how pointers and arrays relate, you can apply pointer comparisons to streamline some types of algorithms. In this project, you will see an example. The program developed here reverses the contents of a string, in place. Thus, instead of copying the string back-to-front into another array, it reverses the contents of the string inside the array that holds it. The program uses two pointer variables to accomplish this. One initially points to the beginning of a string, and the other initially points to the last character in the string. A loop is set up that continues to run as long as the start pointer is less than the end pointer. Each time through the loop, the characters pointed to by the pointers are swapped and the pointers are advanced. When the start pointer is greater than or equal to the end pointer, the string has been reversed. Step by step
  31. 31. Prof. Erwin M. Globio, MSIT Page 31 of 66 1. Create a file called StrRev.cpp. 2. Begin by adding these lines to the file: /* Reverse a string in place. */ #include <iostream> #include <string.h> using namespace std; int main() { char str[ ] = ―this is a test‖; char *start, *end; int len; char t; The string to be reversed is contained in str. The pointers start and end will be used to access the string. 3. Add these lines, which display the original string, obtain the string‘s length, and set the initial values for the start and end pointers: cout << ―Original: ― << str << ―n‖; len = str(str); start = str;end=&str[len-1]; Notice that end points to the last character in the string, not the null terminator. 4. Add the code that reverse the string: while (start < end) { // swap chars t = *starts; *starts = *end; *end = t; // advance pointers starts++; end--; } The process works like this. As long as the start pointer points to a memory location that is less than the end pointer, the loop iterates. Inside the loop, the characters being pointed to by start and end are swapped. Then start is incremented and end is decremented. When end is greater than or equal to start, all of the characters in the string have been reversed. Since both start and end point into the same array, their comparison is meaningful. 5. Here is the complete StrRev.cpp program:
  32. 32. Prof. Erwin M. Globio, MSIT Page 32 of 66 /* Reverse a string in place. */ #include <iostream> #include <string.h> using namespace std; int main() { char str[ ] = ―this is a test‖; char *start, *end; int len; char t; cout << ―Original: ― << str << ―n‖; len = str(str); start = str;end=&str[len-1]; while (start < end) { // swap chars t = *starts; *starts = *end; *end = t; // advance pointers starts++; end--; } The output from the program is shown here: Original: this is a test Reversed: tset a si siht Arrays of Pointers Pointers can be arrayed like any other data type. For example, declaration for an int pointer array of size 10 is int *p[10]; Here, pi is an array of ten integer pointers. To assign the address of an int variable called var to the third element of the pointer array, you would write int var; fpi[2] = &var;
  33. 33. Prof. Erwin M. Globio, MSIT Page 33 of 66 Remember, pi is an array of int pointers. The only thing that the array elements can hold are the addresses of integer values—not the values themselves. To find the value of var, you would write *pi[2] Like other arrays, arrays of pointers can be initialized. A common use for initialized pointer arrays is to hold pointers to strings. Here is an example that uses a two-dimensional array of character pointers to implement a small dictionary: Here is a sample run: Enter word: network An interconnected group of computers. When the array dictionary is created, it is initialized with a set of words and their meanings. Recall, C++ stores all string constants in the string table associated with your program, so the array need only store pointers to the strings. The program works by testing the word entered by the user against the strings stored in the dictionary. If a match is found, the meaning is displayed. If no match is found, an error message is printed. Notice
  34. 34. Prof. Erwin M. Globio, MSIT Page 34 of 66 that dictionary ends with two null strings. These mark the end of the array. Recall that a null string contains only the terminating null character. The for loop runs until the first character in a string is null. This condition is tested with this expression: *dictionary[i][0] The array indices specify a pointer to a string. The * obtains the character at that location. If this character is null, then the expression is false and the loop terminates. Otherwise, the expression is true and the loop continues. The Null Pointer Convention After a pointer is declared, but before it has been assigned, it will contain an arbitrary value. Should you try to use the pointer prior to giving it a value, you will probably crash your program. While there is no sure way to avoid using an uninitialized pointer, C++ programmers have adopted a procedure that helps prevent some errors. By convention, if a pointer contains the null (zero) value, it is assumed to point to nothing. Thus, if all unused pointers are given the null value and you avoid the use of a null pointer, you can avoid the accidental misuse of an uninitialized pointer. This is a good practice to follow. Any type of pointer can be initialized to null when it is declared. For example, the following initializes p to null: float *p = 0; // p is now a null pointer To check for a null pointer, use an if statement, like one of these: if(p) // succeeds if p is not null if(!p) // succeeds if p is null Multiple Indirection A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Consider Figure 4-2. As you can see, in the case of a normal pointer, the value of the pointer is the address of a value. In the case of a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the desired value. Multiple indirection can be carried on to whatever extent desired, but there are few cases where more than a pointer to a pointer is needed, or, indeed, even wise to use. Excessive indirection is difficult to follow and prone to conceptual errors.
  35. 35. Prof. Erwin M. Globio, MSIT Page 35 of 66 COURSE TITLE : ITEC223 – Advance Programming EXERCISE NUMBER : 5 COURSE TOPIC : Pointers and String I. Objectives: To know how is Pointers and String worked using C. II. Tasks / Procedure / Instructions: Asnwer the following question. 1. What is it called when one pointer points to another pointer? _____________________________________________________________________________ _____________________________________________________________________________ 2. Of what significant is a null pointer in C++? _____________________________________________________________________________ _____________________________________________________________________________ Supplementary Programming (50 points) 1. Write a program that counts the uppercase letters in a string. Have it display the result.
  36. 36. Prof. Erwin M. Globio, MSIT Page 36 of 66 Chapter 7 Structures in Arrays, Functions and Pointers What is a Structure? Structure is a collection of variables under a single name. Variables can be of any type: int, float, char etc. The main difference between structure and array is that arrays are collections of the same data type and structure is a collection of variables under a single name. Declaring a Structure: The structure is declared by using the keyword struct followed by structure name, also called a tag. Then the structure members (variables) are defined with their type and variable names inside the open and close braces { and }. Finally, the closed braces end with a semicolon denoted as ; following the statement. The above structure declaration is also called a Structure Specifier. Example: Three variables: custnum of type int, salary of type int, commission of type float are structuremembers and the structure name is Customer. This structure is declared as follows: In the above example, it is seen that variables of different types such as int and float are grouped in a single structure name Customer. Arrays behave in the same way, declaring structures does not mean that memory is allocated. Structure declaration gives a skeleton or template for the structure. After declaring the structure, the next step is to define a structure variable.
  37. 37. Prof. Erwin M. Globio, MSIT Page 37 of 66 How to declare Structure Variable? This is similar to variable declaration. For variable declaration, data type is defined followed by variable name. For structure variable declaration, the data type is the name of the structure followed by thestructure variable name. In the above example, structure variable cust1 is defined as: What happens when this is defined? When structure is defined, it allocates or reserves space in memory. The memory space allocated will be cumulative of all defined structure members. In the above example, there are 3 structure members: custnum, salary and commission. Of these, two are of type int and one is of type float. If integer space allocated by a system is 2 bytes and float four bytes the above would allocate 2bytes for custnum, 2 bytes for salary and 4 bytes for commission. How to access structure members in C++? To access structure members, the operator used is the dot operator denoted by (.). The dot operatorfor accessing structure members is used thusly: structure variable name.member name For example: To assign 2000 for the structure member salary in the above example of structure Customer with structure variable cust1 this is written as:
  38. 38. Prof. Erwin M. Globio, MSIT Page 38 of 66 CHAPTER 8 Pointers to structures All that we have discussed so far has been OK but runs into problems when structures have to be moved between functions for the following reasons.  if the structure is large it is more efficient to pass a pointer to the structure instead of the structure its self. This techniquepri is also used to pass pointers to arrays between functions.  When passing a structure to a function, you actually pass a COPY of the structure. Therefore it is not possible to change the values of members within the structure as the copy is destroyed when the function ends. Here is an example. (these are 2 examples, the one to the left uses a pointer) | | struct x {int a; int b; int c;} ; | struct x {int a; int b; int c;} ; | void function(struct x); | void function(struct x *); | main() | main() { | { struct x z; | struct x z, *pz; /* 3 */ | pz = &z; /* 4 */ z.a = 10; /* 1 */ | z.a = 10; z.a++; | z.a++; | function(z); /* 2 */ | function(pz); /* 5 */ } | } | void function( struct x z) | void function(struct x * pz) { | { /* 6 */ printf(" first member %d n", z.a); | printf(" first member %d n", (*pz).a); } | } | Here is the annotation. 1. Give a structure member a value. 2. Pass a COPY of the whole structure to the function. 3. Define 'pz' a pointer to a structure of type 'x'. 4. Put the address of 'z' into 'pz'. 'pz' now POINTS to 'z'. PLEASE NOTE. 'z' is defined to reserve memory equal to the size of the structure. 'pz' only holds an address so will be 4 bytes long. 5. Pass the pointer into the function. 6. Print the value of the member 'a'. The (*pz).a syntax is used a great deal in C and it was decided to create a short hand for it. So: (*pz).a == pz->a
  39. 39. Prof. Erwin M. Globio, MSIT Page 39 of 66 CHAPTER 9 Structures and Arrays #include <iostream> #include <fstream.h> #include <string.h> using namespace std; ofstream outData; //input file structure ifstream inData; char menu_id[10]; char menu_name[10]; char menu_col[10]; char menu_row[10]; char button_id[10]; char button_label_1[10]; char button_label_2[10]; char button_label_3[10]; char button_col[10]; char button_row[10]; //menu file structure struct menu { int mid; char name[20]; int mcol; int mrow; int bid; char blabel[24]; int bcol; int brow; }; //List of menus enum menu_id { MAIN = 1 }; //Define Main menu menu Main_menu[3]; void createMenu(menu newMenu[], int menu_num, MAS_Configure_Button_Request_Message*msg )
  40. 40. Prof. Erwin M. Globio, MSIT Page 40 of 66 int y = 0; while ((!inData.getline(menu_id,10, '$').eof()) && (atoi(menu_id) == menu_num)) { newMenu[y].mid= atoi(menu_id); inData.getline(menu_name, 10, '$'); newMenu[y].name[0] = '0'; strcpy(newMenu[y].name,menu_name); outData << " Main Menu Name " << newMenu[y].name << " " ; inData.getline( menu_col, 10, '$'); newMenu[y].mcol = atoi(menu_col); inData.getline( menu_row, 10, '$'); newMenu[y].mrow = atoi(menu_row); inData.getline( button_id, 10, '$'); newMenu[y].bid = atoi(button_id); inData.getline( button_label_1, 10, '$'); inData.getline( button_label_2, 10, '$'); inData.getline( button_label_3, 10, '$'); newMenu[y].blabel[0] = '0'; strcpy(newMenu[y].blabel,button_label_1); strcat(newMenu[y].blabel,button_label_2); strcat(newMenu[y].blabel,button_label_3); outData << newMenu[y].blabel << "; " ; inData.getline( button_col ,10, '$'); newMenu[y].bcol = atoi(button_col); inData.getline( button_row ,10, 'n'); newMenu[y].brow = atoi(button_row); y++; } } int main() { int loop; inData.open("data.txt"); if (!inData) { cout << "*** Problem with opening data.txt. End program***" << endl; return(1); }
  41. 41. Prof. Erwin M. Globio, MSIT Page 41 of 66 outData.open("test.txt"); if (!outData) { cout << "*** Problem with opening test.txt. End program***" << endl; return(2); } createMenu(Main_menu, MAIN, msg); for (loop = 0; loop < 3; loop ++) { outData << " Main menu" << Main_menu[loop].bid << endl; outData << " Main menu" << Main_menu[loop].blabel << endl; } inData.close(); outData.close(); return 0; } CHAPTER EXERCISES Example1: A Simple use of structures Here‘s a program that uses a struct variable to manage the records in the given file. Andy DeGeneres Math 98 Gail Stevens English 100 Lia Jacobs Science 99 # include <iostream.h> struct record { char fname[10]; char lname[10]; char subject[10]; int grades; }; record stud; //record has become like a variable that we can use to define the stud variable char n1[10]; char n2[10]; char s[10]; int gr; main() { //this is how you assign a value to struct elements record.fname = ―Andy‖;
  42. 42. Prof. Erwin M. Globio, MSIT Page 42 of 66 record.lname = ―DeGeneres‖; record.subject = ―Math‖; record.grade = 98; //this is how you assign an inputted value to struct elements cout<<‖Enter a First Name‖; cin>>n1; cout<<‖Enter a Last Name‖; cin>>n2; cout<<‖Enter a subject‖; cin>>s; cout<<‖Enter a grade‖; cin>>gr; record.fname = n1; record.lname = n2; record.subject = s; record.grade = gr; //this is how you retrieve values from a struct cout<‖ntStudent 1:‖; cout<<‖nt FnamettLnamettSubjectttGrade‖; cout<<‖nt‖<<record.fname<<‖tt‖ <<record.lname; cout<<‖tt‖ <<record.subject<<‖tt‖ <<record.grade‖; } ******************End of Example 1*********************** Example2: Stuctures, Pointers and Functions struct x {int a; int b; int c;} ; /* Declare the structure. */ void function(struct x * ); /* the function prototype */ main() { /* Declare two variables. * z == type struct x * pz == a pointer to type struct x */ struct x z, *pz; pz = &z; /* put the address of 'z' into 'pz' */ z.a = 10; /* initialize z.a */ z.a++; /* Increment z.a */ /* print the contents of 'z.a' * using the pointer 'pz' */ printf(" first member before the function call %d n", pz->a);
  43. 43. Prof. Erwin M. Globio, MSIT Page 43 of 66 /* Call 'function' passing the * pointer 'pz' */ function(pz); /* Print the NEW value of 'z.a' * using three different notations */ printf(" first member after the function call %d n", pz->a); printf(" first member after the function call %d n", (*pz).a); printf(" first member after the function call %d n", z.a); } void function(struct x * pz) { /* Print the value of 'z.a' by * referencing the pointer 'pz' * which holds the address of 'z' */ printf(" first member inside the function %d n", pz->a); /* Increment the value of 'z.a' * this is the source location * in memory. */ pz->a++; } *********************End of Example 2*************************** Example 3: Arrays and Structures #include <iostream.h> /* Declare a structure. It MUST * be declared before use. */ struct record_format { char name[20]; int age; }; main () { int count=0; struct record_format record[]= { {"Joe Brown", 21}, {"James Dean", 34}, {"David Williams", 54}, {"Neil Harrison", 62}, {"EOF", -1} }; /*
  44. 44. Prof. Erwin M. Globio, MSIT Page 44 of 66 * Print the contents of the structure. */ while( record[count].age != -1) { cout<<"name is %s tage is %d n", record[count].name, record[count].age; count++; } } /************************************************************************ * * Program will produce: * * name is Joe Brown age is 21 * name is James Dean age is 34 * name is David Williams age is 54 * name is Neil Harrison age is 62 * ************************************************************************* / *************************End of Example 3************************ CHAPTER QUIZ COURSE TOPIC : Applying Structures in Functions, Pointers and Arrays III. Objectives:  To learn and understand how to declare a structure.
  45. 45. Prof. Erwin M. Globio, MSIT Page 45 of 66  To understand and use structures with the previously learned constructs, particularly pointers, functions and arrays IV. Tasks / Procedure / Instructions: Part I. Declaration of Structures in Functions, Pointers and Arrays 7. What is the syntax in declaring a structure? _____________________________________________________________________________ _____________________________________________________________________________ __________ 8. What is the use of the dot (.) operator? _____________________________________________________________________________ _____________________________________________________________________________ __________ 9. How do you display the content a structure element? (you may use an example to answer this) _____________________________________________________________________________ _____________________________________________________________________________ __________ 10. How do you declare an array of structures? _____________________________________________________________________________ _____________________________________________________________________________ __________ 11. What is a member? _____________________________________________________________________________ _____________________________________________________________________________ __________ 12. True or False. A structure, once declared, is used similarly to variables. Show an example. _____________________________________________________________________________ _____________________________________________________________________________ _______ Supplementary Programming (50 points) 2. Write a program that defines a structure to add two fractions together. CHAPTER 10 File Handling What is a File?
  46. 46. Prof. Erwin M. Globio, MSIT Page 46 of 66 Abstractly, a file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. The collection of bytes may be interpreted, for example, as characters, words, lines, paragraphs and pages from a textual document; fields and records belonging to a database; or pixels from a graphical image. The meaning attached to a particular file is determined entirely by the data structures and operations used by a program to process the file. It is conceivable (and it sometimes happens) that a graphics file will be read and displayed by a program designed to process textual data. The result is that no meaningful output occurs (probably) and this is to be expected. A file is simply a machine decipherable storage media where programs and data are stored for machine usage. Essentially there are two kinds of files that programmers deal with text files and binary files. These two classes of files will be discussed in the following sections. ASCII Text files A text file can be a stream of characters that a computer can process sequentially. It is not only processed sequentially but only in forward direction. For this reason a text file is usually opened for only one kind of operation (reading, writing, or appending) at any given time. Similarly, since text files only process characters, they can only read or write data one character at a time. (In C Programming Language, Functions are provided that deal with lines of text, but these still essentially process data one character at a time.) A text stream in C is a special kind of file. Depending on the requirements of the operating system, newline characters may be converted to or from carriage-return/linefeed combinations depending on whether data is being written to, or read from, the file. Other character conversions may also occur to satisfy the storage requirements of the operating system. These translations occur transparently and they occur because the programmer has signalled the intention to process a text file. Binary files A binary file is no different to a text file. It is a collection of bytes. In C Programming Language a byte and a character are equivalent. Hence a binary file is also referred to as a character stream, but there are two essential differences. 1. No special processing of the data occurs and each byte of data is transferred to or from the disk unprocessed. 2. C Programming Language places no constructs on the file, and it may be read from, or written to, in any manner chosen by the programmer. Binary files can be either processed sequentially or, depending on the needs of the application, they can be processed using random access techniques. In C Programming Language, processing a file using random access techniques involves moving the current file position to an appropriate place in the file before reading or writing data. This indicates a second characteristic of binary files is that they are generally processed using read and write operations simultaneously. For example, a database file will be created and processed as a binary file. A record update operation will involve locating the appropriate record, reading the record into memory, modifying it in some way, and finally writing the record back to disk at its
  47. 47. Prof. Erwin M. Globio, MSIT Page 47 of 66 appropriate location in the file. These kinds of operations are common to many binary files, but are rarely found in applications that process text files. Creating a file and output some data In order to create files we have to learn about File I/O i.e. how to write data into a file and how to read data from a file. We will start this section with an example of writing data to a file. We begin as before with the include statement for stdio.h, then define some variables for use in the example including a rather strange looking new type. EXAMPLE: /* Program to create a file and write some data the file */ #include <stdio.h> #include <stdio.h> main( ) { FILE *fp; char stuff[25]; int index; fp = fopen("TENLINES.TXT","w"); /* open for writing */ strcpy(stuff,"This is an example line."); for (index = 1; index <= 10; index++) fprintf(fp,"%s Line number %dn", stuff, index); fclose(fp); /* close the file before ending program */ } The type FILE is used for a file variable and is defined in the stdio.h file. It is used to define a file pointer for use in file operations. Before we can write to a file, we must open it. What this really means is that we must tell the system that we want to write to a file and what the file name is. We do this with the fopen() function illustrated in the first line of the program. The file pointer, fp in our case, points to the file and two arguments are required in the parentheses, the file name first, followed by the file type. The file name is any valid DOS file name, and can be expressed in upper or lower case letters, or even mixed if you so desire. It is enclosed in double quotes. For this example we have chosen the name TENLINES.TXT. This file should not exist on your disk at this time. If you have a file with this name, you should change its name or move it because when we execute this program, its contents will be erased. If you don‘t have a file by this name, that is good because we will create one and put some data into it. You are permitted to include a directory with the file name.The directory must, of course, be a valid directory otherwise an error will occur. Also, because of the way C handles literal strings, the directory separation character must be written twice. For example, if the file is to be stored in the PROJECTS sub directory then the file name should be entered as ―PROJECTSTENLINES.TXT‖. The second parameter is the file attribute and can be any of three letters, r, w, or a, and must be lower case. Reading (r) When an r is used, the file is opened for reading, a w is used to indicate a file to be used for writing, and an a indicates that you desire to append additional data to the data already in an existing file. Most C compilers have other file attributes available; check your
  48. 48. Prof. Erwin M. Globio, MSIT Page 48 of 66 Reference Manual for details. Using the r indicates that the file is assumed to be a text file. Opening a file for reading requires that the file already exist. If it does not exist, the file pointer will be set to NULL and can be checked by the program. EXAMPLE: Here is a small program that reads a file and display its contents on screen. /* Program to display the contents of a file on screen */ #include <stdio.h> void main() { FILE *fopen(), *fp; int c; fp = fopen("prog.c","r"); c = getc(fp) ; while (c!= EOF) { putchar(c); c = getc(fp); } fclose(fp); } Writing (w) When a file is opened for writing, it will be created if it does not already exist and it will be reset if it does, resulting in the deletion of any data already there. Using the w indicates that the file is assumed to be a text file. EXAMPLE: Here is the program to create a file and write some data into the file. #include <stdio.h> int main() { FILE *fp; file = fopen("file.txt","w"); /*Create a file and add text*/ fprintf(fp,"%s","This is just an example :)"); /*writes data to the file*/ fclose(fp); /*done!*/ return 0; } Appending (a) When a file is opened for appending, it will be created if it does not already exist and it will be initially empty. If it does exist, the data input point will be positioned at the end of
  49. 49. Prof. Erwin M. Globio, MSIT Page 49 of 66 the present data so that any new data will be added to any data that already exists in the file. Using the a indicates that the file is assumed to be a text file. Here is a program that will add text to a file which already exists and there is some text in the file. #include <stdio.h> int main() { FILE *fp file = fopen("file.txt","a"); fprintf(fp,"%s","This is just an example :)"); /*append some text*/ fclose(fp); return 0; } Outputting to the file The job of actually outputting to the file is nearly identical to the outputting we have already done to the standard output device. The only real differences are the new function names and the addition of the file pointer as one of the function arguments. In the example program, fprintf replaces our familiar printf function name, and the file pointer defined earlier is the first argument within the parentheses. The remainder of the statement looks like, and in fact is identical to, the printf statement. Closing a file To close a file you simply use the function fclose with the file pointer in the parentheses. Actually, in this simple program, it is not necessary to close the file because the system will close all open files before returning to DOS, but it is good programming practice for you to close all files in spite of the fact that they will be closed automatically, because that would act as a reminder to you of what files are open at the end of each program. You can open a file for writing, close it, and reopen it for reading, then close it, and open it again for appending, etc. Each time you open it, you could use the same file pointer, or you could use a different one. The file pointer is simply a tool that you use to point to a file and you decide what file it will point to. Compile and run this program. When you run it, you will not get any output to the monitor because it doesn’t generate any. After running it, look at your directory for a file named TENLINES.TXT and type it; that is where your output will be. Compare the output with that specified in the program; they should agree! Do not erase the file named TENLINES.TXT yet; we will use it in some of the other examples in this section. Reading from a text file Now for our first program that reads from a file. This program begins with the familiar include, some data definitions, and the file opening statement which should require no explanation except for the fact that an r is used here because we want to read it. #include <stdio.h>
  50. 50. Prof. Erwin M. Globio, MSIT Page 50 of 66 main( ) { FILE *fp; char c; funny = fopen("TENLINES.TXT", "r"); if (fp == NULL) printf("File doesn't existn"); else { do { c = getc(fp); /* get one character from the file */ putchar(c); /* display it on the monitor */ } while (c != EOF); /* repeat until EOF (end of file) */ } fclose(fp); } In this program we check to see that the file exists, and if it does, we execute the main body of the program. If it doesn‘t, we print a message and quit. If the file does not exist, the system will set the pointer equal to NULL which we can test. The main body of the program is one do while loop in which a single character is read from the file and output to the monitor until an EOF (end of file) is detected from the input file. The file is then closed and the program is terminated. At this point, we have the potential for one of the most common and most perplexing problems of programming in C. The variable returned from the getc function is a character, so we can use a char variable for this purpose. There is a problem that could develop here if we happened to use an unsigned char however, because C usually returns a minus one for an EOF – which an unsigned char type variable is not capable of containing. An unsigned char type variable can only have the values of zero to 255, so it will return a 255 for a minus one in C. This is a very frustrating problem to try to find. The program can never find the EOF and will therefore never terminate the loop. This is easy to prevent: always have a char or int type variable for use in returning an EOF. There is another problem with this program but we will worry about it when we get to the next program and solve it with the one following that. After you compile and run this program and are satisfied with the results, it would be a good exercise to change the name of TENLINES.TXT and run the program again to see that the NULL test actually works as stated. Be sure to change the name back because we are still not finished with TENLINES.TXT. File Handling In C++ we say data flows as streams into and out of programs. There are different kinds of streams of data flow for input and output. Each stream is associated with a class, which contains member functions and definitions for dealing with that particular kind of flow. For example, the if stream class represents the input disc files,. Thus each file in C++ is an object of a particular stream class. CHAPTER EXERCISE FILE HANDLING: READ,WRITE, APPEND to a FILE
  51. 51. Prof. Erwin M. Globio, MSIT Page 51 of 66 EXAMPLE 1: Program to create a file and write some data the file #include <stdio.h> #include <stdio.h> main( ) { FILE *fp; char stuff[25]; int index; fp = fopen("TENLINES.TXT","w"); /* open for writing */ strcpy(stuff,"This is an example line."); for (index = 1; index <= 10; index++) fprintf(fp,"%s Line number %dn", stuff, index); fclose(fp); /* close the file before ending program */ } Example 2. A program that reads a file and display its contents on screen. /* Program to display the contents of a file on screen */ #include <stdio.h> void main() { FILE *fopen(), *fp; int c; fp = fopen("prog.c","r"); c = getc(fp) ; while (c!= EOF) { putchar(c); c = getc(fp); } fclose(fp); } Example 3: A program to create a file and write some data into the file. #include <stdio.h> int main() { FILE *fp; file = fopen("file.txt","w"); /*Create a file and add text*/ fprintf(fp,"%s","This is just an example :)"); /*writes data to the file*/ fclose(fp); /*done!*/ return 0;
  52. 52. Prof. Erwin M. Globio, MSIT Page 52 of 66 }
  53. 53. Prof. Erwin M. Globio, MSIT Page 53 of 66 CHAPTER QUIZ COURSE TOPIC : File Handling V. Objectives:  To learn and understand how to manage external files, particularly, .txt formats.  To create, write to, read from and append to files using c++ constructs. VI. Tasks / Procedure / Instructions: Part I. Declaration of Structures in Functions, Pointers and Arrays 1. What is a file? _____________________________________________________________________________ _____________________________________________________________________________ __________ 3. When do we use the r command? _____________________________________________________________________________ _____________________________________________________________________________ __________ 4. TRUE Or FALSE? When you open a file for appending, a new one will be created if the file is not yet existing. _____________________________________________________________________________ _____________________________________________________________________________ __________ Supplementary Programming (50 points) 5. Write a program that will count characters in a file. Prompt the user for file and the count the number of characters and lines in it. Sample Output: ** The program must prompt the user to enter another file if the file entered cannot be opened. CHAPTER 11 Enter Filename: There are <n> characters in < filename> There are <n> lines.
  54. 54. Prof. Erwin M. Globio, MSIT Page 54 of 66 Introduction to Visual C++ Visual C++ comes within Microsoft Visual Studio. Visual Studio also contains Visual Basic, Visual C#, and Visual J#. Using Visual Studio, you can mix and match languages within one "solution". We will, however, focus on developing C++ code throughout these labs. For your first C++ program, you will build a console mode application that displays a greeting message. This (i.e. a console mode application) is the kind of VC++ programs that you will build for all your lab and class exercises/assignments. Console mode programs are often simpler to build than Windows applications, and this example will take you through the steps of creating, building and executing a program in Visual C++. We first assume that you use the built-in code editor in Visual Studio to edit your code; then we will show you how to build and run your C++ programs that you have created with any external editors. 1.1.1 How to start Press on your window desktop, choose All Programs from the popup menu, then choose Microsoft Visual Studio , and Microsoft Visual Studio 1.1.2 Starting Your First Program Select Visual C++ Development Settings, then click on Start Visual Studio. Note: If you want to choose another environment later, click on Tools menu -> Import and Export ->Reset all Settings ->Next, then you can pick either save current settings or overwrite current settings. The next thing you will see is the Start Page. To get started on your first program, you must create a "project" that will keep track of all the parts of your program, including the C++ source code, the header files, etc. Therefore, click the "Create Project" link. A "New Project" dialogue box similar to the one below will appear.
  55. 55. Prof. Erwin M. Globio, MSIT Page 55 of 66 Follow these steps:  For a "Name:", type a project name ("hello")  "Location:", you can leave it in default location D:VS2008  Note: files created on D drive will not be deleted unless the user do so.  Click on "OK" The "Win32 Application Wizard" will appear. As demonstrated below, click on "Application Settings" and select "Empty Project".
  56. 56. Prof. Erwin M. Globio, MSIT Page 56 of 66 After this, click on "Finish". You will notice that it doesn't appear like anything has changed (you still see the "Start Page"). However, look at the "Solution Explorer" on the left-hand side you will see "Solution 'hello' (1 project)". You want to add C++ source code to this project. Select Project --> Add New Item... from the main menu, and select C++ File (.cpp) from the "Templates" section on the right-hand side. Type in the file name: "hello.cpp" in the Name:box. Click on "Add". This file will be added to the hello work space that we have just created, and a blank document will be opened for editing EXERCISE: Type this code in the code window // FILE: hello.cpp // PURPOSE: An example of a simple I/O stream #include <iostream> using namespace std; int main() { char name[50]; cout << "Please enter your name:" << endl; cin >> name; cout << "Hello, " << name << endl; return 0; } SAVE it as Hello.cpp. Building the hello Project In order to compile any code in Visual C++, you have to create a project. A project holds three major types of information: 1) It remembers all of the source code files that combine together to create one executable. In this simple example, the file hello.cpp will be the only source file, but in larger applications you often break the code up into several different files to make it easier to understand (and also to make it possible for several people to work on it simultaneously). The project maintains a list of the different source files and compiles all of them as necessary each time you want to create a new executable. 2) It remembers compiler and linker options particular to this specific application. For example, it remembers which libraries to link into the executable, whether or not you want to use pre-compiled headers, and so on. 3) It remembers what type of project you wish to build: a console application, a windows application, etc.
  57. 57. Prof. Erwin M. Globio, MSIT Page 57 of 66 If you are familiar with makefiles, then it is easy to think of a project as a machine- generated makefile that has a very easy-to-understand user interface to manipulate it. For now we will create a very simple project file and use it to compile hello.cpp. 1. Compile the hello project by selecting Build --> Compile from the main menu. It simply compiles the source file and forms the object file (hello.obj) for it. It does not perform a link, so it is useful only for quickly compiling a file to check for errors. 2. Select Build --> Build hello from the menu bar to link the program. It compiles all of the source files in the project that have been modified since the last build, and then links them to create an executable. 3. Choose Debug --> to run the program. A DOS window will popup. If errors or warnings are displayed in the Build status window, there is probably an error in the source file. Check your source file again for missing semicolons, quotes, or braces. Now, we will continue using Visual C++ in another project, so select File --> Close Solution. This will return you to the Start Page. How to compile, link and execute a program with multiple files? The preceding section showed the procedure for creating a C++ program with only one file component: hello.cpp, and we used the built-in VC++ source code editor to edit the file. However, when you are working on a large program, you would break your program into smaller, more manageable parts. In other words, your project would contain more than one C++ source files. Moreover, you might not have used the VC++ source code editor to edit your files. The following section demonstrates how to create, compile, and execute a VC++ project with more than one file. Exercise: 1.2.1 Creating the project Step 1. Select File --> New --> Project.... Step 2. Set the project name to lab1. Step 3. Pick a project location, for example D:VS2008 Step 4. Click on "OK" to create the project. Step 5. Under "Application Settings", select "Empty project". Step 6. Click on "Finish". You have now created a project that has information stored in the following folder: D:VS2008lab1 You can get to this folder through the "Workarea" icon on the desktop.
  58. 58. Prof. Erwin M. Globio, MSIT Page 58 of 66 It is always a good practice to put the source files in this folder. Let's do that now Get multiple files using anonymous FTP Obtain the files you need for this lab by clicking here: CS Dept FTP Server  Right click on these files and save them to your project folder; 1. date.h 2. date.cpp 3. main.cpp The three files are now copied so the next step is to place them in a folder on your PC.  Move your cursor over your local system D:VS2008lab1 folder and right-click.  Select the Paste option in the resultant pop-up menu. Even though the files are in the appropriate directory, you must tell Visual Studio that these files are part of the project. Adding existing files to the project 1. Select Project --> Add Existing Item.... 2. You should be looking in the lab1 directory. Highlight the .h and .cpp files: date.cpp, date.h and main.cpp 3. Select "Add" to add the files to the project. To view the contents of any of these files, double click on the file name in the "Solution Explorer". Compile, build and execute your progam 1. Select Build --> Build lab1 (This will compile and link the files). 2. Select Debug --> Start Without Debugging CHAPTER EXERCISE Example : Small program for beginners demonstrating the use of loops and iostream + iomanip libraries. // Program to make a pyramid of characters based on input from user // Purpose is to examine use of <iomanip.h> and how setw is used // Created by Gary Paduana // email : gary3141@home.com // Written on 4.15.01 # include <iostream.h>
  59. 59. Prof. Erwin M. Globio, MSIT Page 59 of 66 # include <iomanip.h> // library that has the setw output manipulator int main () { char letter; // letter is the symbol or letter made into a giant triangle int width; // width is how far to go into the center of screen int base; // base is how many symbols are on bottom line int a; // a is how many lines down the triangle is int b = 1; // b is how many symbols are displayed on each line int counter = 0; // counter is how many times the loop executed cout<<"This program will make a triangle of the symbol entered."<<endl; cout<<"It must be an odd number for the triangle to form properly."<<endl; cout<<"If an even number is entered, it will be lowered to the previous odd."<<endl; while(cin) // This allows the program to loop until the user closes the window { cout<<"Enter a symbol or character."<<endl; cin>>letter; cout<<"Enter the number of characters the base should have."<<endl; cin>>base; width = (base / 2) + 5 - counter; // This is how far into the center it should space until it //starts outputting the symbol // It must first be given a value before it enters the loop a = 1; // a is how many lines down the triangle is, and natuarally it starts on the first line while(width > 5) // It will loop and continue to output the symbol until it //reaches 5 spaces from the left margin... // so that everything isn't jammed against the side { width = (base / 2) + 5 - counter; // This is how far into the center it should space until it starts outputting the symbol cout<<setw(width); // setw is an output manipulator in the <iomanip.h> //library. this tell the compiler how many lines // to move until it first sends a character to the screen. //It is currently set to move the value of // "width" spaces to the right before it outputs. while(b > 0) // This while loop will continue to output the desired //symbol to the current line until it is equal to 1 { cout<<letter; // outputs the letter or symbol entered b--; // b is decremented so only so many letters are //outputted per line } cout<<endl; // an endl is used to jump to the next line to output the
  60. 60. Prof. Erwin M. Globio, MSIT Page 60 of 66 //next part of the triangle b = (a * 2) - 1; // the number of symbols per line is found using //this equation width--; // the width is decremented so that everything is // spaced properly b = b + 2; // b is given 2 more symbols because it is on the next line //, and every line has 2 more than the previous a++; // this is how many lines into the triangle it is counter++; // the counter is used to ensure proper spacing done // by the width variable } cout<<endl<<endl; // endl is used to add some space between each time //the program is executed b = 1; // b is returned to 1 because the program started over counter = 0; // counter is returned to 0 because the program started } return 0; } *********************End of Example ************************************ CHAPTER 12
  61. 61. Prof. Erwin M. Globio, MSIT Page 61 of 66 Microsoft Foundations Classes The MFC library provides it own version of C's file processing. This is done through a class named CStdioFile. The CStdioFile class is derived from CFile. As done for the FILE structure, to start normal file input/outputoperations, declare a variable of type CStdioFile. This class has five constructors whose syntaxes are: CStdioFile(); CStdioFile(CAtlTransactionManager* pTM); CStdioFile(FILE* pOpenStream); CStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags); CStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags, CAtlTransactionManager* pTM); The default constructor allows you to initiate file processing without giving much detail. If you use it, you can then call the Open() method that the CStdioFile class inherits fromCFile. Pass the same arguments you would for a CFile variable. 1. To create a new application, on the main menu, click File -> New Project... 2. In the middle list, click MFC Application 3. Set the Name to LoanPreparation1 4. Click OK 5. In the first page of the MFC Application Wizard, click Next 6. In the second page of the wizard, click Dialog Box 7. Click Next 8. In the third page of the wizard, change the Dialog Title to Loan Preparation 9. Click Next twice 10. Click Finish 11. On the dialog box, click TODO: and press Delete 12. Press the OK button and press Delete 13. Click the Cancel button to select it 14. In the Properties window, click Caption, type Close and press Enter 15. Design the dialog box as follows:
  62. 62. Prof. Erwin M. Globio, MSIT Page 62 of 66 Control Caption ID Right Align Text Static Text Prepared By: Edit Control IDC_CUSTOMERNAME Static Text Prepared For: Edit Control IDC_EMPLOYEENAME Static Text ________________ Static Text Loan Amount: Edit Control IDC_PRINCIPAL True Static Text Interest Rate: Edit Control IDC_INTERESTRATE True Static Text % Static Text Paid In: Edit Control IDC_PERIODS True Static Text Months
  63. 63. Prof. Erwin M. Globio, MSIT Page 63 of 66 Button Evaluate IDC_EVALUATE Static Text _________________ Static Text Future Value: Edit Control IDC_FUTUREVALUE True Static Text Monthly Payment: Edit Control IDC_MONTHLYPAYMENT True Static Text _________________ Static Text Save As: Edit Control IDC_FILESAVE True Button Save IDC_SAVE_BTN Static Text File to Open: Edit Control IDC_FILEOPEN True Button Open IDC_OPEN_BTN Static Text File Name: Button Reset IDC_RESET_BTN Button Close IDCANCEL 16. Right-click each edit control, click Add Variable, select the category as Value, set the options as follows and click Finish on each: Control ID Category Variable Type Variable Name IDC_CUSTOMERNAME Value CString m_CustomerName IDC_EMPLOYEENAME Value CString m_EmployeeName IDC_PRINCIPAL Value CString m_Principal IDC_INTERESTRATE Value CString m_InterestRate IDC_PERIODS Value CString m_Periods IDC_FUTUREVALUE Value CString m_FutureValue IDC_MONTHLYPAYMENT Value CString m_MonthlyPayment IDC_FILESAVE Value CString m_FileSave IDC_FILEOPEN Value CString m_FileOpen 17. Access the source file of the dialog box and change the initializations in the constructor as follows:
  64. 64. Prof. Erwin M. Globio, MSIT Page 64 of 66 1. CLoanPreparation1Dlg::CLoanPreparation1Dlg(CWnd* pParent /*=NULL*/) 2. : CDialogEx(CLoanPreparation1Dlg::IDD, pParent) 3. , m_CustomerName(_T("")) 4. , m_EmployeeName(_T("")) 5. , m_Principal(_T("0.00")) 6. , m_InterestRate(_T("0.00")) 7. , m_Periods(_T("0")) 8. , m_FutureValue(_T("0.00")) 9. , m_MonthlyPayment(_T("0.00")) 10. , m_FileSave(_T("")) 11. , m_FileOpen(_T("")) 12. { 13. m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } 14. Return to the dialog box 15. Double-click the Evaluate button 16. Implement the event as follows: 17. void CLoanPreparation1Dlg::OnBnClickedEvaluate() 18. { 19. UpdateData(TRUE); 20. 21. double Principal = _wtof(m_Principal); 22. double InterestRate = _wtof(m_InterestRate) / 100; 23. double Periods = _wtof(m_Periods) / 12; 24. double InterestAmount = Principal * InterestRate * Periods; 25. double FutureValue = Principal + InterestAmount; 26. double MonthlyPayment = FutureValue / _wtof(m_Periods); 27. 28. m_FutureValue.Format(L"%.2f", FutureValue); 29. m_MonthlyPayment.Format(L"%.2f", MonthlyPayment); 30. 31. UpdateData(FALSE); } 32. Return to the dialog box 33. Double-click the Reset button 34. Implement the event as follows: 35. void CLoanPreparation1Dlg::OnBnClickedResetBtn() 36. { 37. m_CustomerName = L""; 38. m_EmployeeName = L""; 39. m_Principal = L"0.00"; 40. m_InterestRate = L"0.00"; 41. m_Periods = L"0.00"; 42. m_FutureValue = L"0.00"; 43. m_MonthlyPayment = L"0.00"; 44. m_FileSave = L""; 45. m_FileOpen = L"";
  65. 65. Prof. Erwin M. Globio, MSIT Page 65 of 66 46. 47. UpdateData(FALSE); } CHAPTER QUIZ COURSE TOPIC : Introduction to Visual C++/ MFC Application
  66. 66. Prof. Erwin M. Globio, MSIT Page 66 of 66 I. Objectives:  To learn and understand how to use visual c++ objects  To be able to apply Microsoft Foundation Classes II. Tasks / Procedure / Instructions: Make an MFC application that would ask the users to enter a pizza combo. Each combination has a corresponding price (set your own prices). Additional fees will be due for every extra toppings that the users may wish to add. The application must also compute for the total amount payable by the user (customer). See the sample output below.