C++ Programming: Arrays in C++ 1) One Dimensional Array
C++ Programming: Arrays in C++ 1) One Dimensional Array
C++ PROGRAMMING
ARRAYS IN C++
1) ONE DIMENSIONAL ARRAY
An array (Linear) is a series of elements of the same type (Homogenous data elements)
placed in contiguous memory locations that can be individually referenced by adding an
index number to a unique identifier.
That means that, for example, we can store 5 values of type int in an array without having
to declare 5 different variables, each one with a different identifier. Instead of that, using an
array we can store 5 different values of the same type, int for example, with a unique
identifier.
For example, an array to contain 5 integer values of type intcalled NUMcould be represented
like this:
Where, each blank panel represents an element of the array, that in this case are integer
values of type int. These elements are numbered from 0 to 4 since in arrays the first index
is always 0, independently of its length.
Like a regular variable, an array must be declared before it is used. A typical declaration for
an array in C++ is:
Syntax: data_typearray_name[subscripted Value];
wheredata_type is a valid type (like int, float...), array_name is a valid identifier and
the elements field (which is always enclosed in square brackets [], specifies how many of
these elements the array has to contain and it should be +ve integer number or variable.)
Therefore, in order to declare an array called NUM as the one shown in the above diagram it
is as simple as:
int NUM [5];
INITIALIZING ARRAYS:
When we declare an array, we have the possibility to assign initial values to each one of its
elements by enclosing the values in braces { }. For example:
int NUM [5] = { 16, 2, 77, 40, 12071 };
This declaration would have created an array like this:
1) The amount of values between braces {} must not be larger than the number of
elements that we declare for the array between square brackets [].
P a g e | 38
Computer Science ( D9) : XII - Paper –I
2) When an initialization of values is provided for an array, C++ allows the possibility of
leaving the square brackets empty []. In this case, the compiler will assume a size for
the array that matches the number of values included between braces {}:
Solve Problem: 1) print the content of array in reverse order 2) Sort the content of
array in ascending/descending order using Bubble Sort method.
CHARACTER ARRAY:
The strings are in fact sequences of characters; we can represent them also as plain arrays of
char elements.
For example, the following array:
charst [20];
is an array that can store up to 20 elements of type char. It can be represented as:
P a g e | 39
Computer Science ( D9) : XII - Paper –I
Notice how after the valid content a null character ('\0') has been included in order to
indicate the end of the sequence. The panels in gray color represent char elements with
undetermined values.
INITIALIZATION OF NULL-TERMINATED CHARACTER SEQUENCES
Because arrays of characters are ordinary arrays they follow all their same rules. For example, if we want to
initialize an array of characters with some predetermined sequence of characters we can do it just like any other
array:
charmyword[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
In this case we would have declared an array of 6 elements of type char initialized with the
characters that form the word "Hello" plus a null character '\0' at the end.
But arrays of char elements have an additional method to initialize their values: using string
literals.
For example, cin and cout support null-terminated sequences as valid containers for
sequences of characters, so they can be used directly to extract strings of characters from cin
or to insert them into cout. For example:
// null-terminated sequences of characters Please, enter your first name: John
#include <iostream.h> Hello, John!
void main ()
{
char question[] = "Please, enter your first
name: ";
char greeting[] = "Hello, ";
charyourname [80];
cout<< question;
cin>>yourname;
cout<< greeting <<yourname<<"!";
}
Solve problem:
1) Convert upper case string into lower case and vice versa
2) Count number of words and characters in the string
Hint: (0-255 ASCII characters: A/a -26+26, no.-10,sysmbols-32,control char-34, graphic char-128)
A->65--Z->90;a->97—z->122
P a g e | 40
Computer Science ( D9) : XII - Paper –I
P a g e | 41
Computer Science ( D9) : XII - Paper –I
POINTERS TO FUNCTIONS:
Q. What is Call by reference? What is the advantage of call by reference over call by value?
1. Call by value and Call by reference
// call by Value // function Define // call by reference USING // define function
#include void swap(int X, int Y) POINTER void swap(int *X, int *Y)
<iostream.h> { #include {
#include<conio.h> int T; <iostream.h> int T;
void main () T=X #include<conio.h> T = *X
{ X= Y; void main () *X= *Y;
void swap(int ,int) Y = T; { *Y = T;
int A, B; } void swap(int * ,int *) }
cout<<”Enter the value of A int A, B;
and B”; cout<<”Enter the value of
cin>> A >> B; A and B”;
cin>> A >> B;
cout<<”Before swap the
content of A and B are “ cout<<”Before swap the
<<A <<B; content of A and B are “
<<A <<B;
swap(A , B);
swap(&A ,& B);
cout<<”After swap the
content of A and B are “ cout<<”After swap the
<<A <<B; content of A and B are “
getch(); <<A <<B;
getch();
}
}
P a g e | 42
Computer Science ( D9) : XII - Paper –I
After that, p and numbers would be equivalent and would have the same properties.
P a g e | 43
Computer Science ( D9) : XII - Paper –I
Include files
Class declaration
DECLARATION OF CLASS:
A class is way to bind the data and its associated functions together. It allows the data (and
functions) to be hidden.
Classes are generally declared using the keyword class, with the following format:
classclass_name
{
private:
Variables declarations; // data members
Functions declarations; // member functions
public:
Variables declarations;//data members
Functions declarations;//member functions
};
P a g e | 44
Computer Science ( D9) : XII - Paper –I
wherethe class_name is identifiers for the class. The body of the declaration can contain
members that can be either data or function declaration, and optionally access specifiers.
Access specifiers is one of the following three keywords: private, public or
protected. These specifiers modify the access rights that the members following them
acquire:
classcircle
{
float r, area; //data member
public:
voidgetrad(flaot); // member function
void calarea(); //member functions
intdisplayarea (void); //member function
};
Declares a class (i.e., a type) called circle. This class contains four members: two data
members of type float (data member r and data member area) with private access
(because private is the default access level) and two member functions with public access:
getrad(float), calarea() and displayarea(), of which for now we have only included
their declaration, not their definition.
The variable declared inside the class are known as data members and the functions are
known as member functions. Only the member functions can have access to the private data
members and private functions.
However, the public members (both data member and member function) can be accessed
from the outside the class.
Q. Describe how member function of class can be defined outside the class definition
and inside the class definition.
P a g e | 45
Computer Science ( D9) : XII - Paper –I
Q. What is an object? Describe how members of a class be accessed using object of that
class?
CREATING OBJECTS:
Once a class has been declared, we can create variables of that type by using the class name
(like any other build-in type variable). This statement should be define inside the main
program (function) i.e. void main()
P a g e | 46
Computer Science ( D9) : XII - Paper –I
Where keyword class is optional, followed name of the class declared, and var1, var2 are the
variables declared of type class class_name called as objects
E.g.class circle X;
class circle X1,X2;
circleZ; // where X,X1,X2, Z are the objects of the type class circle
The declaration of an object is similar to that of a variable of any basic type ieint X; int
X1,X2 etc.
e.g.X.getrad();
X.getrad(2.0);
X.r = 2.0 ; // invalid accessed through object directly, can be accessed only through a member function.
// To find the area of circle using OOP //member function are define outside the class
#include<iostream.h> void circle::calarea()
#include<conio.h> {
class circle area = 3.14 * r * r;
{ }
private:
void circle::displayarea()
float r, area; // data members
{
public: cout<<"The area of the circle is ::"<<area;
void getrad() }
{
cout<<"Enter the value of radius :"; //main program
cin>>r; void main()
} {
clrscr();
void calarea(); // member function class circle X; // create object X of type
void displayarea(); //member function X.getrad(); //access members through object X
}; X.calarea();
X.displayarea();
getch();
}
//To find the area of circle using OOP with parameter as void circle::displayarea()
variable. {
#include<iostream.h> cout<<"The area of the circle is ::"<<area;
#include<conio.h> }
P a g e | 47
Computer Science ( D9) : XII - Paper –I
class circle
{ //main program
private: void main()
float r, area; // data members {
public: clrscr();
void getrad(float R) class circle X; // create object X of type class circle
{ float R;
r = R; cout<<"Enter the value of radius :";
} cin>>R;
void calarea(); // member function X.getrad(R); // access member function with parameter
through object X
void displayarea(); //member function X.calarea();
}; X.displayarea();
//member function are define outside the class getch();
void circle::calarea() }
{
area = 3.14 * r * r;
}
MEMORY ALLOCATION FOR OBJECTS: The member functions are created and place
in the memory space only once. Since all the objects belonging to that class use the same
member functions. Only space for member variables is allocated separately for each object.
Q. Explain the short the three special characteristics of a statics data member in a class?
P a g e | 48
Computer Science ( D9) : XII - Paper –I
P a g e | 49
Computer Science ( D9) : XII - Paper –I
hours = h ; cout<<"-----------------------\n";
minute = m; T3.puttime();
} getch();
void puttime() }
{
cout<<hours<< " hours and "; Output:
cout<<minute << " minute \n";
2 hours 45 minute
}
3 hours 30 minute
void sum(time , time); //member
------------------------------
function
6 hours 15 minute
};
//member function are define outside the class
void time ::sum(time t1, time t2)
{
minute = t1.minute + t2.minute;
hours = minute /60;
minute = minute % 60;
hours= hours+t1.hours+t2.hours;
}
Q. What is friend function? Give the characteristics of a friend function. Or Write any
three characteristics of a friend function.
FRIEND FUNCTION:
The private member cannot be accessed from outside the class. That is a non-member
function cannot have an access to the private data of a class because of main concept of the
OOPs are data hiding and encapsulation. Now a friend function can be declared to have
access to these data members. Friend is a special mechanism for letting non-member
functions access private data. A friend function may be either declared or define within the
scope of a class definition. The key word friend informs the compiler that it is not a member
function of the class.
Class ABC
{
------
------
public:
-----
-----
Friend void xyz(); // declared xyz as a friend member function of class ABC
};
P a g e | 50
Computer Science ( D9) : XII - Paper –I
It can be declared either in the public or the private part of a class without affecting its
meaning.
Usually, it has the objects as arguments.
#include <iostream.h> void main()
class sample {
{ sample X;
private: X.setvalue();
int a; cout<<”Mean value = “<< mean(X)
int b; <<endl;
public: getch();
void setvalue() }
{
a = 25; Output: Mean value =32.5
b = 40;
}
friend float mean(sample s); //friend
declared
};
float mean(sample s)
{
return float(s.a+s.b)/2.0;
}
P a g e | 51
Computer Science ( D9) : XII - Paper –I
P a g e | 52
Computer Science ( D9) : XII - Paper –I
DESTRUCTOR:
A destructor, as the name implies is used to destroy the objects that have been created by
constructor. Like a constructor, the destructor is a member function whose name is same as
the class name but is preceded by tilde (~). Refer previous program.
Rules for writing Destructor function:
1) A destructor name must be the same as that of its class name.
2) It should be preceded by tilde (~).
3) It is declared with no return type, even don’t uses void word.
4) It may not be inheritance, virtual or static.
5) It should always have public access within the class.
6) Like other C++ functions, they can have default arguments.
7) They invoked automatically when the objects are destroyed.
C++ strongly supports the concept of reusability. This is basically done by creating new
classes, reusing the properties of the existing ones. The mechanism of deriving a new class
P a g e | 53
Computer Science ( D9) : XII - Paper –I
from old one is called inheritance (derivation). The old class is referred to as the Base
class and newly created class is called as Derived class.
A
A B
A
B C D
B C
A
A
B
B C
C
D
Multilevel Inheritance
Hybrid Inheritance
The colon indicates that the derived-class-name is derived from the base-class-name. The
visibility-mode is optional and if present may be either private or public. The default mode
is private.
Example: single inheritance
Class B : public A // public derivation
{
//member of ABC derived and XYZ is base class
};
P a g e | 54
Computer Science ( D9) : XII - Paper –I
P a g e | 55
Computer Science ( D9) : XII - Paper –I
overloading. When an operator is overloaded, its original meaning is not lost. Most of
operator of C++ can be overload except the following:
1) Class member access operator (.*, ->*)
2) Scope resolution operator (::)
3) Size operator (sizeof)
4) Conditional operator ( ?:)
Where return-type is the type of value returned by the specified operation an op is the
operator being overloaded. The op is preceded by the keyword operator. operator op is the
function name.
P a g e | 56
Computer Science ( D9) : XII - Paper –I
Q. Explain the three types of data conversion in C++ with a suitable example.
TYPE CONVERSIONS:
We know that C++ allows data to the right of an assignment operator is automatically
converted to the type of the variable on the left.
e.g.
int m;
float x = 3.14;
m=x;
convertx to an integer before its value is assign to m. similarly it will happened with in case
of class objects.
P a g e | 57
Computer Science ( D9) : XII - Paper –I
Three types of situations might arise in the data conversion between un-compatible types:
1) Conversion from built-in type to class type.
2) Conversion from class type to build-in type.
3) Conversion from one class type to another type.
POLYMORPHISM:
Polymorphism is one the major feature of OOPs. It simply means “one name, multiple
form” (poly many and morphism form)
Polymorphism
Run-time
Compile time
polymorphism
polymorphism
Choosing a function and operator in normal way, during compilation time is called as early
binding or static binding or static linkage. This is also known as compile-time polymorphism.
The appropriate member function can be selected at run time called as late binding or
dynamic binding or run-time polymorphism.
Q. State any five basic rules for virtual function that satisfy the compiler requirement.
The general syntax of the virtual function declaration is:
class class-name
{
private:
------------
------------
public:
virtual void getrad();
--------------------
};
Rules for virtual functions:
The virtual functions must be member of some class.
They cannot be static members.
They are accessed by using object pointers.
A virtual function can be a friend of another class.
We cannot have virtual constructors.
P a g e | 58
Computer Science ( D9) : XII - Paper –I
The input and output system of C++ handles files operations which are very similar to the
console input and output operations. It uses file steam as an interface between the program
and the files. The stream that supplies data to the program is known as input stream and the
one that receives data from the program is known as output stream.
Input stream
Program
Disk Files
Output stream
The function open() can be open multiple files that use the same stream object.
Syntax :
file-stream-classstream-object;
stream-object.open(“filesname”);
e.g.ofstreamoutfile; // ofile (output) is object of type ofstream
outfile.open(“data.new”); // open() is member function of class ofstream
P a g e | 59
Computer Science ( D9) : XII - Paper –I
Example 1: Example 2:
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
#include<fstream.h> #include<fstream.h>
void main() void main()
{ {
clrscr(); clrscr();
ifstreaminfile("data.new"); // constructor
ofstreamoutfile("data.new"); // char ch;
constructor infile.seekg(0,ios::beg); // go to start
char line[100]; while(infile)
cout<<"Enter the your sentence ..."; {
cin.get(line,100,'\n'); infile.get(ch);
outfile<< line; cout<<ch;
}
outfile.close(); infile.close();
getch(); getch();
} }
P a g e | 60