Saturday 29 December 2012

Mobile Bill Generator Program in C

#include<stdio.h>

int main()
{
    int calls,c1; float bill,rental;
  
    printf("Program for call billing\n\n");
    printf("                    WELCOME TO RELAINCE COMMUNICATION \n\n\n");
    printf("Enter the no. of Calls= ");
    scanf("%d",&calls);

    if (calls>0 && calls<=100)   /*100*0-->rs.0/call 100*.50-->50 paisa/call*/
        bill=calls*0;

    else if (calls>100 && calls<=200)
          {    c1=calls-100;
        bill= (100*0)+(c1*1);  }

    else if (calls>200 && calls<=300)
          {    c1=calls-200;
        bill=(100*0)+(100*1)+(c1*0.5);  }

    else if (calls>300 && calls<=500)
          {    c1=calls-300;
        bill=(100*0)+(100*1)+(100*0.5)+(c1*0.3); }

    else
          {    c1=calls-500;
        bill=(100*0)+(100*1)+(100*0.5)+(100*0.3)+(c1*0.2); }

    rental=bill+100;

    printf("Your Monthly bill is=Rs.%0.2f \n",bill);
    printf("Your Complete bill with monthly Rental charge is=Rs.%0.2f",rental);
    return 0;
}

Wednesday 26 December 2012

Merging 2 Sorted Array's

#include<stdio.h>

 int main()
{
    int a[20],b[20],c[40],i,j,k,n1,n2;
    clrscr();
    printf("Merging 2 sorted arrays...\n\n");

    //array 1 input
    printf("Enter how many elements in array1: ");
    scanf("%d",&n1);

    for(i=0;i<n1;i++)
    {
        printf("Enter element %d: ",i+1);
        scanf("%d",&a[i]);
    }

    //array 2 input
    printf("Enter how many elements in array2: ");
    scanf("%d",&n2);

    for(i=0;i<n2;i++)
    {
        printf("Enter element %d: ",i+1);
        scanf("%d",&b[i]);
    }

    //merging
    for(i=0,j=0,k=0;i<n1&&j<n2;k++)
    {
        if(a[i]<b[j])
        {
            c[k]=a[i];
            i++;
        }
        else if(a[i]==b[j])
        {
            c[k]==a[j];
            j++;
        }
        else
        {
            c[k]=b[j];
            j++;
        }
    }

    //remaining elements of array 1
    while(i<n1)
    {
        c[k]=a[i];
        i++;
        k++;
    }

    //remaining elements of array 2
    while(j<n2)
    {
        c[k]=b[j];
        j++;
        k++;
    }

    //output
    printf("\n\nArray after merging elements of both arrays are..\n");
    for(i=0;i<(n1+n2);i++)
        printf("%d\t",c[i]);
return 0;
}

Thursday 20 December 2012

Frequency of letters in a String-NAGARRO's placement question

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

int main()
{
    int i=0;
    char str[20];
    int cap[26]={0};
    int small[26]={0};
    printf("\nEnter your string: ");
    gets(str);
    while(str[i]!='\0')
    {
        if (str[i]>='A'&&str[i]<='Z')
            cap[str[i]-'A']++;
        else if(str[i]>='a'&&str[i]<='z')
            small[str[i]-'a']++;
        i++;
    }
    int max=0;
    int capf = 1;
    int pos=0;
    for(i=0;i<26;i++)
    {
        if(max<cap[i])
        {
            max=cap[i];
            pos=i;
            capf=1;
        }
        if(max<small[i])
        {
            max=small[i];
            pos=i;
            capf=0;
        }
    }
    if (capf)
        printf("\nThe maximum occurance alphabet is %c with %d times",pos+'A',max);
    else
        printf("\nThe maximum occurance alphabet is %c with %d times",pos+'a',max);
    return 0;
}


-Gaurav Singhal

Wednesday 19 December 2012

C program to convert Figures into Words

#include<stdio.h>

int main()
{
    long int n,t;
    char a[][10]={" ","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"};
    char b[][10]={" "," ","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
    char c[][10]={" ","Leven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
    printf("Enter a number\n");
    scanf("%ld",&n);
    if(n>=1000&&n<10000)
    {
        t=n/1000;
        printf("%s thousand ",a[t]);
        n=n-(t*1000);
    }
    if(n>=100&&n<1000)
    {
        t=n/100;
        if((t*100)==n)
            printf("%s hundred",a[t]);
        else
            printf("%s hundred and ",a[t]);
        n=n-(t*100);
    }
    if(n>10&&n<100)
    {
        if(n>10&&n<20)
        {
            t=n-10;
            printf("%s ",c[t]);
            n=100000;
        }
        else
        {   t=n/10;
        if((t*10)==n)
            printf("%s ",b[t]);
        else
            printf("%s ",b[t]);
        }   n=n-(t*10);
    }
    if(n>0&&n<=10)
        printf("%s",a[n]);
    return 0;
}



-Gaurav Singhal

Monday 17 December 2012

Sathiya Pattern in C

#include<stdio.h>
int main()
{
    int n=15,i,j,n1;
    n1=n-1;
    printf("");
    printf("\t\t\t\t      *\n");
    printf("\t\t\t\t      *\n");
    for(i=1;i<=n;i++)
    {
        printf("\t\t\t  ");
        if(i==1)
        {
            printf("\b\b**");
            printf("*");
            for(j=2;j<(n1/2);j++)
                printf(" ");
            for(j=n1/2;j<n1;j++)
                printf("*");
            printf("\n");
        }
        if(i>=2 && i<(n/2))
        {
            if(i==n/4+1)
            {
                printf("*  *  *  *");
            }
            else
            {
                printf("*");
                for(j=2;j<(n1/2);j++)
                    printf(" ");
                printf("*");
            }
            printf("\n");
        }
        if(i==n/2)
        {
            for(j=1;j<n1;j++)
                printf("*");
            printf("\n");
        }
        if(i>(n/2) && i<n)
        {
            if(i==n-4)
            {
                printf("   *  *  *  *");
            }
            else
            {
                for(j=1;j<(n1/2);j++)
                    printf(" ");
                printf("*");
                for(j=((n1/2)+1);j<n1-1;j++)
                    printf(" ");
                printf("*");
            }
            printf("\n");
        }
        if(i==n)
        {
            for(j=1;j<=(n1/2);j++)
                printf("*");
            for(j=(n1/2)+1;j<n1-1;j++)
                printf(" ");
            printf("***");
            printf("\n");
        }
    }
    printf("\t\t\t  *\n");
    printf("\t\t\t  *\n");
    printf("\n\n\t\t\t\t\t\tGaurav\n");
    return 0;
}


output:

-Gaurav Singhal

Saturday 15 December 2012

Sum of Prime Numbers

 #include <stdio.h>
 #include <math.h>
 int main(void)
 {
     unsigned int i,j,s=0,is_prime,sq;

     for(i=3;i<=1000;i++)  

//you can make the program for upperbound and lowerbound also.....
     {
         is_prime = 1; // Assuming that current value of i is prime
         sq=sqrt(i);
         // Checking for prime
         for(j=2;j<=sq;j++)
         {
             if(i%j==0) // Not prime, set is_prime to 0 and break
             {
                 is_prime = 0;
                 break;
             }
         }

         if(is_prime) // If the number is prime, sum it up
         {
             s += i;
             // optionally you can print the prime numbers too
             printf("%d ",i);
         }
     }

     printf("\n\nThe sum of the prime numbers = %d",s);
     return 0;
 }

Thursday 13 December 2012

Langrange Interpolation Formula

#include <stdio.h>

#define N 100

int main()
{
    /*
    y=(x-x2)(x-x3)...(x-xn)/(x1-x2)(x1-x3)...(x1-xn)*y[1]
    +(x-x1)(x-x3)...(x-xn)/(x2-x2)(x2-x3)...(x2-xn)*y[2]
    +...+
    (x-x1)(x-x2)...(x-x(n-1))/(xn-x1)(xn-x2)...(xn-x(n-1))*y[n]
    */
    float x[N]={0},y[N]={0};
    int i,j;
    float res,ans=0,givx=0;
    int n=0;
    printf("\nEnter the total number of points for interpolation\n");
    scanf("%d",&n);
    printf("\nEnter the values of x\n");
    for(i=0;i<n;i++)
    scanf("%f",&x[i]);
    printf("\nEnter the values of y\n");
    for(i=0;i<n;i++)
    scanf("%f",&y[i]);
    printf("\nEnter the values of x to find y\n");
    scanf("%f",&givx);
    for(i=0;i<n;i++)
    {
       res=1;
       for(j=0;j<n;j++)
       {
       if(i==j)
        continue;
       res=res*(givx-x[j])/(x[i]-x[j]);
       }
       ans=ans+res*y[i];
    }
    printf("\nanswer = %g\n",ans);
    return 0;
}

Tuesday 11 December 2012

Memory Allocation in C


When an ELF executable is executed, a process is created and its process image is create in the RAM. However, it is here in the process image in RAM, all the variables are assigned memory. Sometimes memory is allocated statically i.e. defined how much memory at the compile time, and at times it has to be allocated dynamically. Where, it is specified at run time the amount of memory needed.

Static Memory Allocation

First of all, please note, static memory allocation is not related to the ‘static’ variables in C programing.
Look at the following statement of a program:

int var = 30;
It is an initialized variable which is of datatype ‘int’ and has been allocated memory of the size of ‘int’ (lets say 4 bytes, which is a standard in Linux). Such kind of memory allocations are called static memory allocations. Note, at compile time we know here that ‘sizeof(int)’ amount of memory will be allocated. Here are some more examples of static memory allocation

char c;
float fvar;
int array[12];
This also explains why arrays take only constants as their sizes.

Worth mentioning, all such static memory allocations take place in the stack of the process image with certain exceptions like uninitialised global variables, const string pointers etc.

Dynamic Memory Allocations

In several cases, we might not know how much memory do we need at the compile-time. Its can only be specified at the run-time based on the value of a certain variable. For example, in the case of linked lists, where a node can be added/deleted at runtime, or matrices of varying rows/columns. For such scenarios, we have dynamic memory allocations. C provides following methods to allocate memory. Dynamic memory allocation always allocates memory in the heap of the process image.

       void *malloc(size_t size);
       void *calloc(size_t nmemb, size_t size);
       void *realloc(void *ptr, size_t size);
1. ‘malloc()’ is used for allocating a specific amount (in bytes) of memory. It returns a pointer to the memory allocated. However, the returned pointer is a void pointer which needs to be type-casted for regular use. It does not initialise the allocated memory. It returns a NULL pointer in case the allocations fails due to any reason. So, one can check for success/failure of this method by checking if the returned pointer is NULL or not. For more such details regarding malloc method, please refer its man page.
ex:
int *ptr = NULL;
int amt = 30;
ptr = (int*) malloc ( amt * sizeof(int));
2. ‘calloc()’ is used for allocating a specific amount of a particle datatype of a memory. Hence, it takes two arguments as one can see in the syntax provided above. ‘calloc()’ also returns the pointer to the allocated chunk of memory, and it also needs the type casting. However, it attempts to initialise all the bits of the allocated memory to zero. It returns a NULL pointer in case the allocations fails due to any reason. For more details on this method, please refer to its man page.
ex:
int *ptr = NULL;
ptr = (int*) malloc ( amt,  sizeof(int));
3. Another method for dynamic memory allocation is ‘realloc()’. The above two methods are there for fresh memory allocations. However, what if one just wants to expand/shrink an already allocated chunk of memory? For such cases we have ‘realloc()’. Depending upon the memory layout, it either just allocates the extra memory demanded or re-allocated the whole requested memory. It behaves similar to ‘malloc()’ as far as memory allocations are concerned.
ex:
int *newPtr = NULL;
newPtr = (int*) realloc (ptr, amt + extra);
Note, ‘realloc()’ can also do fresh allocation of memory if the input pointer is a NULL.

Freeing up

Power comes with responsibility. Since C gives you the power to use and allocated memory as per our needs, hence it is the onus of the programmer to take care of allocated and free memory. Hence, freeing up of allocated memory is very essential in C programming and avoids many vulnerabilities.

All the statically allocated memory is free-ed automatically as its scope ends. However, the dynamically allocated memory have to be free-ed by the programmer. Here is the method which is used to free memory allocated on heap.
ex:
void free(void *ptr);

A complete example implementation


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

int main()
{
    int size = 15; //static memory allocation
    int i; //static memory allocation
    int *mptr = NULL; 
    int *cptr = NULL;

    //Using malloc
    mptr = (int*) malloc (size *sizeof(int)); //dynamic memory allocation
    if (mptr == NULL)
    {
         printf("Error in  memory allocation\n");
    }
    else
    {
        printf("Use new chunk of memory\n");
        for (i = 0; i < size; i++)
        {
            mptr[i] = i;
        }
    }

    //Using calloc
    cptr = (int*) calloc (size, sizeof(int)); //dynamic memory allocation
    if (cptr == NULL)
    {
         printf("Error in  memory allocation\n");
    }
    else
    {
        printf("Use new chunk of memory\n");
        for (i = 0; i < size; i++)
        {
            cptr[i] = i;
        }
    }

    //Using realloc
    size += size; //Increase size
    mptr = (int*) realloc (mptr, size * sizeof(int)); //extend the dynamic memory allocation
    if (mptr == NULL)
    {
         printf("Error in  memory allocation\n");
    }
    else
    {
        printf("Use new chunk of memory\n");
        for (i = 0; i < size; i++)
        {
            mptr[i] = i;
        }
    }

    //Free-ing up memory
    if (cptr)
        free(cptr);
    cptr = NULL;
    if (mptr)
        free(mptr);
    mptr = NULL;
    // No need to free size and i
    
    return 0;
}


- Gaurav Singhal

Monday 10 December 2012

Final Class in C++

Concept of Final Class in C++

•Class which Can't be inherited by other class, that class is called final class.
•Types of Final Class

 1. Final class: Object of it will be on heap.

class final2 { public:     static final2* Create()     {         return (new final2()) ;     } private:     ~final2()     {        ;     } }; int main() {     final2 *f ;     f = final2::Create() ; // Object only on Heap }
No one can Inherit this final2 class. Suppose if one is going to inherit it then
class child : public final2 { public:     child(){ ;} } ;
Now Error will come.Child class can't inherit final class.. Because destructor of final class is private.


2. Final class: Object of it will be on Stack
class temp { private:     ~temp() {; }     friend class Final; // Due to friend , Final class can use private member functions of temp class }; class Final: virtual public temp { // Define all data members and functions as you want public:     Final()     {     ;     }     ~Final(); };
Now this final class can't be inherited by other class.Suppose one is going to inherit it to his class then,
Example:
Code: CPP
class Child : public Final { public:     Child(){ ;}     ~Child() { ;} };
Due to temp class is inherited virtually to Final class. So when child class's constructor called, then first temp class constructor will be called. By Child class's constructor, we are calling temp class constructor. Child class can't call temp class's private destructor because child is not a friend of temp class. This is the rule of C++.
Due to this rule in C++, Compiler sees that it is violating the rules, then it flashes error.




-Gaurav Singhal

Friday 7 December 2012

Priority Queue program in C

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

void insert();
void show();
void del();

typedef struct node
{
    char info;
    int prior;
    struct node *next;
}n;
n *front=NULL,*rear=NULL;
int main()
{
    int ch;
    while(1)
    {
    printf("\n1. Insert Element");
    printf("\n2. Delete Element");
        printf("\n3. Show");
        printf("\n4. Exit");
        printf("\nChoice -: ");
    fflush(stdin);
    ch=getche();
    switch(ch)
    {
        case '1':
        insert();
        break;
        case '2':
        del();
        break;
        case '3':
        show();
        break;
        case '4':
        exit(0);
        break;
        default:
        printf("Wrong Input");
        getch();
        }
    }
}
void insert()
{
    n *ptr,*temp,*par;
    temp=(n*)malloc(sizeof(n));
    if(temp==NULL)
    {
        printf("Memory not allocated..");
        getch();
        exit(1);
    }
    printf("\nEnter data: ");
    fflush(stdin);
    scanf("%c",&temp->info);
    while(1)
    {
    printf("\nEnter Priority for '%c' data: ",temp->info);
    scanf("%d",&temp->prior);
    if(temp->prior > 0)
        break;
    }
    temp->next=NULL;

    if(front==NULL && rear==NULL)
    {
        front=rear=temp;
    }
    else
    {
        par=ptr=front;
        while((ptr->prior) <= (temp->prior) && ptr!=NULL)
        {
            par=ptr;
            ptr=ptr->next;
        }
        //node entering at rear
        if(ptr==NULL)
        {
            par->next=temp;
            temp->next=NULL;
            rear=temp;
        }
        //node entering before front
        else if(par==ptr)
        {
            front=temp;
            temp->next=ptr;
        }
        //node entering in middle
        else
        {
            par->next=temp;
            temp->next=ptr;
        }
    }
}
void show()
{
    n *ptr;
    printf("\nQueue: ");
    ptr=front;
    while(ptr!=NULL)
    {
        printf("%c\t",ptr->info);
        ptr=ptr->next;
    }
    getch();
}
void del()
{
    if(front==NULL)
    {
        printf("Priority Queue is Empty");
        getch();
        return;
    }
    printf("Element Deleted is '%c'",front->info);
    front=front->next;
}



-Gaurav Singhal
Like this page and comment about the program....
Thank You...

Thursday 6 December 2012

Vertical Histogram in C

#include<stdio.h>
#include<conio.h>
int main()
{
    int a[10],i,j,n,max,copy_max;;

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

    //input array
    for(i=0;i<n;i++)
    {
        printf("Enter the element %d: ",i+1);
        scanf("%d",&a[i]);
    }

    //finding max no.
    max=a[0];
    for(i=0;i<n;i++)
    {
        if(a[i]>max)
            max=a[i];
    }
    copy_max=max;

    //logic for vertical histogram
    for(i=0;i<copy_max;i++,max--)
    {
        for(j=0;j<n;j++)
        {
            if(a[j]>=max)
                printf(" * ");
            else
                printf("   ");
        }
        printf("\n");
    }
    return 0;
}


output..
Enter no of Elements: 3
Enter element 1: 4
Enter element 1: 5
Enter element 1: 3

    *
*  *
*  *  *
*  *  *
*  *  *
 

Sunday 2 December 2012

Insertion Sort In Detail

This technique actually goes through N-1 passes through the list where N is number of elements in the array. Each pass P can be considered to be for the elements from 1 to N-1. Each pass is actually an effort to place the element P in its correct position among the elements from position 0 to P.

Example:
Let us take an array of numbers A= (34, 8 , 64, 51, 32, 21).



Code:
  +---------------+-------+-------+-------+-------+-------+------+-----------------+
  |  Original     |   34  |   8   |   64  |   51  |   32  |  21  | Position Moved  |
  +---------------+-------+-------+-------+-------+-------+------+-----------------+
  | After P1      |    8  |   34  |   64  |   51  |   32  |  21  |           1     |
  +---------------+-------+-------+-------+-------+-------+------+-----------------+
  | After p2      |    8  |   34  |   64  |   51  |   32  |  21  |           0     |
  +---------------+-------+-------+-------+-------+-------+------+-----------------+
  | After p3      |    8  |   34  |   51  |   64  |   32  |  21  |           1     |
  +---------------+-------+-------+-------+-------+-------+------+-----------------+
  | After p4      |    8  |   32  |   34  |   51  |   64  |  21  |           3     |
  +---------------+-------+-------+-------+-------+-------+------+-----------------+
  | After p5      |    8  |   21  |   32  |   34  |   51  |  64  |           4     |
  +---------------+-------+-------+-------+-------+-------+------+-----------------+
Pseudo code: or Algorithm
Code:
  insertionSort(array A)
  begin
      for i := 1 to length[A]-1 do
      begin
          value := A[i];
          j := i - 1;
          done := false;
          repeat
              if A[j] > value then
              begin
                  A[j + 1] := A[j];
                  j := j - 1;
                  if j < 0 then
                      done := true;
              end
              else
                  done := true;
          until done;
          A[j + 1] := value;
      end;
  end;
Code in C language:
Code:
  void InsertionSort (int A[], int N)
  {
              int j, P;
              int Tmp;
   
              for (P=1; P<N; P++)
              {
                          Tmp=A[P];
                          for (j=P; j>0 && A[j-1]>Tmp; j--)
                          A[j] =A[j-1];
                          A[j]=Tmp;
              }
  }
Runtime Complexity:

It is O (N2). This is because there are two for loops and in the worst case the two for loops are both going to run N times. The point where Insertion Sort scores over Bubble Sort is its best case analysis. Note that when the elements are fully sorted, then the inner for loop will immediately break. This will give a runtime of O(N).




- Gaurav Singhal