Calculating the result of a power and a base without math.h - c

At my university I was asked to create a program that asks the user for two inputs. One is the base and the other is the power of a number. I am not allowed to use math.h only loops.
This is my code thus far:
#include <stdio.h>
int main() {
int base;
printf(" Please enter the base: ");
scanf("%d", &base);
int power;
printf(" Please enter the power: ");
scanf("%d", &power);
printf("\n%d ^ %d is the same as...\n\n", base, power);
printf(" %d", base);
int reps;
int number;
for(reps = base; reps <= power; reps += 1) {
printf("* %d ", base);
}
for(number; number <= power;number += 1) {
int result = base * base;
for (result; number <= power; result = base * result) {
result = result * base;
printf("\n or %d", result);
}
}
return 0;
}
Please help me. I am so lost and I feel like crying :( not that it matters.

(Your main issue is that you are using an uninitialised variable; the behaviour of doing that in C is undefined.)
But let's rework the answer. The first thing to do is to separate the actual power function from all the input and output. With regards to that function, I'll put my favourite way into the answer pool on the understanding that you'll work through it carefully and understand it.
You can ace this problem using a technique called exponentiation by squaring:
int getPower(int base, int power/*must be non-negative*/)
{
int ret = 1;
while (power){
if (power & 1){ /*this means the current value of `power` is odd*/
ret *= base;
}
power >>= 1; /*ToDo - figure this out with your debugger*/
base *= base;
}
return ret;
}
The method is adequately explained in https://en.wikipedia.org/wiki/Exponentiation_by_squaring

The loop for calculating the power looks like this
int product = 1;
for(int multiplicationCounter = 1;multiplicationCounter <= power; multiplicationCounter ++) {
product *= base;
}
printf("Result is %d", product);
You can integrate this in your code, maybe change the output.
This should replace your whole second for-loop.

assume both base and power is positive integer,
then
int Result =1;
for (int i=0; i<=power;i++)
{
if(power==0)
Result=1;
Result =Result*base;
}

This should work
#include <stdio.h>
int main()
{
int base;
printf(" Please enter the base: ");
scanf("%d", &base);
int power;
printf(" Please enter the power: ");
scanf("%d", &power);
printf("\n%d ^ %d is the same as...\n\n", base, power);
printf(" %d", base);
int reps;
int number;
int result=1:
for(number=1; number <= power;number += 1)
{
result=result*base
}
printf("The result is %d", result);
return 0;
}

Related

Printing the number with highest sum of devisors

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.

How can assign only the three largest integers from a for loop in C into three separate variables?

I am trying to make a program that takes two user inputs (x and y), checks all numbers in the interval for all prime numbers, and then prints only the three largest prime numbers if available. So far, my code checks all the prime numbers in an interval starting from the largest to the smallest.
My code:
#include <stdio.h>
#include <stdlib.h>
void inputXY(int *x, int *y) {
printf("Enter value of x: ");
scanf("%d", x);
printf("Enter value of y: ");
scanf("%d", y);
}
void swap(int*x, int*y){
int temp;
temp = *x;
*x=*y;
*y=temp;
}
int primechecker(int divisor,int dividend){
if(dividend==divisor) return 1;
else if(dividend%divisor==0) return 0;
else primeChecker(divisor+1,dividend);
}
void largestonly(int*counter, int*largest1, int*largest2, int*largest3){
int temp;
temp=*counter;
if (temp>*largest1&&*largest2) ///incomplete attempt
}
void printlargest(int *x, int *y, int*largest1, int*largest2, int*largest3){ ///I do not know if this would work, since I have not equated largest1, largest2, and largest3 to zeroes. My idea here is that, if any specific variables are empty, different specific lines should be printed.
if (*largest1==0&&(*largest2&&*largest3!=0)) {
printf("There are two prime numbers: ");
printf("%d, %d", *largest2, *largest3);
}
else if (*largest1&&*largest2==0&&*largest3!=0){
printf("There is only one prime number: ");
printf("%d", *largest3);
}
else if (*largest1&&*largest2&&largest3!=0){
printf("The three largest prime numbers between %d and %d are: ", *x, *y);
printf("%d, %d, %d", *largest1, *largest2, *largest3);
}
else if (*largest1&&*largest2&&largest3==0){
printf("No prime numbers found!");
}
}
int main(){
int x,y,largest1, largest2, largest3, counter, divisor, dividend, i;
divisor=2;
dividend=counter;
inputXY(&x, &y);
if ((x&&y==0),(x&&y==1)) printf("Invalid range!\n");
if (x>y) swap(&x, &y);
for (i=0; i<=3; i++){
for(counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1) largestonly(&counter, &largest1, &largest2, &largest3);
}
}
printlargest(&x, &y, &largest1, &largest2, &largest3);
return 0;
}
I have yet to successfully write a working function that can sort all the integers produced by the for loop in main(). It is the largestonly() function as seen above. In relation to that, my printlargest() function undoubtedly does not work. My idea in here is that if largest1 does not contain any value (or is equal to 0 or some other more appropriate value that I could not think of), the function will only print the two largest prime numbers found. Relatively, if both largest1 and largest2 are empty, only the largest prime number will be printed. If all variables are empty, it should print "No prime numbers found!". I am very lost with what to do with my code at the moment so any type of help will be greatly appreciated. Thank you.
There are a few things to do here.
First, pay attention to the line 21, you call a primeChecker() function that doesn't exist. It will raise an error when compiling.
Second, you don't have to "sort" anything. You only have to store the prime numbers into the variables as they arrive. I noticed you consider largest3 to be the first one that has to be filled (at least it is what can be understood from printlargest()), this gives us the following:
void largestonly(int counter, int* largest1, int* largest2, int* largest3){
if(*largest3 == 0)
*largest3 = counter;
else if(*largest2 == 0)
*largest2 = counter;
else if(*largest1 == 0)
*largest1 = counter;
}
Additionally, there is no need to pass the address of counter in the first place, as you won't need to modify it.
Lastly, in the main() function, you don't need a double loop. Think of it this way. If you were to do the exercise mentally, you'd go down the numbers, check if they were primes, and write them down if they satisfy the conditions: being primes and being the first, second or third. You wouldn't need to do it 3 times. Hence:
int main(){
int x,y;
inputXY(&x, &y);
int largest1 = 0;
int largest2 = 0;
int largest3 = 0;
int divisor = 2;
if ((x&&y==0),(x&&y==1)) printf("Invalid range!\n");
if (x>y) swap(&x, &y);
for(int counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1)
largestonly(counter, &largest1, &largest2, &largest3);
}
printlargest(&x, &y, &largest1, &largest2, &largest3);
return 0;
}
Also, the way you declared your variables without initializing them can sometimes be dangerous. In this case, as largest1, largest2 and largest3 weren't set to 0, you'd have had no chance to trigger any of the printlargest() cases. It may be because you were stuck on a part of your program you thought would also handle that but I still want to point it out, just in case.
EDIT: you could also add a condition in the for loop such that if largest1 is not equal to 0, it exits the loop. It would prevent the program to loop through (potentially) big amount of numbers when you already have everything you need. It would look like this (with the existing for loop, for context):
for(int counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1)
largestonly(counter, &largest1, &largest2, &largest3);
if(largest1 != 0)
break;
}
Hope this clears out the issues you had, feel free to ask anything if necessary, or to point out things I'd have misunderstood in your question.
Here's the full code:
#include <stdio.h>
#include <stdlib.h>
void inputXY(int *x, int *y) {
printf("Enter value of x: ");
scanf("%d", x);
printf("Enter value of y: ");
scanf("%d", y);
}
void swap(int*x, int*y){
int temp;
temp = *x;
*x=*y;
*y=temp;
}
int primechecker(int divisor,int dividend){
if(dividend==divisor) return 1;
else if(dividend%divisor==0) return 0;
else primechecker(divisor+1,dividend);
}
void largestonly(int counter, int* largest1, int* largest2, int* largest3){
if(*largest3 == 0)
*largest3 = counter;
else if(*largest2 == 0)
*largest2 = counter;
else if(*largest1 == 0)
*largest1 = counter;
}
void printlargest(int *x, int *y, int*largest1, int*largest2, int*largest3){ ///I do not know if this would work, since I have not equated largest1, largest2, and largest3 to zeroes. My idea here is that, if any specific variables are empty, different specific lines should be printed.
if (*largest1==0&&(*largest2&&*largest3!=0)) {
printf("There are two prime numbers: ");
printf("%d, %d", *largest2, *largest3);
}
else if (*largest1&&*largest2==0&&*largest3!=0){
printf("There is only one prime number: ");
printf("%d", *largest3);
}
else if (*largest1&&*largest2&&largest3!=0){
printf("The three largest prime numbers between %d and %d are: ", *x, *y);
printf("%d, %d, %d", *largest1, *largest2, *largest3);
}
else if (*largest1&&*largest2&&largest3==0){
printf("No prime numbers found!");
}
}
int main(){
int x,y;
inputXY(&x, &y);
int largest1 = 0;
int largest2 = 0;
int largest3 = 0;
int divisor = 2;
if ((x&&y==0),(x&&y==1)) printf("Invalid range!\n");
if (x>y) swap(&x, &y);
for(int counter=y;counter>=x;counter--) {
if (primechecker(divisor,counter)==1)
largestonly(counter, &largest1, &largest2, &largest3);
}
printlargest(&x, &y, &largest1, &largest2, &largest3);
return 0;
}
First, define how you would check for a prime number:
bool is_prime(int num)
{
if (num < 2)
return false;
for (int i = 2; i <= num / i; ++i)
if (num % i == 0)
return false;
return true;
}
Then, define a function that returns the 3 largest prime numbers in a given interval:
void get_max_3_in_range(int lo, int hi, int *max1, int *max2, int *max3)
{
*max1 = 0; // smallest
*max2 = 0;
*max3 = 0; // largest
int round = 0;
for (int i = lo; i <= hi; ++i) {
if (is_prime(i)) {
if (round % 3 == 0) *max1 = i;
if (round % 3 == 1) *max2 = i;
if (round % 3 == 2) *max3 = i;
++round;
}
}
if (*max1 > *max2) swap_int(max1, max2);
if (*max2 > *max3) swap_int(max2, max3);
}
Here is your swap():
void swap_int(int *v1, int *v2)
{
int tmp = *v1;
*v1 = *v2;
*v2 = tmp;
}
Driver program:
int main(void)
{
int x, y;
inputXY(&x, &y);
int max1, max2, max3;
get_max_3_in_range(x, y, &max1, &max2, &max3);
printf("x = %d\ty = %d\n", x, y);
printf("max1 = %d\tmax2 = %d\tmax3 = %d\n", max1, max2, max3);
}
Output:
Enter value of x: 0
Enter value of y: 100
x = 0 y = 100
max1 = 83 max2 = 89 max3 = 97
You can choose what to output in case one or more of the maximums is/are zero. Here, I chose to print them all.
Side note: Your inputXY() is very error-prone. Because if the user enters a string, your code will break. scanf() returns a value that you must check.
Following is a better version:
void inputXY(int *x, int *y)
{
for(;;) {
printf("Enter value of x: ");
if (scanf("%d", x) != 1)
flush_stdin();
else
break;
}
flush_stdin();
for(;;) {
printf("Enter value of y: ");
if (scanf("%d", y) != 1)
flush_stdin();
else
break;
}
}
And flush_stdin() (Never do fflush(stdin)!!) will clear what remained in the buffer, in case the user didn't enter (just) a number:
void flush_stdin(void)
{
scanf("%*[^\n]");
}

No output in C program

This my first program of C programming using recursive functions, it calculates the sum of the first n natural numbers. I am not able to get an output from it, it asks for the number but after that the program doesnt respond, can someone please help me out?
int n();
int main(){
int num;
printf("Enter num:\n");
scanf("%d", &num);
n(num);
printf("The sum of %d is: %f", num, n(num));
return 0;
}
int n(int x){
if (x != 0){
return n(x) + n(x-1);
**strong text** }
else{
return x;
}
}
Firstly, in the recursive function, return n(x) + n(x-1); should have been return x + n(x-1); as in the first case, n(x) will continuously make a called to another n(x), therefore making an infinite loop, or, more formally, return a 0xC00000FD exception, a Stack Overflow exception.
Also, in the last printf() function, %f should have been %d:
#include <stdio.h>
int n(int x)
{
if (x > 0) {return x + n(x-1);} return x;
}
int main()
{
int num;
printf("Enter num: ");
scanf("%d", &num);
printf("The sum of %d is: %d", num, n(num));
return 0;
}
Using %f to print an integer will caused an undefined behavior, because %f is a float format specifier, as noted here.
If you really want to convert it to a float:
#include <stdio.h>
int n(int x)
{
if (x > 0) {return x + n(x-1);} return x;
}
int main()
{
int num;
printf("Enter num: ");
scanf("%d", &num);
printf("The sum of %d is: %f", num, (double) n(num));
return 0;
}
*Note: Ran on Code::Blocks 20.03, Windows 10 64bit.
More info on format specifiers : https://www.tutorialspoint.com/format-specifiers-in-c
It should be return x instead of calling the same function,
you can use type conversion for changing the integer into a float,
int n();
int main(){
int num,x;
printf("Enter num:\n");
scanf("%d", &num);
x=n(num);
printf("The sum of %d is: %f", num, float(x));
return 0;
}
int n(int x){
if (x != 0){
return x + n(x-1);
**strong text** }
else{
return x;
}
}

Scanning and printing variable data type "double" in C

I'm studying algorithms and would love to learn. My problem is this, I can't output a number "600851475143" using the integer data type in C. So I switched to doubles. However the output is "0.0000". Can someone kindly tell me what I'm doing wrong? I simply want to scan and print any number in the double data type then I'm going to focus on getting the highest prime factor :)
#include <stdio.h>
#include <math.h>
int main()
{
double number;
double div = 2;
double highest = 2;
printf("Please input a number: ");
scanf("%lf", &number);
printf("\n You entered: %lf", &number);
while(number!=0){
if(fmod(number,div) != 0){div = div + 1;}
else{
number = number / div;
printf("\n %lf", div);
if(highest < div){highest = div;}
if(number == 1){break;}
}
}
printf("\n The highest number is %lf", highest);
return 0;}
What I did:
Searched for "scan double in c" in google, learned the "%lf" is the right way to go, but the program doesn't show anything.
I checked out various questions in Stackoverflow like:
Why does scanf need lf for doubles
Reading in double values with scanf in c
Difference between float and double
Read and Write within a file in C (double it)
Reading and writing double precision from/to files
float vs. double precision
Reading in double values with scanf in c
Other sites I searched:
http://www.technoburst.net/2011/07/reading-double-in-c-using-scanf.html
Thank you for enlightening me with your knowledge.
The problem is in function printf("%lf",&number) should be printf("%lf",number)
Compiling with a compiler with warnings shows the issue:
dbl.c:13:31: warning: format specifies type 'double' but the argument has type
'double *' [-Wformat]
printf("\n You entered: %lf", &number);
~~~ ^~~~~~~
1 warning generated.
Change that line to:
printf("\n You entered: %lf", number);
You're trying to print the number's address instead of the number.
Also, try adding a newline to the end:
printf("\n The highest number is %lf\n", highest);
Since, you're working with integral numbers, though, I'd advise you to just use a long long, assuming you have a C99 compiler:
#include <stdio.h>
#include <math.h>
int main()
{
long long number;
long long div = 2;
long long highest = 2;
printf("Please input a number: ");
scanf("%lld", &number);
printf("\n You entered: %lld", number);
while(number!=0){
if(number % div != 0){div = div + 1;}
else{
number = number / div;
printf("\n %lld", div);
if(highest < div){highest = div;}
if(number == 1){break;}
}
}
printf("\n The highest number is %lld\n", highest);
return 0;}
You can also reformat your code a bit for readability:
#include <stdio.h>
#include <math.h>
int main() {
long long number, div, highest;
div = highest = 2;
printf("Please input a number: ");
scanf("%lld", &number);
printf("\n You entered: %lld", number);
while(number != 0) {
if (number % div != 0) div += 1;
else {
number /= div;
printf("\n %lld", div);
if (highest < div) highest = div;
if (number == 1) break;
}
}
printf("\n The highest number is %lld\n", highest);
return 0;
}
I would also advise doing the newlines a little differently, which leaves you with:
#include <stdio.h>
#include <math.h>
int main() {
long long number, div, highest;
div = highest = 2;
printf("Please input a number: ");
scanf("%lld", &number);
printf("\n You entered: %lld\n", number);
while(number != 0) {
if (number % div != 0) div += 1;
else {
number /= div;
printf("%lld\n", div);
if (highest < div) highest = div;
if (number == 1) break;
}
}
printf("The highest number is %lld\n", highest);
return 0;
}

Problem determining if a number is an Armstrong Number

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)

Resources