0

enter image description hereThis is the code for finding an Armstrong number of 3 digits. But when i enter strings or any other special character it categorizes it as an armstrong number while it should be other way around.

#include <stdio.h>

#include <stdlib.h>

int main() {
  int a, original, rev, rem;
  printf("Enter the number : \n");
  scanf("%d", & a);

  original = a;

  rev = 0;
  while (a != 0) {

    rem = a % 10;
    rev = rev + (rem * rem * rem);
    a /= 10;
  }
  if (rev == original) {
    printf("Its an Armstrong number\n");
  } else {
    printf("Its not an Armstrong number \n");
  }

}

3 Answers3

3

It is Undefined Behaviour as you use not initialized variable a.

You should have checked for the incorrect input:

  if(scanf("%d", &a) != 1)
  {
    printf("Invalid input\n");
    return 1;
  }
0___________
  • 60,014
  • 4
  • 34
  • 74
3

You need to check the result of scanf - it will return the number of items successfully converted and assigned.

if ( scanf( "%d", &a ) != 1 )
  // bad input
else
  // check if a is an armstrong #

An input like nnnniii is not a valid integer, so the read fails and a is not updated.

While the initial value of auto variables is indeterminate, it's possible that a has an initial value of 0, so your test passes by accident.

John Bode
  • 119,563
  • 19
  • 122
  • 198
1
#include <stdio.h>
#include <stdlib.h>

int main() {
  int a, original, rev, rem;
  printf("Enter the number : \n");
  if(scanf("%d", &a) != 1)
  {
    printf("This is not number\n");
    return 1;
  }
 
  original = a;
  rev = 0;
  while (a != 0) {
    rem = a % 10;
    rev = rev + (rem * rem * rem);
    a /= 10;
  }

 if (rev == original) {
    printf("Its an Armstrong number\n");
  } else {
    printf("Its not an Armstrong number \n");
  }

}

When you get value, you need to check it is number or not.

tzztson
  • 328
  • 3
  • 22