Classes C++ program to display the cube of the number up to a given integer
Write a program in C++ to display the cube of the number up to a given integer using class objects in object-oriented programming.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include<iostream> using namespace std; class a { protected: int n; public: int cube() { cout<<"enter the number :"<<endl; cin>>n; for(int i=0; i<n; i++) { cout<<" cube of "<<i<<" is "<<"="<<(i*i*i)<<endl; } } }; int main() { a obj; obj.cube(); } |
Output
enter the number : 3
cube of 0 is 0.
cube of 1 is 1.
cube of 2 is 8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
#include<iostream> //header file using namespace std; //namespace class a //a class is created with the name of "a" { //starting of class a protected:
int n; //n is integer type variable and it is protected. its means that this a is only accessible //within this class and within its child(if any). public: int cube() //cube is a function and this function is public. its means that this function //is accessible anywhere outside the class { //starting of cube function cout<<"enter the number :"<<endl; //ask the user to enter a number cin>>n; //input a number for(int i=0; i<n; i++) //loop is started with value o and loop will execute until value of i is less //than n, increment the loop if condition is true { //starting of for loop cout<<" cube of "<<i<<" is "<<"="<<(i*i*i)<<endl; // calculates the value of i and show } //ending of for loop } //ending of cube function }; //ending of class a int main() //starting the main function { //main function started a obj; //a is the class name and obj is the object of the class a. //we can access the cube funtion of class a with the help of this object. obj.cube(); //cube function is a property of object obj and obj is a object of class a } //ending of main function |