2 Writing First C++ Program

Jyoti Pareek

epgp books

Before writing first C++ program let us understand the steps of program creation and execution. We know that the solution of the problem that we want computer to perform for us has to be conveyed to the computer in the form of program written in programming language. From problem in hand to obtaining final output from the program, many steps need to be carried out.

 

Steps of Program Creation and Execution

 

1. Understanding the problem : To solve a problem first we need to understand what is to be done.

2. Formulating solution Once we understand what is to be done we need to work out how to solve it. We need to work out step by step solution for solving the problem in hand.

3. Writing Program Step by step solution that we have worked out is to be converted into programming language statements.

4. Keying in program using editor provided by programing environment or using independent editor

5. Preprocessing  The pre-processor transform our program before actual compilation. It performs transformations such as inclusion of header files, Macro expansion, Conditional compilation etc.

6. Compilation Program written in higher level programming language need to be converted in equivalent machine language program. This task is performed by the system software called compiler. Compiler takes as input a file with extension .cpp containing program written in higher level programming language, and produces equivalent machine language program in .obj file.

7. Linking object modules The object modules of library functions and functions defined in another program that have been called in the program, need to be included in the program to make it executable. Linker combines needed object modules with our object module to make it executable and generates. All the .obj files provided to linker are linked together and final executable program is produced in .exe file.

8. Loading .exe file in main memory  CPU can excess data from main memory only. So if we want our executable file to be executed, it has to be brought into main memory. Loader, a system software loads the executable file from secondary memory to main memory.

9.Executing .exe file The executable file can be executed by writing the name of the executable file without extension on command prompt. Also it can be executed by choosing appropriate menu option in Integrated Programming Environment (IDE)

 

 

 

The general structure of C++ program

 

1.   Documentation Section

2.    Preprocessor Directives / Compiler Directives Section Contains file inclusion directives, Macros etc.

3.  Global Declaration Section

4.  Class declaration or definition Section

5.  C++ program entry point – function main ( )

6.  Beginning of the main function:  Left brace {

(i)   Object/Variables declaration part

(ii)   Executable statements

7.  End of the main program: Right brace}

8.  Other user defined functions if needed

 

Let us understand the structure of C++ program with the help of simple hello world program. The following program does not have all the possible components of C++ program, but it does provide us the glimpse of basic structure of C++ program :

 

//     Program : Saying Hello with C++ #include <iostream>

 

void main()

{

 

std :: cout            << “Hello World ! I have begun my journey of learning Object oriented concepts and programming using C++” ;

 

}

//    note the semicolons; they terminate statements

 

/*   main( ) is a function that takes no arguments ( ) and returns an int (integer value) to indicate success or failure */

 

Basic components of Program Comments

 

Comments are parts of the source code disregarded by the compiler. They simply do nothing. Their purpose is to allow the programmer to insert notes or explanation of difficult code to make the program readable and easy to understand. C++ supports two ways to insert comments:

 

// line comment

/* block comment */

Line comment – discards everything from where the pair of slash signs (//) is found up to the end of that same line.

Block comment – discards everything between the /*characters and the first appearance of the */characters, it may run into multiple lines.

 

Header File <iostream>

 

When we want to use any function in our C++ program then first we need to import their declaration/prototype from C++ library, for importing their declaration we need to include header file in program by using #include.

 

Header files contain declarations of Functions, Macros and Variables, which is used into any C++ program. Header file have an extension “.h”.

 

The # symbol at the start indicates that this isn’t a C++ statement but it is the directive for the C++ pre-processor. Pre-processor processes pre-processor directives before the program is subjected to compilation. The #include tells the pre-processor to read in a text file and copy its contents in the program and treat it as if it was part of the program’s text.

For example:

 

·    #include<filename>          // includes predefined header file

 

Predefined header files contains declaration/prototype of functions which are provides to us in the form of C++ libraries. These functions are pre-created and their object modules are available with the compile. By means of including the header file we provide the declaration / prototype of these functions and variables to our program, which assures the compiler that the object module of these functions will be made available at the time of linking, and hence compiler allows us to use these functions in our program. Header files may also contain declaration of variables and definition of user defined data type.

 

·         #include”filename“//  includes user-defined header file  By means of including User defined header files, we can use user defined functions, variable and user defined data type defined in other file(s).

 

Output with cout

 

The cout is a predefined object of ostream class. It is associated with the standard output device, which is usually a display screen. The cout is used with stream insertion operator (<<) to display the output on a console.

 

The cin is a predefined object of istream class. It is associated with the standard input device, which is usually a keyboard. The cin is used with stream extraction operator (>>) to read the input from the keyboard.  We will discuss more about cin and cout in later modules.

 

Namespace std

 

A namespace is a named scope. When we use functions defined in more than one standard libraries and user defined libraries, it may happen that different libraries have functions of same name defined in them. In such case call to such function will create ambiguity as to which function out of many functions available with the same name is to be called. We can define variables, classes, functions, libraries etc. in different namespaces to avoid such naming conflict. The :: operator is used to specify that the function, object etc. that we are using belongs to which namespace.

 

For example, if we wish to use cout which is defined in std namespace std, we can write:

 

std :: cout << “String to be displayed… \n”;

 

or we can write a “using directive” as follows

 

using namespace std; // “make all names from namespace std available” cout << ” String to be displayed…\n”; // no need of std:: qualification cin >> x; // no need of std:: qualification

 

Statement Separator

 

In C++, the statements are separated using semicolon (;) at the end of the statement. Many statements can be written in a single line.

 

//     Program : Saying Hello with C++ #include <iostream>

 

void main()

{

 

std :: cout                          << “Hello World ! I have begun my journey of learning Object oriented concepts and programming using C++” ;

 

}

 

or each statement can be written in its own line.

 

//     Program : Saying Hello with C++ #include <iostream>

 

void main()

{

std :: cout        <<      “Hello World ! I have begun my journey of learning Object oriented

concepts and programming using C++” ;

}

 

The division of code in different lines serves only to make the program more readable and easy to use, but has no effect on the actual behavior of the program.

 

Compiling and Executing C++ Program

 

There are different compilers available for compiling the C++ Program. List is of available C++ compiler is long; some of them are listed below

 

1.      Borland C++ / Turbo C++

2.      Visual C++ [Microsoft Platform]

3.      Dev C++

4.      GCC

5.      Eclipse

 

We will discuss how to compile C++ program using GCC and Visual C++ compilers

Compiling and Executing C++ Program using GNU Compiler

 

The GNU Compiler Collection (GCC) includes front ends for C, C++ , Objective-C, etc., as well as libraries for these languages. GCC can be used on many different platforms, but is commonly used on Unix and Linux. It is also possible to use GCC on a windows machine you should take a look at Cygwin.

 

You can enter your program using any text editor and save it. After writing your program you can use the following command to compile the program: For c programs:

  • # gcc -o <output name> <your-source.c> For c++ programs:
  • # g++ <your-source.cpp> -o <output name>

On some systems, g++ is also installed with the name c++.

 

Note : To understand in detail how to compile C++ program with GCC compiler, please see the video in self-learning section.

 

Compiling and Executing C++ Program Microsoft Visual Studio Express

 

Microsoft Visual Studio Express is a set of integrated development environments (IDEs) developed by Microsoft as a freeware and registerware function-limited version of the non-free Microsoft Visual Studio. Express editions started with Visual Studio 2005.

 

Visual Studio Express was supplemented by the Visual Studio Community edition, which is also available for free. The community edition works with plugins, a feature that was previously exclusive to the paid editions (Professional and higher).

 

Note : To understand in detail how to compile C++ program with Microsoft Visual Studio Express , please see the video in self-learning section.

 

you can view video on Writing First C++ Program

Additional References

 

1) Stanley Lippmann, “C++ Primer”, Pearson Education.

2) Bjarne Stroustrup, “The C++ Programming Language”, Pearson Education.

3) Scott Mayer, “Effective C++”, Addison Wesley.

4) Bhushan Trivedi , Programming with ANSI C++, 2/e , Oxford University Press.

5) Yashavant P. Kanetkar “Let Us C++” , Bpb Publications.

6) Abhiram G. Ranade, “An Introduction to Programming through C++” , McGraw Hill

7) Ellis and B. Stroustrup “Annotated C++ Reference Manual”, http://www.stroustrup.com/arm.html

8) Herbert Schildt, “Complete Reference C++”, McGraw Hill Publications.

9) Ashok Kamthane, “Object Oriented Programming with ANSI and Turbo C++”, Pearson Education

10) E Balaguruswami, “Object Oriented Programming With C++”, Tata McGraw Hill

11) “C++ FAQs”, Pearson Education.