CHAPTER 2

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…

}//MAIN
Figure 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( ). 

1.	#include<iostream>
2.	using namespace std;
3.	main(){
4.	     // Body of main…
5.	     return 0;
6.	}//MAIN
1.	#include<iostream>
2.	using namespace std;
3.	int main(){
4.	     // Body of main…
5.	     return 0;
6.	}//MAIN
1.	#include<iostream>
2.	using namespace std;
3.	void main(){
4.	     // Body of main…
5.	     // No return needed
6.	}//MAIN
Figure 2.2 - Different ways of returning to the terminating a C\C++ program

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.
1.	#include<stdio.h>
2.	main(){
3.	printf("Welcome to the world of C");
4.	return 0;
5.	}//MAIN
1.	#include<iostream>
2.	using namespace std;
3.	main(){
4.	cout<<"Welcome to the world of C++";
5.	return 0;
6.	}//MAIN

Figure 2.3a - Simple C screen output

Figure 2.3b - Simple C++ screen output

Welcome to the world of C
Welcome to the world of C++

Figure 2.3c - Output of figure 2.3a

Figure 2.3d - Output of figure 2.3b


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.

PRESENT AND DECORATE YOUR PROGRAM OUTPUT

The program’s output should be presentable, nice, and neat.  For the output to be clear and legible you must leave sufficient space and lines, so make sure that the output is grouped, aligned, and indented. Striking a spacebar on the keyboard will provide an output space. The use of tab \t will provide multiple designated spaces; for example, it may provide eight blank spaces; the  "\n" (back slash n) or endl (pronounced end el) will cause the output to be displayed on the next line.  The endl (end line) belongs to C++ and is equivalent to \n of C, although be sure to a place quotation around  \n when you use it.  

COMMENT YOUR PROGRAM

You do not just write a program for yourself. Others might need to read or follow your program, or you may forget what you have done. Therefore, you should insert comments in your program.  To comment in C you use /*        */.  This comment lets you use more than one line to describe what is going on.  To comment in C++ you use // and you are allowed only one line of comment. Although you may comment less with C++, its advantage is the use of less keystroke. Also in C, if you neglect to close the comment with */, the entire program after /* will be considered as a comment.  Be aware that C and C++ comments will not be executed.  Example of comments in C and C++ are shown below.

Comment in C: /* The payroll program written by A. Ebrahimi 8/14/98 */
Comment in C++: // The payroll program written by A. Ebrahimi 8/14/98

LET’S CREATE A SIMPLE CACULATOR

Before a computer became what it is today, it was merely a calculator doing arithmetic. Obviously today’s computers do more than just a computation of numbers and formulas. As a first trial with a computational program we are going to show you the program "Simple Calculator." The objective of this program is for you to familiarize yourself with arithmetic operations such as addition, subtraction, multiplication, division, and the remainder of two numbers.  Just type the following examples in the computer, run them in C and C++ and see the results.  The detail of running a program in C/C++ is shown in appendix A.
1.	 #include<stdio.h> 
2.	
3.	 main() {
4.	  printf( "5 + 3 = %d\n", 5+3 );
5.	  printf( "5 - 3 = %d\n", 5-3 );
6.	  printf( "5 * 3 = %d\n", 5*3 );
7.	  printf( "5 / 3 = %d\n", 5/3 );
8.	  printf( "5 rem 3 = %d\n", 5%3 );
9.	  return 0;
10.	 }//MAIN
1.	#include <iostream> 
2.	using namespace std;
3.	main () {
4.	   cout << "5 + 3 = " << 5+3 << endl;
5.	   cout << "5 - 3 = " << 5-3 << endl; 
6.	   cout << "5 * 3 = "<< 5*3 << endl;
7.	   cout << "5 / 3 = "<< 5/3 << endl;
8.	   cout << "5 rem 3 = " << 5%3 << endl;
9.	   return 0;
10.	}//MAIN

Figure 2.7a - C version of Simple Calculator.

Figure 2.7b - C++ version of Simple Calculator.

5 + 3 = 8
5 - 3 = 2
5 * 3 = 15
5 / 3 = 1
5 rem 3 = 2
Figure 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.

KEYWORD const : ANOTHER WAY TO NAME FIXED DATA

An alternative to the use of define would be the keyword const. The keyword const will allocate a memory location for that name, with the condition that its content will not change during the run time of the program. In addition to the keyword const there is a need for another keyword explaining what kind of data would be held as a constant in the memory location. This information can be used to assign enough space and further operations. For example, the key word int stands for integer number. Let’s look at the following program.

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.

C/C++ ARE SENSITIVE TO CASES

An uppercase letter has a different value than a lowercase letter.  As a result, an uppercase name is completely different from a lowercase name. You have to be consistent, and never use different cases for the same name in a program. The convention for constant name is to use uppercase letters, while variables and other names are shown in lowercase letters. One reason a constant name is shown in uppercase, is that it stands out and can easily be found and modified if needed.

COMPOUND ARITHMETIC OPERATION

How does a computer perform the following operations: 4 * 8 - 2?
By assigning each of the above numbers to a constant name, a program may look as follows:

  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

RULE OF OPERATOR PRECEDENCE:
WHAT IS THE DIFFERENCE BETWEEN 4 * 8 + 2 AND 2 + 4 * 8 ?


The result of both arithmetic expressions is the same: 34. One reason for this is that the multiplication is carried out before the addition. This notion follows the rules of precedence as dealt with in mathematics. The output to Figure 2.11 will be 30.

ORDER OF PRECEDENCE: PLEASE EXCUSE MY DEAR AUNT SALLY

The order of execution for arithmetic operations can be remembered by the following sentence:

Please Excuse My Dear Aunt Sally.

Please Parenthesis

Excuse

Exponent

My

Multiplication

Dear

Division

Aunt

Addition

Sally

Subtraction

Table 2.1 - Order of operations in C/C++.

This order of operation goes from left to right, which ever comes first. Yet, when it comes to a series of exponents, the operation goes from right to the left. Moreover, the minus sign has the highest order of precedence compared to other operation signs. Note that division and multiplication have the same order, just as subtraction and addition have the same order.   

WHY DO WE NEED A VARIABLE? ASSIGNMENT STATEMENT

How can addition be done before multiplication in this expression 2 + 4 * 8? One solution is to use parentheses and enclose the addition (2 + 4) * 8.  The second solution is to store the addition result in a temporary memory location and give it a name. The third number will then multiply the temporary memory location. This temporary memory is normally declared as a variable rather than a constant, since there are possibilities that it can be reused for other operations, as well as to be assigned a new value. 

                               tempresult = FIRSTNUM + SECONDNUM; cout << tempresult * THIRDNUM;

DECLARE A NAME AS A VARIABLE RATHER THAN CONSTANT

In C++ a variable name can be declared anywhere before its usage, while in C a variable name must be declared at the beginning of a block. The beginning of a block is marked by an open brace { and the end of a block is marked by a corresponding closing brace  }.

When declaring a variable it is necessary to provide other information, such as the type of data (data type) and the type of storage class (scope of variable). While it is essential for a user to explicitly provide the data type, the type of storage class can be set aside by the language as default if the user does not define it.  For example int age; is the same as automatic int age; where the variable age is declared as an integer data type with the storage class of automatic.

NAMING RESTRICTION FOR VARIABLES AND CONSTANTS

A name (identifier) must be at least one letter, or start with a letter followed by more letter(s) and/or digit(s). A name, whether a variable or a constant, cannot start with a number, include embedded blank space, or special characters, such as a dollar sign ‘$’ or a minus sign ‘-’.  Mysteriously, the underscore ‘_’ character is exempted and can be used to represent a name or to be part of a name.  The underscore is used to join names that consist of more than one word such as Hours_Worked instead of writing it as HoursWorked.  The following are legal variable names: N, Gross_Pay, GrossPay, _, and pay1. The following are illegal variable names: Gross-Pay, 2pay, gross pay (with a space between gross and pay).

CHOOSE THE RIGHT NAME FOR VARIABLES AND FOR CONSTANTS

The names of variables and constants should be self-explanatory and meaningful. In other words, they should represent what they are holding. For example, if you are computing gross pay, the variable names hours_worked, and hourly_rate are more suitable than abbreviating letters or words such as hw or hr, respectively, or choosing X and Y. Be consistent in your style when you write your names in lowercase or uppercase. The convention is to use uppercase for constant names.

WHAT WOULD BE THE OUTPUT? A VARIABLE NAME VARIES ITS VALUE

The output of a program is determined by the output routines of C and C++, such as printf and cout. The output of the following program is generated by cout, which will display the current content of the variables. In these three variables firstnumber and secondnumber are initially set to 1 and the sum of these two variables is set to the thirdnumber, which has the value of 2. The first cout will display the output as: 1 1 2. On the next line after cout, the content of the variable firstnumber is changed by the value of the secondnumber and the content of the secondnumber is changed by the value of the thirdnumber. Finally, the content of the thirdnumber is changed with the sum of the firstnumber and the secondnumber. After the above changes the final cout will display the current content of the variables firstnumber, secondnumber and thirdnumber, which is 1 2 3. 

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.	 }//MAIN
Figure 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
1.	#include<iostream>
2.	using namespace std;
3.	void main(){
4.	      // Body of main…
5.	      // No return
6.	}//MAIN
instead of
1.	#include<iostream>
2.	using namespace std;
3.	main(){
4.	      //Body of main…
5.	      return 0;
6.	}//MAIN

Figure 2.12 - Avoiding a return value from the main( ) function.

TEST THE COMPUTER MEMORY AS WELL AS YOUR OWN 

What would be the output of the following tricky program in Figure 2.13 be for the input 10 20 30? What goes in and what comes out? 

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.

At first glance, the quick response would be 10  20  30 as stated in the input data. However, with little thought you then realize that the output is simply 30 20 30. Why? It is important to remember that there are only two memory locations, namely, firstnumber and secondnumber.  Each can hold only a single value at a time. Therefore, the last value will replace the previous value.

WHAT IS AN INTERACTIVE PROGRAM?

When a program asks the user to respond and the user complies we have an interaction, i.e., an interactive program. For example, a program may display "your age by the year 2005", and ask the user to enter the year of his/her birth. Let us assume that he/she enters the input 1968. The program will then figure out his/her age by the year 2005 and then display it on the screen.

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

Try the program yourself. Can you tell what kind of input could cause a problem? There will be cases in which this program will give illogical answers.  We will examine this type of situation later.

COMPARISON OF C AND C++ UP TO NOW: SEE FOR YOURSELF

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.	 }//MAIN
Figure 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.	}//MAIN
Figure 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.

BUILDING LARGER PROGRAMS: SOFTWARE AN INVOICE PROGRAM

If you are wondering how big programs (software) can get, let me take a moment to show you the foundation of an invoice that can be enhanced and expanded as time goes by. Figure 2.18 shows the starting shell of an invoice program, which will be developed as the book progresses.

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.	}//MAIN	
Figure 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.

BUILDING A PAYROLL PROGRAM: THE FIRST VERSION

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.	 }//MAIN 
Figure 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

DON'T RE-INVENT THE WHEEL: USE BUILT-IN FUNCTIONS

There are numerous programs that are pre-written and are part of C/C++ libraries. Simply admitting them into your program will allow you to use them as if you had written them yourself. These pre-written programs are known as built-in functions.

There are hundreds of these built-in functions that you can use. There are libraries full of them!  While you may not be interested in some specific tasks, it is good for you to know that these built-in functions are available. If the need arises, you can use them without having to reinvent the wheel. You may at some point build your own function from scratch or modify the existing built-in functions.

Table 2.2 below contains a list of some built-in C/C++ functions:

Function

Result

pow(m,n )

The function takes two variables( m and n ) and returns the power of m raised to n. ( Power function ).

sqrt(n)

The function takes a variable n and returns the square root of n.

rand( )

The function takes no arguments and returns a generated random number (think of lottery numbers).

time( )

The time function takes no parameters and gives the time/date of the system.



strcmp(m,n )

The function compares two strings, m vs n (e.g. names, telephones, etc.).  Zero (0) is returned if the two strings are equivalent.  If string m is less than string n, a negative value is returned. Otherwise a positive value is returned, as string m is greater than string n.

strcpy(n,m)

The function copies the content of string m into string n. (backup of a name)

clrscr( )

The function takes no arguments and clears the screen.

Table 2.2 - Build-in C/C++ Fucntions

CLOSING REMARKS AND LOOKING AHEAD

A program can be divided into three major parts. First is the input part, where data is written into the program and stored in memory locations that the programmer names. The second major part is the process part where the computation takes place and the result is created and stored. The third and final part is the output part, where the required information, whether from input or from the process part, is displayed.

The system words cinof C++ and scanf of C are responsible for grabbing the input data from the keyboard. As part of the process, the assignment statement (designated by an = sign) is used to change the content of a variable.  Basic arithmetic operations such as addition, subtraction, and multiplication, do most of the computation. The word coutof C++ and printf of C are responsible for displaying the information on the screen.

User names are used as identifiers to hold different kinds of data. However, a name must be declared before it is used. It is also necessary to indicate what type of the data is going to be held. The basic data types are int, which stands for integer-whole number, float that stands for numbers with fractions or mixed numbers, and char that stands for a character that includes a letter, a digit, a sign, etc.

Up to now, you have seen small and simple programs. In the next chapter, this will change, as you will learn about the concept of repetition with the loop. The loop is one of the greatest strengths of programming. It has the ability to repeatedly pull in information, process it, and display it as many times you want, or for as long as some information remains. I am certain that you will be impressed.