INFORMATION FROM DR. EBRAHIMI'S C++ PROGRAMING EASY WAYS

Home                  ABOUT US                    CONTACT US                  TUTORIAL

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++.

 

Text Box:           
main( ){           
 
            // Body of main…
 
}//MAIN

  

 

 

 

 

 


 

    

Text Box: 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 statement return 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( ). 

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

Text Box:  
1.      #include<stdio.h>
2.      main(){
3.      printf(”Welcome to the world of C");                         
4.      return 0;
5.      }//MAIN

Text Box:  
1.      #include<iostream>
2.      using namespace std;
3.      main(){
4.      cout<<”Welcome to the world of C++";   
5.      return 0;
6.      }//MAIN

                                                             

 

 

 

 

 

 

 

 

 

Text Box: Figure 2.3a – Simple C screen output
Text Box: Figure 2.3b – Simple C++ screen output

  

 

 

 

Text Box: Welcome to the world of C
Text Box: Welcome to the world of C++

  

 

 

Text Box: Figure 2.3c – Output of figure 2.3a
Text Box: 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 word printf 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 printf and 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 printf respectively 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:

 

 

Text Box:  
    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
 
 
 
 

  

 

 

 

 

 

 

 

 

 

 

 

  


 

Text Box:  
    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
 
 

  


 

           

 

 

 

 

 

 

 

 

 

 

 

Text Box: Figure 2.5 – C++ version of menu using iostream.h include file and cout.

  

 

Text Box: Figure 2.6 – The output of Figure 2.4 and Figure 2.5.
Text Box:  
               Ebrahimi Bank of New York
                 Old Westbury, NY 11568
 
          1.  Deposit             2.  Withdraw
          3.  Transfer            4.  Loan
          5.  Balance             6.  Help

  

 

 

 

 

 

 

 

 

 

 

 

 


 

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.

                                                                     

Text Box:  
    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
Text Box: Figure 2.7b – C++ version of Simple Calculator.
 
Text Box:  
    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                                          
 
Text Box: Figure 2.7a – C version of Simple Calculator.

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Text Box: 5 + 3 = 8
5 - 3 = 2
5 * 3 = 15
5 / 3 = 1
5 rem 3 = 2

  

 

 

 

 

 

 

Text Box: 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 and cout 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++.

 

Hosted by www.Geocities.ws

1