Saturday, 30 May 2015

C program to find hcf and lcm using recursion.

#include <stdio.h>
 #include<conio.h>
long gcd(long, long);

int main() {
  long x, y, hcf, lcm;
  clrscr();
  printf("Enter two integers\n");
  scanf("%ld%ld", &x, &y);

  hcf = gcd(x, y);
  lcm = (x*y)/hcf;

  printf("Greatest common divisor of %ld and %ld = %ld\n", x, y, hcf);
  printf("Least common multiple of %ld and %ld = %ld\n", x, y, lcm);

  getch();
}

long gcd(long a, long b) {
  if (b == 0) {
    return a;
  }
  else {
    return gcd(b, a % b);
  }
}

Output:-
Enter two integers
9
24
Greatest common divisor of 9 and 24 = 3

Least common multiple of 9 and 24 = 72

Fibonacci series program in c using recursion


#include<stdio.h>
#include<conio.h>

void printFibonacci(int);

void main(){

    int k,n;
    long int i=0,j=1,f;
          clrscr();
    printf("Enter the range of the Fibonacci series: ");
    scanf("%d",&n);

    printf("Fibonacci Series: ");
    printf("%d %d ",0,1);
    printFibonacci(n);

    getch();
}

void printFibonacci(int n){

    static long int first=0,second=1,sum;

    if(n>0){
         sum = first + second;
         first = second;
         second = sum;
         printf("%ld ",sum);
         printFibonacci(n-1);
    }

}

Sample output:

Enter the range of the Fibonacci series: 10
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89


Print factorial of a given number using recursive function.

#include<stdio.h>
#include<conio.h>

int fact(int);
void  main(){
  int num,f;
  clrscr();
  printf("\nEnter a number: ");
  scanf("%d",&num);
  f=fact(num);
  printf("\nFactorial of %d is: %d",num,f);
  getch();
}

int fact(int n){
   if(n==1)
       return 1;
   else
       return(n*fact(n-1));
 }

Output:-
Enter a number: 6
Factorial of 6 is: 720

Friday, 29 May 2015

What is recursion?

A function that calls itself is known as recursive function and this technique is known as recursion in C programming.
Example of recursion in C programming
Write a C program to find sum of first n natural numbers using recursion. Note: Positive integers are known as natural number i.e. 1, 2, 3....n

#include <stdio.h>
#include<conio.h>
int sum(int n);
void  main(){
    int num,add;
    clrscr();
    printf("Enter a positive integer:\n");
    scanf("%d",&num);
    add=sum(num);
    printf("sum=%d",add);
    getch();
}
int sum(int n){
    if(n==0)
       return n;
    else
       return n+sum(n-1);    /*self call  to function sum() */
}
Output
Enter a positive integer:
5
15
In, this simple C program, sum() function is invoked from the same function. If n is not equal to 0 then, the function calls itself passing argument 1 less than the previous argument it was called with. Suppose, n is 5 initially. Then, during next function calls, 4 is passed to function and the value of argument decreases by 1 in each recursive call. When, n becomes equal to 0, the value of n is returned which is the sum numbers from 5 to 1.
For better visualization of recursion in this example:
sum(5)
=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15
Every recursive function must be provided with a way to end the recursion. In this example when, n is equal to 0, there is no recursive call and recursion ends.
Advantages and Disadvantages of Recursion
Recursion is more elegant and requires few variables which make program clean. Recursion can be used to replace complex nesting code by dividing the problem into same problem of its sub-type.
In other hand, it is hard to think the logic of a recursive function. It is also difficult to debug the code containing recursion.


Wednesday, 27 May 2015

Call by value and call by reference.

Call by Value
If data is passed by value, the data is copied from the variable used in for example main() to a variable used by the function. So if the data passed (that is stored in the function variable) is modified inside the function, the value is only changed in the variable used inside the function. Let’s take a look at a call by value example:
#include <stdio.h>
#include<conio.h>
void call_by_value(int x) {
               printf("Inside call_by_value x = %d before adding 10.\n", x);
               x += 10;
               printf("Inside call_by_value x = %d after adding 10.\n", x);
} 
void main() {
               int a=10;
               clrscr();
               printf("a = %d before function call_by_value.\n", a);
               call_by_value(a);
               printf("a = %d after function call_by_value.\n", a);
               getch();
} 
The output of this call by value code example will look like this:
a = 10 before function call_by_value.
Inside call_by_value x = 10 before adding 10.
Inside call_by_value x = 20 after adding 10.
a = 10 after function call_by_value. 
Ok, let’s take a look at what is happening in this call-by-value source code example. In the main() we create a integer that has the value of 10. We print some information at every stage, beginning by printing our variable a. Then function call_by_value is called and we input the variable a. This variable (a) is then copied to the function variable x. In the function we add 10 to x (and also call some print statements). Then when the next statement is called in main() the value of variable a is printed. We can see that the value of variable a isn’t changed by the call of the function call_by_value().
Call by Reference
If data is passed by reference, a pointer to the data is copied instead of the actual variable as is done in a call by value. Because a pointer is copied, if the value at that pointers address is changed in the function, the value is also changed in main(). Let’s take a look at a code example:
#include <stdio.h>
#include<conio.h>
void call_by_reference(int *y) {
               printf("Inside call_by_reference y = %d before adding 10.\n", *y);
               (*y) += 10;
               printf("Inside call_by_reference y = %d after adding 10.\n", *y);
}
void main() {
               int b=10;
               clrscr();
               printf("b = %d before function call_by_reference.\n", b);
               call_by_reference(&b);
               printf("b = %d after function call_by_reference.\n", b);
               getch();
} 
The output of this call by reference source code example will look like this:
b = 10 before function call_by_reference.
Inside call_by_reference y = 10 before adding 10.
Inside call_by_reference y = 20 after adding 10.
b = 20 after function call_by_reference. 
Let’s explain what is happening in this source code example. We start with an integer b that has the value 10. The function call_by_reference() is called and the address of the variable b is passed to this function. Inside the function there is some before and after print statement done and there is 10 added to the value at the memory pointed by y. Therefore at the end of the function the value is 20. Then in main() we again print the variable b and as you can see the value is changed (as expected) to 20.



What is function in c.

C functions are basic building blocks in a program. All C programs are written using functions to improve re-usability, understandability and to keep track on them.
A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.
Defining a Function:
The general form of a function definition in C programming language is as follows:
return_type function_name( parameter list )
{
   body of the function
}
A function definition in C programming language consists of a function header and a function body. Here are all the parts of a function:
·        Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
·        Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.
·        Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
·        Function Body: The function body contains a collection of statements that define what the function does.
Example:
Following is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum between the two:
/* function returning the max between two numbers */
int max(int num1, int num2)
{
   /* local variable declaration */
   int result;

   if (num1 > num2)
      result = num1;
   else
      result = num2;

   return result;
}
Function Declarations:
A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.
A function declaration has the following parts:
return_type function_name( parameter list );
For the above defined function max(), following is the function declaration:
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so following is also valid declaration:
int max(int, int);
Function declaration is required when you define a function in one source file and you call that function in another file. In such case you should declare the function at the top of the file calling the function.
Calling a Function:
While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task.
When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. For example:
#include <stdio.h>
#include<conio.h>
/* function declaration */
int max(int num1, int num2);

int main ()
{
   /* local variable definition */
   clrscr();
   int a = 100;
   int b = 200;
   int ret;

   /* calling a function to get max value */
   ret = max(a, b);

   printf( "Max value is : %d\n", ret );

getch();
}

/* function returning the max between two numbers */
int max(int num1, int num2)
{
   /* local variable declaration */
   int result;

   if (num1 > num2)
      result = num1;
   else
      result = num2;

   return result;
}
I kept max() function along with main() function and compiled the source code. While running final executable, it would produce the following result:
Max value is : 200