Apr 19, 2012

C Program to solve the producer consumer problem

Write a C Program to solve the producer consumer problem with two processes using semaphores.
Producer-consumer problem is the standard example of multiple process synchronization problem. The problem occurs when concurrently producer and consumer tries to fill the data and pick the data when it is full or empty. producer consumer problem is also known as bounded-buffer problem. In this program We use the semaphores, to solve the problem.Read more about C Programming Language . and read the C Programming Language (2nd Edition) by K and R.
/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>


#define NUM_LOOPS 20
int main(int argc, char* argv[])
{
    int sem_set_id;
    union semun sem_val;
    int child_pid;
    int i;
    struct sembuf sem_op;
    int rc;
    struct timespec delay;
    
    
    sem_set_id = semget(IPC_PRIVATE, 1, 0600);
    if (sem_set_id == -1) {
        perror("main: semget");
        exit(1);
    }
    printf("Semaphore set created,
    semaphore set id '%d'.\n", sem_set_id);
    
    
    sem_val.val = 0;
    rc = semctl(sem_set_id, 0, SETVAL, sem_val);
    child_pid = fork();
    switch (child_pid) {
        case -1:
        perror("fork");
        exit(1);
        case 0:
        for (i=0; i<NUM_LOOPS; i++) {
            sem_op.sem_num = 0;
            sem_op.sem_op = -1;
            sem_op.sem_flg = 0;
            semop(sem_set_id, &sem_op, 1);
            printf("consumer: '%d'\n", i);
            fflush(stdout);
            sleep(3);
        }
        break;
        default:
        for (i=0; i<NUM_LOOPS; i++)
        {
            printf("producer: '%d'\n", i);
            fflush(stdout);
            sem_op.sem_num = 0;
            sem_op.sem_op = 1;
            sem_op.sem_flg = 0;
            semop(sem_set_id, &sem_op, 1);
            sleep(2);
            if (rand() > 3*(RAND_MAX/4))
            {
                delay.tv_sec = 0;
                delay.tv_nsec = 10;
                nanosleep(&delay, NULL);
            }
        }
        break;
    }
    
    
    return 0;
}
Read more c programs
C Basic
C Strings
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link

Apr 18, 2012

C program to implement Round Robin CPU scheduling algorithm.

Write a C program to implement Round Robin CPU scheduling algorithm.
In Round Robin scheduling algorithm, a small time slice or quantum is defined, all the tasks are kept in queue. The CPU scheduler picks the first task from the queue ,sets a timer to interrupt after one quantum, and dispatches the process. If the process is still running at the end of the quantum, the CPU is preempted and the process is added to the tail of the queue. If the process finishes before the end of the quantum, the process itself releases the CPU voluntarily. In either case, the CPU scheduler assigns the CPU to the next process in the ready queue. Every time a process is granted the CPU, a context switch occurs, which adds overhead to the process execution time. Round Robin scheduler is mainly used for the time sharing systems. Read more about C Programming Language . and read the C Programming Language (2nd Edition) by K and R.

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/


#include<stdio.h>
#include<conio.h>
struct process
{
    char na[20];
    int at,bt,ft,tat,rem;
    float ntat;
}Q[5],temp;
int rr[20],q,x,k;
main()
{
    int f,r,n,i,j,tt=0,qt,t,flag,wt=0;
    float awt=0,antat=0,atat=0;
    clrscr();
    printf("Enter the no. of jobs:");
    scanf("%d",&n);
    for(r=0;r<n;r++)
    {
        printf("Enter process name,arrival time and burst time:\n");
        scanf("%s%d%d",Q[r].na,&Q[r].at,&Q[r].bt);
    }
    printf("Enter quantum:\n");
    scanf("%d",&qt);
    for(i=0;i<n;i++)
    {
        for(j=i+1;j<n;j++)
        {
            if(Q[i].at>Q[j].at)
            {
                temp=Q[i];
                Q[i]=Q[j];
                Q[j]=temp;
            }
        }
    }
    for(i=0;i<n;i++)
    {
        Q[i].rem=Q[i].bt;
        Q[i].ft=0;
    }
    tt=0;
    q=0;
    rr[q]=0;
    do
    {
        for(j=0;j<n;j++)
        if(tt>=Q[j].at)
        {
            x=0;
            for(k=0;k<=q;k++)
            if(rr[k]==j)
            x++;
            if(x==0)
            {
                q++;
                rr[q]=j;
            }
        }
        if(q==0)
        i=0;
        if(Q[i].rem==0)
        i++;
        if(i>q)
        i=(i-1)%q;
        if(i<=q)
        {
            if(Q[i].rem>0)
            {
                if(Q[i].rem<qt)
                {
                    tt+=Q[i].rem;
                    Q[i].rem=0;
                }
                else
                {
                    tt+=qt;
                    Q[i].rem-=qt;
                }
                Q[i].ft=tt;
            }
            i++;
        }
        flag=0;
        for(j=0;j<n;j++)
        if(Q[j].rem>0)
        flag++;
    }while(flag!=0);
    clrscr();
    printf("\n\n\t\tROUND ROBIN ALGORITHM");
    printf("\n***************************");
    printf("\nprocesses Arrival time burst time finish time tat wt ntat");
    for(f=0;f<n;f++)
    {
        wt=Q[f].ft-Q[f].bt-Q[f].at;
        Q[f].tat=Q[f].ft-Q[f].at;
        Q[f].ntat=(float)Q[f].tat/Q[f].bt;
        antat+=Q[f].ntat;
        atat+=Q[f].tat;
        awt+=wt;
        printf("\n\t%s\t%d\t\t%d\t%d\t%d\t%d %f",
        Q[f].na,Q[f].at,Q[f].bt,Q[f].ft,Q[f].tat,wt,Q[f].ntat);
    }
    antat/=n;
    atat/=n;
    awt/=n;
    printf("\nAverage tat is %f",atat);
    printf("\nAverage normalised tat is %f",antat);
    printf("\n average waiting time is %f",awt);
getch();    }
 
  
Read more Similar C Programs
C Basic

Search Algorithms.
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!


To browse more C Programs visit this link

C Program to demonstrate modf function.

Write a C program to demonstrate modf function. modf() defined in the C math.h library.
modf function breaks the double/float values to integral part and fractional part. 
Example: res = modf(3.142, &iptr) returns res=142 and iptr=3. Read more about C Programming Language . and read the C Programming Language (2nd Edition). by K and R.


/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

#include<stdio.h>
#include<math.h>
#include<conio.h>
int main()
{
    double num,integral,result;
    clrscr();
    printf("\n Enter fractional Number\n");
    scanf("%lf",&num);
    result = modf(num, &integral);
    
    printf("%.4lf = %.4lf + %.4lf\n", num, integral, result);
    
    return 0;
}
Read more Similar C Programs
Matrix Programs
Learn C Programming
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link

Apr 17, 2012

C Program to check whether two strings are anagrams of each other.

C Strings:
Write a c program to check whether two strings are anagrams of each other.
Two strings are said to be anagrams, if the characters in the strings are same in terms of numbers and value ,only arrangement or order of characters are may be different.
Example: "dfghjkl" and "lkjghdf" are anagrams of each other.
Read more about C Programming Language . and read the C Programming Language (2nd Edition). by K and R.
/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

#include<stdio.h>
#include<string.h>
# define NO_OF_CHARS 256
int Anagram(char *str1, char *str2)
{
    // Create two count arrays and initialize all values as 0
    int count1[NO_OF_CHARS] = {0};
    int count2[NO_OF_CHARS] = {0};
    int i;
    
    // For each character in input strings, increment count in
    // the corresponding count array
    for (i = 0; str1[i] && str2[i];  i++)
    {
        count1[str1[i]]++;
        count2[str2[i]]++;
    }
    
    // If both strings are of different length. Removing this condition
    // will make the program fail for strings like "aaca" and "aca"
    if (str1[i] || str2[i])
    return 0;
    
    // Compare count arrays
    for (i = 0; i < NO_OF_CHARS; i++)
    if (count1[i] != count2[i])
    return 0;
    
    return 1;
}
main()
{
    char str[100], str1[100];
    int flag = 0;
    
    printf("Enter first string\n");
    gets(str);
    
    printf("Enter second string\n");
    gets(str1);
    
    
    flag=Anagram(str, str1);
    if (flag==1)
    printf("\"%s\" and \"%s\" are anagrams.\n", str, str1);
    else
    printf("\"%s\" and \"%s\" are not anagrams.\n", str, str1);
    
    return 0;
}


Read more c programs
C Basic
C Strings
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link

Apr 16, 2012

K & R C Chapter 3 Exercise Solutions

We have already provided solutions to all the exercises in the book "C Programming Language (2nd Edition)" popularly known as K & R C book.

In this blog post I will give links to all the exercises from Chapter 3 of the book for easy reference.

Chapter 3: Control Flow

  1. Exercise 3-1. Our binary search makes two tests inside the loop, when one would suffice (at the price of more tests outside). Write a version with only one test inside the loop and measure the difference in run-time.
    Solution to Exercise 3-1.

  2. Exercise 3-2.Write a function escape(s,t) that converts characters like newline and tab into visible escape sequences like \n and \t as it copies the string t to s . Use a switch . Write a function for the other direction as well, converting escape sequences into the real characters.
    Solution to Exercise 3-2.

  3. Exercise 3-3.Write a function expand(s1,s2) that expands shorthand notations like a-z in the string s1 into the equivalent complete list abc...xyz in s2 . Allow for letters of either case and digits, and be prepared to handle cases like a-b-c and a-z0-9 and -a-z . Arrange that a leading or trailing - is taken literally.
    Solution to Exercise 3-3.

  4. Exercise 3-4.In a two's complement number representation, our version of itoa does not handle the largest negative number, that is, the value of n equal to -(2 to the power (wordsize - 1)) . Explain why not. Modify it to print that value correctly regardless of the machine on which it runs.
    Solution to Exercise 3-4.

  5. Exercise 3-5. Write the function itob(n,s,b) that converts the integer n into a base b character representation in the string s . In particular, itob(n,s,16) formats n as a hexadecimal integer in s
    Solution to Exercise 3-5.

  6. Exercise 3-6. Write a version of itoa that accepts three arguments instead of two. The third argument is a minimum field width; the converted number must be padded with blanks on the left if necessary to make it wide enough.
    Solution to Exercise 3-6.
You can purchase the book from here or here.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Like to get updates right inside your feed reader? Grab our feed!




To browse more C Programs visit this link