×

Armstrong number using for loop in C++

What is For Loop?

A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently.

The syntax that can be used for the for loop in the C++ programming language is given below:

for (initialization statement; termination condition; increment or decrement statement (used for modifying value for further evaluation))
{
    /* main body of the “for” loop */
}

Working of For Loop in C++

In for loop, the initialization command is implemented only once. After that, it checks the test expression of the loop and finds whether the test expression is false or true. And, for loop is dismissed if the test expression is false.   
If the test expression of the 'F' loop becomes true, then the program line provided in the F loop’s body is executed, and the update expression is changed accordingly.
Again, the entire process of evaluation is to be done. The loop executes its body until and unless the value of the test expression in for loop becomes false.

The loop automatically terminates as soon as the test expression result becomes false.

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 For 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, a=0, b; 
/* declaring various variables and initialization the value of 'a' as 0 */ 
      cout<<"input any natural number that you want to check as Armstrong or  not: ";
/* here we let user to enter a number via this program line */ 
    cin>>n;
/* assigning the value entered by the user to variable 'n' */
    for (b=n; n>0; n=n/10)
/* for (initialization statement; test expression or termination condition; increment or decrement statement) */
 {
         c=n % 10;
/* initializing assignment operator and assigning the value ‘n % 10’ to ‘c’ */
         a=a+(c*c*c); 
/* initializing assignment operator and assigning the value of ‘c*c*c’ to ‘a’ */
    }
    if(a==b) 
/* 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"<< b;
/* printing the value of result as an output */
    else // else statement
         cout<<"The number %d, that you have entered is not an Armstrong number.\n"<< b;
/* printing the value of result as an output */
}

OUTPUT

Input any natural number that you want to check as Armstrong or not : 153
The number 153, that you have entered is an Armstrong number

EXPLANATION

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.

After that, we wrote a statement which will allow the user to enter the value for the variable ‘n’ with the ‘scanf’ command. The value in variable n holds that value which we want to test.

In the following line we initialized a ‘for’ 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 for loop, we initialized an if else statement and put the condition (a==n). 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 (153>0) here you can see the ‘for’ loop test expression is true,

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

a=a +b*b*b     (a = 0 +3*3*3) So, the value of a is 27.

n=n/10            (n=153/10)        So, the value of n is 15.

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

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

a=a +b*b*b      (a = 27 +5*5*5)      So the value of a is now 152.

n=n/10             (n=15/10)                  So the value of n is now 1.

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

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

a=a +b*b*b      (a = 152 +1*1*1)     So, the value of a is now 153.

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

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


Related Topics

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

C++ | C Plus Plus Data type

Data type in every language is very important. Data type means the different kinds of data that are supported by a particular programming language. A computer language’s data types specify the...

15 minutes read.

Parameterize Constructor

C++ Parameterized Constructor A constructor having parameters is known as parameterize constructor. Parameterize constructor is used to assign different values. Syntax: className(data-type argument){   // Constructor definition   }   className(data-type argument, data-type argument){   // Constructor definition   } A parameterized constructor can be passed values to constructor function in two ways: 1)...

1 minute read.

C++ Program to find largest subarray with 0 sum

Write a program to find the largest subarray that has a sum zero. The array contains positive and negative numbers. Print the length of the max subarray whose sum turns...

4 minutes read.

Delete Operator in C++

Overview We can reserve allocation for a variable or an array at runtime in C++. Dynamic memory allocation is the term for this. After utilising a variable in C++, we must...

4 minutes read.

New Operator in C++

Dynamic memory allocation in C++ means manually allocating the memory by the developer duing run-time. The dynamic memory is allocated in the heap section of the RAM, whereas the static...

3 minutes read.

C++ this pointer

'this' is a pointer that points to the object for which this function was called. The 'this' pointer holds the memory address of the current object. The 'this' pointer is implicitly passed to...

2 minutes read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

Dynamic Constructor in C++

Dynamic constructors create dynamic memory by using a dynamic memory allocator new within the constructor. This allows us to initialize objects dynamically. The term dynamic constructor is used when memory...

2 minutes read.

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

Virtual class in C++

Introduction to Virtual Base class Virtual base classes can be utilized in virtual inheritance as a mechanism for examining many "instances" of a certain class while searching through multiple inheritances in...

6 minutes read.

C++ Inheritance

What do you mean by Inheritance ? The ability to define new classes based on existing classes in order to reuse and organise code is referred to as inheritance. Single inheritance...

7 minutes read.

Array program in C++

What is an Array? An array is a set of identically typed elements that are organized into contiguous memory locations and each element can be independently accessed using an index. We can...

16 minutes read.

Reverse function in C++

The function std::reverse() is included in the standard template library of C++. It takes in a beginning and ending iterator, reversing the order. To use the reverse statement, we need...

2 minutes read.

Difference between C and C++

What do you mean by C? C is a machine-independent structure or procedural oriented computer language that is widely utilized in a variety of applications. C is a fundamental programming language...

4 minutes read.

Copy elision in C++

The Copy Omission is another name for the Copy Elision. One of the several compiler optimization techniques is copy elision. It prevents items from being copied inadvertently. This Copy Elision approach...

3 minutes read.

C++ Try-Catch

Every useful program will eventually encounter unexpected outcomes. By entering data that are incorrect, users might create mistakes. Sometimes the program's creator didn't consider all of the options or was...

7 minutes read.

Initialize Vector in C++

Initialize Vector in C++  The following comparison operators are defined for vector and those are given below. ==, <, <=, !=, >,>=  This allows you to access the element of a vector using...

3 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

Differences between Local and Global Variable

Define Global Variable Global variables are those that may be accessible worldwide across a programme and are defined outside of any functions or blocks. It may be accessed by any function in...

3 minutes read.