-4

The below code has been written aiming to generate all the armstrong* numbers below 1000.

*armstrong numbers:An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3^3 + 7^3 + 1^3 = 371.

#include<iostream>
using namespace std;
int main()
{
 int n,sum=0,digit,a,b;
 for(n;n<1000;n++)
  {
  a=n;
  b=n;
  for(b;b>=0;b/10)
  {
   digit=b%10;
   sum+=(digit*digit*digit);
  }
   (sum==a)?cout<<a:cout<<" ";
 }
 return 0;
}
Victor Tran
  • 516
  • 4
  • 16
  • 4
    Hello and welcome to SO. Please take [the tour](http://stackoverflow.com/tour) and read the [help page](http://stackoverflow.com/help). Here is a nice list of [C++ books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). –  Jan 13 '17 at 13:47
  • 1
    You are not initializing `n` - this cannot work properly – UnholySheep Jan 13 '17 at 13:48
  • 3
    `for(b;b>=0;b/10)` <-- and that is an infinite loop. – Frédéric Hamidi Jan 13 '17 at 13:49
  • See the above comments but you need to write your loops with an initial value for the looping variable as: `for (n = ; n < 1000; n++)`. Writing `int n, sum = 0;` earlier only initialises `sum` not `n`. – CodingLumis Jan 13 '17 at 13:51
  • 1
    You do not need to worry about these things. Your compiler [should tell you](http://coliru.stacked-crooked.com/a/f1e252e026eb8833). Use it properly. – nwp Jan 13 '17 at 13:51

2 Answers2

2

n is initially an undefined value. You'll need to set it to 0 before the for loop.

Also, b isn't being changed. Did you mean b /= 10 rather than b / 10?

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
Victor Tran
  • 516
  • 4
  • 16
  • #include using namespace std; int main() { int n,sum=0,digit,a,b; for(n=0;n<1000;n++)//Also initialised n { a=n; for(b=n;b>=0;b/=10)//I have changed b/10 to b/=10. { digit=b%10; sum+=(digit*digit*digit); } (sum==a)?cout< – Lordinkavu Jan 14 '17 at 03:28
1

I'd suggest to structure the code to make it easier to read, e.g. by introducing a function bool isArmstrong(int number); distinguish logic from using the logic; never let variables be uninitialised; introduce variables right there where they are used; give variables a meaning by using names other than a,b;

Then things like not initialized variables or infinite loops become much more apparent:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

bool isArmstrong(int number) {

    int cubeSum = 0;
    for (int remainingPortion = number; remainingPortion > 0; remainingPortion/=10) {
        int digit = remainingPortion % 10;
        cubeSum += digit*digit*digit;
    }
    return (cubeSum == number);
}

int main() {

    for (int number = 0; number < 1000; number++)
    {
        if (isArmstrong(number))
            printf("%d is an armstrong number\n", number);
    }

    return 0;
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58