C++ | Square and cube of each digit in number

Introduction

This tutorial will create a program to calculate square and cube of each digit in number. The first one will calculate square of each digit in number. The next one will calculate cube of each digit in number. This program cannot be extended. Go enjoy the program. Lets begin……………

Program to calculate square of each digit in number

#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type int
int no,m,s;
//Input the number
cout<<"Enter the no."<<endl;
cin>>no;
//using while loop.
while(no>0)
{
m=no%10;
s=m*m;
cout<<"Square of "<<m<<" is "<<s<<endl;
no=no/10;
}
//get character
getch();
}

Output

Enter the no.
1234
Square of 4 is 16
Square of 3 is 9
Square of 2 is 4
Square of 1 is 1

Program to calculate cube of each digit in number.

#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type int
int no,m,c;
//Input the number
cout<<"Enter the no."<<endl;
cin>>no;
//using while loop.
while(no>0)
{
m=no%10;
c=m*m*m;
cout<<"Cube of "<<m<<" is "<<s<<endl;
no=no/10;
}
//get character
getch();
}

Output

Enter the no.
1234
Cube of 4 is 64
Cube of 3 is 27
Cube of 2 is 8
Cube of 1 is 1

How does it work

  1. You enter the number.
  2. The last digit of numbers is separated.
  3. The square or cube is calculated.
  4. The square or cube is printed.

Extending it

The program cannot be extended.

Explanation.

  1. Include ‘iostream.h’ and ‘conio.h’ files.
  2. Add void main.
  3. Start program by first clearing the screen.
  4. Declare the variables as int (name them as you want.)
  5. Add the cout and cin of number.
  6. Add the loop.
  7. Calculate the square or cube.
  8. Print it.

At the end

You learnt creating the c++ program of calculating square or cube of each digit in number. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s