Showing posts with label C program. Show all posts
Showing posts with label C program. Show all posts

Monday, 23 September 2013

Sunday, 22 September 2013

Saturday, 21 September 2013

Friday, 20 September 2013

Monday, 16 September 2013

Saturday, 14 September 2013

Showing posts with label C program. Show all posts
Showing posts with label C program. Show all posts

Monday, 23 September 2013

Program to print Pascal Triangle


C program to print Pascal triangle using for loop

#include<stdio.h>
long fact(int);
int main(){
    int line,i,j;

    printf("Enter the no. of lines: ");
    scanf("%d",&line);

    for(i=0;i<line;i++){
         for(j=0;j<line-i-1;j++)
             printf(" ");

         for(j=0;j<=i;j++)
             printf("%ld ",fact(i)/(fact(j)*fact(i-j)));
         printf("\n");
    }
    return 0;
}

long fact(int num){
    long f=1;
    int i=1;
    while(i<=num){
         f=f*i;
         i++;
  }
  return f;
 }

Output:

Enter the no. of lines: 8
       1
      1 1
     1 2 1
    1 3 3 1
   1 4 6 4 1
  1 5 10 10 5 1
 1 6 15 20 15 6 1
1 7 21 35 35 21 7 1


Sunday, 22 September 2013

Pointers to pointers in c


Pointers to pointers in c programming language

C pointers to pointers: A pointer is pointing to 
another pointers is called pointers to pointer.


Examples of pointers to pointers in c:


What will be output if you will execute following code?


#include<stdio.h>

int main(){

int s=2,*r=&s,**q=&r,***p=&q;

printf("%d",p[0][0][0]);
return 0;

}


Output: 2

Explanation:


As we know p[i] =*(p+i)

So,

P[0][0][0]=*(p[0][0]+0)=**p[0]=***p

Another rule is: *&i=i

So,

***p=*** (&q) =**q=** (&r) =*r=*(&s) =s=2

Saturday, 21 September 2013

Program in c for Selection Sort


C program for Selection Sort:

Let’s sort this array in ascending order using selection sort algorithm. Bubble sort algorithm was based on repeated comparison of successive elements in an array and exchanging elements if necessary. In selection sort there is a slight difference. One element in the array (usually the first/last element) is assumed as the minimum/maximum of the whole array elements. Now all other members are compared against this assumed min/max element. Based on this comparisons result, exchanges are made between the min/max element and the other element. 
The selection sorting algorithm is also an inefficient one (just like Bubble sort). Selection sort requires 0.5 *(n*n-n) comparisons. The total number of comparisons required is almost same for both Bubble sorting and Selection sorting.


#include<stdio.h>
int main(){

  int s,i,j,temp,a[20];

  printf("Enter total elements: ");
  scanf("%d",&s);

  printf("Enter %d elements: ",s);
  for(i=0;i<s;i++)
      scanf("%d",&a[i]);
 //selection sort 
  for(i=0;i<s;i++){
      for(j=i+1;j<s;j++){
           if(a[i]>a[j]){
               temp=a[i];
              a[i]=a[j];
              a[j]=temp;
           }
      }
  }

  printf("After sorting is:\n ");
  for(i=0;i<s;i++)
      printf(" %d",a[i]);

  return 0;
}

Working of Selection sort:
The element in the first position is assumed to be minimum. It is then compared with other elements one by one (using the 2nd FOR loop). After the first pass of the first FOR loop, the minimum of the whole array (in this case 1) is placed in first position of the array. When the second pass of first FOR loop begins, the next element (i.e second element) is assumed to be minimum and the whole process repeats. 

Compiling the source code....
$gcc main.c -o demo -lm -pthread -lgmp -lreadline 2>&1

Executing the program....
$demo
Enter total elements: Enter 5 elements: 45 67 2 5 77
After sorting is:
  2 5 45 67 77

Program in C for Insertion Sort


C program for Insertion sort:

Insertion sorting algorithm sorts one element at a time. It begins by sorting the first 2 elements in order. In the next step, it takes the third element and compares it against the first two sorted elements. Exchanges are made if necessary and the 3 elements will be sorted with respect to each other. As next step, it takes the fourth element and it compares against the first 3 sorted elements. The process repeats until the whole array of elements are sorted.

#include <stdio.h>
#include <stdlib.h>
int main(){
    int a[10];
     int i,size,j,temp;
    printf("enter sizeelements");
    scanf("%d",&size);
  
    for(i=0;i<size;i++){
    scanf("%d ",&a[i]);
    }
  
  
    for(i=0;i<size;i++){
        for(j=0;j<i;j++){
            
            if(a[j+1]<a[j]){
                temp=a[j+1];
                a[j+1]=a[j];
                a[j]=temp;
                
            }
            
        }
    }
    printf("After sort ");
    for(i=0;i<size;i++){
    printf("%d ",a[i]);
    }
 return 0;
 }

Executing the program....
$demo
enter sizeelementsAfter sort 2 5 45 67 77 



Program in c for BubbleSort


C program for Bubble Sort:

 The first member of the list is compared with the next element. To sort in ascending order we usually begin the process by checking if first element is greater than next element.
 If yes, we interchange their position accordingly. i.e first element is moved to second element’s position and second element is moved to first element’s position. 
If No, then we dont interchange any elements. As next step, the element in second position is compared with element in third position and the process of interchanging elements is performed if required. The whole process of comparing and interchanging is repeated till last element.
 When the process gets completed, the largest element in array will get placed in the last position of the list/array.

#include<stdio.h>
int main(){

  int s,temp,i,j,a[20];

  printf("Enter total numbers of elements: ");
  scanf("%d",&s);

  printf("Enter %d elements: ",s);
  for(i=0;i<s;i++)
      scanf("%d",&a[i]);

  //Bubble sorting algorithm
  for(i=0;i<s;i++){
      for(j=0;j<s;j++){
           if(a[j]>a[j+1]){
               temp=a[j];
              a[j]=a[j+1];
              a[j+1]=temp;
           }
      }
  }

  printf("After sorting:\n ");
  for(i=0;i<s;i++)
      printf(" %d",a[i]);

  return 0;
}

Compiling the source code....
$gcc main.c -o demo -lm -pthread -lgmp -lreadline 2>&1

Executing the program....
$demo
Enter total numbers of elements: Enter 6 elements:5 2 7 8 66 23
 After sorting:
  2 5 7 8 23 66

Sorting Elements using Quicksort


C program to sort elements using Quicksort:

#include<stdio.h>

void quicksort(int [10],int,int);

int main(){
  int x[20],size,i;

  printf("Enter size of the array: ");
  scanf("%d",&size);

  printf("Enter %d elements: ",size);
  for(i=0;i<size;i++)
    scanf("%d",&x[i]);

  quicksort(x,0,size-1);

  printf("Sorted elements: ");
  for(i=0;i<size;i++)
    printf(" %d",x[i]);

  return 0;
}

void quicksort(int x[10],int first,int last){
    int pivot,j,temp,i;

     if(first<last){
         pivot=first;
         i=first;
         j=last;

         while(i<j){
             while(x[i]<=x[pivot]&&i<last)
                 i++;
             while(x[j]>x[pivot])
                 j--;
             if(i<j){
                 temp=x[i];
                  x[i]=x[j];
                  x[j]=temp;
             }
         }

         temp=x[pivot];
         x[pivot]=x[j];
         x[j]=temp;
         quicksort(x,first,j-1);
         quicksort(x,j+1,last);

    }
}

Compiling the source code....
$gcc main.c -o demo -lm -pthread -lgmp -lreadline 2>&1

Executing the program....
$demo
Enter size of the array: Enter 6 elements: 5 7 23 8 66 2
Sorted elements:  2 5 7 8 23 66


Matrix multiplication in c


C program for multiplication of two matrices:

#include<stdio.h>
int main(){
  int a[3][3],b[3][3],c[3][3],i,j;
  printf("Enter the First matrix->");
  for(i=0;i<3;i++)
      for(j=0;j<3;j++)
           scanf("%d",&a[i][j]);
  printf("\nEnter the Second matrix->");
  for(i=0;i<3;i++)
      for(j=0;j<3;j++)
           scanf("%d",&b[i][j]);
  printf("\nThe First matrix is\n");
  for(i=0;i<3;i++){
      printf("\n");
      for(j=0;j<3;j++)
           printf("%d\t",a[i][j]);
  }
  printf("\nThe Second matrix is\n");
  for(i=0;i<3;i++){
      printf("\n");
      for(j=0;j<3;j++)
      printf("%d\t",b[i][j]);
   }
  
    for (i=0;i<3;i++)            //initialisation of mat mul
    {
        for (j=0;j<3;j++)
        {
             c[i][j]=0;
        }
    }
   for(i=0;i<3;i++){
       for(j=0;j<3;j++){
           int k;
       
            for (k=0;k<3;k++)
            {
                c[i][j]+=a[i][k]*b[k][j];
            }
       }}
   printf("\nmultiplication of matrix is\n");
   for(i=0;i<3;i++){
       printf("\n");
       for(j=0;j<3;j++)
            printf("%d\t",c[i][j]);
   }
   return 0;
}


Enter the First matrix->
Enter the Second matrix->
The First matrix is

1 2 3 
4 5 6 
2 4 6 
The Second matrix is

8 1 2 
3 4 5 
6 1 2 
The Multiplication of two matrix is

32 12 18 
83 30 45 
64 24 36 


Friday, 20 September 2013

Display Pascal Triangle in C


C program to display Pascal Triangle

#include<stdio.h>  
main()
{
    int i,j,k[50],l[50][50],m;
    printf("Enter the number of rows.\n");
    scanf("%d",&m);
    for(i=1;i<=m;i++)  
    {  
        for(j=0;j<(m-i);j++)  
        printf("   ");  
        for(j=0;j<i;j++)  
        {  
            k[0]=1;  
            if(j==i-1)  
            k[j]=1;  
            l[i][j]=k[j];  
            k[j+1]=l[i-1][j]+l[i-1][j+1];  
            printf("%5d ",k[j]);  
        }  
        printf("\n");
    }
}


Executing the program....
$demo
Enter the number of rows.
                1 
             1     1 
          1     2     1 
       1     3     3     1 
    1     4     6     4     1 

Program to print triangle in C


C program to print Triangle in C:

#include<stdio.h>
main()
{
    int j,i,k,l;
    char c;
    do
    {
        printf("Enter the number of stars in the base..\n");
        scanf("%d",&k);
        for (i=1;i<=k;i++)  
        {  
            for(l=0;l<(k-i);l++)  
                printf(" ");  
            for (j=0;j<i;j++)  
                printf ("1 ");  
            printf("\n");  
        }  
        printf("\n Enter y to try more...press any other key exit...\t");
    c=getchar();
    c=getchar();
    }
    while(c=='y');
}

------------------------------------------------------------------------------------------------

without using do while loop:

#include<stdio.h>  
main()
{
    int j,i,k,l;
    k=6;
    
    
        for (i=1;i<=k;i++)  
        {  
            for(l=0;l<(k-i);l++)  
                printf(" ");  
            for (j=0;j<i;j++)  
                printf ("* ");  
            printf("\n");  
        }  
}
-------------------------------------------------------------------------------------------------------

Executing the program....
$demo
Enter the number of stars in the base.. 6
     1 
    1 1 
   1 1 1 
  1 1 1 1 
 1 1 1 1 1 
1 1 1 1 1 1 

 Enter y to try more...press any other key exit...

C program for fibonnaci series


C program for displaying elements of FIBONNACI series:

#include <stdlib.h>
#include <stdio.h>

int main(){
    int a[20],i;
    a[0]=1;
    a[1]=1;
    printf("%d ",a[1]);
    for(i=1;i<10;i++){
        a[i]=a[i-2]+a[i-1];
      
        printf("%d ",a[i]);
    }

return 0;
}







Compile and Execute C Online (GNU GCC version 4.7.2)


Executing the program....
$demo
11 2 3 5 8 13 21 34 55 



Palindrome program


C program to check whether the given string or word is a Palindrome or not:


#include<stdio.h>  
#include<string.h>
int main()
{
    int i,j=0,k;
    char a[20];
    printf("Enter a word to check whether its a palindrome.\n");
    scanf("%s",a);
    k=strlen(a);  
    for (i=0;i<k/2;i++)  
    {  
        if(a[i]==a[k-i-1])  
        ;                  //empty statement.  
        else  
         {  
          j++;  
          break;  
         }  
    }  
    if(j>0)  
    printf("The word is not palindrome .\n");
    else  
    printf("The word is palindrome .\n");
    return 0;
}


Executing the program....
$demo
Enter a word to check whether its a palindrome.
abcba
The word is palindrome .

C program for Stack


C program for performing Stack Operation


#include <stdio.h>
#include <stdlib.h>

void push(int);
void pop();
void display();

static int a[10];
static  int top=-1;
int main(){

push(1);
push(5);
push(8);
pop();
push(12);
push(11);

display();
return 0;
  
}
    void push(int i){
        if(top==9){
        printf("stack overflow");
        }
        else
        a[++top]=i;
        
    }
  
    void pop(){
        if(top== -1){
        printf("stack underflow");
        }
        else
        top--;
    }
  
    void display(){
        int i;
        for(i=0;i<top+1;i++)
        printf("%d ",a[i]);
    }


Executing the program....
$demo
1 5 12 11 

Converting String to Integer in C



C program for converting string to an integer using atoi() function:

#include<stdio.h>  
#include<stdlib.h>  

int main(){
    char str[50];
    int number;
 
    //Accepting a numer in string format  
    printf("Enter any number as a string : ");
    scanf("%s",str);
    
    //Converting string into the number;  
    number = atoi(str);  
         if(number==0 && str[0]!='0')
             printf("\nInvalid number");
         else
             printf("\n Equivalent number is : %d",number);
    return 0;
}

OUTPUT:

Enter any number as a string : 23anil
 Equivalent number is : 23



Monday, 16 September 2013

Dynamic memory allocation




Allocate a dynamic array of a stated size.Load numbers into the array and then sum the numbers in the array.

#include <stdio.h>

#include <stdlib.h>


int main()
{
int retval;   /* value returned from scanf */
long *nums;   /* pointer to arrray of numbers to sum */
short how_many;/* number of numbers to input and sum */
short inum;   /* counter to index into nums array */
long sum;     /* sum of numbers in nums array */
    /*
    *    input number of elements to allocate
    */
    printf("\nHow many numbers to sum? ");
    scanf("%hd",&how_many);
    /*
    *    dynamically allocate memory for how_manay 
    *    long's
    */
 nums = (long *)calloc(how_many, sizeof(long) );

    if(nums == (long *)NULL)
    {
         fprintf(stderr,"\nCould not allocate memory");
         return 1;
    }
    /*
    *    input numbers to store in array
    */
    for( inum =0; inum < how_many; ++inum)
    {
         printf("\nEnter #%d: ", inum + 1);
         retval = scanf("%ld",&nums[inum] );
    }
    /*
    *    sum the numbers in the array
    */
    for( sum = inum = 0; inum < how_many; ++inum )
    {
         /*
         *    add number to sum
         */
         sum += nums[inum];
         /*
         *    show running total
         */
         printf("\n%3d: %10ld %10ld",
              inum+1,nums[inum],sum);
    }
    /*
    *    print the final total
    */
    printf("\nThe sum of the %d numbers",how_many);
    printf(" entered is %ld\n",sum);
    /*
    *    free the memory back to the heap
    */
    free( (char *)nums );
    return 0;

}

Executing the program....
$demo
How many numbers to sum? 
Enter #1: 
Enter #2: 
  1:         21         21
  2:          3         24
The sum of the 2 numbers entered is 24

Concept of pointers in C


Const, volatile and Pointers

It is possible to create a const pointer, a pointer to a const variable, a volatile pointer and a pointer to a volative variable.
const int x = 5;
int const *ptrX = &x;
Here ptrX is a pointer to a const, not a const that also happens to ba a pointer. The const keyword modifies the item that is to the immediate right, which is the *, not ptrX. If the code had been as follows:
int y = 10;
int *const ptrY = &y;
The const keyword in the above code would have modified ptrY, not the * and a const pinter to an integer would have been created. The pointer is constant, not the item being pointed to. If a pointer points at a const variable then the variable cannot be modified through that pointer. The pointer, which is not a const, can be modified.
 The pointer can be changed to point at a variable that is not const. If a pointer is defined as being a const pointer, then the pointer can never be modified but the memory to which it refers can be changed. In the above paragraphs, the keyword volatile can be substituted for wherever the word const is used. The syntax rules for using volatile are the same as those for const. The following program demostrates both correct and incorrect uses of const.


#include <iostream.h>

int const X = 1;   // X is a const

const int Y = 2;
const int *ptrY = &Y;   // ptrY is a pointer to a const int 

const int Z = 3;
int const *ptrZ = &Z;   // ptrZ is also a pointer to const int

int W= 4;
int *const ptrW = &W;   // const pointer to int

int T = 5;              // an integer

const int *const ptrT;  // uninitialized const pointer to const 
                        // int

int main()
{
    X = 10;        // ERROR - cannot modify a const
    *ptrY = 11;    // ERROR - cannot modify a const through a 
                   // pointer
    ptrY = &Z;     // OKAY - ptrY itself is not const
    *ptrZ = 12;    // ERROR - cannot modify a const through
                   // a pointer
    ptrZ = &W;     // OKAY - ptrZ itself is not const
    *ptrW = 13;    // OKAY - ptrW does not point to a const
    ptrW = &T;     // ERROR - cannot modify ptrW, it is a const
    ptrT = &T;     // ERROR - cannot modify ptrT, it is a const

    return 0;
}

Saturday, 14 September 2013

C program for inserting elements in circular Linkedlist




C program for inserting elements in circular Linkedlist


#include <stdio.h>
#include <stdlib.h>

//structure of node 
struct node{
int data;
struct node *link;
};

 //prototype declaration
void insert(struct node **,struct node **,int );
void display(struct node *);

int main(){
struct node *front;
struct node *rear;
front=rear=NULL;
insert(&front,&rear,10);
insert(&front,&rear,32);
insert(&front,&rear,30);
insert(&front,&rear,50);
insert(&front,&rear,42);
insert(&front,&rear,60);

display(front);
return 0;
}

//inserting elements in the circular linked list 
void insert(struct node **f,struct node **r,int num){
struct node *temp;

//allocating memory for the temp pointer
temp=(struct node *)malloc(sizeof(struct node));
temp->data=num;

if((*f)==NULL){

*f=temp;
}
else
(*r)->link=temp;

//last element that is rear sholud point to the front element that is front ,point it's link to front *r=temp;
(*r)->link=*f;

}


//display the elements from front
void display(struct node *f){
struct node *p,*q;
p=NULL;
//q pointer points to the first element that is front
q=f;
while(q!=p){
printf("%d ",q->data);
q=q->link;

p=f;
}
}


Executing the program....
$demo
10 32 30 50 42 60