This program is not showing 153 as Armstrong Number while for other numbers the output is correct. Like I checked for 407 it gave the right answer but when I checked 153 it showed not an Armstrong number.
#include <stdio.h>
#include <math.h>
int main() {
int no, copy, re, n = 0, ans = 0;
printf("\n\tEnter a new number: ");
scanf("%d", &no);
copy = no;
while (copy != 0) {
copy = copy / 10;
n++;
}
copy = no;
while (copy != 0) {
re = copy % 10;
ans = ans + pow(re, n);
copy = copy / 10;
}
if (ans == no) {
printf("\n\t %d is an Armstrong number", no);
} else {
printf("\n\t %d is not an Armstrong number", no);
}
getch();
return 0;
}
First of all You need to give proper name for variable
Try this code it works for me
#include <stdio.h>
#include <math.h>
int main()
{
int number, originalNumber, remainder, result = 0, n = 0 ;
printf("Enter an integer: ");
scanf("%d", &number);
originalNumber = number;
while (originalNumber != 0)
{
originalNumber /= 10;
++n;
}
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber%10;
result += pow(remainder, n);
originalNumber /= 10;
}
if(result == number)
printf("%d is an Armstrong number.", number);
else
printf("%d is not an Armstrong number.", number);
return 0;
}
In this program, the number of digits of an integer is calculated first and stored in n variable.
And the pow() function is used to compute the power of individual digits in each iteration of the while loop.
Your code has no problem. It works fine. Compiling your code gcc -o file filename.c -lm and run as ./file to avoid the linkage problems.
In my Visual Studio 2013 I got below image with your code.
You may try different compiler software , I think.
Built-in "pow" function cannot be used in this case. Instead you can use this:
int power(int n,int r)
{
int i,p=1;
for(i=1;i<=r;i++)
p=p*n;
return p;
}
and call it in your main function
result += power(remainder, n);
It will work for all cases.
Your algorithm is correct and your program performs as expected (except for the missing newlines) on my system. If your system reports 153 as not being an Armstrong number, it is broken, possibly because of the floating point operation for raising the digits to the n-th power. Try this alternative:
#include <stdio.h>
#include <math.h>
int main(void) {
int no, copy, re, i, d, n = 0, ans = 0;
printf("Enter a new number: ");
if (scanf("%d", &no) == 1) {
copy = no;
while (copy != 0) {
copy = copy / 10;
n++;
}
copy = no;
while (copy != 0) {
d = copy % 10;
for (re = d, i = 1; i < n; i++) {
re *= d;
}
ans = ans + re;
copy = copy / 10;
}
if (ans == no) {
printf("%d is an Armstrong number\n", no);
} else {
printf("%d is not an Armstrong number\n", no);
}
getch();
}
return 0;
}
Related
Trying to make a code that gets the factorial of the inputted number.
int factorial(int number, int i)
{
int endval;
for(i = number - 1; i>0; i--){
endval = number * i;
}
if (endval == 0){
printf("1");
}
return endval;
}
int main()
{
int endvalue, numA, numB;
char userchoice[1];
printf("Enter a choice to make (f for factorial): \n");
scanf("%s", userchoice);
if(strcmp(userchoice, "f")== 0){
printf("Enter a value to get it's factorial: ");
scanf("%d", &numA);
endvalue = factorial(numA, numB);
printf("%d", endvalue);
return 0;}
getch();
return 0;
}
For some reason the whole for loop doesn't do anything in the function when I set the answer (number*i)= endval. It just prints out the same number I inputted and gives me an absurd answer for 0!.
int factorial(int number, int i)
{
int endval;
for(i = number - 1; i>0; i--){
endval = number * i;
}
if (endval == 0){
printf("1");
}
return endval;
}
However the code works perfectly fine when I remove endval variable entirely (with the exception that it gets 0! = 10)
int factorial(int number, int i)
{
for(i = number - 1; i>0; i--){
number = number * i;
}
if (number == 0) {printf("1");}
return number;
}
Is there anything I missed in the code that's causing these errors?
A definiton of factorial is:
factorial(0) = 1
factorial(n) = n * factorial(n-1)
Note: Factorial is legal only for number >= 0
In C, this definition is:
int factorial(int number)
{
if (number < 0)
return -1;
if (number == 0)
return (1);
/*else*/
return (number * factorial(number-1));
}
#include <stdio.h>
#include <string.h>
int factorial(int number)
{
int endval=1;
for(int i = number ; i>0; i--){
endval *= i;
}
return endval;
}
int main()
{
int endvalue=0;
int numA=0;
char userchoice[1];
printf("Enter a choice to make (f for factorial): ");
int ret=scanf("%s", userchoice);
if (!ret){
printf("Error in scanf: %d", ret);
}
if(strcmp(userchoice, "f")== 0){
printf("Enter a value to get it's factorial: ");
scanf("%d", &numA);
endvalue = factorial(numA);
printf("%d", endvalue);
return 0;
}
getchar();
return 0;
}
Code with some changes will work
factorial() function can get only one argument.
As a good habit all variables must be initialized.
Add include statement to source and be explicit not rely on compiler.
As we use strcmp() we must include string.h
use standard getchar() instead of getch()
Also can check return value of library function scanf() to ensure reading is correct or not.
You can use warnings from compiler to get most of above notes. In gcc: gcc -Wall code.c
Use a debugger to run program line by line and monitor variables value in each steps or use as many printf() to see what happens in function call.
There are possibly few things to correct. See please attached code.
int factorial(int number)
{
if (number == 0){ return 1; }
int endval=1, i;
for(i = 1; i<=number; i++) { endval *= i; }
return endval;
}
int main() {
int endvalue, numA;
char userchoice[1];
printf("Enter a choice to make (f for factorial): \n");
scanf("%s", userchoice);
if(strcmp(userchoice, "f")== 0) {
printf("Enter a value to get it's factorial: ");
scanf("%d", &numA);
endvalue = factorial(numA);
printf("%d", endvalue);
return 0;
}
getch();
return 0;
}
test case:
input: 1234
output: 24
input: 2468
output: 2468
input: 6
output: 6
I have this code:
#include <stdio.h>
#include <math.h>
int main() {
int num;
printf("Enter a number: \n");
scanf("%d", &num);
int numberLength = floor(log10(abs(num))) + 1;
int inputNumberArray[numberLength];
int evenNumberCount = 0;
int even[10];//new even no. array
int i = 0;
do {
inputNumberArray[i] = num % 10;
num = num / 10;
i++;
} while (num != 0);
i = 0;
while (i < numberLength) {
if (inputNumberArray[i] % 2 == 0) {
evenNumberCount ++;
even[i] = inputNumberArray[i];
}
i++;
}
printf("array count %d\n", evenNumberCount);
i = 0;
for (i = 0; i < 8; i++) {
printf(" %d", even[i]);//print even array
}
i = 0;
int result = 0;
for (i = 0; i < 10; i++) {
if (evenNumberCount == 1) {
if (even[i] != 0) {
result = even[i];
} else {
break;
}
} else {
if (even[i] != 0) {
result = result + even[i] * pow(10, i);
} else
break;
}
}
printf("\nresult is %d", result);
/*
int a = 0;
a = pow(10, 2);
printf("\na is %d", a);
*/
}
when I enter number 1234, the result/outcome is 4, instead of 24.
but when I test the rest of test case, it is fine.
the wrong code I think is this: result = result + even[i] * pow(10, i);
Can you help on this?
Thanks in advance.
why do you have to read as number?
Simplest algorithm would be
Read as text
Validate
loop through and confirm if divisible by 2 and print live
next thing, have you try to debug?
debug would let you know what are doing wrong. Finally the issue is with indexing.
evenNumberCount ++; /// this is technically in the wrong place.
even[i]=inputNumberArray[i]; /// This is incorrect.
As the user Popeye suggested, an easier approach to accomplish this would be to just read in the entire input from the user as a string. With this approach, you can iterate through each letter in the char array and use the isdigit() method to see if the character is a digit or not. You can then easily check if that number is even or not.
Here is a quick source code I wrote up to show this approach in action:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char input[100] = { '\0' };
char outputNum[100] = { '\0' };
// Get input from user
printf("Enter a number: ");
scanf_s("%s", input, sizeof(input));
// Find the prime numbers
int outputNumIndex = 0;
for (int i = 0; i < strlen(input); i++)
{
if (isdigit(input[i]))
{
if (input[i] % 2 == 0)
{
outputNum[outputNumIndex++] = input[i];
}
}
}
if (outputNum[0] == '\0')
{
outputNum[0] = '0';
}
// Print the result
printf("Result is %s", outputNum);
return 0;
}
I figured out the solution, which is easier to understand.
#include <stdio.h>
#include <math.h>
#define INIT_VALUE 999
int extEvenDigits1(int num);
void extEvenDigits2(int num, int *result);
int main()
{
int number, result = INIT_VALUE;
printf("Enter a number: \n");
scanf("%d", &number);
printf("extEvenDigits1(): %d\n", extEvenDigits1(number));
extEvenDigits2(number, &result);
printf("extEvenDigits2(): %d\n", result);
return 0;
}
int extEvenDigits1(int num)
{
int result = -1;
int count = 0;
while (num > 1) {
int digit = num % 10;
if (digit % 2 == 0) {
result = result == -1 ? digit : result + digit * pow(10, count);
count++;
}
num = num / 10;
}
return result;
}
}
You are overcomplicating things, I'm afraid.
You could read the number as a string and easily process every character producing another string to be printed.
If you are required to deal with a numeric type, there is a simpler solution:
#include <stdio.h>
int main(void)
{
// Keep asking for numbers until scanf fails.
for (;;)
{
printf("Enter a number:\n");
// Using a bigger type, we can store numbers with more digits.
long long int number;
// Always check the value returned by scanf.
int ret = scanf("%lld", &number);
if (ret != 1)
break;
long long int result = 0;
// Use a multiple of ten as the "position" of the resulting digit.
long long int power = 1;
// The number is "consumed" while the result is formed.
while (number)
{
// Check the last digit of what remains of the original number
if (number % 2 == 0)
{
// Put that digit in the correct position of the result
result += (number % 10) * power;
// No need to call pow()
power *= 10;
}
// Remove the last digit.
number /= 10;
}
printf("result is %lld\n\n", result);
}
}
I'm pretty new in programming and I making a decimal to binary converter. I need help to make the print output starts from right to left (reversed).(Sorry if my code is messy)
int main()
{
int num, form;
printf("Decimal to Binary\n\n");
printf(" Value : ");
scanf("%d", &num);
printf(" Expected Format (Type 2 for binary): ");
scanf("%d", &form);
if (form == 2)
printf(" %d base 10 is ", num);
if (form == 2)
do {
if (num % 2 == 0) {
printf("0");
num = num / 2;
}
else {
printf("1");
num = num / 2;
}
} while (num > 0);
else
printf("Invalid input!");
return 0;
}
If I input the value to 25,I expected the output will be "11001", but the actual output is "10011"
Some recursion.. It's looks much more better, for my opinion
#include <stdio.h>
void rec(int num)
{
if (num==0) return;
rec(num>>1);
printf("%d", num%2);
}
int main()
{
int n;
printf("Enter an integer in decimal number system\n");
scanf("%d", &n);
printf("%d in binary number system is: ", n);
rec(n);
printf("\n");
return 0;
}
One possibility would be recursion as Jean-Francois Fabre said. Since you mentioned you are a beginner, recursions are sometimes hard to understand at the beginning, so another possibility that I didn't find in his link would be something like this
#include <stdio.h>
int main()
{
int n, c, k;
printf("Enter an integer in decimal number system\n");
scanf("%d", &n);
printf("%d in binary number system is:\n", n);
for (c = 8; c >= 0; c--)
{
k = n >> c;
if (k & 1)
printf("1");
else
printf("0");
}
printf("\n");
return 0;
}
You can use c to specify the length of your output, or calculate in advance to have a perfect output.
I recently made code in C that reads a set of numbers until zero (zero ends the number set) and prints its prefix sum:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, sum;
sum = 0;
while(x)
{
scanf("%d", &x);
sum += x;
if(x != 0)
{
printf("%d,", sum);
}
else{
break;
}
}
return 0;
}
If I were to type 2 3 5 7 11 0: It would print the following:
2,5,10,17,28,
I was wondering how to remove the comma by the number 28 or to add commas to numbers until the last number?
My preferred solution, adapted to the code in the question, is:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int sum = 0;
int x;
const char *pad = ""; /* Or put a prefix here */
while (scanf("%d", &x) == 1 && x != 0)
{
sum += x;
printf("%s%d", pad, sum);
pad = ","; /* Or use ", " if you prefer */
}
putchar('\n');
return 0;
}
Note that this code does not test the uninitialized variable x on the first iteration (unlike the code in the question), and it checks that the scanf() succeeds before using the value (unlike the code in the question). These are routine precautions you should be taking. It would be possible to adapt the code to keep track of how many bytes have been printed on the line (what's the return value from printf()?) and arrange for pad to contain "\n" (instead of a comma, or ",\n" if you want a comma at the end of all lines except the last) when the line gets 'too long'.
Note too that if you type the numbers at the program, the output gets messy. If the program is reading from a built-in list of numbers, or reading from a file, then you get good outputs.
You could use the following approach:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 0;
int sum = 0;
int i = -1;
int ret;
while(1)
{
i++;
ret = scanf("%d", &x);
if(ret != 1)
break;
sum += x;
if(x != 0)
{
if(i == 0)
printf("%d", sum);
else
printf(",%d", sum);
}
else
{
break;
}
}
printf("\n");
return 0;
}
Output:
1
2
3
0
1,3,6
Print the comma before all but the first value. It's not elegant but it works.
if(x != 0)
{
if(sum == x) // On the first pass, sum == x
printf("%d", sum);
else
printf(",%d", sum);
}
Of course, this could break if you have negative values. In that case, keeping a counter or bool would be better.
print comma only after the first iteration (use a custom flag) , print result no matter what:
int first_iteration = 1;
...
if (!first_iteration)
{
printf(",");
}
sum += x;
first_iteration = 0;
printf("%d", sum);
There is always a clumsy but tried-and-true method:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, sum;
sum = 0;
comma = 0;
while(x)
{
scanf("%d", &x);
sum += x;
if(x != 0)
{
if (comma != 0)
{
printf(",");
}
printf("%d", sum);
comma = 1;
}
else{
break;
}
}
return 0;
}
I'm writing a C program that counts the number of odd digits from user input.
Eg.
Please enter the number: 12345
countOddDigits(): 3
int countOddDigits(int num);
int main()
{
int number;
printf("Please enter the number: \n");
scanf("%d", &number);
printf("countOddDigits(): %d\n", countOddDigits(number));
return 0;
}
int countOddDigits(int num)
{
int result = 0, n;
while(num != 0){
n = num % 10;
if(n % 2 != 0){
result++;
}
n /= 10;
}
return result;
}
The code is not working.
Can someone tell me where does it go wrong?
There were a few mistakes in your code. Here is a working version of your code:
#include <stdio.h>
int countOddDigits(int n);
int main()
{
int number;
printf("Please enter the number: \n");
scanf("%d", &number);
printf("countOddDigits(): %d\n", countOddDigits(number));
return 0;
}
int countOddDigits(int n)
{
int result = 0;
while(n != 0){
if(n % 2 != 0)
result++;
n /= 10;
}
return result;
}
You are mixing n and num together - there is no need for two variables.
n%=10 is just causing mistakes - you need to check the last digit if(n%2!=0) and then move to the next one n/=10, that's all.
Looping variable is not correct. Your outer loop is
while (num !=0)
but the num variable is never decremented; the final statement decrements the n variable. My guess is you want to initialize
int n = num;
while (n != 0 )
{ ...
n/= 10;
}