Recursive function crashing - c

I wrote this recursive function to calculate the terms of the sequence:
and to place them in a float array of maximum 1000 element, but this function is crashing as I run and input the float A and I don't see what's the problem in there.
#include<stdio.h>
#include<math.h>
void triple_root(float B[1000],int i,float A,float b,float c){
float x;
x = 0.333*((A/(b*b))+(1/c));
B[i] = x;
if(fabs(x-b)<=0.00001|| i==999)
puts(" ");
else triple_root(B,i+1,A,x,b);
}
int main(){
float A[1000],b;
int i;
scanf("%f",&b);
triple_root(A,0,b,1,1);
for(i=0;i<1000;i++){
printf("%f\n",A[i]);
}
getchar();
}
P.S.: The integer i initial value is 0, and the two floats b and c initial value is 1.

There is no explicit test to make sure i stays below 1000; your code assumes that the recursion will stop before that happens, but I see nothing to insure this.

Even with your latest edit, the code didn't compile for me. It's possible that you were running a broken binary. Not to worry, though! I managed to fix it.
Remove the <conio.h> include. You will rarely if ever need this non-standard header. Change getch to getchar.
Change void main to int main. main returns int, not void.
Viola! http://ideone.com/zeAuP1

Related

recursion c, program does not display

im facing an problem in this program, may anyone tell me, what im doing wrong, the program won't display anything after i give it input.
(Code is about sum of digits enter #example 12345 = 15)
#include<stdio.h>
int sum(int num);
int sum(int num){
int total=0;
if(sum==0){
return total;
}
else{
total+=num%10;
num/=10;
return sum(num);
}
}
int main()
{
int num,k;
printf("Enter 5 positive number: ");
scanf("%d",&num);
printf("Sum is: %d",sum(num));
}
Here is a rule of thumb, whenever you have a non-stopping recursion program try to verify your base cases.
Here you are verifying sum the function instead of num the parameter. The C compiler let's you do that because functions in C are pointers, and pointers hold the addresses as numeric value.
You just need to change the condition from sum==0 to num==0. It will now print something. However, the logic of your program is still wrong. You can change your sum function to this.
int sum(int num){
if(num==0) {
return 0;
}
return num % 10 + sum(num/10);
}
And you can try learning more about recursion through stack since recursion is basically just stack.
In your code the total gets initialized to zero every time the function is called. and a variable named sum is not initialized. Just change sum==0 to num==0.I have also given the logic to sum the digits of a number.

function declaration and call and definition in c

Why is this code not running after printing of array if I take value of n>=9?
#include <stdio.h>
#include <math.h>
float mean_function(float array[],int n);
int main() {
int i,n;
float array[n],mean,sum=0,s2,summation,deno,C[i],elements;
printf("Enter No of Elements\n");
scanf("%d",&n);
printf("Enter Elements\n");
for(i=0;i<n;i++){
scanf("%f",&array[i]);
printf("%f",array[i]);
}
printf("sample variance(s2) : (sum((x-mean)*(x-mean)))/(n-1) /n");
printf("population variance(sigma2) : (sum((x-u)*(x-u))/n");
mean_function(array,n);
for(i=0;i<n;i++) {
deno=((array[i]-mean)*(array[i]-mean));
C[i]=deno;
summation=summation+C[i];
}
s2=((summation)/(n-1));
printf("s2=%f \n",s2);
}
float mean_function(float array[],int n) {
int i;
float sum=0,mean;
for(i=0;i<n;i++){ sum=sum+array[i]; }
mean=(sum/n);
return mean;
}
Why is this code not running after printing of array if I take value
of n>=9?
Some thoughts about your code (and about building programs in steps):
Arrays in C don't change in size once defined. VLAs are out for a variety of reasons. malloc() is in.
Use double, unless there is a specific reason to use floats.
Define and initialize one variable per line. Uninit vars can only result in an error as mentioned by #Jens.
Function declarations at the top (which you have done)
During development, there is no need to complicate things with a scanf (at least initially). It only adds an unwarranted layer of complexity. If you are testing statistical functions (mean, variance), put numbers in a pre-defined static array and verify functionality first.
C[i] as been declared with uninitialized i.
For this initial phase of building this program, I include a basic program.
I am not a fan of zero space between tokens (but ignore that)
Consider calling your array something other than 'array'.
Calculating the size of the samples array allows you to change the number of elements without changing anything else in code; which adds another layer of complexity to an already difficult phase.
#include <stdio.h>
#include <math.h>
double sample_mean(double* p, int n);
int main()
{
double samples[] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 16.5, 2.3};
double mean = 0.0;
int size_samples = sizeof samples/sizeof(double);
printf("size_samples = %d\n", size_samples);
mean = sample_mean(samples, size_samples);
printf("Mean = %.2lf", mean);
}
// -------------------------------
double sample_mean(double* p, int n)
{
double mean = 0.0;
double total = 0.0;
for(int i = 0; i < n; i++)
total += *p++;
mean = total/n;
return mean;
}
Once this functionality is present (saved), you can start working on other stat functions. This way you can work step by step to get closer to the desired outcome.
Next up you can define sample_variance(double* p, int n) and work on that knowing that additional(new errors) are not coming from your code written so far.
Output:
size_samples = 8
Mean = 5.24
I hope it helps.
The code is likely not running because array[n] is declared with an uninitialized n. At the time you read n with scanf(), the array does not automatically "grow into the right size". You should either declare array big enough, or if you really want it to be user-defined, use malloc to allocate it (read the comp.lang.c FAQ) and all Stackoverflow questions tagged array...)
In addition, the scanf at some point fails. Note that when you enter numbers, you also have the "Enter" as a newline ('\n') in the input stream. You never read the newline so the next scanf fails.
This becomes obvious when you actually check the return value from scanf with code like this:
if (scanf("%f", &array[i]) == 1) {
/* successfully converted 1 item */
}
else {
/* scanf failed */
}
Usually what you want is to skip whitespace in the input. You do this by placing a space in the scanf format. Note that a single space tells scanf to skip any amount of white-space.
if (scanf(" %f", &array[i]) == 1) {

C : My 'Poisson calculator' gives me #1.INF00. Why does this happen?

Before anything, here's my code:
#include <stdio.h>
#include <conio.h>
#include <math.h>
main()
{
float Exp, Act, Px, Facto_Act;
printf("\n This is Poisson Distribution Calculator!");
printf("\n Enter the expected value of success in a time period:");
scanf("%f",& Exp);
printf("\n Enter the actual or calculated value of success in a time period:");
scanf("%f",& Act);
Px=pow(M_E,-Exp)*pow(Exp,Act)/Facto_Act;
printf("\n Poisson probability is:%f", Px);
getch();
return 0;
}
Facto_Act(float Act)
{
float c;
float result=1;
for(c=1;c<=Act;c++)
result=result*c;
return result;
}
Further explanation:
Poisson equation looks like this:
P(x)= (e^-Lambda)(Lambda^x)/(x!)
Exp: Expected number of events in a given time(Lambda)
Act: Actual number of events in a given time(x)
Px: Probability of an event occuring in a given time( P(x) )
Facto_Act: Factorial of Actual number of events in a given time(x!)
When I figured out how to do factorials for integer in C, I will try to add factorials for positive decimals too. But #1.INF00 is not a value I expect.
When I compile the code, there are no more coding errors shown. But when I enter the expected value of successes in a period, then the actual value of succesess in a period, I always end up with #1.INF00. I am very noobful of C, and while this site has helped me improved my programs by a bit, I can't understand the '#1.INF00' means.
I decided not to make Facto_Act a function
I decided to circumvent the entire Facto_Act function problem by not making Facto_Act a function, then trying to call it. It seems that factorials can be performed without making a new function for it. Thus Facto_Act is now a variable. This is my new code:
#include <stdio.h>
#include <conio.h>
#include <math.h>
main()
{
double Exp, Px;
int c, Act, Act2, Facto_Act=1;
printf("\n This is Poisson Distribution Calculator!");
printf("\n Enter the expected value of success in a time period:");
scanf("%lf",& Exp);
printf("\n Enter the actual or calculated value of success
\n in a time period(must be an integer!):");
scanf("%d",& Act);
/*My factorial starts here*/
for (c=1;c<=Act;c++)
Facto_Act=Facto_Act*c;
/*My factorial ends here*/
Px=(pow(M_E,-Exp))*(pow(Exp,Act))/Facto_Act;
printf("\n Poisson probability is:%lf", Px);
getch();
return 0;
}
I thank you all for helping me out.
You declared a variable named FactoAct of type float. Since it is an extern variable with no initialisation, it has a value of 0.
Later you define a function Facto_Act(float Act) with an implicit return type of "int".
Your division xxx / FactoAct divides xxx by the variable FactoAct, which is zero. That's where your INF result comes from.
When you had the function at the top, when the compiler saw xxx / FactoAct, FactoAct was not the result of a call to the function, it was the function itself. You can't divide a number by a function. It doesn't make sense. The only thing you can do with a function is take its address, or call it.
You probably want FactoAct (x) or something like that.
PS. Don't use float instead of double, unless you have a reason that you can put into clear words why in your specific case float is better than double.

C return value is displaying some bizarre behavior

A fair warning — I'm very new to C, and there's some unpredictable behavior. I'm not sure how to begin troubleshooting this.
I'm trying to solve one of the early Euler problems (to do with numerical palindromes) and I'm having trouble with my check function. When a number a is passed through rev(a), everything works as it should. When passed through ret(a) (a function which will eventually check for equality, bool type, etc), it returns totally wrong number — something to do with memory, I think. Can anybody help me, please?
#include <stdio.h>
#include <stdbool.h>
int rev(int a);
int check(int a);
main() {
int a = 12;
printf("%i ", a);
printf("%i ", rev(a));
printf("%i\n", ret(a));
}
int ret(int a){
return rev(a);
}
int rev(int a){
int b;
while (a>0){
b = (b*10) + a%10;
a/=10;
}
return b;
}
In rev, the first iteration of the loop
int b;
while (a>0){
b = (b*10) + a%10;
operates on an uninitialised value of b. This makes the end result unpredictable and almost certainly wrong.
The fix is pretty simple - you just need to initialise b to 0
int rev(int a){
int b = 0;
// function unchanged beyond this
If calls to rev worked for you, this was just luck (either good or bad, depending how you look at it). Reading the content of uninitialised memory can have any effect, including the stack for b just happening to be set to 0. You'd probably have found that changing platform or compiler flags caused things to break.

Factorial program using recursive function in c with while loop

Factorial program using recursion in C with while loop. Hi all thanks for your valuable replies.
You all said use (if condition Instead of while). Its correct I accept your suggestion. Then why don't I use while for finding the factorial using recursive function.
Somebody said while(n>1) is an infinite loop. But in this program n value is decremented in the fact(n-1) function itself. Now in this program I put a printf() and getch() after the while loop to know the value of n. The printf() and getch() function executes only when the while condition becomes false.
When I run this program the printf() function and getch() function executes repeatedly and the printf() function return n value = 1. So I determine that the value of n is decremented. Then why does this program execute the while loop again and again?
In all function the return statement is the last function termination statement. When the execution reaches the return statement the execution terminate from the function and go back to the next line of the called function.But in this program after the execution reaches the return statement it will repeat the same function to execute. Why is that?
Note: I am using Turbo C 3.0 to run this program,
#include<stdio.h>
int fact(int n)
{
int x=1;
while(n>1)
{
x=n*fact(n-1);
}
printf("N value after the while loop:%d",n);
getch();
return(x);
}
void main()
{
int n,fact1;
scanf("%d",&n);
fact1=fact(n);
printf("%d",fact1);
}
You do have an infinite loop. The line fact(n-1) doesn't decrease the value of n. It invoked another call of the function with a smaller n.
So, if you call fact(2), you have a call with n==2. In this function, you have an infinite loop that call fact(1). In this second call, n==1, so the loop condition is false, and this call prints your line and return - into the infinite loop of the first call (which its n is still 2).
First of all may I suggest you put a prompt like that before scanf? It is strange to be prompted for a number by the console when there is no text asking you to do so. Looks like the program has hung.
printf("Give the value of n:");
So in order to fix your program I would suggest you do something like the example below.
You have to understand how recursion works. You can't just be calculating a number inside the while(). You have to be returning something , else it's an infinite loop.
#include<stdio.h>
int fact(int n)
{
int x=1;
while(n>1)
{
x = n*fact(n-1);
return x;
}
return x;
}
void main()
{
int n,fact1;
printf("Please provide the value of \'n\':");
scanf("%d",&n);
fact1=fact(n);
printf("Result is %d",fact1);
return 0;
}
Here i would have a pretty easy code to understand for you. It is very short and effective. Of course i coded it using recursion:
The only header you need to include is stdio.h.
Main:
int main() {
unsigned long n;
scanf("%lu", &n);
printf("%lu\n", factorial(n));
}
Function calculation factorial:
unsigned long factorial(unsigned long n) {
if (n==1) {
return 1;
} else {
return n * factorial(n-1);
}
}
As you see it's a pretty short and effective program. I used unsigned longs, so that the program can output and can calculate with very long numbers without getting overflows or stuff like that. You don't need any kind of loop, just the recursive function.

Resources