Void Factorial Using Pointers in C - c

I want to do a void factorial function in C that uses pointers. This is my code but it won't run.
#include <stdio.h>
void factorial(int, int*);
int main()
{
int n;
int r = 0;
printf("Enter n : ");
scanf("%d", &n);
if (n < 0)
{
printf("No factorial for negative");
}
else
{
factorial(n , &r);
printf("factorial of %d is %d", n, r);
}
}
void factorial(int n , int *r)
{
if (n == 0 || n == 1)
{
*r= 1;
}
else
{
*r= n* factorial((n-1), r);
}
}
The error I get is in the last line of the code saying : invalid operands of type "int" and "void" to binary operator * , what does that mean and how to fix it?

Well, if factorial() returns void (which is basically , returning nothing) , this line does not make any sense
*result = num * factorial ((num-1), result);

It's because factorial() returns void.
Try:
factorial((num-1), result);
*result= num *(*result);
Instead of that line.

You cannot use return value of a function if it is declared to return void.
If you want to declare function this way then your factorial function can be:
void factorial(int num , int *result)
{
if (num == 0 || num == 1)
{
//*result = 1;
return;
}
else
{
*result *= num;
factorial ((num-1), result);
}
But also in main function you should change int res = 0 into int res = 1.

void Factorial(int *a,int *result){
if (*a == 0 || *a == 1){
return;
}
else{
*result *= *a;
*a -= 1;
Factorial(a,result);
}}

Related

why this c program can't compile factorial

#include <stdio.h>
int FAC(int a)
{
if (a >= 1, a--)
{
return a + 1 * a;
FAC(a);
}
}
int main()
{
int a = 0;
int ret = 0;
scanf("%d", &a);
ret = FAC(a);
printf("%d\n", ret);
}
if I input 5 the outcome is 8
But in the first function should't it be
5>=1 5-1 return 5*4 4>=1...
First of all, you're returning a value before you're using recursion. The return keyword takes effect immediately, so all statements following this won't be executed.
Also, your factorial function does not actually calculate the factorial of a.
Examples for factorial functions:
Recursive
int factorial(int n) {
if(n > 0) {
return n * factorial(n - 1); // n! = n * (n-1) * (n-2) * ... * 1
} else {
return 1;
}
}
Iterative
// Does exactly the same, just an iterative function
int factorial(int n) {
int fac = 1;
for(; n > 0; n--) {
fac *= n;
}
return fac;
}
Your factorial function (FAC) should ideally be something like:
unsigned int FAC(unsigned int a)
{
// base condition - break out of recursion
if (a <= 1)
return 1;
return a * FAC(a - 1);
}
unsigned int restricts range of argument to be in [0, UINT_MAX].
Do note that FAC returns a unsigned int, so you may be able to provide argument value up to 12, else there will be an overflow and you can see weird output.
BTW, UINT_MAX is defined in limits.h
#include <stdio.h>
int FAC(int a)
{
if (a < 0) {
return -1;
} else {
if (a == 0) {
return 1;
} else {
return (a * FAC(a-1));
}
}
}
int main()
{
int a = 0;
int ret = 0;
scanf("%d", &a);
ret = FAC(a);
if (ret == -1) {
printf("%s\n", "Input was a negative integer.");
} else {
printf("%d\n", ret);
}
}

Factorial calculator using functions in C

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

BackTracking in C Sum of prime numbers?

I want to make a backtracking program to calculate the sum of every prime number smaller then n. Can you help me doing that ? I was working on a code but I do not know why it is not working ! Thx in advance !
I think I`m doing something wrong !
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int v[20],n;
void afisare(int k)
{
int i;
for(i=0;i<=k;i++)
{
printf("%d",v[i]);
}
}
int valid(int k)
{
int i,prim=0;
for(i=1;i<k;i++)
{
if(v[k]%i==0)
{
prim++;
}
}
if(prim==2)
{
return 1;
}
else
{
return 0;
}
}
void backtr(int k)
{
int val;
for(val=1;val<=n;val++)
{
v[k]=val;
if(valid(k))
{
if(k<n-1)
{
afisare(k);
}
else
{
backtr(k+1);
}
}
}
}
int main()
{
int n;
printf("n=");
scanf("%d",&n);
backtr(1);
return 0;
}
A bit late but I hope to help someone else
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int verify(int s) {
if (s == 0)
return 0;
else if (s == 1)
return 1;
else
int z = 0;
int i = 1;
while (i <= s) {
if (s % i == 0)
z++;
i++;
}
if (z == 2)
return s;
else
return 0;
}
int backback(int n, int s, int *sum) {
if (s == n) {
return;
}
int z = verify(s);
*sum = *sum + z;
backback(n, s + 1, sum);
return *sum;
}
int back(int n) {
if (n <= 0)
return 0;
else if (n == 1)
return 1;
else
int sum = 0;
int x = backback(n, 0, &sum);
return x;
}
int main(void) {
int n;
printf("Insert an integer number: \t");
scanf("%d", &n);
int x = back(n);
if (x == 0)
printf("\nInvalid number");
else if (x == 1)
printf("\nThe sum of prime numbers of the number %d is: \t%d", n, x);
else
printf("\nThe sum of prime numbers of the number %d is: \t%d", n, x);
return 0;
}

C programm to find middle number

Hi this is my code to find the middle number of three but when i give a=3 b=2 and c=1 i get wrong output.How can i find the right middle number?Is there any way with arrays?
thank you
#include<stdio.h>
int main()
{
int a,b,c;
int min,mid,max,i=1;
printf("Enter number: ");
scanf("%d",&a);
printf("\nEnter number: ");
scanf("%d",&b);
printf("\nEnter number: ");
scanf("%d",&c);
if(((a<b)&&(b<c)) || ((a>b)&&(a<c)))
{
min=a;
mid=b;
max=c;
}
if(((b<a)&&(a>c)) || ((a>b)&&(a<c)))
{
min=c;
mid=a;
max=b;
}
if(((c<a)&&(c>b)) || ((c>a)&&(c<b)))
{
min=b;
mid=c;
max=a;
}
printf("\nMid is %d",mid);
for(i=min;i<=max;i++)
{
if(i==mid)
continue;
printf("\n%d",i);
}
getchar();
getchar();
}
To make your life easier, write a function called min. It takes two integers and returns the one which is smaller. Now use this function like this:
int min = min(min(a,b),c);
Similar with max.
To get the mid value, just make this calculation:
int mid = a + b + c - max - min;
If you have a sorted array:
int nums[N];
Then:
For N even the median is: (nums[N/2] + nums[(N/2)-1])/2
For N odd the median is: nums[(N-1)/2]
If your array is not sorted, then check the Median of Medians
if you are able to find maximum and minimum values, you can find the middle value like this:
int a = 1, b = 2, c = 3;
int minVal = min(a, b);
int maxVal = max(maxVal, c);
int midVal = a + b + c - maxVal - minVal;
midVal should contain the middle value of those 3 numbers.
Sorting with an array is pretty simple:
#include<stdio.h>
#include<errno.h>
#include<string.h>
#include<stdlib.h>
int compar( const void *a, const void *b)
{
return *(int*)a > *(int*)b;
}
void die(const char *msg)
{
if( errno )
fprintf(stderr, "%s: %s\n", strerror(errno), msg);
else
fprintf(stderr, "%s\n", msg);
exit(EXIT_FAILURE);
}
int get_input(void)
{
int ret;
errno = 0;
if( scanf("%d", &ret ) != 1 )
die("invalid input");
return ret;
}
void * xmalloc(size_t s)
{
void *ret;
ret = malloc(s);
if(ret == NULL)
die("malloc");
return ret;
}
int main(int argc, char **argv)
{
int *a;
int *b;
int count;
count = get_input();
a = b = xmalloc( count * sizeof *a);
while(count-- > 0)
*b++ = get_input();
qsort(a, b - a, sizeof *a, compar);
printf("sorted:");
while(a != b)
printf(" %d", *a++);
putchar('\n');
return EXIT_SUCCESS;
}
int a,b,c;
if(b>a && a>c || c>a && a>b)
printf("The middle number is a");
else if(a>b && b>c || c>b && b>a)
printf("The middle number is b");
else
printf("The middle number is c");

Return a blank integer in c

I want to write a power function that prints "Unable to compute o^o" when asked to do so or return the integer result. how can I accomplish this?
My current code prints the error statement as well as the result statement.
My code:
#include <stdio.h>
double power(int base,int n);
int main() {
int no1,no2;
printf("Enter two numbers:\n");
printf("If you want to compute x^y enter x y\n");
scanf("%i%i", &no1, &no2);
printf("The value of %i^%i is %f", no1, no2, power(no1,no2));
return 0;
}
double power(int base, int n) {
double result = 1;
if( n == 0 && base == 0){
printf("Unable to compute 0^0\n");
}
else if( n == 0 && base != 0) {
result = 1;
}
else if( n>0 ){
for(n ; n>0 ; n--) {
result = result*base;
}
}
else if( n<0 ){
int temp = -n;
result = power(base,temp);
result = (float)1.0/result;
}
return result;
}
EDIT: I am actually a novice. I am in the first chapter of K&R where I found a power function. I wanted to improve that thing and found this hurdle. Hence please provide resources if possible so that I understand your answers.
#BartoszMarcinkowski gives you the correct answer, as an alternative (if you can't pass an extra variable) you can return NAN and check the result with isnan().
In computing, NaN, standing for not a number, is a numeric data type
value representing an undefined or unrepresentable value, especially
in floating-point calculations.
#include <stdio.h>
#include <math.h>
double power(int base,int n);
int main(void)
{
double f;
f = power(2, 2);
if (isnan(f)) {
printf("Unable to compute power\n");
} else {
printf("%f\n", f);
}
return 0;
}
double power(int base, int n) {
double result = 1;
if( n == 0 && base == 0){
return NAN;
}
...
return result;
}
It is common for C functions to return 0 on success or error code in case of failure.
#include <stdio.h>
int power(int base,int n, double *result);
int main() {
int no1, no2;
printf("Enter two numbers:\n");
printf("If you want to compute x^y enter x y\n");
scanf("%i%i", &no1, &no2);
double result;
int error = power(no1, no2, &result);
if(error == 0)
printf("The value of %i^%i is %f\n", no1, no2, result);
return 0;
}
int power(int base, int n, double *result) {
*result = 1;
if(n == 0 && base == 0){
printf("Unable to compute 0^0\n");
return 1;
} else if(n == 0 && base != 0) {
*result = 1;
return 0;
} else if(n>0){
for(; n>0 ; n--) {
*result = *result*base;
}
return 0;
} else if(n < 0){
int temp = -n;
power(base,temp, result);
*result = (float) 1.0 / *result;
return 0;
}
return 1;
}
Note : My answer is in reference to the user's post saying that he is
a novice at learning C, so I have assumed that he might not have yet
be comfortable dealing with pointers.
You can have an error flag in your code that tells the main function that an error has occurred.
You can use a global integer, that is common to all functions of your program to inform of errors in code.
After calling the power function, you check whether the error FLAG is set, which means errors have occurred. So you print the error message instead of the result.
What value you should use for showing a error has occurred is arbitrary. In most cases, a non-zero (sometimes negative) value can indicate the specific error. For example:
FLAG = -1 might indicate invalid input
FLAG = -2 might indicate invalid operation
And so on. etc. Here I have chosen FLAG = non-zero value to mean error has occurred.
#include <stdio.h>
double power(int base,int n);
--> char FLAG = 0;
int main() {
int no1,no2;
---- your code ---
double and = power(no1,no2);
--> if (char) {
printf("error : both values cannot be negative);
char = 0;
} else {
printf("The value of %i^%i is %f", no1, no2, ans);
}
return 0;
}
double power(int base, int n) {
---- your code ---
if( n == 0 && base == 0){
printf("Unable to compute 0^0\n");
--> FLAG = -1;
return 0;
}
else if( n == 0 && base != 0) {
result = 1;
}
else ---- your code ---
}

Resources