My function should get a non-negative integer, and return how many digits there are in the number, for Example for the number 563 the function return 3.
And for 0 will return 1.
*I'm new in c so it still very confusing for me.
Thanks.
Here is my code:
#include <stdio.h>
int numOfDigits(int n); //Declartion
void main()
{
int num1, counter = 0, newNum;
printf("Enter A Number: ");
scanf("%d", &num1);
}
int numOfDigits(int n1)
{
int counter = 0;
if (n1 == 0)
return 1;
while (n1 > 0) {
counter++;
n1 /= 10;
}
return counter;
}
What should I write to make the program work?
Just call the digit counting function that you made and assign its return value to a variable, and then print the value of that variable using printf() function; or alternatively, call your digit counting function inside printf() as an argument:
#include <stdio.h>
int numOfDigits(int n);
int main(void)
{
int num1;
int counter = 0;
printf("Enter A Number: ");
scanf("%d", &num1);
counter = numOfDigits(num1);
printf("number of digits: %d\n", counter);
//printf("number of digits: %d\n", numOfDigits(num1)); alternate method
}
int numOfDigits(int n1)
{
int counter = 0;
if (n1 == 0)
return 1;
while (n1 > 0) {
counter++;
n1 /= 10;
}
return counter;
}
A couple of notes:
Since you mentioned that you need to get a non-negative number, consider using unsigned int type, and change the format specifier inside scanf() and printf() call to "%u".
Function main should be declared as int main(void) or int main(int argc, char **argv)
Related
#include <stdio.h>
int factorial(int b)
{
return (b * factorial(b - 1));
}
int main()
{
int num;
printf("Enter a no:\n");
scanf("%d", &num);
printf("factorial is %d\n", factorial(num));
return 0;
}
You are missing a base case. Also, you don't want negative numbers to be input, so make the function arguments and return type to be of unsigned int.
A base case is a condition to end the recursion. Since it wasn't present, the program was executing even for negative values of b.
#include <stdio.h>
unsigned int factorial(unsigned int b)
{
if (b <= 1)
{
return b;
}
return (b * factorial(b - 1));
}
int main()
{
int num;
printf("Enter a no:\n");
scanf("%d", &num);
printf("factorial is %u\n", factorial(num));
return 0;
}
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;
}
I am learning about functions and how to call upon them and use them in class. I don't quite understand where I've gone wrong here. I know that there are some mistakes around the int main part. I have asked my teacher and he is reluctant on giving me an example that would solve my problems or help me out. I think my main problem is at factorial_result = factorial();
#include <stdio.h>
void mystamp(void)
{
printf("My name is John Appleseed\n");
printf("My lab time is 12:30 on Sunday\n");
return;
}
int getnum(void)
{
int local_var;
printf("Please enter an integer: ");
scanf("%d%*c", local_var);
return(local_var);
}
int factorial(void)
{
int x,f=1,local_var;
for(x=1; x <= local_var; x++)
f = f * x;
return(f);
}
int main(void)
{
int result;
int factorial_result;
mystamp();
result = getnum();
factorial_result = factorial();
printf("You typed %d\n", result);
printf("The factorial is %d\n", factorial_result);
return;
}
Declare local_var as a global variable and do:
local_var = getnum();
OR
Change main() to:
int main(void)
{
int result;
int factorial_result;
mystamp();
result = getnum();
factorial_result = factorial(result);
printf("You typed %d\n", result);
printf("The factorial is %d\n", factorial_result);
return;
}
And factorial() to:
int factorial(int n)
{
int x,f=1,local_var=n;
for(x=1; x <= local_var; x++)
f = f * x;
return(f);
}
Your factorial should be calculated based on the input( i.e in your case int result ).
So, your method factorial() should looks as follows :
int factorial( int number )
{
int factorial_value = 1;
while( number > 0 )
{
factorial_value *= number;
number--;
}
return factorial_value;
}
Then, the correct factorial would be returned and printed accordingly ! Regarding the scope of the variables that you have used, see the comments under your question.
#include <stdio.h>
int factorial(int);
int main()
{
int num;
int result;
printf("Enter a number to find it's Factorial: ");
scanf("%d", &num);
if (num < 0)
{
printf("Factorial of negative number not possible\n");
}
else
{
result = factorial(num);
printf("The Factorial of %d is %d.\n", num, result);
}
return 0;
}
int factorial(int num)
{
if (num == 0 || num == 1)
{
return 1;
}
else
{
return(num * factorial(num - 1));
}
}
This is a simple factorial program using recursion calling function !
include
int main()
{
int c, n, fact = 1;
printf("Enter a number to calculate its factorial\n"); scanf("%d", &n);
for (c = 1; c <= n; c++) fact = fact * c;
printf("Factorial of %d = %d\n", n, fact);
return 0;
}
int main()
{
int i,n;
printf("Enter the number");
scanf("%d",&n);
i=pali(n);
if(n==i)
printf("Number is pall");
else
printf("Not Pall");
}
int pali(int n)
{
int r;
static sum=0;
if(n!=0)
{
r=n%10;
sum=sum*10+r;
pali(n/10);
}
return sum;
}
I used a static variable to add up the sum. Is there any way where no static variable will be used?
Yes, the typical ("functional") approach is to carry the state in the form of a function argument. This often makes it necessary/nice to have a second function that does the actual recursion, which you can start by calling with the proper initial values for the state:
int do_pali(int sum, int n)
{
if(n != 0)
{
const int r = n % 10;
return do_pali(10 * sum + r, n / 10);
}
return sum;
}
the public function then just becomes:
int pali(int n)
{
return do_pali(0, n);
}
In languages with inner functions this can be more neatly expressed (GCC supports this as an extension).
Sure, you can do it this way :
#include <stdio.h>
int pali(int n)
{
int sum = 0;
int keeper = 0;
for (int i = n; i > 0; i /= 10) {
if (keeper != 0) {
sum *= 10;
sum += (keeper - i * 10);
}
keeper = i;
}
sum *= 10;
sum += keeper;
return sum;
}
int main(int argc, char** argv)
{
int i, n;
printf("Enter the number : ");
scanf("%d",&n);
i = pali(n);
if(n == i)
printf("Number is palindrome");
else
printf("Not Palindrome");
}
Using recursion is even easier :
#include <stdio.h>
int pali(int n, int sum)
{
sum += n - ((n / 10) * 10);
n /= 10;
if (n > 0)
pali(n, sum * 10);
else
return sum;
}
int main(int argc, char** argv)
{
int i, n;
printf("Enter the number : ");
scanf("%d",&n);
i = pali(n, 0);
if(n == i)
printf("Number is palindrome");
else
printf("Not Palindrome");
}
And a recursive version with only one parameter :
#include <stdio.h>
int pali(int n)
{
int fUnit, lUnit;
fUnit = n;
int mul = 1;
while (fUnit > 10) {
fUnit /= 10;
mul *= 10;
}
lUnit = n - ((n / 10) * 10);
n -= (fUnit * mul);
n /= 10;
if (mul == 1) return 1;
else if (fUnit == lUnit) return pali(n);
else return 0;
}
int main(int argc, char** argv)
{
int n;
printf("Enter the number : ");
scanf("%d",&n);
if(pali(n) == 1)
printf("Number is palindrome");
else
printf("Not Palindrome");
}
Since your function returns sum you could replace this line:
pali(n/10);
with
sum=pali(n/10);
You'd also have to move it up a line too.
Here is an optimized version that
Doesn't use local static.
Only includes stdio.h
Uses recursion.
#include <stdio.h>
static void perform_useless_recursion (int n)
{
if(n--)
{
perform_useless_recursion(n);
}
}
_Bool is_pali (int n)
{
perform_useless_recursion(1);
int sum = 0;
for(int i=n; i!=0; i/=10)
{
sum = sum*10 + i%10;
}
return n == sum;
}
int main (void)
{
int n=5005;
if(is_pali(n))
printf("Number is pall");
else
printf("Not Pall");
return 0;
}
The code could be improved even further by removing the perform_useless_recursion() function.
The advantage of this code is that the actual calculation is performed by a fast loop, instead of slow, dangerous recursion. In the real world outside artificial school assignments, there is no reason to write inefficient and dangerous code when you could write efficient and safe code. As a bonus, removing recursion also gives far more readable code.
If you benchmark this code you'll notice that it will be faster than all other versions posted and consumes less memory.
You can make a function that check only the first and the last digits of the number and pass the rest of the number onward.
To explain better, think about the following cases:
pali(1220) would check for the first (1) and last (0) digits. Since 1 != 0 pali would return false.
pali(17891) would check first (1) and last (1). Since they're equal then the function would recursively return pali(789) (which itself would return false since 7 != 9).
pali(878) would check that 8=8 and recursively return pali(7)
pali(3) would check that first (3) and last (3) numbers are equal and return 0.
The challenge here is to develop an algorithm that:
Check if first and last numbers are the same (even if it's only one digit!)
Strip the number from first and last digits and call itself on the remainder
Then all you need to do is apply recursion. Here's a sample implementation:
int pali(int number)
{
int smallDigit, bigDigit;
/* When recursion ends suceffuly*/
if (number == 0)
return 1;
/* Check for first and last digit of a number */
smallDigit = number % 10;
bigDigit = number;
while(bigDigit/10!=0)
{
bigDigit = bigDigit/10;
smallDigit = smallDigit*10;
}
/* Check to see if both digits are equal (Note: you can't use smallDigit here because it's been multiplied by 10 a few times) */
if (bigDigit != number%10)
return 0;
else
{
number = (number - smallDigit)/10; /* This is why smallDigit was multiplied by 10 a few times */
return pali(number); /* Recursion time */
}
}
I need to make a program that checks to see if an entered value has any repeated digits. The user is asked to enter numbers until the entered value is 0. If there are any repeated digits, it displays "repeated digits" and then asks the user to enter another value. If there are no repeated digits, it displays "no repeated digits" and asks the user to enter another number. So far, this is what i have. It terminates the program when 0 is entered, but it always displays "no repeated digits" even if there are some.
#include <stdbool.h>
#include <stdio.h>
int main(void)
{
bool digit_seen[10] = {false};
int digit;
long int n = 0;
printf("Enter a number: ");
scanf("%ld", &n);
while(n >= 0){
if(n==0)
break;
while (n > 0){
digit = n % 10;
if (digit_seen[digit]){
digit_seen[digit] = true;
break;
}
n /= 10;
}
if (n > 0)
printf("Repeated digit: %d\n", digit);
else
printf("No repeated digit\n");
scanf("%ld", &n);
}
return 0;
}
A couple of things:
1: A bool only has two states: true and false. If you trying to build a frequency counter of each digit seen, for the presence of a digit more than once, then you should use a data type that can count to at least two, like a char or short or int, or your own enum.
2: This code:
if (digit_seen[digit]){
digit_seen[digit] = true;
break;
}
Is never going to be evaluated as true since you initialized digit_seen to be false at the start of your main function. What you should be doing is something like this:
#include <stdio.h>
int main(int argc, char *argv[])
{
int digit_seen[10] = {0};
int entry;
int i, flag = 0;
printf("Enter a number: ");
scanf("%ld", &entry);
while(entry > 0)
{
int digit = (entry%10);
digit_seen[digit]++;
if(digit_seen[digit]>=2)
{
printf("Repeated digit: %d\n", digit);
}
entry /= 10;
}
for(i = 0; i < 10; i++)
{
if(digit_seen[i]>1) flag=1;
}
if(!flag)
{
printf("No repeated digits\n");
}
return 0;
}
#include <stdio.h>
int main() {
int seen [10] ={0}; // we set every element for a number is just 0
int N,rem;
printf("Enter the number:");
scanf("%d", &N);
while(N>0){
rem = N%10;
seen[rem]+=1;
N = N/10;
}
int i;
for(i=0;i<10;i++){ // checking the number seen counts
if(seen[i]==0){
continue;
}
printf("%d seen %d times\n",i,seen[i]); // just returned the given numbers informations
}
return 0;
}