C++ Chapter 3

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Chapter Three

 

Let us familiarize ourselves with C++ using a simple C++ program as an illustration.

 

//program-3.01 A sample C++ program

#include <iostream.h> //pre-processor dir (header file)

void main() //start of function main()

{ //opening brace-start of function

cout << "Hello!"; //function body

} //closing brace

 

Output: Hello!

 

The first line is called a preprocessor directive (it always begins with #); its purpose is to include the file called iostream.h (all such files end in .h extension and are called header files). The inclusion of this file is essential since it contains function declaration for cin, cout, etc. (that is, all input / output operations). There may be other header files such as <string.h>, <conio.h>, etc.

 

The next line is the function declaration. All C++ programs will have one function called main(); they may have other functions as well. All function names end in parentheses () (though they may not always be empty). The term void means it does not return any value (see later).

 

The function code is sandwitched between braces. There may be additional pairs of braces to mark what are called blocks or compound statements.

 

The function code consists of a single statement (

cout << "Hello!";

). This causes the string to be output on the console. Every statement is terminated by a semi-colon.

 

The << symbol (called insertion operator) directs the output stream, just as >> directs the input (see below). This is followed by the closing brace.

 

This program has to be compiled, linked and then executed. Before compilation the header files are replaced by the function declaration contained in them, the symbolic constants are replaced by their actual values, then they are checked for syntax. If there is no error then an executable object file is created. Linking refers to linking the file with other external files / modules.

 

The following sample program adds 12 and 18.

 

//program-3.02 To add two numbers

#include <iostream.h>

void main() //a method/function

{

int a = 12; //declare & initialize

int b = 18; //declare & initialize

int c; //declare - not initialized

 

/* Now add a, b and assign result to c */

 

c = a + b;

/* Output the result */

 

cout << "The sum is " << c;

}

Output:

The sum is 30

This is how a sample C++ program looks like. Just get the look and feel of it. Before we explain it in greater detail, some basic concepts should be understood. However four key points are:

 

C++ is case-sensitive

Pairs of braces should be matched correctly

All statements end in semi-colon

White spaces are discarded by the compiler, so we make liberal use of white spaces to improve readability

 

Now we analyze the program:

 

1. The double slash // or /* . . . */ is used to insert comments for documentation -ignored by the compiler (like REM in BASIC).

 

2. The sign // serves for a single-line comment, if the comment spills over to the next line, another // is needed. We may also use /* COMMENTS */ for comments and remarks, even if spanning several lines.

 

3. Every statement ends in a semi-colon (;)

 

4. It is a free-form language - spacing and indentations are strictly for our convenience. However, it is strongly recommended that proper indentation, as also proper documentation at every step, be strictly maintained for ease of understanding and editing.

 

5. Codes are enclosed within a pair of curly braces { }. This is true both for function main() as well for any other functions.

 

6. Additional pairs of braces may occur within the main braces enclosing parts of codes (groups of statements). Codes within braces form a BLOCK.

 

7. All variables shall be properly declared and (if necessary) initialized. Variables used without declaration would generate error during compilation.

 

Statement by statement analysis of the program:

 

 

(A)

The first line declares a method (function/process/procedure) named main(). All C++ program begin execution at main(). Thus every program must have the method main(); there may be additional methods.

 

(B)

The token main() is preceded by the keyword void (that is, it does not send back any value to its caller-or, in other words, main() does not return a value).

 

(C)

Every function is followed by a pair of parentheses, and the codes are enclosed within curly braces (block). There may be additional pair of braces within this to form nested blocks.

 

(D)

The single or comma separated list within the parentheses of a method are called its arguments. In this case, the argument list is empty. That is, in this case, the function does not take arguments and thus the name of the method is followed by empty parentheses.

 

(E)

The first 3 lines of the code declare 3 variables (a, b, c) all of integer type. We may write them in separate lines or in one line (int a=12, b=18, c;) - in the latter case the keyword int is written only once and the variables are comma-separated. In any case note the semi-colon at the end. The first two variables are also initialized to 12 and 18 and the third variable (namely, c) is declared but not initialized. We may initialize in the same statement as declaration (int a=12;) or in different statements (int a; a=12;) -- being a free-form syntax, it makes no difference whether the statements are written in one line or in different lines.

 

(F)

Now we add the variables a, b and assign the result to the third variable c, using the statement c = a + b; (note the semi-colon).

 

(G)

Lastly the result is displayed using cout << - a method for output to the console - terminating the same with a semi-colon.

 

(H)

Finally we close the code with the closing brace

}

 

 

Let us write another program - this time we find the square of a number:

 

//program-3.03 To find square of a number

#include <iostream.h>

void main()

{

int a = 15;

int b;

b = a * a; //calculate square

cout << "The square is " << b; //display

}

 

Output: The square is 225

Note the last line for displaying the output. This is what we call cascading.

That is, the statement (

cout << "The square is " << b;) is equivalent to two statements (cout << "The square is "; cout << b;).

The following program illustrates the use of cascaded

cout << and also illustrates the use of sizeof()

to extract the number of bytes in which various data types are stored.

#include <iostream.h>

void main()

{

cout << "Bytes for short = " << sizeof (short) << endl;

cout << "Bytes for int = " << sizeof (int) << endl;

cout << "Bytes for long = " << sizeof (long) << endl;

cout << "Bytes for float = " << sizeof (float) << endl;

cout << "Bytes for double = " << sizeof (double) << endl;

}

Output:

Bytes for short = 2

Bytes for int = 2

Bytes for long = 4

Bytes for float = 4

Bytes for double = 8

The facility is available for

cin >> as well. We use cin >>

for input from keyboard at run time. We will write the program to square a number using keyboard input. The >> symbol is called extraction operator.

//program-3.04 To find square of a number (keyboard input)

#include <iostream.h>

void main()

{

int a, b; //declare two int variables

cout << "Enter a number...";

cin >> a; //read value input from keyboard

b = a * a; //calculate square

cout << "The square is " << b; //display

}

Output:

Enter a number... 12

//12 is entered by user

The square is 144

//program-3.05 To change case of an input character

#include <iostream.h>

void main()

{

char ch; //declare a character variable

cout << "Enter an uppercase character...";

cin >> ch;

ch += 32; //uppercase ASCII value+32 = lowercase

cout << ch;

}

 

Output: Enter an uppercase character... M

//entered by user

m

The same thing may be achieved by using a ready-to-use prewritten, pre-compiled code available in C++ library. Using

 

tolower(character) function we get the same output as shown below. The function declaration for this library function is contained in a header file ctype.h, which is included.

 

#include <iostream.h>

#include <ctype.h> //include header file

void main()

{

char ch; //declare a character variable

cout << "Enter an uppercase character...";

cin >> ch;

char cap = tolower(ch); //a library function

cout << cap;

}

 

Output: same as before.

The following program finds the sum of three numbers numbers.

 

 

 

#include <iostream.h>

void main()

{

int a, b, c, s;

cout << "Enter 3 numbers ";

cin >> a;

cin >> b;

cin >> c;

s = a + b + c;

cout << "The sum is = ";

cout << s;

}

Using cascaded

cout, cin objects, the multiple cout << and cin >>

operator can be written thus:

#include <iostream.h>

void main()

{

int a, b, c, s;

cout << "Enter 3 numbers ";

cin >> a >> b >> c;

s = a + b + c;

cout << "The sum is = " << s;

}

In both the cases the input values may be entered one at a time, followed by the RETURN key or the three numbers may be entered in one line separated by space. This is because

cin >>

reads the keyboard entry until it encounters a white space (blank or tab or new line).

Output (first run)

Enter 3 numbers: 10

11

12 (press ENTER)

The sum is = 33

Output (second run)

Enter three numbers:

The sum is = 33

The following program illustrates another important feature.

#include <iostream.h>

void main()

{

int a, b, v;

cout << "Enter 2 numbers: ";

cin >> a >> b;

v = (a + b) / 2;

cout << "The average is = " << v;

}

Output (first run):

Enter two numbers: 10 12

The average = 11

 

//correct answer

Output (second run):

Enter two numbers: 5 8

The average = 6

//wrong answer; it should be

6.5

10 11 12 (press ENTER): (press ENTER)(press ENTER):

Perhaps it is because

v has been declared as an int variable. Rewrite declaring v as float

.

No use, the same error will persist. There is still another rectification to be made.

Consider the statement:

v = (a + b) / 2;

 

 

 

All the operands (variables) on the right side of the expression are integers. To get a

float answer, not only must the receiving variable (here v) be a float, but also at least one of the variables of the right side expression must be a float. The result of evaluating an expression in mixed mode arithmetic is that of the widest data type. So write v = (a + b) / 2.0; in place

v = (a + b) / 2;

Now the code executes correctly.

However if the variables

a, b as well as v are floats (or doubles) then v = (a + b) / 2

will work all right.

Global & Local Variables

Variables declared above the

main() and outside all functions are global variables. Variables declared within main()

or within a function are local variables. When there is no ambiguity, the simple variable name is used. When there is a global as well as local variable by the same name the simple variable name refers to the local one. To access the global one, we use the scope resolution operator (::) as shown below:

 

#include <iostream.h>

/* global variables */

int a = 5;

int b = 7;

void main()

{

int b = 2; //local variables

int c = 9;

cout << a << endl; //(1)

cout << c << endl; //(2)

cout << b << endl; //(3)

cout << ::b << endl; //(4)

}

Output:

5 //value of a (global) as there is no local a-----(1)

9 //value of c (local) as there is no global c-----(2)

2 //value of b (local) without :: operator--------(3)

7 //value of ::b (global) with :: operator -------(4)

 

When there is no ambiguity, the simple variable name is used, for example, in line (1) a refers to global since there is no local a. Similarly, in line (2) c refers to local c since there is no global c.

 

When there is a global as well as local variable by the same name, for example

b in line (3), (4), the simple variable name refers to the local one. To access the global one, we use the scope resolution operator (::) and ::b refers to the global b.

:

0

You have much knowledge

Niti Sharma's picture

You have much knowledge about C++