why the function giving ans 0 - c

int get_fact(int N)
{
int fact=1;
while(N--)
{
fact=fact*N;
}
return fact;
}
Why it is giving ans zero??
Tried to have the factorial of N.
here while loop used.but somehow 0 is multiplicatd. But why this happened?

A while loop let you do repeated execution of code until the Boolean value becomes false(when the condition becomes 0).
This line
while (N--)
will continue executing until the value of N equals 0, at which point the condition becomes false. Any number multiplied by 0 results in 0.
There's your answer.
Change that to:
int get_fact(int N)
{
int fact = 1;
while(N)
{
fact = fact * N;
N--;
}
return fact;
}
On the difference between prefix and postfix ++ in C, see also;
https://www.eskimo.com/~scs/readings/autoincrement.990118.html

Related

Any idea on why this program is returning that 987 is a prime number (when it is not a prime number)?

I think the problem is with the for-loop but I cannot understand it. This is an assignment in school that I only should use for-loops and if statements to solve!
#include <stdio.h>
int is_prime(int n){
for (int i=2;i<n;i++){
if (n%i!=0){
return 1;
}
else{
return 0;
};
};
}
int main(void){
printf("%d\n", is_prime(11)); // 11 is a prime. Should print 1.
printf("%d\n", is_prime(383)); // 383 is a prime. Should print 1.
printf("%d\n", is_prime(987)); // 987 is not a prime. Should print 0.
}
For starters the null statement after the if statement and the for loop itself
for (int i=2;i<n;i++){
if (n%i!=0){
return 1;
}
else{
return 0;
};
^^^
};
^^^
is redundant.
Due to the if statement the for loop is interrupted as soon as either n % i is not equal to 0 or is equal to 0. So in general the behavior of the function does not depend on whether the passed number is prime or not prime.
If you will move the return statement
return 1;
outside the loop as others advised nevertheless the function will be still incorrect. It will show that 0 and 1 are prime numbers while they are not.
Also the condition of the loop makes the loop inefficient at least because it is clear before entering the loop that any even number except 2 is not a prime number.
Pay attention to that the function parameter should have unsigned integer type.
The function can be defined the following way
#include <stdio.h>
int is_prime( unsigned long long int n )
{
int prime = n % 2 == 0 ? n == 2 : n != 1;
for ( unsigned long long int i = 3; prime && i <= n / i; i += 2 )
{
prime = n % i != 0;
}
return prime;
}
int main(void)
{
printf( "%d\n", is_prime( 11 ) );
printf( "%d\n", is_prime( 383 ) );
printf( "%d\n", is_prime( 987 ) );
return 0;
}
The program output is
1
1
0
The problem is return 1 inside the loop. When you find one i that is not a factor of n, you assume n to be prime. But you have to ensure that all i are not a factor of prime, so the return 1 must be placed after the loop. However, that would cause numbers < 2 to be considered prime, as they do not enter the loop at all. Therefore, you also have to add an additional if at the beginning.
By the way: Every divisor of n (expect n itself) must be <= sqrt(n), therefore you can speed up your function quite a bit.
#include <math.h>
int is_prime(int n) {
if (n < 2)
return 0;
int max_divisor = sqrt(n);
for (int i = 2; i <= max_divisor; i++) {
if (n % i == 0)
return 0;
}
return 1;
}
Problem: return statement
return 1;
}
else{
return 0;
It causes the loop to exit then and there. In your case too, it exits as soon as the first '1' is achieved.
Solution: Instead you should try to store the values in a variable and compare with '1' or '0' at the end of loop

why is my variable storing value from previous recursion runs?

the first image is of the Program with regular recursion format, I am returning values for both cases but self call to the function is made only when the argument is a natural number. The result is as expected
in the second program, however, I am not returning any value for natural numbers, the only return case is when the argument is 0.
Ideally, (taking 5 as the input) recursion will happen till num value equals 0. First with
sum = 5 + add(5-1);
sum = 4 + add(4-1);
sum = 3 + add(3-1);
sum = 2 + add(2-1);
sum = 1 + add(1-1);
At this stage, the function will return 0 as flow moves to else block,and value of sum for that loop is 0.
Now, with 0 being returned we rise one step up and 0 will take place of add(1-1) in the line
sum = num + add(num-1);
it should look like
sum = 1 + 0;
the function add(num) should terminate now, after assigning 1 to variable sum.
Two main questions.
No value should rise up for sum = 2 + add(2-1), as in the previous step no value is returned. for add(1), after getting value from add(0), summation of 1 and returned value is stored in variable sum and then exits out of function body.
Every time recursion occurs new variable sum is declared and initiated to 0, so, I don't see why the computer is storing the values of the sum from previous calls to the function, when instead it should start a fresh new variable sum.
to me, after completion of code, the value of variable sum in add() should be 1.
Please someone, if you can make sense of this code. Let me know. Much appreciated
P.s: you can try this on any online C compiler as well. Here is the code:
#include <stdlib.h>
#include <stdio.h>
int add(int num);
int main(){
int number,sum;
printf("enter a number of your choice: ");
scanf("%d",&number);
sum = add(number);
printf("SUM = %d",sum);
}
int add(int num){
int sum = 0;
if(num != 0)
sum = num + add(num-1);
else
return sum;
}
sum = add(number);
Using the return value of a function that flowed off the end without explicitly returning a value is undefined behavior. UB means anything is allowed to happen, including giving you the (false) illusion that a variable is "storing value from previous recursion runs". Quoting from C11 6.9.1/12:
If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
A function declared to return an int must always return a value (i.e. an int value). Your code doesn't.
int add(int num){
int sum = 0;
if(num != 0)
// If the execution gets in here
sum = num + add(num-1);
else
return sum;
// it will continue here (when the recursion ends).
// And here it is WITHOUT a returned value - that's bad.
}
You probably want:
int add(int num){
int sum = 0;
if(num != 0)
sum = num + add(num-1);
return sum;
}
or
int add(int num){
if(num != 0)
return num + add(num-1);
else
return sum;
}
or (more clear and secure):
int add(int num){
if(num <= 0)
{
return 0;
}
return num + add(num-1);
}

the sum of divisor (other than itself)

Write a program that reads integer from the keyboard and, on the output, writes the sum of the divisors of n (other than itself).
I've created a method that finds the sum of divisor. Using the while statement I can have up to 10 integers entered by the user until EOF. In the while statement I had sum = the output of sum_divisor and print out sum.
If I enter 0 0 0 4 5 6 12 then the output should be 0 0 0 3 1 6 16.
The output I get is 0 0 0 3 4 10 26. How can I make it so that it doesn't add the sum_divisor to the previous sum?
#include <stdio.h>
int sum_divisor(int x);
int main()
{
int x;
int sum;
printf("Enter up to 10 positive integer ending with EOF:\n");
while((scanf("%d",&x)) != EOF){
sum = sum_divisor(x);
printf("%d ", sum);
}
return 0;
}
int sum_divisor(int x){
int i;
int sum;
if(x<= 0){
sum = 0;
}
else{
for(i=1;i<x;++i)
{
if(x%i==0)
sum += i;
}
}
return sum;
}
You should initialise sum to zero within your function. Otherwise, it will be set to some arbitrary value and the else block will have an arbitrary result.
In other words, change:
int sum;
into:
int sum = 0;
Of course, once you've done that, there's no need to explicitly do anything for the case where x is less than one. In addition, the initial if is superfluous since the for body won't execute when x is less than one, so you could get away with something like:
int sumDivisors (int x) {
int i, sum = 0;
for (i = 1 ; i < x; i++) {
if ((x % i) == 0) {
sum += i;
}
}
return sum;
}
As an aside, the values you're actually seeing without the initialisation are accumulating:
0 -> 0
0 -> 0
0 -> 0
3 -> 3
1 -> 4
6 -> 10
16 -> 26
This is almost certainly because each call to the function is reusing the same memory for the stack frame, including the variable sum, so sum is simply being added to each time (that the passed-in parameter is greater than one).
However, that's simply an artifact of the implementation, it's not guaranteed by the standard, which states quite clearly in C11 6.7.9 Initialization /10:
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
In other words, don't rely on this.
And, as yet another aside, it's a mathematical given that, if a number n divides evenly by a, it also divides evenly by n/a. You can use this to your advantage to possibly make the code a little more efficient (though, as with all optimisations, you should measure, not guess).
Since you're discounting the number itself as a divisor, you have to treat the divisor 1 as a special case. You also have to treat perfect squares as a special case so that you don't add the square root twice.
The following code would be a good starting point for that:
int sumDivisors (int x) {
int i, sum;
// Always return zero for -inf..1 inclusive.
if (x < 2)
return 0;
// Otherwise, 1 is factor, search for others
// up to but NOT including sqrt(x).
for (i = 2, sum = 1 ; i * i < x; i++) {
if ((x % i) == 0) {
sum += i;
sum += x / i;
}
}
// Add in sqrt(x) ONCE for a perfect square.
if (i * i == x)
sum += i;
return sum;
}
When you call sum_divisor inside the while statement the same block of stack is being allocated, and therefore the sum variable is allocated in the same position on every call. At the first call the value is 0,(but not necessarily), the next time the value will be the one you calculated on the previous call.
int sum = 0; should fix it.
int sum_divisor(int x){
if(x <= 0) { // you do not need to even alocate space for i an sum if x < 1.
return 0;
}
int i = 1;
int sum = 0;
for(i=1;i<x;++i)
{
if(x%i==0)
sum += i;
}
return sum;
}

checking for co-prime in C prgramming language

#include <stdio.h>
int iscoprime(int num1, int num2);
int main() {
int x;
x = iscoprime( 7, 8 );
printf("%d",x);a
}
int iscoprime(int num1, int num2) {
int r = 0;
int gcd = 0;
int i;
for(i = 0; (i < num1) || (i < num2) ; ++i) {
if( (num1 % i == 0) && (num2 % i == 0)) {
gcd = i;
}
}
if ( gcd == 1 ) r = 1;
return r;
}
Error: this program has stopped..??? :(
Your program has some flaws.
1) The for loop starts with i value 0. So, in the first iteration itself, floating point exception will occur. It should start from 1.
2) Your question stated that the program is finding the gcd. Which doesn't seem to be the matter. It seems to me that it is finding whether the given numbers are co-prime or not.
If its a GCD program, the return statement should be
return gcd; //without the previous if condition
Its unclear what you want your return value to mean from the iscoprime function. It looks like it returns the greatest common divisor and then checks if it is 1, then the two inputs are co-prime, and else it uses r's initial value of 0 hence meaning it will print 1 if the numbers are co-prime and 0 if they are not. Your for loop doesn't quite make sense. The max greatest common divisor of two numbers can have would be the lower of the two values. I would start your for loop at this value, 7 in your case and decrement i with each iteration and return i when both numbers divide by i without a remainder. This would would then be your greatest common divisor, if it is 1, then your two numbers are co-prime.
While this implementation is fine for small numbers, if the numbers are going to be very large, I would have a look at https://en.wikipedia.org/wiki/Euclidean_algorithm which can compute the GCD very fast and the same will still apply, if the GCD is 1, the two inputs are co-prime.

Transform iterative function into recursive one - C

EDIT: NOT HOMEWORK, i am trying to solve a test from past years, just learning.
I have this function, and would like to know what steps to take in order to transform it into a recursive one.
This is my function, it sums the N first odd numbers:
4^2 = 1+3+5+7 = 16;
int quadIT(int n){
int x=0;
int z=1;
int y=n;
while(y>0){
x+=z;
z+=2;
y--;
}
return x;
}
Probably the function above is not the best approach.
I would appreciate any help here.
I don't want to give you a straight answer, but rather show you roughly how to do it.
These two are equivalent:
int foo(int n){
if (n == 0){
return something
} else {
do something
return foo(n-1);
}
}
while(n > 0){
do something
n--;
}
When you convert an iteration to recursion, look at the loop variable. In this case, that is your variable y. Make it a parameter of your recursive function. Next, look at other variables that change as you iterate through your loop, and make them parameters, too. At this point, you should have your function's declaration down:
int quatItRecursive(int y, int x, int z) {
...
}
Now you are ready to work on the body of your function. Start with the base case by considering the result that you get when the loop does not start (i.e. when n is zero). In this case, your function return x. So now you have your base case:
int quatItRecursive(int y, int x, int z) {
if (y == 0) {
return x;
}
...
}
To complete the body, add the recursive step, i.e. a call that performs the step of your loop. It is a recursive call now, with parameters that equal what the variables would be in the next iteration of the loop:
int quatItRecursive(int y, int x, int z) {
if (y == 0) {
return x;
}
return quatItRecursive(y-1, x + z, z + 2);
}
Finally, add a wrapper that takes a single parameter, the way your original function did:
int quantIT(int n) {
return quatItRecursive(n, 0, 1);
}
You need to break down the problem into using a reduced version of itself, plus some extra bit. In this case, the sum of the first N odd numbers is the sum of the first N-1 odd numbers plus a quantity you can calculate.
So
int sum_odd(int n)
{
if (!n) return 0;
return sum_odd(n-1) + some_calculation_here;
}
int quadIT(int n)
{
if ( n == 1 )
{
return 1;
}
else
{
return ((2*n)-1 + quadIT(n-1));
}
}
The recursive function can be defined the following way
#include <iostream>
unsigned long long quadIT( unsigned long long n )
{
return n == 0 ? 0 : 2 * n - 1 + quadIT( n - 1 );
}
int main()
{
for ( unsigned long long i = 0; i < 10; i++ )
{
std::cout << quadIT( i ) << std::endl;
}
}
The output is
0
1
4
9
16
25
36
49
64
81
Take into account that the function parameter should be defined as some unsigned integral type. Otherwise the function will be more compound.

Resources