Chapter 2

Basics of C++

CHAPTER OUTLINE
2.1   INTRODUCTION

A programmer must know rules and steps to develop programs with C++. Programs given in this book are developed using Borland’s C++ IDE compiler version 3.0. Let us try to follow the steps for creating, compiling and running programs under Borland’s C++ IDE compiler.

2.2   STEPS TO CREATE AND EXECUTE A C++ PROGRAM

For creating and executing a C++ program, one must follow various phases. The C++ program is created with an editor and saved with extension .cpp. Following this step, compilation and execution operations are to be performed. The following phases are essential in ‘C++’ when a program is to be executed in MS-DOS mode.

  1. Create
  2. Save
  3. Compile
  4. Execute.

We would now see the steps in each phase.

  1. Steps for creation of a C++ program
    • Open the Turbo C++ editor. In this book, the path selected for opening the C++ editor is C:TURBOC3TCBIN. Executable file TC is to be clicked in BIN file to open the window of C++.
    • In the Edit menu section with alt+f, select the New option. A new file is selected with this procedure.
    • The program should be written in ‘C++’ editor.
  2. Saving a C++ program
    • Save the program using the Save option in the file menu with extension .cpp. The reader may create his/her own folder where programs are to be stored. The file name does not necessarily include extension “.cpp.” The default extension is “.cpp.” The user can also specify his/her own extension. The C++ program includes preprocessor directives.
  3. Compilation of a C++ program
    • The source program contains statements that are to be translated into object codes. These object codes are used for execution by the computer. So, compile the source code with alt+c keys.
    • If the program contains errors, the programmer should correct it using C++ editor.
    • If there is no error in the program, compilation proceeds and the translated program is stored in another file with the same file name and with extension “.obj.” This object file is stored on a secondary storage device such as the disk.
  4. Linking and running/execution of a C++ program
    • The linking is also an essential process. It puts together all the program files and functions that are required by the program. For example, if the programmer is using pow() function, then the object code of this function should be brought from math.h library of the system and linked to the main() program. After linking, the program code is stored on the disk. The program code generated is called the executable code.
    • Run the executable code file with alt+r, in case of no errors. In case there are errors, correct the program, and follow steps (1), (2), (3), and (4).
2.3   FLOWCHART FOR CREATING A SOURCE FILE, COMPILING, LINKING AND EXECUTING IN C++

The following steps are necessary for execution of a program in C++.

  • Write the code for a program and save it
  • Compile the program with a compiler
  • Link the program with library functions
  • Run the program.

A flowchart for implementing the aforesaid steps is given in Figure 2.1

Figure 2.1

Figure 2.1 Flowchart for creating a C++ program, compiling and linking

The process of compiling, linking and running a program in C++ is elaborated in the following section.

2.4   C++ ENVIRONMENTS

C++ programs can be implemented on different operating systems such as UNIX, Linux, Windows, and DOS, etc. C++ programs executed under DOS environment can also run successfully under Windows, because we have to follow the same programming rules on both platforms. Only the C++ execution environments are different.

Various types of C++ compilers are described below.

  1. GNU C++: The GNU C++ is a compiler and it is available in the source code form. It is available in different versions.
  2. NDP C++: NDP C++ is also a C++ compiler, i.e. compatible with AT&T C++ 2.0 for DOS,UNIX, Sun OS, etc.
  3. Oregon C++: Oregon C++ is a C++ compiler compatible with AT&T C++ 2.0 for a variety of UNIX systems.
  4. Zortech C++ Version 2.1: This compiler has been developed for MS-DOS, OS/2, and UNIX.
  5. Borland C++: Borland C++ compiler is a combination of two compilers. They are ANSI standard C compiler and C++ compiler. It runs on MS-DOS. Borland C++ includes Turbo Assembler, Turbo Debugger, and Turbo Profiler.

In the following section, brief information for creating, compiling, and executing C++ programs are described using Borland C++ compiler.

2.5  TYPICAL C++ ENVIRONMENT (BORLAND C++)

In this section, brief information is given about the different platforms for C++ implementation, and execution of C++ programs using Borland C++ compiler under the Windows platform is described.

STEP 1: OPEN ANY TEXT EDITOR

Unix/Linux platform:

Use text editors such as Gedit, Kwrite, Medit, ed, VI, etc.

Windows platform:

Use text editors such as Notepad, Wordpad, etc.

Alternately, one can use integrated Borland C++ compiler, which supports its own text editor. Once Turbo C++ is installed, it automatically creates a directory turboc3 and subdirectory bin. Follow the path c: urboc3 and click the executable file tc. One can use desktop shortcut for turboc3. Turbo C++ screen appears, which is blank initially and has a menu bar at the top, which is shown as follows.

image

STEP 2: WRITE THE CODE FOR THE PROGRAM

Write the code to fulfill the requirements of the program, if possible using the proper syntax and indentation using an editor.

image

Alternatively, create a source program using integrated Turbo C++ editor. Go to the File menu and select New. The file name NONAME00.CPP appears on the screen at the centre of the window. Check whether your source program is typed correctly. If mistakes are found, correct them.

STEP 3: SAVE THE FILE WITH .CPP AS AN EXTENSION

image

Now press F2 to save your program or use Save option with .cpp extension. You can change the file name and save it using the Save option in File menu. In the following window the file is saved with ABC.CPP.

STEP 4: COMPILE THE PROGRAM

Unix/Linux platform:

Open the terminal window; change the working directory to the directory where the program file is stored.

Compile the program using the command: g++ filename.cpp

It will display the errors and warnings. If there are any errors and warnings, correct them and save the corrected file again.

After successful compilation, file a.out will be created in the same directory.

Windows platform:

Use IDE such as Turbo C++.

From the File menu, open the program file and compile it using ‘Compile’ option in Compile menu or use Alt+F9.

It will display the errors and warnings. If there are any errors or warnings, correct them and save the corrected file again, compile again. If program is correct, then the window shows:

  • Warnings: 0
  • Errors: 0

After successful compilation, a file filename.obj will be created in the same directory. The following window shows the compilation of a program named ABC.CPP.

image

STEP 5: RUN THE PROGRAM

Unix/Linux platform:

Use command ./a.out to run the program.

Windows platform:

Use ‘Run’ option from Run menu of Turbo C++ IDE or use ctrl+F9 and see the output as per program.

The following window shows execution of ABC.CPP program.

image
2.6   STRUCTURE OF A C++ PROGRAM

C++ programs consist of objects, classes, functions, variables, and other statements. Figure 2.2 shows four different parts of a C++ program.

  • Preprocessor directives (Include header files section): Preprocessing refers to the first step in compiling a C++ file from a source language into machine language. One of the most important features of C++ language is to offer preprocessor directives. The preprocessor directives are to be included at the beginning of the program before the main(). It begins with symbol# (hash). It can be placed anywhere, but quite often, it is declared at the beginning before the main() function or any particular function. In traditional C, # (hash) must begin at the first column.
    Preprocessor directives include header files
    Class declaration or definition
    Class function definitions
    The main() function and program

    Fig. 2.2 Parts of C++ program

    The following is a preprocessor directive that can be used in C++ programs besides many more.

    The #define directive

    For example

    #define PI 3.14

    This statement defines macro templates. During preprocessing, the preprocessor replaces every occurrence of PI (identifier) with 3.14 (substitute value). Here, PI is a macro template and 3.14 is its macro expansion. The macro templates are generally declared with capital letters for quick identification. One can also define macros with small letters. The macro templates and its expansions must be separated with at least one blank space. It is not necessary to provide space between # and define. It is optional to the programmer. To increase readability, the programmer should provide space.

    Include header files section

    One can write modular programs by making use of the #include directives. It is used to read the content of file that is included at the beginning of the program. Another file can be included at the start of the program with #include name_of_the_file.cpp.

    The C++ program also depends on some header files for function prototypes. They are used in the program. Each header file is to be extended with a .h extension. The file should be included using #include directive as per the format given below.

    Example: #include<iostream.h> or #include“iostream.h”

    In this example, <iostream.h> header file is included at the beginning by the programmer. This preprocessor directive is essential, which uses input/output statements such cin and cout. All the definitions and prototypes of the function defined in this file are available in the current program. This file also gets compiled with the original program.

    Besides the <iostream.h> header file, numerous other header files are used in programs in different chapters. Details of such header files are not given, which is beyond the scope of this discussion.

  • Class declaration or definition: Declaration of class is done in this section. In class definition, prototype or definitions of function are also declared.
  • Class function definitions: This part contains definition of functions. The definition of function can also be written outside the class but before main(). The outside definitions of function should need class name and scope access operator before the function name.
  • The main() function: Like C, C++ programs also start with the main() function. The execution of every program starts with the main() function. The programming rules for C++ are the same as C. However, there are a few differences that are discussed at appropriate places.
2.7   ILLUSTRATIVE SIMPLE PROGRAM IN C++ WITHOUT CLASS

A simple C++ program is as follows:      image

#include<iostream.h>

#include<conio.h>

// First Simple program

int main()

{

clrscr();

cout<<“ Hello! Welcome to the world of C++”;

return 0;

}

  • Every C++ program executes from the main().
  • Opening and closing braces are used for the beginning and ending of the program, respectively. Braces must be balanced. The number of opening braces should be the same as that of closing braces.
  • The flow of the program can be followed by proper documentation. One can use comments in the program. A comment statement starts with two successive back slashes with no space between them, i.e. it begins with a double slash symbol(//) in the program statement as shown in the above program. A comment can be placed anywhere in the line and it does not end with any symbol.

    Comment symbols similar to those used in C++ can also be used. In C, comment symbols /* and */ are used in programs. These symbols are also permitted in C++ programs.

  • Header files are needed at the beginning of the program; they include the definition of the functions that are used in the program. In the above program #include<conio.h> header file is used, which takes care of clrscr() and the header file #include<iostream.h> helps stream programming feature such as cout and cin .
  • The statement cout<<“ Hello! Welcome to the world of C++”; displays the string enclosed between the quotation marks and escape sequence is used to print the string on the next line.
  • The cout (C out) and << (insertion operator) are the identifiers used in C++.

In C++, int main() returns an integer value to operating system. Operating system checks whether the program is executed successfully. The return value of the function int main() is used for successful execution of the program. If the returned value is zero (0), it means that the program is executed successfully. A non-zero value indicates that the program execution was unsuccessful.

The prototype of main() function in C++ is as follows. The return statement is used in the program at the end of the main() function to return a value. If there is no return statement, the compiler displays a warning message “Function should return a value”. The default int is to be returned to the main() in case int is not specified in the main().

int main();

int main(int argc, char *argv[]);

C++ programs are coupled with class. A class encapsulates data and associated member functions. A detailed description is given in the classes and objects chapter in this book.

2.8   HEADER FILES AND LIBRARIES

This part describes library functions that are provided with the C++ compiler. The source code for these library functions are not provided, but they are in a compiled form. We have to link the code of the library functions with the compiled programmer’s code to form the entire program. The library functions perform operations such as managing memory, reading and writing disk files, input/output, mathematical operations, etc.

Numerous library functions are supported by different files. For example, math.h supports functions such as abs(), pow(), sqrt(), floor(), ceil(), etc. The conio.h supports functions such as getch(), getche(), clrscr(), gotoxy(), import(), etc. These files should be included while library functions are to be used in the programs. They are provided with C++ compiler. These files have the extension .h and they are called as header files. Table 2.1 gives a list of some of the header files and functions supported by them. The programmer is advised to refer library functions from the C++ compiler.

 

Table 2.1 The header files and library functions

Name of the header file
Function of the header file
List of the few functions supported by the header files
alloc.h

Memory management functions

calloc(), malloc(), free(), realloc(), etc.

complex.h

Complex math functions

asin(), atan(), arg(), tanh(), etc.

ctype.h

Automatic type conversion functions

toupper(), tolower(), islower(),isupper(), etc.

dos.h

Perform DOS functions

getdate(), gatetime(), int 86(),sleep(),etc.

graphics.h

Graphics functions

arc(), bar(), circle(), getx(), etc.

process.h

Process functions

exit(), abort(), system(), etc.

stdio.h

Standatrd input/output functions

puts(), gets(), fopen(), fclose(),printf(), getchar(), putchar(),etc.

stdlibh.h

Standard library functions

ato()l, atoi(), time(), abort(), etc.

string.h

Manipulates various string operations with different functions

strcpy(), strcat(), strlen(), etc.

time.h

Declare functions that manipulate time and date

time(), stime(), difftime(), local-time(), etc.

SUMMARY
  1. Steps to develop programs with C++.
  2. Phases of execution of a C++ program.
    • Create
    • Save
    • Compile
    • Execute
  3. Flowchart for creating a source file, compiling, linking and executing in C ++. Following four steps are described briefly

    Step 1: Open any text editor.

    Step 2: Write the code for the program.

    Step 3: Save the file with .cpp as an extension.

    Step 4: Compile the program.

    Step 5: Run the program.

  4. Structure of C ++ program.
  5. Header and library files.
EXERCISES

(A) Answer the following questions

  1. Explain the steps for execution of a C++ program using Borland C++ compiler.
  2. Show and explain the flowchart for creating, compiling, linking and executing a C++ program.
  3. What are the roles of header files?
  4. Compare main() functions of C with C++.
  5. Why do we use comment statements in the program. Write your answer to the point.
  6. Elaborate the structure of C++ program.
  7. Name the various C++ compilers that exist in the market other than the Borland C++ compiler.
  8. What do you mean by namespace?

(B) Answer the following by selecting the appropriate options

  1. To open a file in C++ with Turbo C++ editor, the key combination used is
    • alt+f
    • alt+o
    • alt+n
  2. To save a file in C ++ with Turbo C++ editor, the short key to be used is
    • F2
    • F3
    • F4
  3. To compile a file in C ++ with Turbo C++ editor, the key combination used is
    • alt+c
    • alt+k
    • alt+i
  4. To run a program in C++ with Turbo C++ editor, the key combination used is
    • alt+F9
    • ctrl+F9
    • ctrl+F10
  5. Comment line to be used in C++ starts with
    • \
    • //
    • **
  6. The following code is acceptable by machines/computers for the execution of a program
    • source code
    • object code
    • none of the above
  7. Every program in C++ must start with
    • {
    • }
    • main()
  8. A simple C++ program executes
    • with pre-processor directives
    • without pre-processor directives
  9. In C++ the function main has a default return type
    • float
    • integer
    • character
  10. The scope of the variable/s is/are confined
    • to a block
    • out of block
    • none of the above
  11. #include instructs the
    • compiler
    • assembler
    • none of the above
  12. #define is a
    • instruction
    • directive
    • decision statement
  13. The compiler translates source code into
    • octal code
    • object code
    • decimal
  14. Borland C++ consists of
    • ANSI standard C compiler
    • C++ compiler
    • both
    • none of these
  15. The iostream.h header file supports
    • input/output statements such as cin and cout
    • process management
    • memory allocation
  16. The exit() function is supported by the which of the following header files
    • math.h
    • process.h
    • graphics.h
    • dos.h
  17. The circle() function is supported by the which of the following header files
    • alloc.h
    • math.h
    • graphics.h
    • ctype.h
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset