Site icon T4Tutorials.com

C++ inheritance n terms of odd natural number and their sum

Write a program in C++ to display the n terms of odd natural number and their sum like 1 3 5 7 by using the single inheritance in C++.

#include<iostream>
#include <conio.h>
using namespace std;

class num
{
public:

    int i;
    int input;
    int sum = 0;
};
class num2: public num
{
public:
    void proces()
    {
    cout << "plz Input number of terms : ";
    cin >> input;
    cout << "The odd numbers are :";

    for (i = 1; i <= input; i++)
    {
        cout << "\t" << 2 * i - 1;
        sum += 2 * i - 1;
    }
    cout << endl;
    cout << "\nThe Sum of odd Natural Number upto " << input << " are:";
    cout << sum;
    }

};
int main()
{
    num2 a;
    a.proces();



}

WAP in C++ to display the n terms of odd natural number and their sum like 1 3 5 7 by using the multiple inheritance.

#include<iostream>
#include <conio.h>
using namespace std;

class num
{
public:

    int i;
    int input;
 
};
class num3:public num
{
	public:
int sum = 0;	
		
};
class num2: public num3
{
public:
    void proces()
    {
    cout << "plz Input number of terms : ";
    cin >> input;
    cout << "The odd numbers are :";

    for (i = 1; i <= input; i++)
    {
        cout << "\t" << 2 * i - 1;
        sum += 2 * i - 1;
    }
    cout << endl;
    cout << "\nThe Sum of odd Natural Number upto " << input << " are:";
    cout << sum;
    }

};
int main()
{
    num2 abj;
    abj.proces();



}

Write a program to display the n terms of odd natural number and their sum with the help of multi-level inheritance in C++.

#include<iostream>
#include <conio.h>
using namespace std;

class num
{
public:

    int i;
    int input;
 
};
class num3:public num
{
	public:
int sum = 0;	
		
};
class num2: public num3
{
public:
    void proces()
    {
    cout << "plz Input number of terms : ";
    cin >> input;
    cout << "The odd numbers are :";

    for (i = 1; i <= input; i++)
    {
        cout << "\t" << 2 * i - 1;
        sum += 2 * i - 1;
    }
    cout << endl;
    cout << "\nThe Sum of odd Natural Number upto " << input << " are:";
    cout << sum;
    }

};
int main()
{
    num2 abj;
    abj.proces();



}
Exit mobile version