Return a blank integer in c - 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 ---
}

Related

Prime factorization programm doesn't work for certain inputs

I'm a beginner. I am suppossed to write a simple primal factorization programm and what i came up with has a weird behavior.
Inputs are suppossede to be in the range of 64 bits integer(long long).
It works just fine until i input values of certain length i.e. 13. (picture attached), in which case it just shut's down without an error, which i assume indicated that the programm sees the number as 0, because it should give an error otherwise.
Now, i think problem may be in pointers or in scanf function, so i'd much appreciate if somebody points me in the way of where my mistake is.
I programm in VS on Windows 10, using standard command prompt as terminal.
#include<stdio.h>
#include<math.h>
#include<stdbool.h>
#include<stdint.h>
int ReadInput(int64_t *n, int *ret);
void Primal_Factorization(int64_t n);
enum {INPUT_ERROR = 100, SUCCESS = 0};
int main()
{
int ret = SUCCESS;
int64_t n = 0;
while (ReadInput(&n, &ret) > 0)
{
Primal_Factorization(n);
}
if (n < 0)
{
fprintf(stderr, "Error: Chybny vstup!\n");
ret = INPUT_ERROR;
}
return ret;
}
int ReadInput(int64_t *n, int *ret){
if(scanf("%lld", n) != 1){
*n = 0;
fprintf(stderr, "Error: Chybny vstup!\n");
*ret = INPUT_ERROR;
}
return *n;
}
void Primal_Factorization(int64_t n){
int64_t n_sqrt = sqrt(n);
int count;
int64_t n_origin = n;
bool first_iteration = true;
printf("Prvociselny rozklad cisla %lld je:\n", n);
for (int i = 2; i <= n_sqrt; i++){
count = 0;
if(n % i == 0){
if(first_iteration == false) printf(" x ");
while (n % i == 0){
n = n / i;
count++;
}
if(count != 1) printf("%d^%d", i, count);
else printf("%d", i);
first_iteration = false;
} else continue;
}
if(n_origin == n) printf("%lld\n", n);
else if(n != 1) printf(" x %lld\n", n);
else printf("\n");
}
In this function:
int ReadInput(int64_t *n, int *ret){
if(scanf("%lld", n) != 1){
*n = 0;
fprintf(stderr, "Error: Chybny vstup!\n");
*ret = INPUT_ERROR;
}
return *n;
}
The 64-bit integer is returned as an int which is then used in the main() function to check if the value is positive. The range of int is system-dependent, but if the int is 32 bit (very commonly the case), then for example 10^18 will after truncation to 32-bits result in the value -1486618624, i.e. a negative value. Thus the program terminates because the returned value from ReadInput() is negative, but it does not print the error because n (the untruncated 64-bit integer) is positive.
A minimal modification would be to have ReadInput() return a int64_t instead of int:
int64_t ReadInput(int64_t *n, int *ret)

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

Void Factorial Using Pointers in 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);
}}

value returned from a function is not same as received. Why?

I am returning values 1 or 0 from function isprime(0 when it is not prime and 1 when it is prime) but when i print the returned value of x(return value of isprime) it is not same as what I returned from isprime. Why?
#include<stdio.h>
int isprime(int b);
main()
{
int a,rem,i;
printf("enter the number");
scanf("%d", &a);
for(i = 1; i < a; i++)
{
rem = a % i;
if(rem == 0)
{
int x = isprime(i);
printf(" value of x returned for i = %d is %d", i, x);
if(x = 1)
{
printf("%d\n", i);
}
}
}
return (0);
}
/**
*
*returns 1 if b is prime else returns 0
*/
int isprime(int b)
{
int x, count = 0;
printf("input recieved %d \n", b);
for(x = 1; x <= b; x++)
{
if (b % x == 0)
{
count = count + 1;
}
printf("the value of count is %d\n", count);
}
if(count == 2) {
printf("returning the value as 1\n");
return 1;
}
else {
printf("returning the value as 0\n");
return 0;
}
}
if(x = 1)
= is assignment. You need == operator instead. You are doing correct in other if conditions though.
Also, the logic of calculating prime numbers is inefficient. You can break the loop once the count is greater than 2.
if (b % x == 0)
{
count = count + 1;
if (count > 2)
{
// This ensures you are returning correct value later.
break;
}
}
Have a look at this algorithm: Sieve of Eratosthenes
This answer is correct.
For removing such kind of mistakes use it like
if(1=x)
using this approach you can avoid such behavior.
Here I am just approaching to avoid typo mistakes.

Resources