<< Chapter < Page | Chapter >> Page > |
2.7 ) Test the following program which uses a run-time allocated array.
#include<iostream.h>
void main()
{
int num;
cout<<“Please enter the numbers of input: ”
cin>>num;
int a = new int [num];
int total = 0; // Holds total of user’s eight numbers.
int ctr;
for (ctr=0; ctr<num; ctr++)
{
cout<<“Please enter the next number...”;
cin>>a[ctr];
total += a[ctr];
}
cout<<“The total of the numbers is “<<total<<“\n”;
return;
delete [] a;
}
2.8) Given a class named IntArray that contains two private data members: a pointer to the beginning of the array, and an integer representing the size of the array. The public functions include a constructor and member functions that show every element in the IntArray, and show the first IntArray element only. The definition of the class IntArray is as follows:
// IntArray.h
class IntArray
{
private:
int* data; //pointer to the integer array
int size;
public:
IntArray(int* d, int s);
void showList();
void showFirst( );
};
// IntArray.cpp
IntArray::IntArray(int* d, int s)
{
data = d;
size = s;
}
void IntArray::showList()
{
cout<<"Entire list:"<<endl;
for(int x = 0; x<size; x++)
cout<<data[x]<<endl;
cout<<"----------------------"<<endl;
}
void IntArray::showFirst()
{
cout<<"First element is ";
cout<<data[0]<<endl;
}
a. Add to the class IntArray one more member function named findMax which returns the largest element in the array.
b. Write a main program that instantiates one array of integers and then displays the array, the first element and the largest element of the array.
The objectives of Lab session 9 are (1) to learn to write parameterized constructor, constructor with default arguments and (2) to practice destructors.
2.1) Run the following program in a C++ environment.
class Int{
private:
int idata;
public:
Int(){
idata=0;
cout<<"default constructor is called"<<endl;
}
Int(int d=9){
idata=d;
cout<<"constructor with argument is called"<<endl;
}
void showData(){
cout<<"value of idata: "<<idata<<endl;
}
};
void main()
{
Int i;
Int j(8);
Int k=10;
}
a. Explain why the program incurs a compile-time error.
b. Modify the program in order to remove the above error. Run the modified program.
2.2) Run the following program in a C++ environment.
class Vector{
private:
int *value;
int dimension;
public:
Vector(int d=0){
dimension=d;
if (dimension==0)
value=NULL;
else{
value=new int[dimension];
for (int i=0; i<dimension; i++)
value[i]=0;
}
}
void showdata(){
for (int i=0; i<dimension; i++)
cout<<value[i];
cout<<endl;
Notification Switch
Would you like to follow the 'Programming fundamentals in c++' conversation and receive update notifications?