Vous êtes sur la page 1sur 23

Chapter 3

C++
Introduction to C++ Language:
A C++ program is a collection of commands, which tell the computer to do
"something". This collection of commands is usually called C++ source
code, source code or just code. Commands are either "functions" or "keywords".
Keywords are a basic building block of the language, while functions are, in fact,
usually written in terms of simpler functions
Features of C++:

Structure of a Program:
// my first program in C++
# include<iostream.h>
#include<conio.h>
void main()
{
cout << "Hello World!";
getch();
}
Nirmala Foundation College of Commerce and Science

Page 1

Let's examine this program line by line:


Line 1: // my first program in C++
Two slash signs indicate that the rest of the line is a comment inserted by the
programmer but which has no effect on the behavior of the program. Programmers
use them to include short explanations or observations concerning the code or
program. In this case, it is a brief introductory description of the program.
Line 2: #include <iostream>
Lines beginning with a hash sign (#) are directives read and interpreted by what is
known as thepreprocessor. They are special lines interpreted before the
compilation of the program itself begins. In this case, the directive #include
<iostream>, instructs the preprocessor to include a section of standard C++ code,
known as header iostream, that allows to perform standard input and output
operations, such as writing the output of this program (Hello World) to the screen.
Line 3: A blank line.
Blank lines have no effect on a program. They simply improve readability of the
code.
Line 4: main ()
This line initiates the declaration of a function. Essentially, a function is a group of
code statements which are given a name: in this case, this gives the name "main"
to the group of code statements that follow. Functions will be discussed in detail
in a later chapter, but essentially, their definition is introduced with a name (main)
and a pair of parentheses (()), optionally including parameters.
The function named main is a special function in all C++ programs; it is the
function called when the program is run. The execution of all C++ programs
begins with the main function, regardless of where the function is actually located
within the code.
Lines 5 and 7: { and }
The open brace ({) at line 5 indicates the beginning of main's function definition,
and the closing brace (}) at line 7, indicates its end. Everything between these
braces is the function's body that defines what happens when main is called. All
functions use braces to indicate the beginning and end of their definitions.
Line 6: cout << "Hello World!";
This line is a C++ statement. A statement is an expression that can actually
produce some effect. It is the meat of a program, specifying its actual behavior.
Nirmala Foundation College of Commerce and Science

Page 2

Statements are executed in the same order that they appear within a function's
body.
This statement has three parts: First, cout, which identifies
the standard character output device (usually, this is the computer screen).
Second, the insertion operator (<<), which indicates that what follows is inserted
into std::cout. Finally, a sentence within quotes ("Hello world!"), is the content
inserted into the standard output.
Data types:
The data types in C++ are as shown below. While doing programming in any
programming language, you need to use various variables to store various
information. Variables are nothing but reserved memory locations to store values.
This means that when you create a variable you reserve some space in memory.
You may like to store information of various data types like character, wide
character, integer, floating point, double floating point, boolean etc. Based on the
data type of a variable, the operating system allocates memory and decides what
can be stored in the reserved memory.

C++ Data types

User defined type


Structure
Union
Class
Enumeration

Built-in type
Integer
Char
Void
Float
Double

Nirmala Foundation College of Commerce and Science

Derived type
Array
Function
Pointer

Page 3

Variables and its types:


Variable is defined as a portion of memory to store a value.
A variable definition means to tell the compiler where and how much to create the
storage for the variable. A variable definition specifies a data type, and contains a
list of one or more variables of that type as follows:
type variable_list;
For eg: int a;
Char b;
Float c;
Dynamic declaration of a variable:
C++ permits initalization of the variables at run time. This is called a dynamic
initialization.
For eg: we can write,
Float area=3.14*r*r;
Float avg=sum/i;
Observe that declaration and initialization of a variable can be done simultaneosly
at a place where the variable is used for the first time.
Dynamic initialization is extensively used in Object-Oriented Programming
Reference variable:
A reference variable provides an alternative name (alias) for a previously defined
variable. A refernce variable is created as follows:
Syntax:
Data_type & reference-name = variable-name
Nirmala Foundation College of Commerce and Science

Page 4

For eg: float total = 100;


Float &sum = total;
Here total and sum refer to same data type object in memory. If we change total
by total=total + 10;it will change value of both total and sum to 110.
Similarly sum=0; will change value of both variables to zero.
A reference variablemust be initialized at the time of declaration.

Operator in C++:
An operator is a symbol that tells the compiler to perform specific mathematical
or logical manipulations. C++ is rich in built-in operators and provides the
following types of operators:

Arithmetic Operators

Relational Operators

Logical Operators

Assignment Operators
Arithmetic Operators:
Operato
r

Description

Example

Adds two operands

A + B will give 30

Subtracts second operand


from the first

A - B will give -10

Multiplies both operands

A * B will give 200

Divides numerator by denumerator

B / A will give 2

Modulus Operator and


remainder of after an integer

B % A will give 0

Nirmala Foundation College of Commerce and Science

Page 5

division
Relational Operators:
Operator

Description

Example

==

Checks if the values of two


operands are equal or not, if
yes then condition becomes
true.

(A == B) is not true.

!=

Checks if the values of two


operands are equal or not, if
values are not equal then
condition becomes true.

(A != B) is true.

>

Checks if the value of left


operand is greater than the
value of right operand, if yes
then condition becomes true.

(A > B) is not true.

<

Checks if the value of left


operand is less than the value
of right operand, if yes then
condition becomes true.

(A < B) is true.

>=

Checks if the value of left


operand is greater than or
equal to the value of right
operand, if yes then condition
becomes true.

(A >= B) is not true.

<=

Checks if the value of left


operand is less than or equal to
the value of right operand, if
(A <= B) is true.
yes then condition becomes
true.

Logical Operators:
Operator

Description

Example

&&

Called Logical AND operator.


If both the operands are non-

(A && B) is false.

Nirmala Foundation College of Commerce and Science

Page 6

zero, then condition becomes


true.
||

Called Logical OR Operator.


If any of the two operands is
non-zero, then condition
becomes true.

Called Logical NOT Operator.


Use to reverses the logical
state of its operand. If a
!(A && B) is true.
condition is true, then Logical
NOT operator will make false.

(A || B) is true.

Assignment Operator:
Operator

Description

Example

Simple assignment operator,


Assigns values from right side
operands to left side operand

C = A + B will assign value of


A + B into C

+=

Add AND assignment


operator, It adds right operand
to the left operand and assign
the result to left operand

C += A is equivalent to C = C
+A

-=

Subtract AND assignment


operator, It subtracts right
operand from the left operand
and assign the result to left
operand

C -= A is equivalent to C = C A

*=

Multiply AND assignment


operator, It multiplies right
operand with the left operand
and assign the result to left
operand

C *= A is equivalent to C = C
*A

Nirmala Foundation College of Commerce and Science

Page 7

/=

Divide AND assignment


operator, It divides left
C /= A is equivalent to C = C /
operand with the right operand
A
and assign the result to left
operand

%=

Modulus AND assignment


operator, It takes modulus
C %= A is equivalent to C = C
using two operands and assign % A
the result to left operand

<< Insertion operator:


<< is insertion operator or put to operator. It sends (or inserts) the contents of the
variable on its right to the object on its left.
For eg: cout<<string;
This statement will display the contents of string. Here cout is a predefined object
that represents standard output stream in C++.
>>Extraction Operator:
The operator >> is extraction operator or get from operator. It extracts (or takes)
the value from the keyboard and assign it to the variable on its right. This is
similar tyo scanf operation in C Programming.
For eg: cin>>number1;
This statement causes the programmer to wait for the user to type in the number.
The number keyed in is placed in the variable number1. Cin is predefined object
in C++ that corresponds to standard input stream. Here it represent keyboard.
: : Scope Resolution Operator:
A C++ program may contain a block within a block..
Declaration of variable in an inner block hides a declaration of same variable in an
outer block. Therefore each declaration will cause refer to a different data object.
: : Scope resolution operstor can be used to uncover a hidden variable. It has the
form:
Nirmala Foundation College of Commerce and Science

Page 8

: : variable_name;
Memory Management operator:
C++ defines two unary operators new and delete,to perform task of allocating
memory dynamically at run time and freeing memory.
The new operator can be used to create objects of any type. It has the form:
Pointer_variable = new data type;
The new operator allocates sufficient memory to hold a data object of type
data_type and returns the address of the object. The pointer_variable holds the
address oof the memory space allocated.
For eg: p = new int;
Here p is pointer of type int ;
We can also initialize the memory using new operator.
Pointer_variable = new data type(value);
Here values specifies the initial value.
For eg: int *p = new int(25);
When data object is not needed , it is destroyed to release the memory space
for reuse. This is done by using operator delete. The general form of delete is :
Delete pointer_variable;
For eg: delete p;
Delete q;
Control Structures:
In C++, a large number of programs are used that pass messages and process the
data contained in objects. A function is set up to perform task. When the task is
complex, many different algorithms can be designed to achieve goal. The format
of program should be easy to trace the flow of execution of statements. There are
three types of control structures used in C++, they are as follows:
Nirmala Foundation College of Commerce and Science

Page 9

1. Sequential structure (straight line)


2. Selection structure (branching)
3. Loop structure (iteration or repetition)
In C++, if else and switch statements are used for selection structure. Do-while ,
while and for statements are used for loop structure.
a. The if statement
The if statement has two forms:
i.

Simple if statement

ii.

If-else statement
The simple if statement has the form:
If

(expression is true)

{
Action 1;
}
Action2;
Following is the general from of a typical decision making structure found in
most of the programming languages:

Nirmala Foundation College of Commerce and Science

Page 10

The if else statement has the form:


If

(expression is true)

{
Action 1;
}
Else
{
Action 2;
}
Action 3;

The switch statement:


This is a multiple-branching statement,where based ona condition,the
control is transfer to one of the many possible points. This statement has the
form:
Nirmala Foundation College of Commerce and Science

Page 11

Switch(expression)
{
Case 1:
{
Action 1;
}
Case 2:
{
Action 2;
}
:
:
Default:
{
Action x;
}
}

The do-while statement:


The do-while statement is an exist-controlled loop. Based on a condition ,
the control is transferred back to a particular pointinthe program.
The syntax is:
Do
{
Nirmala Foundation College of Commerce and Science

Page 12

Action 1;
}
While(condition is true)
The while statement
This is a loop structure ,but it is entry-controlled loop.
The syntax is:
While(condition istrue)
{
Action1;
}
Action 2;
The for statement
The for is an entry-controlled loop and is used when action is to be repeated
for a predetermined number of times.
The syntax is:
{
Action 1;
}
Action 2;
Functions in C++
A function is a group of statements that together perform a task. Every C++
program has at least one function, which is main(), and all the most trivial
programs can define additional functions.

Nirmala Foundation College of Commerce and Science

Page 13

You can divide up your code into separate functions. How you divide up your
code among different functions is up to you, but logically the division usually is
so each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
The C++ standard library provides numerous built-in functions that your program
can call. For example, function strcat() to concatenate two strings, function
memcpy() to copy one memory location to another location and many more
functions.
A function is knows as with various names like a method or a sub-routine or a
procedure etc.
Defining a Function:
The general form of a C++ function definition is as follows:
return_type function_name( parameter list )
{
body of the function
}
A C++ function definition consists of a function header and a function body. Here
are all the parts of a function:

Return Type: A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the keyword
void.

Function Name: This is the actual name of the function. The function name
and the parameter list together constitute the function signature.

Parameters: A parameter is like a placeholder. When a function is invoked,


you pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the

Nirmala Foundation College of Commerce and Science

Page 14

parameters of a function. Parameters are optional; that is, a function may contain
no parameters.

Function Body: The function body contains a collection of statements that


define what the function does.
Example:
Following is the source code for a function called max(). This function takes two
parameters num1 and num2 and returns the maximum between the two:
// function returning the max between two numbers
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Inline functions
C++ inline function is powerful concept that is commonly used with classes. If a
function is inline, the compiler places a copy of the code of that function at each
point where the function is called at compile time.
Any change to an inline function could require all clients of the function to be
recompiled because compiler would need to replace all the code once again
otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and define
the function before any calls are made to the function. The compiler can ignore
the inline qualifier in case defined function is more than a line.
Nirmala Foundation College of Commerce and Science

Page 15

A function definition in a class definition is an inline function definition, even


without the use of the inline specifier.
Following is an example, which makes use of inline function to return max of two
numbers:
#include <iostream>
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
// Main function for the program
Void main( )
{
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
getch();
}
When the above code is compiled and executed, it produces the following result:
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
Arrays in C++
An array is a collection of identical data objects which are stored in consecutive
memory locations under common variable name.
An array must be declared before it is used in C++ program. The general form for
declaration ofone dimensional array is:
Storage-class data type array-name[expression];
The storage class can be either external,static or an automatic. The data type is
data type of elements of array. The array-name can be any valid variable . the

Nirmala Foundation College of Commerce and Science

Page 16

expression is used todeclare size of the memory locations required. The storageclass is optional.
For eg: int marks[100];
Static char page[8];
The values to the array elements can be assgined as follows:
For eg: int values[7] = {1,2,3,4,5,6,7};
Program on array:
#include<iostream.h>
#include<conio.h>
void main()
{
Int a[100];
int i,n,large;
Cout<<how many numbers ?;
Cin>>n;
For(i=0;i<=n;i++)
{
Cin>>a[i];
}
large=a[0];
For(i=0;i<=n-1;i++)
{
If(large<a[i])
large=a[i];
Nirmala Foundation College of Commerce and Science

Page 17

}
Cout<<largest no:<large;
}

Pointers
A pointer is a variable which holds the memory address of the another variable.
The pointer has the following advantages:
1. It allows to pass variables,arrays,functions,strings and structures as function
arguments.
2. A pointer allows to return structured variables from functions.
3. It supports dynamic allocation and deallocation of memory segments.
4. With help of pointers,variables can be swapped without physically moving them.
5. It allows to establish link between data elements or objects.
Pointer variable consist of two parts:
(i)

Pointer operator

(ii)

Address operator
The pointer operator is a combination of * with a variable .
For eg. int *ptr;
Here ptr is a pointer variable which holds the address of integer data type.
All pointer variables must be declared before they are used.
The address pointer is represented by a combination of & with a pointer variable.
For eg. m=&ptr;
Eg of pointer:
#include<iostream.h>
Nirmala Foundation College of Commerce and Science

Page 18

Main()
{
int x;
int *ptr;
x=10;
Ptr=&x;
cout<<value of x=<<x;
cout<<content of ptr=<<*ptr;
cout<<address of ptr=<<ptr;
}
Pointers and functions
1. Call by value
The call by value method of passing arguments to a function copies the actual
value of an argument into the formal parameter of the function. In this case,
changes made to the parameter inside the function have no effect on the argument.
Void main()
{
funct(x, y)

// call by value

}
Void funct(int a , int b )
{
}
2. Call by reference
The call by reference method of passing arguments to a function copies the
reference of an argument into the formal parameter. Inside the function, the
Nirmala Foundation College of Commerce and Science

Page 19

reference is used to access the actual argument used in the call. This means that
changes made to the parameter affect the passed argument.
void main()
{
funct(& x, & y)

// call by Reference

}
Void funct(int * a , int * b )
{
}
String Functions in C++
Strlen()
Returns the length of string.
Strlen(Mumbai)
Will return 6 as a length of string Mumbai
Strcmp()
It compares two strings.
strcmp(s1, s2)
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2;
greater than 0 if s1>s2.
Strcat()
It concatenates two strings
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
Strrev()
It will reverse the string.
Strrev(mumbai)
Output will be iabmum
For examples :
Nirmala Foundation College of Commerce and Science

Page 20

1)
#include <iostream.h>
#include<conio.h>
#include <string.h>
void main( )
{
char S1[ ] = "test";
char S2[80];
strcpy(S2,S1);
cout << "String1: " << S1 << en
dl;
cout << "String2: " << S2 <<
endl;
getch( );
}
Output :
String1: test
String2: test
1)
#include <iostream.h>
#include <conio.h>
#include <string.h>
void main( )
{
char s1[80], s2[80];
strcpy(s1, "C++");
strcpy(s2, " is power programming.");
cout << "lengths: " << strlen(s1) ;
cout << ' ' << strlen(s2) << endl ;
if(!strcmp(s1, s2))
cout << "The strings are equal"<<endl ;
else
Nirmala Foundation College of Commerce and Science

Page 21

cout << "The Strings not equal<<endl;


strcat(s1, s2);
cout << s1 << endl;
getch( );
}

3)
#include <iostream>
#include<conio.h>
#include <string.h>
void main( )
{
char S1[ ] = "Nirmala College" ;
Cout<<strlen(S1)<<endl ;
getch( );
}
Output :

Nirmala Foundation College of Commerce and Science

Page 22

Nirmala Foundation College of Commerce and Science

Page 23

Vous aimerez peut-être aussi