INPUT, PROCESS, OUTPUT (IPO) The computer is in a constant cycle of input, process,and output. The computer waits for you to enter the required information (input). Based on the entered information, the computer takes the appropriate actions (process). Finally, the result is displayed on the screen or printed out (output). An analogy for input, process and output would be a food processor where food, fruit and other ingredients are put into the machine. Afterward, based on the selected setting, such as cutting, chopping, or mixing, the food processor performs the appropriate task, and finally the desired mixture is ready to be used. THE MAIN SKELETON OF THE C AND C++ PROGRAM A C/C++ program has a main skeleton, regardless of how large or small it is. Every program starts with the word main, followed by an open parenthesis and closed parenthesis. The beginning of the program is marked with an open brace, and the end of the program is marked with a closed brace. Let me show you the simplest program one can create in both C and C++. main( ){ // Body of main… }//MAINFigure 2.1 - main( ) function of C/C++ program The fact remains that this program does not perform any task, and its sole purpose is to illustrate the main skeleton of every program. The word main in the program signifies that this is the main program (main function) where the main activities occur. There are sub-programs (functions) that originate (called) from the main program. After the word main, you observed an open parenthesis immediately followed by a closed parenthesis and nothing in between. The opening and closing braces indicates a block where the program statements will be written in between. THE MAIN PROGRAM WITH RETURN OR WITHOUT IT The nature of every program (function) in C/C++ requires that a value be returned to the point where it was originally activated (called), meaning that once the main program finishes its job, it will return to the operating system from where it was originally called. All that needs to be said for now is that you must type the statementreturn 0; at the very end of your program. You can return other numbers, but for now use zero by convention. Now, if you don’t want to be bothered with the return statement you can avoid it by simply placing the word void before the main( ).
Note that a semicolon ; is placed as a terminator at the end of every statement, which is an operation similar to the use of a period at the end of every sentence in natural languages. WHERE TO PUT AND WHERE TO NOT PUT THE SEMICOLON Similar to English sentences that end with a period, C/C++ statements end with a semicolon, as the statement return 0; ends with a semicolon. It should be understood that not every line of a program is a statement that requires a semicolon. As time progresses, you will find your own ways as to where to place or not to place a semicolon. In addition, the C/C++ compiler gives error messages when a semicolon is missing. However, there are cases in which that if you put a semicolon where it does not belong, you will cause problems. For now just try to remember not to put a semicolon after main(), after the opening { , after the closing } , and after the #include < >. A PROGRAM TO DISPLAY A MESSAGE You may have seen messages on a computer screen displaying a greeting, warning, or help menus. Keep in mind that for any of these messages there is a program, and an example of such a program is listed below.
MEANING OF WORDS AND SYMBOLS IN A C/C++ PROGRAM: KEY WORDS AND USER WORDS When you look at a C/C++ program, you see a series of words and symbols. You may attempt to make sense of them but you will not be sure of their relevance. There are two groups of words in a program: words that are introduced by the programmer (user words) and the words that are not introduced by the programmer but are part of C/C++ language (keywords) or part of its support libraries (system words). Keywords and system words are also known as reserved words since they are reserved for their originally intended purposes and the programmer cannot use them for other purposes. For example, the words main and return are key words, and the wordprintf and cout are C/C++ system words since they are from the C/C++ library. There are not that many key words in C/C++ (about 64), with only 10 that are frequently used, and the rest are used less than 10 percent of the time. WHAT CONSTRUCT OR WORD TELLS THE C/C++ PROGRAM TO DISPLAY? The words printf from C and cout from C++ tell the computer to display a message (echo), or to display a value or a result of an operation. Basically, anything outputted on a computer, whether through a screen or printer, can be done through these predefined routines or other similar constructs. To display a message it is enough to put the message in quotations. Anything typed within the quotations " " will be displayed as it is written. Of course, there are some exceptions, i.e. \n, \t and %d will not appear as written when placed inside the quotation, rather these symbols will instruct the computer how the output should be displayed. WHERE DID printf AND cout COME FROM? The mystery arises from the fact that printfand cout are not part of C/C++ keywords, but they are written in C and C++ and are stored in a library. The exclusion of certain elements from the programming language and their storage in designated libraries that can be readily accessed allows the language to be compact and fast. The printf is placed in the stdio.h library, while cout goes into the iostream.h library. The include routines (codes) stdio.h and iostream.h are known as directive header files which are placed at the top (head) of the program; by including these directives, cout and printf can be used as if they were part of your program. WHY INCLUDE stdio.h AND iostream.h HEADER FILES If you need to input data, or to display a message or result, you need to include at the top (head) the routines (codes) that do these jobs in your program. For example, #include <stdio.h> enables your program to access input/output (i/o) routines such as scanf and printfrespectively in C. Similarly, #include <iostream.h>enables your program to access i/o routines in C++. These routines are known as a directive file, where stdio.h stands for standard input/output header file while iostream.h stands for input/output stream header file. There are other information (files) in these libraries as well, but we will not concern ourselves with them at this time. At a later time you will make your own header file. LET’S WRITE A PROGRAM TO BUILD A MENU On occasions, you may have to select an option from a menu such as that of an ATM machine or a list of items displayed on a computer. How to write a program to display these menus? The basic idea is that you need to use output routines from either C or C++ such as printf or cout,respectively. Therefore, the program will consist of a series of cin or printf where each can have the desired displayed message within a double quotation known as literal. Later on you will be able to make the menu colorful and fancy by using the graphics routines. The following program will display a menu for your bank: 1. #include <stdio.h> 2. 3. main() { 4. printf(" Ebrahimi Bank of New York\n"); 5. printf(" Old Westbury, NY 11568\n\n"); 6. printf("\t 1. Deposit \t\t 2. Withdraw \n"); 7. printf("\t 3. Transfer \t\t 4. Loan \n"); 8. printf("\t 5. Balance \t\t 6. Help \n"); 9. return 0; 10. }//MAIN Figure 2.4 - C version of a menu using stdio.h include file and printf. 1. #include <iostream> 2. using namespace std; 3. main() { 4. cout << " Ebrahimi Bank of New York"<<endl; 5. cout << " Old Westbury, NY 11568"<<endl<<endl; 6. cout << "\t 1. Deposit \t\t 2. Withdraw"<<endl; 7. cout << "\t 3. Transfer \t\t 4. Loan"<<endl; 8. cout << "\t 5. Balance \t\t 6. Help"<<endl; 9. return 0; 10. }//MAIN Figure 2.5 - C++ version of menu using iostream.h include file and cout. Ebrahimi Bank of New York Old Westbury, NY 11568 1. Deposit 2. Withdraw 3. Transfer 4. Loan 5. Balance 6. Help Figure 2.6 - The output of Figure 2.4 and Figure 2.5.
5 + 3 = 8 5 - 3 = 2 5 * 3 = 15 5 / 3 = 1 5 rem 3 = 2Figure 2.7c - The output of both Figures 2.7a and 2.7b. KNOW YOUR ARITHMETIC OPERATION How would you perform arithmetic operations in C/C++? The plus sign + is used to add and minus sign - is used to subtract. The asterisk * is used for multiplication and the slash / for division. In C/C++ the symbol % is for the remainder of two numbers. However, there is no symbol for exponent, and the word pow is used instead. The function pow(m,n) computes m to the power of n and is a built-in function, which is stored in a library of, mathematical functions (math.h). In order to access mathematical function, you must include the following line at the top of your program. #include <math.h> C++ SEEMS EASIER THAN C When it comes to input and output, C++ routines are easier than C, especially for beginners. The input and output routines of C++, such as cin andcout are self- explanatory, whereas C input and output such as scanf and printf are hard to comprehend, since they leave many questions unanswered until the user attains the required knowledge. The fact that beginners have to format the input (scan with format) and output (print formatted) is questionable and troublesome. On the other hand, C++ provides the format for you (by default), however, it may not be precisely what you want. In I/O manipulation, C++ provides numerous routines dealing with a particular task. However, even experienced programmers find it overwhelming to recall the appropriate name for each task. Let’s not forget that real C++ is C with class that deals with object-oriented programming, which is tough to grasp for beginning programmers. USING WORDS AND NAMES TO REPRESENT DATA A program should be fully comprehensible, self-explanatory, and be broad in order to cover a greater range of data, thus not limited to a fixed set of data. The first step in accomplishing these requirements is to use meaningful names throughout the program. If a name contains a value and its value never changes throughout the program, it is constant, it should be declared as such by using the reserved word define or const, for example: const float PI = 3.14; If a name is not declared as a constant it is considered a variable, since a variable name can alter its content at different times. NAMING THE FIXED DATA BY define PREPROCESSOR A program becomes far more flexible and easier to change when a name is used to represent a value. The define preprocessor can be used to replace a name for fixed data. Before the compiler takes charge, the replacement takes place, for that reason define is known as preprocessor. When a change is necessary you only need to change the value once in the define section rather than changing it throughout the program. The preprocessor define can be used to replace more than just a value. Therefore, its usage becomes problematic in some C++ situations (not C), and as a result it is becoming obsolete in C++. Figure 2.8 and 2.9 below show the C and C++ versions of using define. 1. #include<iostream> 2. 3. #define FIRSTNUM 5 4. #define SECONDNUM 3 5. 6. main () { 7. printf( "%d+%d=%d\n", FIRSTNUM, SECONDNUM, FIRSTNUM + SECONDNUM ); 8. printf( "%d-%d=%d\n", FIRSTNUM, SECONDNUM, FIRSTNUM - SECONDNUM ); 9. printf( "%d*%d=%d\n", FIRSTNUM, SECONDNUM, FIRSTNUM * SECONDNUM ); 10. printf( "%d/%d=%d\n", FIRSTNUM, SECONDNUM, FIRSTNUM / SECONDNUM ); 11. printf( "%d%%%d=%d\n", FIRSTNUM, SECONDNUM, FIRSTNUM % SECONDNUM ); 12. return 0; 13. }//MAIN Figure 2.8a - C program using #define.
1. #include<iostream> 2. using namespace std; 3. #define FIRSTNUM 5 4. #define SECONDNUM 3 5. 6. main () { 7. cout << FIRSTNUM<<"+"<<SECONDNUM<<"="<<FIRSTNUM+SECONDNUM<<"\n"; 8. cout << FIRSTNUM<<"-"<<SECONDNUM<<"="<<FIRSTNUM-SECONDNUM<<"\n"; 9. cout << FIRSTNUM<<"*"<<SECONDNUM<<"="<<FIRSTNUM*SECONDNUM<<"\n"; 10. cout << FIRSTNUM<<"/"<<SECONDNUM<<"="<<FIRSTNUM/SECONDNUM<<"\n"; 11. cout << FIRSTNUM<<"%"<<SECONDNUM<<"="<<FIRSTNUM%SECONDNUM<<"\n"; 12. return 0; Figure 2.8b - C++ program using #define.
5+3=8 5-3=2 5*3=15 5/3=1 5%d=2 Figure 2.8c - Output to figures 2.8a and 2.8b.
1. #include<iostream> 2. using namespace std; 3. main () { 4. const int FIRSTNUM = 7; 5. const int SECONDNUM = 2; 6. 7. cout << FIRSTNUM << " + " << SECONDNUM << " = " 8. << FIRSTNUM + SECONDNUM << endl; 9. cout << FIRSTNUM << "- "<< SECONDNUM << " = " 10. << FIRSTNUM - SECONDNUM << endl; 11. cout << FIRSTNUM << "* "<< SECONDNUM << " = " 12. << FIRSTNUM * SECONDNUM << endl; 13. cout << FIRSTNUM << " / "<< SECONDNUM << " = " 14. << FIRSTNUM / SECONDNUM << endl; 15. cout << FIRSTNUM << " % " << SECONDNUM << " = " 16. << FIRSTNUM % SECONDNUM << endl; 17. return 0; 18. }//MAIN Figure 2.9a - C++ program using the const keyword.
7 + 2 = 9 7 - 2 = 5 7 * 2 = 14 7 / 2 = 3 7 % 2 = 1 Figure 2.9b - Output of figure 2.9a.
1. #include<iostream> 2. using namespace std; 3. main (){ 4. const int FIRSTNUM = 4; 5. const int SECONDNUM = 8; 6. const int THIRDNUM = 2; 7. cout << FIRSTNUM * SECONDNUM - THIRDNUM; 8. return 0; 9. }//MAIN Figure 2.10a - Compound Arithmetic - What is the order of operations? 30 Figure 2.10b - Output of figure 2.10a
Table 2.1 - Order of operations in C/C++.
1. #include<iostream> 2. using namespace std; 3. main () { 4. int firstnumber, secondnumber, thirdnumber; 5. 6. firstnumber = 1; secondnumber = 1; 7. thirdnumber = firstnumber + secondnumber; 8. cout << firstnumber << secondnumber << thirdnumber; 9. firstnumber = secondnumber; 10. secondnumber = thirdnumber; 11. thirdnumber = firstnumber + secondnumber; 12. cout << firstnumber << secondnumber << thirdnumber; 13. return 0; 14. }//MAINFigure 2.11 - What would the value of the variables be for both cout statements? WHAT IS A DATA TYPE? All variables used to hold data in a program must be declared by type as to whether it is numerically or non-numerically significant. Numerically significant data can be defined as int (integer) for whole numbers or float for numbers with fractions or mixed numbers. The char (character) data type is used for a letter, a symbol, a digit, etc. There are several variations for integers, such as short int, int, unsigned int, and long int, depending on the size of the number. Similarly double and long double are two possible variations of float numbers of larger sizes. Char represents non-numerical data types. There are other data types such as bool (for boolean) and enum (for enumeration) that are not used as frequently. DECLARING THE DATA TYPE: WHY BOTHER? Data type of a variable or a constant name must be stated at the time of declaration, for example, as to whether the value of a variable or a constant is numerical or non-numerical. Declaring the data type makes it possible for the C/C++ compiler to assign proper storage (save space to run faster and even detect and report improper operations on the data-type checking). NUMERICAL DATA TYPE Numbers, as data types, are grouped into two major forms: int (integer) and float. The numbers that have no decimal point or fraction are called int, such as 5, 32767, and -8. Numbers that are fractional, either having a decimal point or exponential, are considered to be of type float. For example 3.14, 5E is a float. The integer data type depends on its numeric size and can range from short, int, unsigned, to long integers. The data type double is used for larger float data type. WHAT IS A CHARACTER DATA TYPE A letter, a single digit, a sign, or symbols are all considered character data types (char). In a program, a character letter can be used to represent a letter grade. The plus symbol +, minus symbol -, etc. are all character data types. You can summarize by saying that any keyboard entry (strike) is a character. The following are some examples of character data types. char grade; char telephone[14]; WHAT IS INPUT AND WHERE DOES INPUT COME FROM? People have difficulty understanding the relationship between the input data and the program. Beginners have questions on how the input gets to the program and they expect detailed information, therefore, risking being overwhelmed. The relationship may require a simple solution, such as how to operate a telephone, or it may require a complex solution such as how the telephone operates. You may provide input to a program either interactively or through a pre-typed data file. As long as the type of input data matches the type of the variable, a program can execute even if the input values become different. An example of input to a payroll program would be an employee’s name, hours worked, and hourly rate, such as: John Doe 52 25.0. WORDS THAT TELL PROGRAMS TO INPUT The words that are responsible in bringing the data into the program are scanf in C and cin in C++. The syntax is very easy, straightforward, and has the following forms: scanf("%datatypeformat", addressofvariablename) and cin>>variablename. As scanf and cin capture the input data, they are stored in memory addresses. Each is identified by a variable name. As an example, scanf("%d", &hoursworked) and cin>>hoursworked would work the same way, by taking an input integer value and placing it in a memory location designated for hours worked of an employee. KNOW THE RULES OF DEFAULT JUDGMENT Whether it is for convenience, to avoid redundancy, or that C/C++ designers liked it that way, certain rules are pre-defined (defaulted). If you don’t define the rule explicitly, then the rule is defined implicitly for you. For example, if you don’t write anything before the word main in your program, indicating what kind of data type the main program should return, the data type int will be chosen for you by default - int main. In another example, if you don’t declare the storage class a variable should have, the language by default will set the variable storage class to auto (automatic). It is important to familiarize yourself with the default rules of C/C++ as you learn the language. HOW TO AVOID A RETURN VALUE It is required of every C/C++ program, to have a return value, such as return 0. If you happen to dislike the word return in your program, then place the word void before the word main in your program
Figure 2.12 - Avoiding a return value from the main( ) function.
1. #include<iostream> 2. using namespace std; 3. void main(){ 4. int firstnumber, secondnumber; 5. cin >> firstnumber >> secondnumber >> firstnumber; 6. cout << firstnumber << " " << secondnumber << " "<<firstnumber; 7. }//MAIN Figure 2.13 - Testing your understanding of computer memory.
1. #include<iostream> 2. using namespace std; 3. void main(){ 4. int yob, age; 5. cout << "ENTER YOUR YEAR OF BIRTH: "; 6. cin >> yob; 7. age = 2005 - yob; 8. cout << "Your age would be " <<age<<" by the year 2005.\n"; 9. }//MAIN Figure 2.14a - What will your age be by the year 2005? Interactive program with user
ENTER YOUR YEAR OF BIRTH: 1970 Your age would be 35 by the year 2005. Figure 2.14b - Output of figure 2.14a
1. #include<iostream> 2. 3. main() { 4. int firstnumber, secondnumber; 5. float thirdnumber, tempresult, finalresult; 6. printf( "WHAT IS THE FIRST NUMBER " ); 7. scanf( "%d",&firstnumber ); 8. printf( "WHAT IS THE SECOND NUMBER " ); 9. scanf( "%d",&secondnumber ); 10. printf( "WHAT IS THE THIRD NUMBER " ); 11. scanf( "%f",&thirdnumber ); 12. tempresult = firstnumber - secondnumber; 13. finalresult = tempresult * thirdnumber; 14. printf( "THE FINAL RESULT IS %f\n", finalresult ); 15. return 0; 16. }//MAINFigure 2.15a - C version of understanding computer memory. As you can see, there are not many differences until now except for the input and output. For the input and output C uses scanf and printf (see Figure 2.16 above), whereas C++ uses cin and cout (see Figure 2.17 below). The input and output of C require format specification, while C++ will use the default (pre-defined). For instance, scanf and printf, as the names suggest (scan-formatted, print-formatted) use %d for integer-whole number and %f for float (mixed number). The input and output of C++ does not require a format, but a default setup that can be reset is assigned. The word endl in C++ is used to insert a new line in output, while both C and C++ can use \n. 1. #include<iostream> 2. using namespace std; 3. main(){ 4. float firstnumber, secondnumber; 5. float thirdnumber, tempresult, finalresult; 6. cout << "WHAT IS THE FIRST NUMBER:"; 7. cin >> firstnumber; 8. cout << "WHAT IS THE SECOND NUMBER:"; 9. cin >> secondnumber; 10. cout << "WHAT IS THE THIRD NUMBER:"; 11. cin >> thirdnumber; 12. tempresult = firstnumber - secondnumber; 13. finalresult = tempresult * thirdnumber; 14. cout << "THE FINAL RESULT IS " << finalresult << endl; 15. return 0; 16. }//MAINFigure 2.15b - C++ version of understanding computer memory. WHAT IS THE FIRST NUMBER 12 WHAT IS THE SECOND NUMBER 9 WHAT IS THE THIRD NUMBER 4 THE FINAL RESULT IS 12.000000 ß For C THE FINAL RESULT IS 12 ß For C++ Figure 2.15c - Output to figure 2.15a and figure 2.15b using the same input.
1. #include<iostream> 2. using namespace std; 3. main(){ 4. int itemid, quantity; 5. float unitprice,taxamount,subtotal,totalprice; 6. float const SALESTAX = 0.085; 7. cout << "Please Enter the Item ID: "; 8. cin >> itemid; 9. cout << "Please Enter the Quantity: "; 10. cin >> quantity; 11. cout << "Please Enter the Unitprice: "; 12. cin >> unitprice; 13. subtotal = quantity * unitprice; 14. taxamount = subtotal * SALESTAX; 15. totalprice = subtotal + taxamount; 16. cout << "The Item's Id is "<< itemid << endl; 17. cout << "The Quantity is "<< quantity << endl; 18. cout << "The Unit Price is "<< unitprice << endl; 19. cout << "The SubTotal is "<< subtotal << endl; 20. cout << "The Tax Amount is "<< taxamount << endl; 21. cout << "The Total Price is "<< totalprice << endl; 22. return 0; 23. }//MAINFigure 2.16a - Starting shell of an invoice program. HOW DOES AN INVOICE PROGRAM WORK? The invoice program can be divided into three parts. In the first part, known as the input part, the necessary information is entered into the program, such as input data for quantity and unit price. Since the sales tax is fixed, it is assigned in the program as a constant. The second part, known as the processing part, deals with the computation of subtotals, tax amounts, and total prices. In the final part, the output, subtotals, tax amounts, and total prices are displayed. It is desirable to output the input values such as item’s id, unit price, as well as quantity. Please Enter the Item ID: 3445 Please Enter the Quantity: 30 Please Enter the Unitprice: 50 The Item's Id is 3445 The Quantity is 30 The Unit Price is 50 The SubTotal is 1500 The Tax Amount is 127.5 The Total Price is 1627.5 Figure 2.16b - Output of the invoice program of figure 2.16.
1. #include<iostream> 2. using namespace std; 3. main() { 4. int employeeid; 5. int hoursworked; 6. float hourlyrate, grosspay, taxamount, netpay; 7. float const TAXRATE = 0.20; 8. cout << "ENTER THE EMPLOYEE ID: "; 9. cin >> employeeid; 10. cout << "ENTER THE HOURS WORKED: "; 11. cin >> hoursworked; 12. cout << "ENTER THE HOURLY RATE: "; 13. cin >> hourlyrate; 14. grosspay = hoursworked * hourlyrate; 15. taxamount = grosspay * TAXRATE; 16. netpay = grosspay - taxamount; 17. cout << "EMPLOYEE ID IS " << employeeid << endl; 18. cout << "THE HOURS WORKED ARE " << hoursworked << endl; 19. cout << "THE HOURLY RATE IS " << hourlyrate << endl; 20. cout << "THE GROSSPAY IS " << grosspay << endl; 21. cout << "THE TAXAMOUNT IS " << taxamount << endl; 22. cout << "THE NETPAY IS " << netpay << endl; 23. return 0; 24. }//MAINFigure 2.17a - First version of a Payroll Program. HOW DOES THE PAYROLL PROGRAM WORK - FIRST VERSION The Payroll Program consists of three parts. The input part is where the information is entered and stored in memory locations. The input part is done through interaction with the user. The process part or computation part is where the calculation of gross pay, tax amount, and net pay takes place. Simple arithmetic, such as multiplication and subtraction, is used. For simplicity, the tax rate chosen at this time is a constant 20%. In the output part, the input variables and computational variables are displayed. The simple Payroll Program can be extended to cover other issues, such as variable tax rate, and overtime pay. The output for the payroll program can be observed in Figure 2.17b below. ENTER THE EMPLOYEE ID: 8756 ENTER THE HOURS WORKED: 40 ENTER THE HOURLY RATE: 25.25 EMPLOYEE ID IS 8756 THE HOURS WORKED ARE 40 THE HOURLY RATE IS 25.25 THE GROSSPAY IS 1010 THE TAXAMOUNT IS 202 THE NETPAY IS 808 Figure 2.17b - Output to Payroll Program of figure 2.17a
Table 2.2 - Build-in C/C++ Fucntions
|