×

Armstrong Number using While Loop in C++

What is while Loop?

A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the condition no longer met.

The syntax that can be used for the “while” loop in the C++ programming language is following:

while(condition)
     {
      statement(x);
     }

Working of While loop in C++

The test expression which is to be entered into the "while" loop is written between parentheses.

There are currently two options of test expression. If the expression is true, then the "while" loop will be executed automatically and the evaluation procedure will be repeated until the test expression is true. And, if the test expression becomes false then the "while" loop will be terminated and the entire "while" loop procedure will be abandoned.

What are Armstrong Numbers?

Armstrong numbers are those natural positive numbers which are equal to the sum of cubes of each digit.
For example

a b c d... = a*n + b*n + c*n + d*n

Following is the While loop program which test a number entered by the user as an input is Armstrong or not:

#include<iostream>
Using namespace std;
int main ()
{
int n, c, b, a = 0;
/* declaring various variables and initialization the value of 'a' as 0 */ 
    cout<<"Input any natural number that you want to check whether it is an Armstrong number or not: "<<; 
/* here we let user to enter a number via this program line */ 
Cin>>c;
/* assigning the value entered by the user to variable 'n' */
n=c;
/* initializing assignment operator and assigning the value ‘c’ to ‘n’ */
/* Loop to calculate the sum of the cubes of its digits */
while(n>0) /* while (test expression or termination condition) */
{
b=n % 10;
/* initializing assignment operator and assigning the value of ‘n %10’ to ‘b’ */
a=a +b*b*b;
/* initializing assignment operator and assigning the value of ‘a +b*b*b’ to ‘a’ */
n=n/10;
}
/* if else condition to print Armstrong or Not */
if (a ==c)
/* initializing an ‘equal to’ operator and putting the condition to check if the value of a is equal to b or not */
cout<<"The number %d, that you have entered is an Armstrong number.\n"<<c;
else // else statement
cout<<"The number %d, that you have entered is not an Armstrong number.\n"<<c;
/* printing the value of result as an output */
getch ();
}

Output

Input any natural number that you want to check whether it is an Armstrong number or not: 407
The number 407, that you have entered is an Armstrong number.

Explanation of above code:

Initially, we have declared four variables – n, a, b, c. Then, we initialized the value of variable ‘a’ as 0, it means the initial value of variable ‘a’ will be 0 so that we can avoid the value of variable ‘a’ from going into negative.

In the following line we initialized a ‘while’ loop with the test expression or termination condition (n>0) which means the value of the variable ‘n’ must always be more than 0.

After the while loop, we initialized an if else statement and put the condition (n=c). It means that, if the value of ‘n’ is equal to ‘c’, then the statement in the IF part execute. And, if the condition false, then the statement in the else part will print.

Here, you can see how the above code is execute:

1. n>0 (407>0) here you can see the ‘while’ loop test expression is true,

b=n%10           (b=407%10)     So,  the remainder of n%10 is 7.

a=a +b*b*b     (a = 0 +7*7*7) So, the value of a is 343.

n=n/10            (n=407/10)        So, the value of n is 40.

2. n>0 (40>0) here you can see the while loop test expression is true,

b=n%10            (b=40%10)               So, the remainder of n%10 is 0.

a=a +b*b*b      (a = 343 +0*0*0)      So the value of a is now 343.

n=n/10             (n=40/10)                  So the value of n is now 4.

3. n>0 (4>0) here you can see the while loop test expression is true,

b=n%10            (b=4%10)                 So, the remainder of n%10 is 4.

a=a +b*b*b      (a = 343 +4*4*4)     So, the value of a is now 407.

n=n/10              (n=4/10)                   So, the value of n is now 0.

4. n>0 (0>0) here you can see the while loop test expression becomes false. And, the program execution ends.


Related Topics

Constexpr in C++

Constexpr is a keyword in C++ that is used to declare variables or functions as compile-time constants. This means that the value of a constexpr variable or the return value...

3 minutes read.

C++ Deque

Definition: Deque or the Doubly ended queue is a data structure or operation performed under queue where insertion and deletion are allowed at both ends. A deque is an ordered collection of...

5 minutes read.

Palindrome using Do-while loop in C++

What is Palindrome? A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++...

5 minutes read.

How to create the Processes with Fork in C++

 In this article, we are going to explain the different methods that help us to create processes with a fork(). There are two methods to do so. These methods are...

2 minutes read.

goto statement in C and C++

goto statement in C and C++ The goto statement is a jump statement, also sometimes referred to as an unconditional jump statement. Within a function, the goto statement can be used...

3 minutes read.

Auto keyword in C++

The primary function of auto keyword is to assign and detect the value of the data type automatically in C++. The compiler knows the data type of the variable by...

2 minutes read.

C++ Interfaces

The C++ programming language provides programmers with a variety of capabilities and functions. It also enables object-oriented programming, which is essential while working on a project. It will be simple...

7 minutes read.

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j For...

5 minutes read.

C++ Program to move all zeros to the end of the array

Write a program to move all the zeros in the arr[] to the end. The order of the non-zero elements should not be altered and all the zeros should be...

3 minutes read.

Pattern programs in C++

In this article, we are going to discuss different pattern programs in C++. Program for Printing * patterns: Right Angle Triangle* pattern #include <iostream> using namespace std; int main() {     int rows;     cout <<...

3 minutes read.

Array of sets in C++

Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. A collection of data objects stored in a continuous way is...

6 minutes read.

Star pattern in C++ using For Loops

Star patterns are one of the most extensively utilized patterns in any programming language since they help to increase logical thinking and flow control understanding.In the C++ programming language, you...

3 minutes read.

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 minutes read.

C++ Friend function

A friend function has the right to access all private and protected members of a class although it is defined outside that class' scope. Syntax class className{     ......     friend retyrn_type function_Name(argument);     .......   }   return_type function_Name(argument){     ......   } C++ friend function Example #include <iostream>   using namespace std;   class Length   {       private:           int meter;       public:           Length(): meter(5) { }           friend int addMethod(Length); //friend function declaration   };   int addMethod(Length l) // friend function definition   {       l.meter += 10; //accessing private data from non-member function       return l.meter;   }   int main()   {       Length L;       int totallength;       totallength=addMethod(L);       cout<<"Length: "<< totallength;       return 0;   } Output: Length: 15   C++ friend function...

1 minute read.

Object Slicing in C++

In this article, we will learn about Object slicing. When an object from a derived class is assigned to an object from a base class in C++, these extra attributes...

3 minutes read.

C++ Do while loop

In this article, we will discuss the C++ Do-While loop with its syntax, working, key features, algorithm, and examples. Do-While Loop: The do-while loop constitutes a specific style of looping construct in...

5 minutes read.

Sliding Window Technique in C++

Sliding Window Technique or Window Sliding Technique is a computational technique that is mainly used to reduce the use of nested loop and replace it with a single loop. It...

4 minutes read.

C++ cin and cout

In this article, we will discuss the C++ cin and cout with their library and examples. C++ Standard Input/Output: User-program communication is made possible by C++’s usage of input and output (I/O)...

5 minutes read.

Principles of Object-Oriented Programming in C++

What is Object-Oriented Programming? Object-oriented programming is about creating obejcts that represent the real-world entity . In object-oriented programming, objects are created for the class. One of the main objectives of...

5 minutes read.

Type difference of Character literals in C VS C++

Character literals in C: In C, a character literal is represented by a single character enclosed in single quotes, such as 'a' or 'b'. It is of type int. This means...

5 minutes read.