Total Pageviews

Saturday 23 March 2013

REPRESENT INFINITY and NaN IN C PROGRAMMING:

Sometimes, infinity, minus infinity and NaN are useful in programming. To use them, follow the trick...

Infinity:
Eg: int n=1/0;

Minus Infinity:
Eg: int n=log(0);

NaN(Not a Number):
Eg: int n=sqrt(-1);

Wednesday 20 March 2013

STRING STANDARD FUNCTIONS IN C:


  • strlen() - Determines the length of a string. 
Eg: char name[]="antony";
       int length;
       length=strlen(name);
       printf("%d",length);
Output:
6
  • strcpy(s1,s2) - copies the content of s2 to s1.
Eg: char source[]="hai";
       char destination[3];
       strcpy(destination,source);
       printf("source=%s destination=%s",source,destination);
Output:
source=hai destination=hai

  • strncpy(s1,s2,n) - copies 1st n characters from s2 to s1.
Eg: char source[]="hai";
       char destination[3];
       strcpy(destination,source,2);
       printf("source=%s destination=%s",source,destination);
Output:
source=hai destination=ha

  • strcmp(s1,s2) - compares two strings. Case sensitive. 
     return value                                       result
          zero                        -                       s1 = s2
       negative                    -                       s1 < s2
       positive                     -                       s1 > s2
Eg: char s1[]="hai";
       char s2[]="hai";
       printf("%d\n",strcmp(s1,s2));
       printf("%d\n",strcmp(s1,"hello"));
       printf("%d\n",strcmp("hello",s1));
Output:
0
-1
1
       
  • stricmp(s1,s2) - similar to strcmp(), but it is not case sensitive.
  • strncmp(s1,s2,n) - similar to strcmp(), but comparison is done only till n characters
  • strnicmp(s1,s2,n) - compares n characters and it is not case sensitive.
  • strlwr(s) - convert s to lower case.
Eg: char s[]="ABCDE";
       printf("%s",strlwr(s));
Output:
abcde

  • strupr(s) - converts s to upper case.
  • strdup(s) - duplicates the given string at the allocated memory which is pointed by a pointer variable.
Eg: char text1[]="hai",*text2;
       text2=strdup(text1);
       printf("original=%s duplicate=%s",text1,text2);
Output:
original=hai duplicate=hai

  • strchr(string,ch) - returns the pointer to the first occurence of a given character in the string.
Eg: char s[]="have a nice day!";
       char *c;
       c=strchr(s,'a');
       if(c)
           printf("%c is found",c);
       else
           printf("%c is not found",c);
Output:
a is found

  • strrchr(string,ch) -  similar to strchr(). strchr() searches for the occurence of characters from the beginning of the string but strrchr() searches for the occurence of characters from the end.
  • strstr(string1,string2) - finds string2 in string1 and returns the pointer to the location from where the second string starts in the first string.
Eg: char str1[]="welcome to my blog!!!";
       char str2[]="welcome";
       char *c;
       c=strstr(str1,str2);
       if(c)
           printf("%s is found",str2);
       else
           printf("%s is not found",str2);
Output:
welcome is found

  • strcat(str1,str2) - appends str2 at the end of str1 and the resultant string is stored in str1.
Eg: char s1[]="hai", s2[]="hello";
       strcat(s1,s2);
       printf("%s",s1);
Output:
haihello

  • strncat(str1,str2,n) - similar to strcat. 1st n characters of str2 are appended to the end of str1.
  • strrev(string) - reverses the string.
Eg: char a[]="hai";
       puts(strrev(a));
Output:
iah

  • strset(string,symbol) - replaces every character of the string with the symbol.
Eg: char s[]="hai";
       strset(s,"*");
       printf("%s",s);
Output:
***

  • strnset(string,symbol,n) - replaces 1st n characters of the string with the symbol.
  • strspn(str1,str2) - returns the no. of characters matched upto the 1st mismatch character.
Eg: char str1[]="hawaii", str2[]="hang";
       int length;
       length=strspn(str1,str2);
       printf("two strings are equal upto %d characters",length);
Output:
two strings are equal upto 2 characters

  • strpbrk(str1,ch) - searches the 1st occurence of a character in the given string and then it displays the string starting from that character.
Eg: char s[]="hello world!!!";
       char *ptr;
       ptr=strpbrk(s,'o');
       puts(ptr);
Output:
orld!!!


Friday 15 March 2013

Tic Tac Toe Game!!! (C version)



#include<stdio.h>

char ttt[3][3];
int row[3],coln[3];

char check()
{
     int i=1,j=1,count=0,count1=0;
     for(;i<=3;i++)
     {
                   if(row[i]==3)                return ttt[i][1];
                   
                   if(coln[i]==3)               return ttt[1][i];
     }
     
     for(i=1;i<=3;i++)
     {
                      for(j=1;j<=3;j++)
                      {
                                       if(i==j && ttt[i][j]=='x')   count--;
                                       if(i==j && ttt[i][j]=='o')   count++;
                                       if(i+j==4 && ttt[i][j]=='x')   count1--;
                                       if(i+j==4 && ttt[i][j]=='o')   count1++;
                      }
     }
     if(count==3 || count1==3)     return 'o';
     if(count==-3 || count1==-3)    return 'x';
                                                    
     return 'a';
}


void print()
{
     int i,j;
     for(i=1;i<=3;i++)
     {
                      for(j=1;j<=3;j++)
                      {
                                       printf("%c\t",ttt[i][j]);
                      }
                      printf("\n");
     }
}
     
     


int main()
{
    int i,j,dummy=0,count=0;
    char symbol='o',win='a';
    printf("Welcome to Tic Tac Toe!!!\n");
    for(i=1;i<=3;i++)
    {
                    for(j=1;j<=3;j++)
                    {
                                    ttt[i][j]='-';
                                    printf("%c\t",ttt[i][j]);
                    }
                    row[i]=coln[i]=0;
                    printf("\n");             
    }

    while(count<10 && win=='a')
    {
                   while(1)
                   {
                           scanf("%d%d",&i,&j);
                           if(ttt[i][j]=='x' || ttt[i][j]=='o')  printf("enter the correct place\n");
                           else              break;
                   } 
                   
                   
                   if(dummy%2!=0)      symbol='x';
                   else                symbol='o';
                   

                   if(symbol=='x')   
                   {
                                     row[i]--;
                                     coln[j]--;
                   }
                   else
                   {
                       row[i]++;
                       coln[j]++;
                   }
                   ttt[i][j]=symbol;
                   win=check();
                   print(ttt);
                   if(win=='x')     
                   {
                                    printf("x wins!!!\n");
                                    break;
                   }
                   if(win=='o')
                   {
                               printf("o wins!!!\n");
                               break;
                   }
                   dummy++;  
                   count++;
    }
   
    getch();
    return 0;
}

Thursday 14 March 2013

Program which prints the matrix elements in a spiral fashion!!!


#include<stdio.h>

int main()
{
    int **a,n,i,j,start=0,size,count=0,sizz;
    printf("enter the size\n");  //enter the size of nXn matrix
    scanf("%d",&n);
    //dynamic memory allocation of 2-D array
    a=(int**)malloc(sizeof(int*)*n);
    for(i=0;i<n;i++)
    {
                    a[i]=(int*)malloc(sizeof(int)*size);
    }
    //Storing the values from 1 in ascending order in the array
    for(i=0;i<n;i++)
    {
                    for(j=0;j<n;j++)
                    {
                                    a[i][j]=i*n+j+1;
                    }
    }
    printf("Matrix is...\n");
    for(i=0;i<n;i++)
    {
                    for(j=0;j<n;j++)
                    {
                                    printf("%d\t",a[i][j]);
                    }
                    printf("\n");
    }
   
    i=0;j=0;sizz=n*n;
    n--;
    printf("Spiral output of a matrix.....\n")
    while(count<sizz)     //loop until all the elements are printed
    {
                   //printing from left to right

                   while(j<=n && count<sizz)  
                   {
                                 printf("%d",a[i][j]);
                                 j++;
                                 count++;
                   }
                   i++;
                   j--;
                 
                   //printing from right to left

                   while(i<=n && count<sizz)
                   {
                                  printf("%d",a[i][j]);
                                  i++;
                                  count++;
                   }
                   i--;
                   j--;
                   n--;
                 
                   //printing from top to bottom

                   while(j>=start && count<sizz)
                   {
                          printf("%d",a[i][j]);
                          j--;
                          count++;
                   }
                   i--;
                   j++;
                   start++;
                 
                   //printing from bottom to top

                   while(i>=start && count<sizz)
                   {
                           printf("%d",a[i][j]);
                           i--;
                           count++;
                   }
                   i++;
                   j++;          
    }      
   
    getch();
    return 0;
}

OUTPUT:

enter the size
5

Matrix is...
1       2       3       4
5       6       7       8
9       10     11     12
13     14     15     16

Spiral output of a matrix.....
1       2       3       4       8       12      16      15      14      13
9       5       6       7       11      10




Wednesday 13 March 2013

Finding no. of characters, spaces and tabs in C:


#include<stdio.h>

int main()
{   
    char str[50];
    int i=0,characters=0,space=0,tab=0;
    puts("enter the string");
    gets(str);
    
    for(i=0;i<strlen(str);i++)
    {
                              if(str[i]=='\t')    tab++;
                              else if(str[i]==' ')      space++;
                              else                  characters++;
    }
    printf("characters=%d\ttab=%d\tspace=%d",characters,tab,space);
                                 
    
    getch();
    return 0;
}


OUTPUT:


enter the string
hai     hello how       are you
characters=17   tab=2   space=2

Tuesday 12 March 2013

Finding reverse of a number

METHOD 1:

#include<stdio.h>
/* Iterative function to reverse digits of num*/
int reversDigits(int num)
{
    int rev_num = 0;
    while(num > 0)
    {
        rev_num = rev_num*10 + num%10;
        num = num/10;
    }
    return rev_num;
}

int main()
{
    int num = 4562;
    printf("Reverse of no. is %d", reversDigits(num));

    getchar();
    return 0;
}

OUTPUT:
Reverse of no. is 2654

Time complexity: O(log(n)) where n is the input number.

The above program gives the output 1 for an input 100. To get the output as 001, a small addition is done in the above program.


int reversDigits(int num)
{
    int rev_num = 0,zero=0;
    while(num>0)
    {
        if(num%10==0)    
        {
            zero++;
            num=num/10;
        }
        else    break;
    }
    while(num > 0)
    {
        rev_num = rev_num*10 + num%10;
        num = num/10;
    }
    return rev_num;
}



METHOD 2:



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

int main()
{
    char a[5];     //Get the number as a string
    int n;
    printf("enter a number\n");
    scanf("%s",a);
    strrev(a);      //reverse the string using strrev() function
    n=atoi(a);     //convert string to integer
    printf("%d",n);
    getch();
    return 0;
}

OUTPUT:
enter a number
1234
4321
C program to print "Hello World" without using semicolon!


#include <stdio.h>
     
void main()
{
   if(printf("hello world!")) { }
}
C program which doesn't terminate when ctrl+c is pressed!!!


We can use signal handling in C for this. When ctrl+c is pressed, SIGINT signal is generated, we can catch this signal and run our defined signal handler.


#include <stdio.h>
#include <signal.h>

/* Signal Handler for SIGINT */
void sigintHandler(int sig_num)
{
//Reset handler to catch the SIGINT the next time
signal(SIGINT, sigintHandler);
printf("\n Cannot be terminated using Ctrl+C \n");
fflush(stdout);
}
int main ()
{
//Set the SIGINT signal handler to sigintHandler
signal(SIGINT, sigintHandler);
//infinite loop
while(1)
{}
return 0;
}

Friday 22 February 2013

STARTING ARRAY INDEX IN DYNAMIC MEMORY ALLOCATION:

When an array is created dynamically, the array index starts with 0. So make sure you start from 0th position and use till (n-1)th position.

Even if you try using from, say, 1 to n, the array values will be valid only till (n-1)th location. Hence the data stored in n th location will be lost.

EG:

int *array,array_size=5,i;
array=(int*)malloc(sizeof(int)*array_size);     
//THIS CREATES ARRAY OF SIZE 5 FROM INDEX 0 TO 4

printf("enter the array elements\n");
//IF YOU TRY TO USE 1 TO 5 LIKE BELOW....
for(i=1;i<=array_size;i++)
{
    scanf("%d",&array[i]);
}

//THE VALUE STORED IN array[n] VALUE WILL BE LOST
printf("array elements...\n");
for(i=1;i<=5;i++)
{
    printf("%d",array[i]);
}

OUTPUT:
enter the array elements
1 2 3 4 5
array elements...
1 2 3 4

What happens is, since the allocation for array starts at 0th index and ends at (n-1)th index, array[5] location is invalid. When the input is stored in this place, it is invalid and that is why 5 is missing when displaying array elements.

The conclusion of this post is, STRICTLY use the dynamically allocated array space from 0 th index till (n-1) th index. 

Thanks for reading my blog... Hope it gives a good point :-)
Post your comments which are always welcome ;-)

Saturday 2 February 2013

DYNAMIC MEMORY ALLOCATION OF 1-D AND 2-D ARRAYS

1-D ARRAY:

FORMAT:
datatype *ptr;
int size;
ptr=(datatype*)malloc(sizeof(datatype)*size);

EG:

#include<stdio.h>
#define SIZE 3

int main()
{
    int *array,i;
    array=(int*)malloc(sizeof(int)*SIZE);
    for(i=0;i<SIZE;i++)
    {
        array[i]=0;
        printf("%d\t",array[i]);
    }
    return 0;
}

OUTPUT:
0    0    0

2-D ARRAY:

FORMAT:
datatype **ptr;
int row_size,column_size,i;
ptr=(datatype**)malloc(row_size*sizeof(datatype*));
for(i=0;i<column_size;i++)
{
    ptr[i]=(datatype*)malloc(column_size*sizeof(datatype));
}

EG:

#include<stdio.h>
#define ROW 3
#define COL 3

int main()
{
    int **array,i,j;
    array = (int**)malloc(ROW*sizeof(int*));
    for (i=0; i<ROW; i++)
    {
        array[i] = (int*)malloc(COL*sizeof(int));
    }
    for (i=0; i<ROW; i++)
    {
        for (j=0; j<COL; j++)
        {
            array[i][j]=0;
            printf("%d\t",array[i][j]);
        }
        printf("\n");
    }
    return 0;
}

OUTPUT:
0   0   0
0   0   0
0   0   0

Friday 25 January 2013

GOOD BOOKS FOR LEARNING C:

1)Let Us C by Yashavant Kanetkar
2)The Complete Reference C by Herbert Schildt
3)Computer Programming by Ashok N. Kamthane
HOW TO INITIALISE ALL THE ARRAY ELEMENTS TO A VALUE IN ONE LINE?

Eg:

int arr[100]={[0 ... 99]=-1};

A space must be given after 0 and before 99.

One thing to note is that the above initialisation is possible only if the array index starts from 0. For eg., the following statement will throw an error,

int arr[100]={[1 ... 100]=5};