Printing Fibonacci series using Recursion - c

//assume (main function)
int fibonacci(int a,int b){
//int i inifinite loop(why?)
static int i=1;
if(i==terms){
return 0;
}
else{
int c;
c=a+b;
a=b;
b=c;
printf(" %d ",c);
i++;
fibonacci(a,b);
return 0;
}
}
If I declare i variable in fibonacci function (definition function) it prints infinite loop of garbage values instead I used static i variable then the code prints Fibonacci series, please explain me how the statics variable works in this code?

If you declare the variable i as having automatic storage duration
int fibonacci(int a,int b){
//int i inifinite loop(why?)
int i=1;
//...
then in each recursive call of the function the variable i is initialized anew by the value 1 and you have an infinite loop of recursive calls.
When you declare the variable i as having static storage duration
int fibonacci(int a,int b){
//int i inifinite loop(why?)
static int i=1;
//...
then it is initialized only once before the program starts.
In any case your function is incorrect because even if the variable i is declared as having static storage duration it is not reset to its initial value after recursive function calls. And moreover it is a bad approach when a function depends on a global variable as your function depends on the global variable terms.
Moreover the Fibonacci series is a fixed series. The user should not specify the variables a and b. It should specify for the function the index of the number in the series that he is going to obtain. And the function should return this number instead of returning 0.
For example the function could be defined the following way
unsigned long long int fibonacci( unsigned int n )
{
return n < 2 ? n : fibonacci( n - 1 ) + fibonacci( n - 2 );
}
Here is a demonstration program.
#include <stdio.h>
unsigned long long int fibonacci( unsigned int n )
{
return n < 2 ? n : fibonacci( n - 1 ) + fibonacci( n - 2 );
}
int main()
{
for (unsigned int i = 0; i < 10; i++)
{
printf( "%u -> %llu\n", i, fibonacci( i ) );
}
}
The program output is
0 -> 0
1 -> 1
2 -> 1
3 -> 2
4 -> 3
5 -> 5
6 -> 8
7 -> 13
8 -> 21
9 -> 34

Related

C program to adjust the carry in an integer array

I want to write a C program to adjust the carry in an integer array (i.e. convert the 2 digit number into a single-digit and add the carry to the next number).
For example -
Array - 6 12 3 15 7
Answer: 7 2 4 5 7
Here's my code:
#include<stdio.h>
int main(){
int array[6]={6,22,3,15,7};
int array2[2];
int i;
printf("%d\n",array[1]);
for(i=0;i<6;i++){
if(array[i]>10){
array2[i]=array[i];
printf("Value at %d element of array is: %d \n",i,array2[i]);
}
}
return 0;
}
So far I have been able to write a program that just finds out double-digit numbers in the array.
I'm relatively new to C and don't know much about how to perform arithmetic operations in arrays.
Help me please!!
since we are adding the carry to previous element, we should start in reverse order.
#include <stdio.h>
int main()
{
int i;
int a[5] = {6,22,3,15,7};
for(i=4;i>0;i--)
{
if(a[i]>9)
{
int rem = a[i]%10;
int carry = a[i]/10;
a[i] = rem;
a[i-1] = a[i-1] + carry;
}
}
if(a[0]>9)
a[0] = a[0]%10;
for(i=0;i<5;i++)
{
printf("%d ",a[i]);
}
return 0;
}

The sum in C with recursion

I'm trying to do a program that will do a sum for an array. If i put a printf in the function, it returns right, but at the final the result is incorrect. Why?
#include <stdio.h>
int summ(int a[100],int n)
{
static int sum=0;
static int i=0;
if(i<n)
{
sum+=a[i];
++i;
return (summ(a,n)+sum);
}
}
int main()
{
int b[100];
int n,i,suma;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&b[i]);
}
suma=summ(b,n);
printf("Suma=%d",suma);
return 0;
}
Compiling your code with warnings enabled should yield the following output:
program.c:13:1: warning: control may reach end of non-void function [-Wreturn-type]
This means that your summ function lacks a base case - i.e. it does not specify what should be returned once n is reached.
Once you fix this problem, your code starts returning the correct value. However, your function would still need some fixing, because you should not be using static variables in it. Any static variable in a function makes the function non-reentrant, which is very bad. In particular, your function can be run only once; second invocation would yield an error, because neither i nor sum could be reset.
Here is a simple recursive implementation of what you are looking to build:
int summ_impl(int a[], size_t i, size_t n) {
return i != n ? a[i] + summ_impl(a, i+1, n) : 0;
}
int sum(int a[], size_t n) {
return summ_impl(a, 0, n);
}
With recursion:
int summ(int *a, int n) {
if (n-- > 0)//the n is equal to n-1 after check condition
return (summ(a,n) + a[n]);//return the n-1 sum (recursion) + current value
return (0);
}
This way, the function will call itself while it not equal to zero (so between n and 0)
So we got:
a = [1,2,3]
the function will return
3 + sum before
-> 2 + sum before
-> 1 + sum before
-> 0
When the function go back in the stack
0 + 1 + 2 + 3 -> 6

Run Time Check Failure Stack around the variable was corrupted

#include <stdio.h>
main()
{
int num[9], i = 0, count = 0;
while (i<10)
{
scanf("%d", &num[i]);
if (num[i] % 2 == 0)
{
count++;
}
i++;
}
printf("we have %d double numbers\n", count);
}
Run-Time Check Failure #2 - Stack around the variable was corrupted
What should I do?
Your while loop hits all values of i from 0 to 9 inclusive, but attempting to access num[9] takes you out of bounds. You'll need to reduce the while loop range:
while (i<9) {
...
}
In addition, you really should give your main() function a return type, since modern compilers don't tolerate it being missing:
int main()
{
...
return 0;
}
The valid range of indices that can be used to access an array with N elements is [0, N - 1] or that is the same [0, N ).
Thus the condition in the while statement
while (i<10)
has to be rewritten like
while (i < 9)
The reason of the error is using "magic numbers" throughout the program.
Try to use named constants instead of magic numbers, In this case it will be easy to understand what magic number is used in what part of the code.
The program can look like
#include <stdio.h>
#define N 9
int main( void )
{
int num[N];
unsigned int count = 0;
unsigned int i = 0;
while ( i < N )
{
scanf( "%d", &num[i] );
if ( num[i] % 2 == 0 ) ++count;
i++;
}
printf( "we have %u double numbers\n", count);
}
Instead of the while loop it would be better to use a for-loop because the variable i is not used outside the loop.
For example
#include <stdio.h>
#define N 9
int main( void )
{
int num[N];
unsigned int count = 0;
for ( unsigned int i = 0; i < N; i++ )
{
scanf( "%d", &num[i] );
if ( num[i] % 2 == 0 ) ++count;
}
printf( "we have %u double numbers\n", count);
}
A more correct approach of declaring indices of arrays is using the type size_t for them.
In fact the array is not used in the program. You could count even entered values without using an array.
Take into account that according to the C Standard the function main without parameters shall be declared like
int main( void )

What does 'c' parameter do in coding?

What does parameter do in programming ?
For example
void main()
int n = 6;
int test(int n)
Is the int n inside the int test refer to the void main int 6 ?
Can anyone explain further for me.
Tq guys have better understanding now.
Based on your description..
n = 6 both in the main function and the test function.
E.g.
void main()
{
int n = 6;
test(n); //shows 8
print("%d", n); //shows 6
}
int test(int n)
{
n = n + 2;
return n;
}
Here we have two 'n' in two functions representing two different values.
If that function is inside main then "int test(int n)" is declaration of function and u need to write that function outside main.When u call test function u just pass value and no declaration of variable is required.For example test(n) will refer the n in the main program.

Finding frequency of an integer in an array and calculating x to the nth power

I am trying to solve two different C problems and would like some help and advice in order to better understand how C works and if I'm on the right track with these.
First problem is: To write a function that counts the number of times the value (x) appears among the first (n) elements of an array and returns that count as the frequency of x in theArray. So, an example would be if the array being passed contained the values {5, 7, 23, 8, 23, 67, 23}. And n was 7 and x was 23, then it would return a value of 3 since 23 occurs 3 times within the first 7 elements of the array.
Here is what I have so far:
#include <stdio.h>
#define SIZE 20 /* just for example - function should work with array of any size */
int frequency (int theArray[], int n, int x)
{
int i;
int count = 0;
for (i = 0; i < n; i++)
{
if (theArray[i] == x)
{
count = count++;
}
}
return (count);
}
int main(void)
{
/* hard code n and x just as examples */
int n = 12; /* look through first 12 items of array */
int x = 5; /* value to find */
int numberFrequency;
long int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
numberFrequency = frequency (theArray[SIZE], n, x);
printf ("%i", numberFrequency);
return 0;
}
Currently I'm getting a run time error message and believe it has something to do with the for loop function.
Second problem is: Write a function that raises an integer to a positive integer power. Have the function return a long int, which represents the results of calculating x to the nth power. Do not use the C pow library function and do not use recursion!
My code so far:
#include <stdio.h>
int x_to_the_n (int x, int n)
{
int i;
long int result = 1;
if (n == 0)
{
return(result);
}
else
{
for (i = 0; i < n ; ++i)
{
/* equation here - How can I make (x*x*x*x*x*x,etc...? */
result = x*(n*x);
}
}
return (result);
}
int main(void)
{
int x =4;
int n =5;
long int result;
result = x_to_the_n (x, n);
printf ("%i", result);
return 0;
}
I can't use recursion so that is out of the question. So, I thought the next best thing would be a for loop. But I'm a little stuck in how I would go about making a for loop do (xxx*x....) based on value of (n). Any help and advice would be appreciated!
In the first problem you give an element after the array as a parameter to your function.
You define a long int array, and pass it into a function expecting an int array.
long int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
should be
int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
Instead of this:
numberFrequency = frequency (theArray[SIZE], n, x);
try this:
numberFrequency = frequency (theArray, n, x);
And replace:
count = count++;
with:
count++;

Resources