0

This is the code to print all armstrong numbers within a range m to n as input by the user. But when i run it, it does not give proper output. Suppose i input m as 1 and n as some 10000, it only shows '1 is armstrong' and nothing else.Please tell me if something is wrong in my code.

#include<stdio.h> void main() { int m,n,a,i,j=0,r; printf("Enter m\n"); scanf("%d",&m); printf("Enter n\n"); scanf("%d",&n); for(i=m;i<=n;i++) { int temp=i; while(i>0) { r=i%10; j=j+r*r*r; i=i/10; } if(j==temp) { printf("%d is armstrong\n",temp); } } } 
2
  • Try moving an if statement into the while loop. Commented Dec 19, 2018 at 12:11
  • It seems like a bad idea to modify i both in the for loop (i++) and also in the while loop (i=i/10;). It means your for-loop will not run across all values from m to n. Commented Dec 19, 2018 at 13:41

2 Answers 2

2

I see two faults in your program, j is only initialised once, and you are destroying the loop control i. To remedy, initialise j inside the loop, and work with temp instead of with i.

#include<stdio.h> int main(void) // modern style { int m, n, i, j, r; printf("Enter m\n"); scanf("%d", &m); printf("Enter n\n"); scanf("%d", &n); for(i = m; i <= n; i++) { j = 0; // initialise j int temp = i; while(temp > 0) { // work with temp r = temp % 10; j = j + r * r * r; temp = temp / 10; } if(j == i) { printf("%d is armstrong\n", i); } } } 

Program output:

 Enter m 1 Enter n 10000 1 is armstrong 153 is armstrong 370 is armstrong 371 is armstrong 407 is armstrong 
Sign up to request clarification or add additional context in comments.

Comments

2
for(i=m; i<=n; i++) { j = 0; int temp = i; while(temp > 0) { r = temp % 10; j = j + r*r*r; temp = temp/10; } if(j == i) { printf("%d is armstrong\n", i); } } 

In while loop you need to work with variable temp to leave i intact so the for loop continues correctly. Before starting new while loop set j = 0 to start counting again from 0. In if statement compare j == i because temp variable is reduced to 0 by while loop.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.