1

CHAPTER INTRODUCTION TO C++ PROGRAMMING

What is C++?

C++ is an object-oriented programming language. It is superset of C with extension to support OOP. It was developed by BjarneStroustrup. C++ is a combination of C and the increment operator '++'.

Primary new features includes:-

  1. MultipleInheritences
  2. Abstract Classes
  3. Pointer to Class Members
  4. Additional Operator Overloading

General Rules of C++ Syntax

  1. Every program must have one main().
  2. Every statement in C++ will be terminated by Semilcolon.
  3. C++ is Case Sensitive Programming Language.
  4. Compiler compile the program function from TOP to Bottom, and also give the syntax error.
  5. The execution will be started from main(), and also program terminated at main().
  6. Every function must have a functionality, written in block, which consists of a pair of Curly Braces.
  7. Predefined feature of C++, include the appropriate Header File.
  8. All the file save it with file_name>.cpp .

Compiler: It compiles the source file into object file (.OBJ). Linking combines the object file with executable file (.EXE).

Shortcut Key for compile: Alt + F9

Running: the program: to Run the .EXE file to execute the program.

Shortcut Key for Run (Execute): Ctrl + F9

'main()': execution of every program

'iostream.h' : header file

'#' : preprocessor

'#include<iostream.h': preprocessor directive

'cin' : Keyword used for input

'cout': Keyword used for output

'cin' and 'cout' keywords include in iostream.h header file.

'clrscr' and 'getch()' defines in <conio.h> header file.

Input Operator:(Takes the value from the user (keyboard) & assigns it to the variable from Right.) [cin>num;]

Output Operator: (Send the contents of the variable to the screen) [cout<num; ]

COMMENTS: Does not comes in the execution of program. Symbol:  in same line, /*-----*/ for many line.

3

C++ Identifiers:

Identifiers: These are user defined names. Like variables and functions names.

A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).

C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a case sensitive programming language. Thus Manpower and manpower are two different identifiers in C++.

Here are some examples of acceptable identifiers:

mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal

Valid Identifier:

int num1;

int num;

introll_num;

int _num;

int N1um;

C++ Keywords:

Keywords: It is a predefined meaning of C++ that cannot be changed.

Eg. If, else, continue, float, into char, void, while, main.

The following list shows the reserved words in C++. These reserved words may not be used as constant or variable or any other identifier names.

asm / else / new / this
auto / enum / operator / throw
bool / explicit / private / true
break / export / protected / try
case / extern / public / typedef
catch / false / register / typeid
char / float / reinterpret_cast / typename
class / for / return / union
const / friend / short / unsigned
const_cast / goto / signed / using
continue / if / sizeof / virtual
default / inline / static / void
delete / int / static_cast / volatile
do / long / struct / wchar_t
double / mutable / switch / while
dynamic_cast / namespace / template

Variables

A variable is a named memory location, which has a name, a data type, the specific size of memory and a range.It is a data name that is used to store data value for easy retrieval. Eg.Totsalary, stdname etc.

Data Types:

The data type will have characteristics such as the range of values that can be stored and the operations that can be performed on variables of that type.(tell the compiler which type of data we want to store.)

There are 3 types of C++ data types:

Basic data types(Built-in Data types) are:

Name / Description / Size* / Range*
char / Character or small integer. / 1byte / signed: -128 to 127
unsigned: 0 to 255
short int(short) / Short Integer. / 2bytes / signed: -32768 to 32767
unsigned: 0 to 65535
int / Integer. / 4bytes / signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
long int(long) / Long integer. / 4bytes / signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
bool / Boolean value. It can take one of two values: true or false. / 1byte / true or false
float / Floating point number. / 4bytes / +/- 3.4e +/- 38 (~7 digits)
double / Double precision floating point number. / 8bytes / +/- 1.7e +/- 308 (~15 digits)
long double / Long double precision floating point number. / 8bytes / +/- 1.7e +/- 308 (~15 digits)
wchar_t / Wide character. / 2 or 4 bytes / 1 wide character
  1. Boolean Type

The Boolean type can have the value true or false. For example:
[indent]boolisEven = false;
boolkeyFound = true;

  1. Character Type

The character type is used to store characters - typically ASCII characters but not always. For example:
char ch;

charch = '3';

char ch=’A’;

  1. Integer Types

The integer type is used for storing whole numbers. We can use signed, unsigned or plain integer values as follows:
signed int temperature = -32;
unsigned int count = 0;
int height = 100;
int balance = -67;

  1. Floating-Point Types

Floating point types can contain decimal numbers, for example 1.23, -.087. There are three sizes, float (single-precision), double (double-precision) and long double (extended-precision). Some examples:
[indent]floatcelsius = 37.623;
double fahrenheit = 98.415;
long double accountBalance = 1897.23;

Variable Declaration in C++:

All variables must be declared before use, A declaration specifies a type, and contains a list of one or more variables of that type as follows:

typevariable_list;

Here, type must be a valid C++ data type including char, w_char, int, float, double, bool or any user defined object etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here:

int i, j, k;
char c, ch;
float f, salary;
double d;

A variable declaration with an initializer is always a definition. This means that storage is allocated for the variable and could be declared as follows:

int i = 100;

An extern declaration is not a definition and does not allocate storage. In effect, it claims that a definition of the variable exists elsewhere in the program. A variable can be declared multiple times in a program, but it must be defined only once. Following is the declaration of a variable with extern keyword:

extern int i;

Variable Initialization in C++:

Variables are initialized (assigned an value) with an equal sign followed by a constant expression. The general form of initialization is:

variable_name = value;

Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows:

typevariable_name = value;

Some examples are:

int d = 3, f = 5; // initializing d and f.

byte z = 22; // initializes z.

double pi = 3.14159; // declares an approximation of pi.

char x = 'x'; // the variable x has the value 'x'.

Scope of variables

All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous code at the beginning of the body of the function main when we declared that a, b, and result were of type int.
A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block.

Global variables can be referred from anywhere in the code, even inside functions, whenever it is after its declaration.
The scope of local variables is limited to the block enclosed in braces ({}) where they are declared. For example, if they are declared at the beginning of the body of a function (like in function main) their scope is between its declaration point and the end of that function. In the example above, this means that if another function existed in addition to main, the local variables declared in main could not be accessed from the other function and vice versa.

Local Variables:

Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Following is the example using local variables:

#include <iostream
using namespace std;
int main ()
{
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout < c;
return 0;
}

Global Variables:

Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the lifetime of your program.

A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables:

A program can have same name for local and global variables but value of local variable inside a function will take preference. For example:

#include <iostream
using namespace std;
// Global variable declaration:
int g = 20;
int main ()
{
// Local variable declaration:
int g = 10;
cout < g;
return 0;
}

When the above code is compiled and executed, it produces following result:

10

CONSTANTS

Constaints: It has a fixed value throughout the program. Classified into:

*Numeric Constant: Integer Constant, Real Constant (decimal).

*Character Constant: Character Constant (''), String Constant ("").

const type variable = value;

Enumerated Data Type

An enumerated data type is another user-defined type which provides a way for attaching

names to numbers, thereby increasing comprehensibility of the code. The enum keyword

automatically enumerates a list of words by assigning them values 0,1,2, and so on. This facility provides an alternative means for creating symbolic constants. The syntax of an enum statement is similar to that of the struct statement. Examples:

enum shape{circle, square, triangle);

enumcolour(red, blue, green, yellow); enum position(off, on);

The enumerated data types differ slightly in C++ when compared with thoe in ANSI C. In C++, the tag names shape, colour, and position become new type names. By using these tag names, we can declare new variables. Examples:

shape ellipse;// ellipse is of type shape

colour background;// background is of type colour

This is used in advance when we know the finite number of values a variable can take in a program.

'enum' : defines the set of all names that will be permissible values of the type.

'Enumerated' means that all values are listed.

Eg: Sunday=10, Monday=20 and so on….

Program:

#include<iostream.h

enumdays_of_week {sun=1,mon=2,tue=3,wde=4,thu=5,fri=6,sat=7};

void main()

{

days_of_week day1,day2;

day1=mon;day2=thu;

int diff = day2-day1;

cout<”days between=”<diff<endl;

if(day1<day2)

cout<”day1 comes before day2 \ n”;

}

Operator: It isdefined as a symbol that tells compiler to perform mathematical and logical manipulations.

1)Assignment Operators: Values needs to be assigned to variables. The '=' operator is used for assignment.

Int a = 5;

Syntax: Variable-name = expression;

Eg: Sum=a+b;

2)Arithmetic Operators: These operators can operate on any built-in data types like int, char, float. For modulus, float will be used.

OperatorsMeaning

- Subtraction

+ Addition

*Multiplication

/Division

%Modulus (Returns the remainder of the division)

3)Relational Operators: Operators can be used to test the relationship between variables and constant.

Eg: (salary= = 4000) OR (a>b)

OperatorsMeaning

= =equal to

greater than

less than

!=not equal to

>=greater than or equal to

<=less than or equal to

4)Logical Operators: These are symbols used to combineexpressions with relational operators.

OperationOperator

AND

ORII

NOT!

Eg: ((x>7) & (x<14)

(Salary >= 4000 & salary <=5000)

5)Increment/Decrement Operator: The ++ operator adds 1 to the operand and - - operators decrements 1 from the operand.

Syntax: ++ variable; (Post Operator)- -variable(Pre-Operator)

Variable=variable+1 ORvariable += 1

Variable=variable-1 ORvariable- =1

Variable++variable- -(post-operator)

Eg:int 1 = 5;

a= i++;a= ++i

a will be 5a will be 6

i will be 6a will be 6

6) Conditional Operator:Compressed version of if…..else statement. It is also known as TERNARY Operator.

Eg: c = ( a > b) ? a : b;

Where, a, boperands

?:is the conditional operator,

is the relational operator.

If the condition is true then the value a is assigned to c else b is assigned to c.

For more details Refer the book “OBJECT – ORIENTED PROGRAMMING WITH C++” Chapter 3