In: Computer Science
All the answer need to be in C++
1) Write a class for a "Vector". The members of the class will be:
Data: int data[100];
methods:
void inserts(int element);
int remove();
int getsize();
bool is empty():
-------------------------------------------------------------------------------------------------------
2) Using your vector class, create an object using a regular instantiation and a pointer instantiation. What are the advantages and disadvantages of both approaches?
-------------------------------------------------------------------------------------------------------
3) What does the following function do and write a program that uses the function:
int foo(int x);
{
if (x>1)
return x*foo(x-1);
return 1;
}
-------------------------------------------------------------------------------------------------------
4) Write a swap function using references.
1)Code -
#include <iostream>
using namespace std;
//vector class created
class Vector{
//public
public:
//variable declare
int data[100];
int count = -1;
//function to insert method to array
void inserts(int element){
count++;
data[count] = element;
}
//function to remove element from array
int remove(){
if(isEmpty()){
cout<<"Array is empty";
}
else{
count--;
}
}
//function to get the size of array
int getsize(){
return (count+1);
}
//function to check array is empty or not
bool isEmpty(){
if(count == -1)
return true;
else
return false;
}
//display function to display array elemet
void display(){
for(int i=0;i<=count;i++){
cout<<data[i]<<" ";
}
}
};
int main()
{
Vector v;
cout<<"Vector is empty
"<<v.isEmpty()<<endl;
v.inserts(2);
v.inserts(3);
v.inserts(4);
v.inserts(5);
v.inserts(22);
v.inserts(2);
v.display();
cout<<"\nSize "<<v.getsize()<<endl;
v.remove();
v.display();
return 0;
}
Screenshots -
2)
Vector v - this is regular way of creating object
Vector *v = new Vector() - this is a pointer instantiation of object
Pointer instantiation of object provide direct access to memory , reduce storage space and complexity of porgram .
Disadvantage - Pointer object has to be deleted externally. Uninitialized pointer object might cause segmentation fault.
3) This program is used to calculate the factorial of a number . It uses recursive function call to implement it.
Code -
#include <iostream>
using namespace std;
int foo(int x)
{
if (x>1)
return x*foo(x-1);
return 1;
}
int main()
{
cout<<"Factorial of 5 is "<<foo(5);
return 0;
}
Screenshots -
4)
void swap(int &a, int &b) { int temp; temp = a; //temp stores the value at address a a = b; /* put b into a */ b = temp; /* put a into b */ return; }
pls do like , thank you