10.12.14

Recursion in C++

Create a recursive c++ function to fill up an array and make sum of all digit. you have to create different recursive function for fill up and to make sum.


#include<iostream>
using namespace std;

void array_recursive(int array[],int n)
{
     if (n-1>=0)
          {
               cout<<"Enter elements into the array:\n";
               cin>>array[n];
               n--;
               array_recursive(array,n);
           }

}

int sum_array(int array[],int n)
{
            if (n= =0)
                 {
                       return array[0] ;
                  }
            return array[n]+sum_array(array,n-1);
}

int main( )
{
         int n;
         cout<<"Enter the size of an array:\n";
         cin>>n;
         int array[n];
         array_recursive(array,n);
         cout<<"Printing Recursive Data\n";
         for(int i=n; i>0; i--)
             {
                  cout<<array[i]<<"\n";
             }
         cout<<"the sum is: "<<sum_array(array+1,n-1)<<endl;
}

Inheritence in c++ to generate a fibonacci series

Generate a Fibonacci series between 0 and 1000. The first two initial value are 0 and 1


#include<iostream>
using namespace std;
class fibonacci
{
     public:
     void set_digit (int m, int n)
         {
              f1=m;
              f2=n;
          }
      protected:
           int f1;
           int f2;
           int f3;
};

class print : public fibonacci
{
     public:
          void show_print()
              {
                   int maxnum;
                   cout <<"Enter the maximum number of fibonacci series: "<< "\n";
                   cout <<"\nPrinting fibonacci series from 0 to 1000: " << "\n");
                   while (f1+f2 < = 1000)
                   {
                        f3=f1+f2;
                        cout <<f3 <<"\n";
                        f1=f2;
                        f2=f3;
                   }
              }
};
int main()
{
      print p;
      p.set_digit (0, 1);
      p.show_print( );
}

Constructor in c++ to Sum of all multipliers by given range

write a c++ program which contains a constructor to make sum of all multipliers of 7 or 9 between 1 and 100.


#include<iostream>
using namespace std;
class divis
{
      public:
            int sum=0;
            divis();
            ~divis();
            void result();
};

divis :: divis()
{
    int a=1;
    while(a<100)
    {
        if ( (a%7==0) || (a%9==0) )
            {
                cout << a <<"\n";
                sum = sum+a;
            }
        a++;
    }
}

divis :: ~divis()
{
    cout <<"memory released" << "\n";
}

void divis :: result()
{
    cout << "\n The sum of all divisibles: "<< sum << endl;
}

int main( )
{
     divis vs;
     vs.result();
}

27.11.14

Inheritence in C++ to check a Perfect Number (Excercise-19)

Write a Object Oriented C++ program using Inheritance to check whether a given number is perfect or not ?


#include<iostream>
using namespace std;
class perfect
{
     public:
          void setnum (int digit)
              {
                    number = digit;
               }
               protected: 
               int number;
};

class chknumber : public perfect
{
      public:
          int sum=0;
          void getperfect ( )
                 {
                       for ( int i=1; i<number; i++ )
                           {
                                if ( number%i = =0 )
                                     {
                                         sum += i;
                                     }
                            }
                   }
         int chksum( )
                {
                     if  (number = = sum)
                          cout << "Yes!!" << endl<< "the given number is perfect number" << endl << endl;
                     else
                          cout << "Not!!"<< endl << "the given number is not a perfect number" << endl;
                }
};

int main( )
{
     chknumber per;
     int digit;
     cout << "Enter a number to check perfect or not : ";
     cin >> digit;
     per.setnum(digit);
     per.getperfect();
     per.chksum();
     return 0;
}

C++ Definition : object oriented programming

Write answer for the following questions in comments. Give answer in short. Example as source code is preferable with each answer.


How is OOP important in C++?

What is abstract class?

What is this Pointer ? What is its significance?

What is the difference between while and do-while loop?

Why main() function is important in C++?

What is type casting in C++?


What is OOP?

What is the type conversion in C++

What is the difference between local variable and global variable.

Show Inheritance with at least two derived class

Show Data Abstraction and data Encapsulation

Describe Polymorphism with Example

 

Excercise-18 : Recursive Function Progamming



Write a program using recursive function in C++ to find factorial of a given integer number.

Excercise-17 : Function Progamming


Write a program using function to Sum of all Odd numbers from an Array. Use function prototype and parameter

OOP Excercise-16 : Array Progamming



Search an element in an Array of 20 integer values.
      (i) Use one Constructor to get input on variable and array.
(ii) Use one Constructor to Search the Array.
(iii) Use a member function to display the result.
(iv) Use Destructor in any suitable position.

OOP Excercise-15 : Banking System



Define a class to represent a bank account which includes following members:
Data members –   i) Name
ii) Account number
iii) Type of account
iv) Balance Amount
Member functions –
a. To assign initial value
b. To deposit an account
c. To withdraw from an account
                                    d. To display name, account number & balance

23.11.14

Excercise-14 : Count the number of character


Write a c++ program to count number of character in a given string

Excercise-13 : Find ODD or EVEN


Write a c++ program to check whether the given number is odd or even

Function : Excercise-12 : Sum of all even elements from an Array


Write a program of function to Sum of all even elements from an Array. The initial value of the array must take from main ( ) as input

Function : Excercise-11 : recursive function to fill an Integer Array of 5 Elements


Write a program of recursive function in C++ to fill an Integer Array of 5 Elements. After fill the array print/show all elements using recursive function. Take array and size of the array from main() body.
You may follow the below page to solve this problem:
http://c-programming-practice.blogspot.com/2013/06/c-function-to-insert-element-in-array.html

OOP : Excercise-10 : Check palindrome. Use Inheritance


Check whether the given number is palindrome or not. Use individual/separate member function to take input, output and display according to logic. Use Inheritance

OOP : Excercise-9 : Program to find area of triangle, circle, and rectangle using function overloading


Write a C++ program to find area of triangle, circle, and rectangle using function overloading

19.11.14

OOP : Excercise-8 : Check whether the given number is palindrome or not. Use individual member function to take input, output and display. Use Inheritance

Check whether the given number is palindrome or not. Use individual member function to take input, output and display. Use Inheritance or Constructor.

//Program using Constructor
#include<iostream>
using namespace std;
class checkpelindrom
{
int num;
public:
checkpelindrom();
~checkpelindrom();
void view();
};
checkpelindrom :: checkpelindrom()
{
cout<<"Enter the number\n";
cin>>num;
}
checkpelindrom :: ~checkpelindrom()
{
//cout<<"\n\nDestruction";
}
void checkpelindrom :: view()
{
int a ,temp ,rev=0;
temp=num;
while(temp!=0)
{
a=temp%10;
rev=rev*10+a;
temp /=10;
}
if(rev==num)
cout<<"\nIt is a pelindrom number\n\n";
else
cout<<"\nIt is not a pelindrom number\n\n";

}
int main()
{
checkpelindrom cp;
cp.view();
return 0;

}

OOP : Excercise-7 : Search an element in an Array of 10 integer values. Use Constructor and Destructor with Class

Search an element in an Array of 10 integer values. Use Constructor and Destructor with Class

9.11.14

OOP : Excercise-6 : Write a Object Oriented Program to Display Studnet Information

Create a class named as Student containing the following data members:
--Roll_no
--Name
--Marks1, Marks2, Marks3
Write necessary member functions:
1. to accept details of all students
2. to display details of one student
3. to display details of all students(Use Function overloading).
 (Use Function overloading)

OOP : Excercise-5 : Check Whether the given number is Strange or Not.

Note: Use Inheritance to solve this program.

//check strange number using inheritance
‪#‎include‬<iostream>
using namespace std;
//base class
class strange
{
public:
void setdigit(int d)
{
digit=d;
}
protected:
int digit;
};
//derived class
class number : public strange
{
public:
int i,j,t=1,d;
int devide()
{
while(d!=0)
{
j=d%10;
d=d/10;
for(i=2;i<j;i++)
{
if(j%i==0)
{
t=0;
i=j;
}
}
}
}
int check()
{
if(t==1)
cout<<"this number is strange";
else
cout<<"this number is not strange";
}
};
int main()
{
number nmb;
int a;
cin>>a;
nmb.setdigit(a);
nmb.check();
}

Function : Excercise-4.2 : Check Whether the given number is Strange or Not.

[Use user defined function to solve this problem]

#include<iostream>
using namespace std;
int chkstrange(int digit);
int main()
{
int digit,p;
cout<<"Enter Number to Check: ";
cin>>digit;
p= chkstrange(digit);
if (p==1) cout<<"strange";
else
cout<<"Not strange";
}
//function start here
int chkstrange(int digit)
{
int temp,rem,temp2=1;
while(digit!=0)
{
temp=digit/10;
rem=digit%10;
digit=temp;
for(int i=2;i<rem;i++)
    {
    if (rem%i ==0)
    {
    temp2= 0;
    i=rem;
    }
    }   
}
return temp2;
}

18.10.14

OOP : Excercise-4.1 : C++ program to find area of triangle, circle,and rectangle using function overloading

Write a C++ program to find area of triangle, circle,and rectangle using function overloading

OOP : Excercise-3 : C++ program to calculate simple interest amount use default value for rate

Write a C++ program using class to calculate simple interest amount use default value for rate.


//1. calculate simple interset in cpp
‪#‎include‬<iostream>
using namespace std;
main()
{
float SI=0,p,t,r;
cin>>p>>t>>r;
SI=((p*t*r)/100);
cout<<SI;
}


//2. calculate simple interest using function

‪#‎include‬<iostream>
using namespace std;
float interest(float p,float t,float r);
main()
{
float p,t,r,SI=0;
cin>>p>>t>>r;
interest(p,t,r);
}
float interest(float a,float b,float c)
{
float SI;
SI=((a*b*c)/100);
cout<<SI;
}


//3. calculate simple interest in oop. Use member variable and member function as required
‪#‎include‬<iostream>
using namespace std;
class interest
{
public:
float p,t,r;
void get_value()
{
cin>>p>>t>>r;
}
void cal_value()
{
float SI;
SI=((p*t*r)/100);
cout<<SI;
}
};
main()
{
interest in;
in.get_value();
in.cal_value();
}

OOP : Excercise-2 : calculate square and cube of given number using inline function

C++ program using class to calculate square and cube of given number using inline function .

Sample Syntax:

#include<iostream.h>
class power
{
public:
inline int square(int n)
{
 -----------------------------
 -----------------------------
 }
inline int cube(int n)
{
 -----------------------------
 -----------------------------
 }

};
void main()
{
 -------------------------------
 -------------------------------
}


27.9.14

OOP : Excercise-1 : Arithmetic Operators with operands as input

Write a program performing as calculator which allows all Arithmetic Operators with operands as input

1. Write a C program for performing as calculator which allows all Arithmetic Operators with operands from terminal. Few Input and Output sample are given below:
Recommended: Study Char/Char Array in C/C++           
       
            Sample Input: 1 + 4
            Sample Output: 5
            Sample Input: 8 % 2
            Sample Output: 0
            Sample Input: 6 / 2
            Sample Output: 3
            Sample Input: 5 / 2
            Sample Output: 2.5

9.3.14

Excercise: Inheritence

Inheritance, Samples of using inheritance

Inheritance is the property by which one object can inherit the properties of the other object. A general class can be inherited by the other classes.  A class that is inherited is called a base class. A class which is inheriting another class is called a derived class. When a class inherits another class, members of the base class become the members of the derived class. The general form of inheritance is:-

class derived_name : access_specifier base_name
{
};

The derived_name is the name of the derived class. The base_name is the name of the base class. The access_specifier can be private, public or protected. If the access_specifier is public then all public members of the base class become public members of the derived class and protected members of the base class become the protected members of the derived class. If the access_specifier is private then all public and protected members of the base class will become private members of the derived class. If the access_specifier is protected then the public and protected members of the base class become the protected members of the derived class. Whether access_specifier is public, private or protected, private members of the base class will not be accessed by the members of the derived class.

The access_specifier protected provides more flexibility in terms of inheritance. The private members of the base class cannot be accessed by the members of the derived class. The protected members of the base class remain private to their class but can be accessed and inherited by the derived class. The protected members of the base class will remain private to the other elements of the program.

A derived class can inherit one or more base classes. A constructor of the base is executed first and then the constructor of derived class is executed. A destructor of derived class is called before the destructor of base class. The arguments to the base class constructor can be passed as follows:-

            derived_constructor (argument list): base1 (arg_list)
                                                                       base2(arg_list1)

                                                                        baseN(arg_list)

The derived_constructor is the name of the derived class. The argument list is list of the data members of the derived class. The base1 is name of the base class. The arg_list is the list of the members of the base class. Here is a program which illustrates the features of inheritance.

#include<iostream>
using namespace std;

class shape
{

            private :
                        double length;
           
            protected:
                        double breadth;

            public :

                        double len()
                        {
                                    return(length);
                        }
            shape(double length1,double breadth1)
            {
                        length=length1;
                        breadth=breadth1;
            }
            //shape()           {          }
};

class shape1
{
            public:
                        double height;
           
            shape1(double height1)
            {
                        height=height1;
            }
            //shape1()         {          }
};

class cuboid : public shape, private shape1
{
            public:

                        cuboid(double length1,double breadth1,double height1):shape(length1,breadth1),shape1(height1)
                        {
                                    cout << " A constructor is called " << endl;
                        }
                       
                        double volume()
                        {
                                    return(height*breadth*len());
                        }
                        double bre()
                        {
                                    return(breadth);
                        }
                        double ht()
                        {
                                    return(height);
                        }
};

int main()
{
            cuboid c1(2.4,3.5,6.7);
            cout << "The length of the cuboid is : " << c1.len() << endl;
            cout << "The breadth of the cuboid is : " << c1.bre() << endl;
            cout << "The height of the cuboid is : " << c1.ht() << endl;
            cout << "The volume of the cuboid is : " << c1.volume() << endl;
            return(0);
}

The result of the program is:-

inheritance

The program has two base classes shape and shape1 and one derived class called cuboid which inherits shape as public and shape1 as private. The public and protected members of shape become pubic and protected members of derived class cuboid. The private members of shape remain private to the class shape. The members of shape1 class become the private members of the derived class cuboid.

The statement

            class cuboid : public shape, private shape1

states that class cuboid inherits class shape as public and class shape1 as private. The statement

            cuboid(double length1,double breadth1,double height1):shape(length1,breadth1),shape1(height1)
                        {
                                    cout << " A constructor is called " << endl;
                        }

declares the constructor of the class cuboid. When constructor of class cuboid is called first constructor of shape is executed and then constructor of shape1 is executed and after that the constructor of cuboid is executed.   The statements

            double volume()
                        {
                                    return(height*breadth*len());
                        }

calculate the volume of the cuboid. The class cuboid cannot access the private data member length of the shape class. It access the length by calling the function len() which returns the private data member length. The data member breadth becomes the protected member of the class cuboid. The height which is public member of shape1 class becomes the private member of the class cuboid as it inherits the shape 1 class as private. The statements

                        double bre()
                        {
                                    return(breadth);
                        }

returns the breadth of the cuboid as data member breadth cannot be accessed outside the class as it is protected member of cuboid. The statement

            double ht()
                        {
                                    return(height);
                        }

returns the height of the cuboid as data member height cannot be accessed outside the class as height is the private data member of the class cuboid. The statement

            cuboid c1(2.4,3.5,6.7);

creates an object c1 of type cuboid. The constructor is called to initialize the values of the cuboid. The constructor of shape is executed and then constructor of shape1 is executed and then finally constructor of cuboid is executed. The statement

            cout << "The length of the cuboid is : " << c1.len() << endl;

displays the length of the cuboid as c1.len() calls the len() function of class shape which is also the public member function of cuboid. The statement

            cout << "The breadth of the cuboid is : " << c1.bre() << endl;

displays the breadth of the cuboid. As the data member breadth cannot be accessed directly as it is protected member of the class cuboid so the function bre() returns the breadth of the cuboid. The statement
                       
            cout << "The height of the cuboid is : " << c1.ht() << endl;

displays the height of the cuboid. The data member height cannot be accessed directly as it is private member of class cuboid so it is accessed through the function ht() which returns height.

Excercise : Encapsulation

Encapsulation, private public. Sections

The packaging of data values and member functions within one object is called an encapsulation. For example an object of class cube contains data member as side of the cube and member function volume of the cube. It is also called data hiding which helps to maintain the integrity of the object. It saves the data from misuse and outside interference. The data cannot be accessed directly but access controls can be specified in order to obtain the information. The data or object can be made public or private depending on the needs. The data which is private is not accessible outside the scope of the object. When the data is public it can be accessed by the other parts of the program.

Here is a program which shows how private and public members are accessed. The program consists of a class rectangle which has two data members such as length and breadth and the member functions area() and len(). The private data member length cannot be accessed directly. It is accessed using a function len() which is public and which returns the private data member length.

#include<iostream>
using namespace std;

class rectangle
{
            private:
                        double length;

            public:
                        double breadth;
                        double area()
                        {
                                    return(length*breadth);
                        }
                        double len()
                        {
                                    return(length);
                        }
                        rectangle(double lenght1,double breadth1)
                        {
                                    length=lenght1;
                                    breadth=breadth1;
                        }
};

int main()
{
            rectangle r1(3.5,4.6);
            double a=r1.len();
            double b=r1.breadth;
            cout << "The lenght is : " << a <<  endl;
            cout << "The breadth is : " << b << endl;
            cout << "The area is : " << r1.area() << endl;
            return(0);
}

The result of the program is:-

encapsulation

The statement

            private:
                        double length;

declares that data member length of type double which has access specifier as private. It cannot be accessed directly. The statements

            public:
                        double breadth;
                        double area()
                        {
                                    return(length*breadth);
                        }
                        double len()
                        {
                                    return(length);
                        }
                       
declares that data member breadth and member functions len() and area() are public. The member function len() is used to return the data member length which cannot be accessed directly. The statement

            rectangle r1(3.5,4.6);

declares an object r1 of rectangle. The constructor initializes the length and breadth of the object as soon as it is created. The statement

            double a=r1.len();

returns the length of the object. The data member length cannot be accessed directly as it is declared private therefore member function len() is used to return the value of length. The statement double a=r1.length in main() function is invalid as data member length is inaccessible. The statement

            double b=r1.breadth;

equates the value of b to the value of breadth of object r1. The statement

            cout << "The area is : " << r1.area() << endl;

displays the area of the rectangle.

Exercise : Classes and Objects with Constructor-cum-Destructor

Class and Objects

Constructor and Destructor with Methods and properties


A class is a user defined data type like a structure or a union. A class consists of data variables and functions. These variables and functions are called members of the class.  The variables are called data members and functions are called member functions. The member functions are also called methods. The data members are called properties of the class. An object is the instance of the class. An object is like a compound variable of the user defined type. It links both code and data. Within the object, members of the class can be public or private to the object. The declaration of a class is syntactically same as structure. The class is declared using keyword class. The general form of the declaration of the class is:-

class class_name
{
             
            access_specifier:
                        data functions
            access_specifier:
                        data functions

} object_list;

The object_list is optional. The object_list is used to declare objects of the class. The class_name is the name of the class.  The access_specifier can either public, private or protected. The members of the class by default are private to the class. If the access_specifier is private then members of the class are not accessible outside the class. If the access_specifier is public then members of the class can be accessed from outside the class. The protected access_specifier is needed at the time of inheritance. The members can be accessed using an object’s name, a dot operator and name of the member. Here is a program which shows how classes and objects are created.

#include<iostream>
using namespace std;

class cube
{
            public:
                        double side;
                        double volume()
                        {
                                    return(side*side*side);
                        }
};
                       
int main()
{
            double volume1=0;
            cube c1,c2;
            cout << "Enter the lenght of the cube" << endl;
            cin >> c1.side;
            cout << "The volume of the cube is : " << c1.volume() << endl;
            c2.side=c1.side +2;
            cout << "The volume of the second cube is : " << c2.volume() << endl;
            return(0);
}

The result of the program is:-

class

The program consists of a class cube which has data member side of type double and member function which calculates the volume of the cube. The statement

            class cube

declares a class cube. The statements

            public:
                        double side;
                        double volume()
                        {
                                    return(side*side*side);
                        }

declare that access_specifier is public for data member side and member function volume. These members can be accessed from the other parts of the program. The statement

            cube c1,c2;

declares two objects c1 and c2 of type cube. The statement

            cin >> c1.side;

access the data member of the cube. The member is accessed by specifying the name of the object as c1 then dot operator and then name of the variable side. The length entered by the user is stored in c1.side. In the statement

            cout << "The volume of the cube is : " << c1.volume() << endl;

c1.volume() calls the member function volume which returns the volume of the cube of side whose length is entered by the user. The statement

            c2.side=c1.side +2;

equates the side of object c2 to side of object c1 increased by 2.  The objects c2 and c1 are different. The statement

            cout << "The volume of the second cube is : " << c2.volume() << endl;

displays the volume of second object c2.

Constructor and Destructor:


Constructors are used in order to initialize the objects. A constructor is a special kind of a function which is the member of the class. The name of the constructor is same as name of the class. A constructor is automatically called when object is created. A constructor does not have a return type.

A default constructor is a constructor with no parameters. If no constructor is defined by the user then compiler supplies the default constructor. Once the constructor is defined by the user then compiler does not supply default constructor and then user is responsible for defining default constructor. 

A destructor is the complement of the constructor. It is used to destroy the objects. The objects are destroyed in order to deallocate the memory occupied by them. The name of the destructor is same as the name of the constructor as is preceded by a tilt operator ‘~’. A destructor for objects is executed in the reverse order of the constructor functions.

Here is a program which shows how constructors and destructors are used.

#include<iostream>
using namespace std;

class cube
{
            public:
                        double side;
                        double volume()
                        {
                                    return(side*side*side);
                        }
                        cube(double side1)
                        {
                                    cout << "A constructor is called" << endl;
                                    side=side1;
                        }
                        cube()
                        {
                                    cout << "A default constructor is called " << endl;
                        }
                        ~cube()
                        {
                                    cout << "Destructing " << side << endl;
                        }
};
                       
int main()
{
            cube c1(2.34);
            cube c2;
            cout << "The side of the cube is: " << c1.side << endl;
            cout << "The volume of the first cube is : " << c1.volume() << endl;
            cout << "Enter the length of the second cube : " ;
            cin >> c2.side;
            cout << "The volume of second cube is : " << c2.volume() << endl;
            return(0);
}

The result of the program is:-

constructor

The statement
                       
            cube(double side1)
            {         
                                    cout << "A constructor is called" << endl;
                                    side=side1;
            }
declares the constructor of the class cube. The name of the constructor is same as the name of the class. There is no return type in the constructor. It will initialize the value of data member side. The statement

                       
cube()
                        {
                                    cout << "A default constructor is called " << endl;
                        }

declares a default constructor. The statement

                         ~cube()
                        {
                                    cout << "Destructing " << side << endl;
                        }

declares a destructor to deallocate the objects. The statement

            cube c1(2.34);

creates an object c1 of type cube. A constructor is automatically called and initializes the data member side with value 2.34. The statement

                        cube c2;

creates an object of type c2. When object c2 is created a default constructor is called and the message will be printed. The statements

            cout << "The side of the cube is: " << c1.side << endl;
            cout << "The volume of the first cube is : " << c1.volume() << endl;

displays the side and volume of the cube where side has value 2.34. The statement

            cin >> c2.side;

will set the value of the side of the object c2 as entered by the user. At the end of the program objects are deallocated in the reverse order in which constructors are called. First object c2 is deallocated whose side is 2.5 and then object c1 is deallocated whose side is 2.34.

Advantage of the classes:-

It provides protection to the data. The members of the class are by default private to the class while the members of the structure are public. OOP features allow programmer to easily handle complex problems and multi file projects. They help in modeling real world objects such as bank accounts and their related transactions.

Exercise-1:  One steps through integer points of the straight line. The length of a step must be non negative and can be by one bigger than, equal to, or by one smaller than the length of the previous step. What is the minimum number of steps in order to get from x to y ? The length of the f irst and the last step must be 1. View Details

Exercise-2: Some operators checks about the relationship between two values and these operators are called relational operators.
Given two numerical values your job is just to nd out the relationship between them that is
(i) First one is greater than the second
(ii) First one is less than the second or
(iii) First and second one is equal. 

View Details