I'm trying to check whether or not the number provided by the user is an armstrong number. Something is wrong though and I can't figure it out.
Any help is appreciated.
Code attached below.
#include<stdio.h>
int fun(int);
int main()
{
int x,a,b,y=0;
printf("enter the number you want to identify is aN ARMSTRONG OR NOT:");
scanf("%d",&a);
for(int i=1 ; i<=3 ; i++)
{
b = a % 10;
x = fun(b);
y = x+y;
a = a/10;
}
if(y==a)
printf("\narmstrong number");
else
printf("\nnot an armstrong number");
return 0;
}
int fun(int x)
{
int a;
a=x*x*x;
return (a);
}
The primary problem is that you don't keep a record of the number you start out with. You divide a by 10 repeatedly (it ends as 0), and then compare 0 with 153. These are not equal.
Your other problem is that you can't look for 4-digit or longer Armstrong numbers, nor for 1-digit ones other than 1. Your function fun() would be better named cube(); in my code below, it is renamed power() because it is generalized to handle N-digit numbers.
I decided that for the range of powers under consideration, there was no need to go with a more complex algorithm for power() - one that divides by two etc. There would be a saving on 6-10 digit numbers, but you couldn't measure it in this context. If compiled with -DDEBUG, it includes diagnostic printing - which was used to reassure me my code was working right. Also note that the answer echoes the input; this is a basic technique for ensuring that you are getting the right behaviour. And I've wrapped the code up into a function to test whether a number is an Armstrong number, which is called iteratively from the main program. This makes it easier to test. I've added checks to the scanf() to head off problems, another important basic programming technique.
I've checked for most of the Armstrong numbers up to 146511208 and it seems correct. The pair 370 and 371 are intriguing.
#include <stdio.h>
#include <stdbool.h>
#ifndef DEBUG
#define DEBUG 0
#endif
static int power(int x, int n)
{
int r = 1;
int c = n;
while (c-- > 0)
r *= x;
if (DEBUG) printf(" %d**%d = %d\n", x, n, r);
return r;
}
static bool isArmstrongNumber(int n)
{
int y = 0;
int a = n;
int p;
for (p = 0; a != 0; a /= 10, p++)
;
if (DEBUG) printf(" n = %d, p = %d\n", n, p);
a = n;
for (int i = 0; i < p; i++)
{
y += power(a % 10, p);
a /= 10;
}
return(y == n);
}
int main(void)
{
while (1)
{
int a;
printf("Enter the number you want to identify as an Armstrong number or not: ");
if (scanf("%d", &a) != 1 || a <= 0)
break;
else if (isArmstrongNumber(a))
printf("%d is an Armstrong number\n", a);
else
printf("%d is not an Armstrong number\n", a);
}
return 0;
}
One problem might be that you're changing a (so it will no longer have the original value). Also it would only match 1, 153, 370, 371, 407. That's a hint to replace the for and test until a is zero and to change the function to raise to the number of digits.
#include<stdio.h>
#include <math.h>
int power(int, int);
int numberofdigits(int);
//Routine to test if input is an armstrong number.
//See: http://en.wikipedia.org/wiki/Narcissistic_number if you don't know
//what that is.
int main()
{
int input;
int digit;
int sumofdigits = 0;
printf("enter the number you want to identify as an Armstrong or not:");
scanf("%d",&input);
int candidate = input;
int digitcount = numberofdigits(input);
for(int i=1 ; i <= digitcount ; i++)
{
digit = candidate % 10;
sumofdigits = sumofdigits + power(digit, digitcount);
candidate = candidate / 10;
}
if(sumofdigits == input)
printf("\n %d is an Armstrong number", input);
else
printf("\n %d is NOT an Armstrong number", input);
return 0;
}
int numberofdigits(int n);
{
return log10(n) + 1;
}
int power(int n, int pow)
{
int result = n;
int i=1;
while (i < pow)
{
result = result * n;
i++;
}
}
What was wrong with the code:
No use of meaningful variable names, making the meaning of the code hard to understand; remember code is written for humans, not compilers.
Don't use confusing code this code: int x,a,b,y=0; is confusing, do all vars get set to 0 or just y. Always put vars that get initialized on a separate line. It makes reading easier. Go the extra mile to be unambiguous, it will pay off big time in the long run.
Use comments: If you don't know what an armstrong number is, than it will be very hard to tell from your code. Put a few meaningful comments in so people know what your code it supposed to do. This will make it easier for you and others because they know what you meant to do and can see what you actually did and solve the difference if need be.
use meaningful routine names WTF does fun(x) do?. Never name anything fun() it's like fact free science, what's the point?
Don't hardcode things, your routine only accepted armstrong3 numbers, but if you can hardcode then why not do return (input == 153) || (input == 370) || ....
Okay so, the thing is that there are also Armstrong numbers that are not just 3 digits for example 1634, 8208 are 4 digit Armstrong numbers, 54748, 92727, 93084 are 5 digit Armstrong numbers and so on. so to check the number is Armstrong or not, here's what I did.
#include <stdio.h>
int main()
{
int a,b,c,i=0,sum=0;
printf("Enter the number to check is an Armstrong number or not :");
scanf("%d",&a);
//checking the digits of the number.
b=a;
while(b!=0)
{
b=b/10;
i++;
}
// i indicates the digits
b=a;
while(a!=0)
{
int pwr = 1;
c= a%10;
//taking mod to get unit place and getting its nth power of their digits
for(int j=0; j<i; j++)
{
pwr = pwr*c;
}
//Adding the nth power of the unit place
sum += pwr;
a = a/10;
//Dividing the number to give the end condition
}
if(sum==b)
{
printf("The number %d is an Armstrong number",b);
}
else
{
printf("The number %d is not an Armstrong number",b);
}
}
/*
Name: Rakesh Kusuma
Email Id: rockykusuma#gmail.com
Title: Program to Display List of Armstrong Numbers in 'C' Language
*/
#include<stdio.h>
#include<math.h>
int main()
{
int temp,rem, val,max,temp1,count;
int num;
val=0;
num=1;
printf("What is the maximum limit of Armstrong Number Required: ");
scanf("%d",&max);
printf("\nSo the list of Armstrong Numbers Before the number %d are: \n",max);
while(num <=max)
{
count = 0;
temp1 = num;
while(temp1!=0)
{
temp1=temp1/10;
count++;
}
if(count<3)
count = 3;
temp = num;
val = 0;
while(temp>0)
{
rem = temp%10;
val = val+pow(rem,count);
temp = temp/10;
}
if(val==num)
{
printf("\n%d", num);
}
num++;
}
return 0;
}
Check No. is Armstrong or Not using C Language
#include<stdio.h>
#include<conio.h>
void main()
{
A:
int n,n1,rem,ans;
clrscr();
printf("\nEnter No. :: ");
scanf("%d",&n);
n1=n;
ans=0;
while(n>0)
{
rem=n%10;
ans=ans+(rem*rem*rem);
n=n/10;
}
if(n1==ans)
{
printf("\n Your Entered No. is Armstrong...");
}
else
{
printf("\n Your Entered No. is not Armstrong...");
}
printf("\n\nPress 0 to Continue...");
if(getch()=='0')
{
goto A;
}
printf("\n\n\tThank You...");
getch();
}
If you are trying to find a armstrong number the solution you posted is missing a case where your digits are great than 3 ...armstrong numbers can be greater than 3 digits (for example 9474). Here is the code in Python, the logic is simple and it can be converted to any other language.
def check_armstrong(number):
num = str(number)
total=0
for n in range(len(num)):
total+=sum(int(num[n]),len(num))
if (number == total):
print("we have armstrong #",total)
def sum(input,power):
input = input**power
return input
check_armstrong(9474)
Here's a way to check whether a number is armstrong or not
t=int(input("nos of test cases"))
while t>0:
num=int(input("enter any number = "))
n=num
sum=0
while n>0:
digit=n%10
sum += digit ** 3
n=n//10
if num==sum:
print("armstronng num")
else:
print("not armstrong")
t-=1
This is the most simplest code i have made and seen ever for Armstrong number detection:
def is_Armstrong(y):
if y == 0:
print('this is 0')
else:
x = str(y)
i = 0
num = 0
while i<len(x):
num += int(x[i])**(len(x))
i += 1
if num == y:
print('{} is an Armstrong number.'.format(num))
break
else:
print('{} is not an Armstrong number.'. format(y))
is_Armstrong(1634)
Related
In the above mentioned I wanted to ask that what I have done wrong in my code I have tried debugging it many times but was not able to understand the logical error in my code.
Any help would be appreciated.
#include <stdio.h>
#include <math.h>
int digit(int n);
int digit(int n) {
int a;
double i = 0;
do {
a = n % (int)(pow(10, i));
i++;
} while (a != n);
return i;
}
void is_armstrong(int n);
void is_armstrong(int n) {
int a, b;
double sum;
for (int i = 0; i < digit(n); i++) {
a = n / (int)pow(10, (double)i);
b = a % 10;
sum += pow((double)b, 3);
}
if ((int)sum == n) {
printf("%d is an armstrong number.\n", n);
}
}
int main() {
int a, b;
printf("Please input the left hand limit of range : \n");
scanf(" %d", &a);
printf("Please input the right hand limit of range : \n");
scanf(" %d", &b);
for (int i = a; i <= b; i++) {
is_armstrong(i);
}
is_armstrong(153);
return 0;
}
This code is not even showing 153 an Armstrong number.
Noting the comments about using the power function and what your ultimate outcome is in identifying Armstrong numbers over a given range, I did a bit of refactoring to simplify the process in identifying such numbers. Following is the code snippet that provides the functionality.
#include <stdio.h>
void is_armstrong(int n) {
int a, b, c, d;
int sum = 0;
a = n;
c = 0;
while (a != 0) /* Determine the number of digits to raise to a power */
{
a = a / 10;
c = c + 1;
}
a = n; /* Reset the work number */
while (a != 0) /* Noted from the comments to simplify the test */
{
b = a % 10;
d = b;
for (int i = 1; i < c; i++)
{
d = d * b;
}
sum = sum + d; /* Just mulitply each digit by itself the required number of times */
a = a / 10; /* Divide by 10 along with using the modulo function to evaluate each digit */
}
if (sum == n) {
printf("%d is an armstrong number.\n", n);
}
}
int main() {
int a, b;
printf("Please input the left hand limit of range : \n");
scanf(" %d", &a);
printf("Please input the right hand limit of range : \n");
scanf(" %d", &b);
for (int i = a; i <= b; i++) {
is_armstrong(i);
}
return 0;
}
Following are some key points.
Since the power function is not needed, the math.h include file is not needed and linking the math library is also not needed.
Acquiring each digit is simplified by just utilizing the modulo operation in combination with integer division by "10".
Acquiring the value of each digit raised to the nth power is simplified by just performing a repeated multiplication.
Following is test output at the terminal.
#Dev:~/C_Programs/Console/Armstrong/bin/Release$ ./Armstrong
Please input the left hand limit of range :
1
Please input the right hand limit of range :
10000
1 is an armstrong number.
2 is an armstrong number.
3 is an armstrong number.
4 is an armstrong number.
5 is an armstrong number.
6 is an armstrong number.
7 is an armstrong number.
8 is an armstrong number.
9 is an armstrong number.
153 is an armstrong number.
370 is an armstrong number.
371 is an armstrong number.
407 is an armstrong number.
1634 is an armstrong number.
8208 is an armstrong number.
9474 is an armstrong number.
And as a confirmation, it can be seen that the value "153" was recognized as an Armstrong number.
Give the code snippet a try and see if it meets the spirit of your project.
There is no need to count the number of digits in n, you can just sum the cubes of each digit, one at a time dividing the number by 10 at each iteration.
Here is a simplified version:
#include <stdio.h>
void is_armstrong(int n) {
int sum = n;
while (n != 0) {
int b = n % 10;
n /= 10;
sum -= b * b * b;
}
return sum == 0;
}
int main() {
int a, b;
printf("Please input the left hand limit of range:\n");
if (scanf("%d", &a) != 1)
return 1;
printf("Please input the right hand limit of range:\n");
if (scanf("%d", &b) != 1)
return 1;
for (int i = a; i <= b; i++) {
if (is_armstrong(i)) {
printf("%d is an Armstrong number.\n", i);
}
}
return 0;
}
i have a homework but i cant get the answer
I need to write a program in C...
Here is what is needed: You need to enter "n" natural number as input , and from all the natural numbers smaller than "n" , its needed to print the number which has the highest sum of devisors.
For exp: INPUT 10 , OUTPUT 8
Can anyone help me somehow?
I would really appreciate it !
i tried writing a program for finding the devisor of a number but i cant get far from here
#include <stdio.h>
int main() {
int x, i;
printf("\nInput an integer: ");
scanf("%d", &x);
printf("All the divisor of %d are: ", x);
for(i = 1; i < x; i++) {
if((x%i) == 0){
printf("\n%d", i);
}
}
}
I have implemented using function which will takes input number from user and then return the sum of divisor. hope this is one you looking for
/* function to return of sum of divisor
** input: x: integer number from user input
** return sum: sum of divisor of x
*/
int sum_of_divisor(int x)
{
int sum = 0;
for(int i = 1; i < x; i++)
{
if((x%i) == 0)
{
printf("%d\n", i);
sum = sum+i;
}
}
return sum;
}
int main() {
int x, i;
printf("\nInput an integer: ");
scanf("%d", &x);
printf("All the divisor of %d are: ", x);
printf("the sum of divisor is %d ", sum_of_divisor(x));
return 0;
}
Output:
Input an integer: 10
All the divisor of 10 are: 1
2
5
the sum of divisor is 8
After checking if i is a divisor of x, you should then store that value in another variable, for example m.
Repeat until a new divisor i is higher than that number. Add this new value to m.
I have this problem where the number isn't being identified as an Armstrong number. I tried entering 153 which is an Armstrong number which isn't being identified as one. I am learning C. Any help would be nice.
#include <stdio.h>
int main()
{
int x[3],a,b,c,temp;
int temp2 = 0;
printf("Enter a supposed Armstrong number: ");
scanf("%d",&x);
for(int i =0;i<3;i++)
{
temp = x[i]*x[i]*x[i];
temp2 = temp2 + temp;
}
if(temp2 == x)
{
printf("This is an Armstrong number!");
}
else
{
printf("This is not an Armstrong number!");
}
}
TL;DR - To store a 3-digit integer value, you don't need an array with 3 ints.
In your code, x is an array type, and the way you use it, only x[0] get a valid value, x[1] and x[2] are left uninitialized. So, your code produces undefined behavior.
I believe, you don't need to have an array, instead make use of the modulo operator to extract each digit one by one and carry on with the calculation.
with respect to your code x is an integer type array.so,integer type array doesn't work like a char type array.
char type array takes base address and it is still open util '\0'(null) char is found.it is defined for scanf().but for int type array you need to manually define the particular position of the array in the memory to store the inputs.
so,u have to use like this =>
#include <stdio.h>
int main(){
int x[3],n,r,c,temp,i;
int temp2 = 0;
printf("Enter a supposed Armstrong number: ");
scanf("%d",&n);
c=n;
for(i =0;i<3;i++){
x[i]=n%10;
n=n/10;
temp = x[i] * x[i] * x[i];
temp2 = temp2 + temp;
}
if(temp2 == c){
printf("This is an Armstrong number!");
}
else{
printf("This is not an Armstrong number!");
}
return 0;
}
Firstly take input into a single variable of type int and then store it in array after breaking them by % operator then you will be able to find Armstrong number.
E.g
int x=153;
int y[3];
for(int i=2;i>=;i--)
{
y[i]=x%10;
x=x/10;
}
After this step your loop will work properly
You were no need to use an array for getting all digits from given integer input.
#include <stdio.h>
int main() {
int input, temp, rmdr, sum = 0;
printf("Enter a supposed Armstrong number: ");
scanf("%d", &input);
temp = input; // store value of given input (backUp)
for ( ; input>0; ) { // loop till input has data
rmdr = input % 10; // get last digit from input
sum += (rmdr * rmdr * rmdr); // collect cube of remainders
input /= 10; // remove last digit from input
}
// collected sum will compare with temp (backUp)
// because given input will be 0 after loop
if (temp == sum)
printf("This is an Armstrong number!");
else
printf("This is not an Armstrong number!");
}
Thanks all, really helped. I needed to do this for a mini-project.I decided to do this because it seemed the easiest way.
#include <stdio.h>
int main()
{
int x,y,z,temp;
int temp2 = 0;
printf("Enter a supposed Armstrong number: ");
scanf("%d",&x);
z = x;
for(int i =0;i<3;i++)
{
y = x%10;
temp = y*y*y;
temp2 = temp2 + temp;
x = x/10;
}
if(temp2 == z)
{
printf("This is an Armstrong number!");
}
else
{
printf("This is not an Armstrong number!");
}
}
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int i , n , sum=0, rem;
clrscr();
for(i=1;i<=1000;i++)
{
while(i!=0)
{
rem = i%10;
sum = sum + pow(rem,3);
i = i / 10;
}
if(i == sum)
printf("\n %d", i);
}
getch();
}
I tried the above code for printing Armstrong Numbers upto 1000 . The output that I got was a list of zeros. I am not able to find the error in the code. Thanks in advance :)
You should keep a copy of i, so that it could be kept for comparison with the sum variable.
As of now, you compare sum and i, at every step when i has become 0.
You should use a temp variable to store value of i(before performing i/=10).
Also, you can't keep i in the while-loop as it would always be 0, and hence post increment will have no effect on it. You should need another temporary variable, say div.
And, you should finally print temp.
Also, an Armstrong number is an n-digit number that is equal to the sum of the nth powers of its digits.
So, for 1000, you need to caclculate the 4th power.
int temp,div;
for(i=1;i<=1000;i++)
{
temp = i;
div = i;
while(div!=0)
{
rem = div%10;
sum = sum + pow(rem,3);
div = div / 10;
}
if(temp == sum)
printf("\n %d", temp);
}
NOTE :- Probably you're using Turbo C compiler(check that header <conio.h>), which you shouldn't(you should avoid it). You should use GCC(on Linux system), CodeBlocks IDE(on Windows).
You can also use this code to print Armstrong number in given range.
#include<stdio.h>
int main()
{
int num,r,sum,temp;
int min,max;
printf("Enter the minimum range: ");
scanf("%d",&min);
printf("Enter the maximum range: ");
scanf("%d",&max);
printf("Armstrong numbers in given range are: ");
for(num=min;num<=max;num++)
{
temp=num;
sum = 0;
while(temp!=0)
{
r=temp%10;
temp=temp/10;
sum=sum+(r*r*r);
}
if(sum==num)
printf("%d ",num);
}
return 0;
}
I am taking an online C class, but the professor refuses to answer emails and I needed some help.
Anyways, our assignment was to write a program that takes an integer from the user and find the largest even digit and how many times the digit occurs in the given integer.
#include <stdio.h>
void extract(int);
void menu(void);
int main() {
menu();
}
void menu() {
int userOption;
int myValue;
int extractDigit;
do {
printf("\nMENU"
"\n1. Test the function"
"\n2. Quit");
scanf("%d", &userOption);
switch (userOption) {
case 1:
printf("Please enter an int: ");
scanf("%d", &myValue);
extractDigit = digitExtract(myValue);
break;
case 2:
printf("\nExiting . . . ");
break;
default:
printf("\nPlease enter a valid option!");
}
} while (userOption != 2);
}
void digitExtract(int userValue) {
int tempValue;
int x;
int myArr[10] = { 0 };
tempValue = (userValue < 0) ? -userValue : userValue;
do {
myArr[tempValue % 10]++;
tempValue /= 10;
} while (tempValue != 0);
printf("\nFor %d:\n", userValue);
for (x = 0; x < 10; x++) {
printf("\n%d occurence(s) of %d",myArr[x], x);
}
}
I have gotten the program to display both odd & even digit and it's occurrences.
The only part that I am stuck on is having the program to display ONLY the largest even digit and it's occurrence. Everything I've tried has either broken the program's logic or produces some weird output.
Any hints or ideas on how I should proceed?
Thanks ahead of time.
Run a loop from the largest even digit to smallest even digit.
for (x = 8; x >=0; x-=2)
{
if(myArr[x]>0) //if myArr[x]=0 then x does not exist
{
printf("%d occurs %d times",x,myArr[x]);
break; //we have found our maximum even digit. No need to proceed further
}
}
Note:To optimize you should count and store occurrences of only even digits.
Why do you even use the extra loop? To find the largest even digit in an integer and the number of its occurences, a modification to the first loop would suffice.
Consider the following (untested, but I hope you get the idea):
int tempValue;
int x;
int myArr[10] = { 0 };
int maxNum = 0;
tempValue = (userValue < 0) ? -userValue : userValue;
do {
int currNum = tempValue % 10;
myArr[currNum]++;
tempValue /= 10;
if (currNum % 2 == 0 && currNum > maxNum)
maxNum = currNum;
} while (tempValue != 0);
After this, maxNum should contain the largest even digit, and myArr[maxNum] should be the number of its occurences.