C Program to list Armstrong Numbers upto 1000 - c

#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;
}

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.

C program to read 'n' numbers and find out the sum of odd valued digits of each number and print them

i am new to programing, i want to know that how we can find the odd digits in a number.
the condition in this program is we should only use concept of arrays.I tried a code for this as follows:
#include <stdio.h>
int main()
{
int A[50],i,x,y,n,sum=0;
scanf("%d",&n);
printf("the value is %d\n",n);
for(i=0;i<n;i++)
scanf("%d",&A[i]);
for(i=0;i<n;i++){
x=A[i]%10;
if(x%2!=0)
sum=sum+x;
A[i]=A[i]/10;
printf("the sum of odd numbers is %d\n",sum);
}
return 0;
}
but in this the code is checking for only one digit of the first number in the loop and then next time it is going to check the digit of second number.
so, i need to write a code to check all digits in the number and then it goes to next number and check all digits and should continue the same process in the loop.So, for this how should i modify my code?
You were missing a loop that would iterate through every digit of A[i] - the inner while loop below,
#include <stdio.h>
int main()
{
int A[50], i, x, y, n, sum=0;
printf("How many numbers will you input?\n");
scanf("%d",&n);
printf("the value is %d\n",n);
for(i=0; i<n; i++) {
scanf("%d",&A[i]);
}
for(i=0; i<n; i++) {
sum = 0;
while (A[i] > 0) {
x = A[i]%10;
if(x%2 != 0) {
sum = sum + x;
}
A[i] = A[i]/10;
}
printf("the sum of odd numbers is %d\n",sum);
}
return 0;
}
The exact algorithm for iterating through each digit in a nice form can be found in this post - although for a different language. Here, apart from the while loop, you also need to reset the sum each time unless you want a cumulative sum over all provided numbers.
Note that I changed the formatting a bit - more space, extra braces, and a message about what you're prompting the user to input.
int temp;
int sum = 0;
temp = number;
do {
lastDigit = temp % 10;
temp = temp / 10;
sum += (lastDigit %2 != 0) ? lastDigit : 0;
} while(temp > 0);

Average of Even Numbers and Product of all Odd Numbers

#include <stdio.h>
#include <conio.h>
int getn(int n, int i);
int main()
{
int n, i;
getn(n, i);
getch();
return 0;
}
int getn(int n, int i)
{
int even = 0;
int odd = 1;
int avg;
printf("Enter ten integers: \n");
for (i = 1 ; i <= 10 ; i++)
{
printf("Integer %d: ", i);
scanf("%d", &n);
if ( n % 2 == 0 )
{
even = even + n;
}
else
{
odd = odd * n;
}
}
avg = even / 10;
printf("\n\nAverage of even numbers: %d", avg);
printf("\nProduct of odd numbers: %d", odd);
}
It seems the even calculations worked but when it comes to odd it gives the wrong answer. Please help
Our instructor wants us to use looping or iterations. No arrays. Please help me
First, your C code needs some correction:
at least give the prototype of getn before using it
getn is defined to return an int and doesn't return anything. Either replace int with void or return a value.
Second,
Your code computes the product of ten numbers, if this product is too big, it cannot be store as-is in an int. For example, it works well if you enter ten times number 3, the result is 59049, but if you enter ten times number 23, it will answer 1551643729 which is wrong because 23^10=41426511213649 but that can't be stored in an int. This is known as arithmetic overflow.
Your average is bad, because you sum ints, but the average is (in general) a rational number (average(2,3)=2.5 isn't it ?). So double avg = out/10.0; (means compute a floating division) and printf("Average %f\n",avg); would be better.

Calculating the average of user inputs in c

disclaimer: I'm new to programming
I'm working on this problem
so far ive written this which takes user inputs and calculates an average based on them
#include <stdio.h>
int main()
{
int n, i;
float num[100], sum = 0.0, average;
for(i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i+1);
scanf("%f", &num[i]);
sum += num[i];
}
average = sum / n;
printf("Average = %.2f", average);
return 0;
}
I'd like the user to enter -1 to indicate that they are done entering data; I can't figure out how to do that. so if possible can someone explain or give me an idea as to how to do it
Thank you!
#include <stdio.h>
int main()
{
int i = 0;
float num[100], sum = 0.0, average;
float x = 0.0;
while(1) {
printf("%d. Enter number: ", i+1);
scanf("%f", &x);
if(x == -1)
break;
num[i] = x;
sum += num[i];
i++;
}
average = sum / i;
printf("\n Average = %.2f", average);
return 0;
}
There is no need for the array num[] if you don't want the data to be used later.
Hope this will help.!!
You just need the average. No need to store all the entered numbers for that.
You just need the number inputs before the -1 stored in a variable, say count which is incremented upon each iteration of the loop and a variable like sum to hold the sum of all numbers entered so far.
In your program, you have not initialised n before using it. n has only garbage whose value in indeterminate.
You don't even need the average variable for that. You can just print out sum/count while printing the average.
Do
int count=0;
float num, sum = 0;
while(scanf("%f", &num)==1 && num!=-1)
{
count++;
sum += num;
}
to stop reading at -1.
There is no need to declare an array to store entered numbers. All you need is to check whether next entered number is equal to -1 and if not then to add it to the sum.
Pay attention to that according to the assignment the user has to enter integer numbers. The average can be calculated as an integer number or as a float number.
The program can look the following way
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int sum = 0;
printf("Enter a sequence of positive numbers (-1 - exit): ");
for (unsigned int num; scanf("%u", &num) == 1 && num != -1; )
{
++n;
sum += num;
}
if (n)
{
printf("\nAverage = %llu\n", sum / n);
}
else
{
puts("You did not eneter a number. Try next time.");
}
return 0;
}
The program output might look like
Enter a sequence of positive numbers (-1 - exit): 1 2 3 4 5 6 7 8 9 10 -1
Average = 5
If you need to calculate the average as a float number then just declare the variable sum as having the type double and use the corresponding format specifier in the printf statement to output the average.

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