Thursday, August 18, 2016

Reverse string

#include <string.h>
void reverse(char a[])
{
         int i, j,
         int j = strlen(a) -1 ;
         for (i=0; i<j; i++, j--)
         {
                  c = a[i] ;
                  a[i] = a[j] ;
                  a[j] = c ;
        }
}

Print the number in binary format

#include <stdio.h>
int main()
{
       int a  = 10 ;
       printf("Enter a number to print in binary format\n") ;
       scanf("%d", &a) ;
       while (a)
       {
               if (a&1 == 1)
                       printf("1") ;
               else
                      printf("0") ;
               a  = a>>1 ;
       }
       printf("\n") ;
}

Swap bits for given character

Swap first 4 bits of a number to next 4 bits
Example :
1011 0011 to 0011 1011

Get first 4 bits : (Number & 0XF0), shift 4 positions to right (number & 0Xf0) >> 4

Get the last 4 bits : number & 0XOF, shift 4 position to left, number & 0XOF) << 4

Return sum (OR) of above is the swapped number

unsigned char c ;   // input number
c = (c & 0XF0) >> 4 | (c &0X0F) << 4)

Friday, August 12, 2016

C Program to print even and odd numbers using threads

Save file as PrintEvenOdd.c and compile as
gcc PrintEvenOdd.c -lpthread
#include<stdio.h>
#include<pthread.h>

pthread_t tid[2];
unsigned int shared_data = 0;
pthread_mutex_t mutex;
unsigned int rc;
//prototypes for callback functions

void* PrintEvenNos(void*);
void* PrintOddNos(void*);

void main(void)
{
    pthread_create(&tid[0],0,&PrintEvenNos,0);
    pthread_create(&tid[1],0,&PrintOddNos,0);
    sleep(3);

    pthread_join(tid[0],NULL);
    pthread_join(tid[1],NULL);
}

void* PrintEvenNos(void *ptr)
{
     rc = pthread_mutex_lock(&mutex);
     do
     {
         if(shared_data%2 == 0)
         {
             printf("Even:%d\n",shared_data);
             shared_data++;
         }
         else
         {
             rc=pthread_mutex_unlock(&mutex);//if number is odd, do not print, release mutex
         }
     } while (shared_data <= 100);
}

void* PrintOddNos(void* ptr1)
{
    rc = pthread_mutex_lock(&mutex);
    do
    {
        if(shared_data%2 != 0)
        {
            printf("odd:%d\n",shared_data);
            shared_data++;
        }
        else
        {
            rc = pthread_mutex_unlock(&mutex);//if number is even, do not print, release mutex
        }
    } while (shared_data <= 100);
}