Showing posts with label c language example. Show all posts
Showing posts with label c language example. Show all posts

Sunday, September 4, 2011

C program for Binary Search

Hello, Today I am sharing how to implement Binary Search in C Programming 
language. Here is the basic algorithm for binary search:


C program for binary search :

#include<stdio.h>

int main(){
  int a[8];
  int i,x,first,last,mid;

printf("\nEnter 8 sorted elements like 
               [2 4 7 9 12 13 16 20]");
for(i=0;i<8;i++)
{
scanf("%d",&a[i]);
}
printf("\nYou entered following numbers:");
for(i=0;i<8;i++){
printf(" %d",a[i]);
}
printf("\nEnter the number you want to search: ");
scanf("%d",&x);
  
first=0,last=n-1;
while(first<=last){
      mid=(first+last)/2;
      
 if(x==a[mid]){
printf("\nThe number is found at %d", mid);
        return 0;
      }
      else if(x<a[mid]){
last=mid-1;
      }
      else
first=mid+1;
}

    printf("\nThe number is not in the list");

return 0;

}


I hope you this post is helpful for you. Thanks for reading.





Sunday, November 28, 2010

C Program For Fibonacci Series

Hello everybody I want to discuss about How to generate a Fibonacci series in C programming.

What is Fibonacci Series?


The first two Fibonacci numbers are 0 and 1 then next number is addition of previous two numbers.

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89.....
In mathematics it is defined by recurrence relation.

Program Code


  


//C Program for generate Fibonacci series
#include "stdio.h"
#include "conio.h"
void main()
{
int a,b,c,i,n;
clrscr();
a=0;
b=1;
printf("\n enter n for how many times generate series");
scanf("%d",&n);
printf("\n FIBONACCI SERIES\n");
printf("\t%d\t%d",a,b);
for(i=0;i<n;i++)
{
c=a+b;
a=b;
b=c;
printf("\t%d",c);
}
getch();
}

Input\Output



Thursday, November 11, 2010

C Program to check number is palindrome or not



C Program Code


//Check number is palindrome of not
#include "stdio.h"
#include "conio.h"
void main()
{
int num,rev=0,m,r;
clrscr();
printf("enter any number");
scanf("%d",&num);
m=num;
while(num>0)
{
r=num%10;
rev=rev*10+r;
num=num/10;
}
if(rev==m)
printf("given number is palindrome");
else
printf("given number is not palindrome");
getch();
}

Input/Output


enter any number 121
given number is palindrome

enter any number 423
given number is not palindrome

What is Palindrome No?


when we read a number. If backward read is as same as forward read then number is palindrome.