Search This Blog

Body Mass Index Calculator Using C Program - C Program to Calculate BMI

Body Mass Index Calculation is based on your weight and height. Body Mass Index (BMI) = weight/(height*height) where weight is in kilograms and height in meters. The following c program takes weight and height as input and displays BMI and grades into underweight,Normal, Overweight or obesity.

#include<stdio.h>;
void main()
{
float w,h,bmi;
printf("Enter weight in kgs and height in meters");
scanf("%f%f",&w,&h);
bmi=w/(h*h);
printf("bmi: %f",bmi);
bmi<18.5?printf("Underweight"):(bmi<25)?printf("Normal weight"):(bmi<30)?printf("Overweight"):printf("Obesity");
}

Calculate your BMI here

Weight (in kg):
Height (in meters):

Related Posts:

C Program to Display Prime Numbers Less than Given Number
C Program to Display Armstrong Numbers
C Program to Check Armstrong Number
C Program to Reverse a Number
C Program for Quick Sort
C Program to Search an element in array (Linear Search)
Leap Year C Program
C Program to Find Sum of Digits of a Number
C Program to Check Perfect Number
C Program to Find Transpose of Matrix
C Program to Understand Bitwise Operators

Four Different Methods or Tricks to Swap Two Numbers Without Using a Third Variable

In this post, we will see four different methods in c to swap two variables without using a third variable. This type of questions are often asked in technical interviews. Here we will see four different C programs to swap two numbers without a third temporary variable. Using a third variable is not an overhead. But still this kinda questions are asked in technical interviews for programming jobs to test your knowledge in the language.

Trick 1

In the first c program to swap two numbers without a third variable, we swap the values of the two variables in 3 steps which are simple addition and subtractions.

#include<stdio.h>
void main(){
    int a=5,b=10;
    a=b+a; //now a =15
    b=a-b; //now b= 5
    a=a-b; // now a=10 (done)
    printf("a= %d\nb=  %d",a,b);
}


Trick 2

In the second c program to swap two numbers without a third variable, we swap them in a single statement. The statement contains an assignment, addition and subtraction.

#include<stdio.h>
void main(){
    int a=10,b=30;
    a=a+b-(b=a);
    //10+30-(10)  a becomes 30
    // b is assigned with 10 in the same line of code
    printf("a= %d\nb=  %d",a,b);
}

Trick 3

In the third c code, we swap the numbers using bitwise XOR operation. The bitwise operator ^ 
is used in the program. The binary representation of the numbers, the bitwise xor operation on them and the result are shown in the c program as comments. The program is as follows:

#include<stdio.h>
void main(){
    int a=8,b=12;

   /* a: 8 : 01000
       b:12 : 01100
    */
   
    a=a^b; 

    /*      01000 ^
            01100
       a=   00100 (4)
    */


    b=a^b;

    /*      00100 ^
            01100
       b=   01000 (8)
    */

a=b^a;

    /*      01000 ^
            00100
       a=   01100 (12)
    */



    printf("a= %d\nb=  %d",a,b);
}

Trick 4

In the fourth method to swap two numbers without a temporary variable, we swap the numbers using a combination of addition, subtraction and bitwise NOT (inversion) operation. The bitwise operator 
is used in the program. The binary representation of the numbers, the bitwise NOT operation on them and the result are shown in the c program as comments. The program is as follows:

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

    int a=14,b=4;
    
   /* a: 14 : 1110
      b:  4 : 0100
     ~a:   :  0001  
     ~b:   :  1011  
   */
   a=b-~a-1;
    /* b:   0100 -
      ~a:   0001
            0011 -
       1:   0001
            0010
     now a= 0010 
    */
    b=a+~b+1;
    /* a:   0010 +
      ~b:   1011
       1:   0001
    now b:  1110  (14)
       ~b:  0001
    */
    a=a+~b+1;
   /*  a:   0010 +
      ~b:   0001
       1:   0001
    now a:  0100 (4)
   */

    printf("a= %d\nb=  %d",a,b);
}

Spiral Matrix Program in C - Zoho Interview Question - C Program to Read a Matrix in Spiral Order

A spiral matrix is a matrix (two dimensional array) in which the elements are stored in spiral manner. The order of accessing elements in the spiral matrix resembles a spiral. Actually it is a normal NxN two dimensional array. But instead of accessing elements row-wise or column-wise, we access them in spiral order. i.e, in a 3x3 matrix the order of retrieval of elements is spiral order is as follows:

(0,0)  (0,1)   (0,2)  (1,2)   (2,2)   (2,1)   (2,0)   (1,0)   (1,1)

The following picture shows a 4x4 spiral matrix:
4x4 spiral matrix using two dimensional array - C Program for spiral matrix
A 4x4 Spiral matrix

Zoho, an IT company, asked an interview question which was to write a program to read a matrix spirally. In this post, we will answer this interview question  by zoho corporation. The only difference between spiral matrix and normal matrix is the order in which we store elements to matrix or access elements in matrix. The following is the C program to read a spiral matrix.

#include<stdio.h>
void main()
{
int a[10][10],o,cellcount,cc=0,c=0,i=0,j=0,g=1;
printf("\nEnter the order of spiral matrix: ");
scanf("%d",&o);
cellcount=o;
printf("\nEnter the elements:\n");
while(c<o*o)
    {
    cc=0;
    for(;cc<cellcount;j=j+g,cc++)
        scanf("%d",&a[i][j]);
    j=j-g;
    c+=cc;
    cc=0;
    i=i+g;
    cellcount--;
    if(c>=o*o)
        break;
    for(;cc<cellcount;i=i+g,cc++)
        scanf("%d",&a[i][j]);
    c+=cc;
    i=i-g;
    j=j-g;
    g*=-1;
    }
printf("\nThe spiral matrix is:");
for(i=0;i<o;i++)
    {
    printf("\n");
    for(j=0;j<o;j++)
        printf("%d\t",a[i][j]);
    }
}
The above program reads the matrix in spiral fashion and the displays the matrix in normal way. You can use this code not only to read and store the elements in matrix spirally but also to access the elements in the matrix in spiral order.

Related Posts:

C Compiler for Android Phones
C Program to Validate Sudoku - Check Correctness of Sudoku
C Program to Display Pascal's Triangle
C Program to Burst Consecutive Repetition of Numbers in Array
C Program to Display Strings Crossed
Tricky Interview Question - C Program to Rearrange an Array Without Using any Other Arrays
C Program to Convert Between Decimal, Binary, Hexadecimal and Octal Number Systems
C Program to Find Inverse of a Matrix
C Program to Find Largest Integer Formed Using Digits of Given Number
C Program to Count GrandChildren - Interview Question
How to get Random Number in C
C Program to Implement Circular Linked List
C Program to Swap Numbers with Bitwise Operators
C Program for Subtraction Without Using Minus Operator
C Program to Swap Numbers without Temporary Variable

Lexical Analyzer using C Program - Simulation of Lexical Analyzer in C Program

lexical analyzer finite automata, c program for lexical analyzer in c language
Finite Automata for Lexical analyzer (Click to enlarge)
The input to lexical analyzer is character stream. The character stream input is grouped into meaningful units called lexemes, which are then mapped into tokens, the latter constituting the output of the lexical analyzer. The lexical analyzer uses a symbol table. Each identifier, keyword and symbol are given unique id (symbol table id). The lexical analyzer is designed using finite automata. The finite automata for this program is added at the end of the post. The program takes a file input.c (in same file) as input. The input to a lexical analyzer is source string (source code as a long string). A sample input to the lexical analyzer is shown after this program.

Lexical Analyzer Program in C

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

//***********

struct token
{
char type[30];
char name[50];
int id;
}retToken;

//*******

struct symboltable
{
char type[30];
char name[50];
}st[60];

typedef struct token token;

char* sourcecode;
int lexbeg=0,fwdptr=0,state=0;
int symbolcount=0;
token newtoken;
int isexist=0,lineno=1;

//************

int indexof(char *subString,int fromIndex,char *MainString)
{
	int Mainlength,subLength,i,j,retIndex=-1;
	Mainlength=strlen(MainString);
	subLength=strlen(subString);
	if(Mainlength<1||subLength<1||Mainlength-fromIndex<subLength)
		return(-1);
	for(i=fromIndex;Mainlength-i>=subLength;i++)
		{
		if(*(MainString+i)==*(subString))
			{
			retIndex=i;
			for(j=0;j<subLength;j++)
				{
				if(*(MainString+i+j)!=*(subString+j))
					{
					retIndex=-1;
					break;
					}
				}
			if(retIndex!=-1)
				return retIndex;
			}
		}
	return (-1);
}

//************

char * subString(char *MainString,int fromIndex,int toIndex)
{
int Mainlength,j;
char *subStr;
Mainlength=strlen(MainString);
if(fromIndex<0||fromIndex>=Mainlength||toIndex<fromIndex||toIndex>=Mainlength)
	{
	printf("\nError in args: subString fn");
	return(NULL);
	}
subStr=(char *)malloc(1000*sizeof(char));
for(j=0;j<=toIndex-fromIndex;j++)
	*(subStr+j)=*(MainString+fromIndex+j);

*(subStr+j)='\0';
return(subStr);
}

//************

char nextchar()
{
fwdptr++;
return(sourcecode[fwdptr-1]);
}

//************

void retract(int n)
{
fwdptr-=n;
}

//************

int fail(char * msg)
	{
	printf("%s",msg);
	return(-1);
	}

//************

int installid(char *string)
{
int i;
for(i=0;i<symbolcount;i++)
{
if(strcmp(string,st[i].name)==0)
	return i;
}
strcpy(st[symbolcount].name,string);
strcpy(st[symbolcount].type,"identifier");
symbolcount++;
return(symbolcount-1);
}

//************

token getType(char *tok)
{
int i;
token tt;
for(i=0;i<symbolcount;i++)
	{
	if(strcmp(st[i].name,tok)==0)
		{
        strcpy(tt.type,st[i].type);
        strcpy(tt.name,st[i].name);
        tt.id=i;
		return(tt);
		}
	}

}

//************

int isSymbol(char c)
{
int i;
char syms[]={'.','<','>',',','{','}','(',')','#',';'};
for(i=0;i<10;i++)
{
if(c==syms[i])
	return(i+41);
}
return(0);
}

void nextToken()
{
char c;
char *temptok;
state=0;
while(*(sourcecode+fwdptr)!='\0'&&state!=-1)
{
switch(state)
	{
	case -1:return;
	case 0:c=nextchar();
		if(c==' '||c=='\t'||c=='\n')
			{
			state=0;
			lexbeg++;
			if(c=='\n')
				{
				lineno++;
				printf("\nline %d: ",lineno);
				}
			if(c=='\0')
				state=-1;
			}
		else if(c=='<')
			state=1;
		else if(c=='>')
			state=5;
		else if(c=='=')
			state=8;
		else if(isalpha(c))
			state=10;
		else if(isdigit(c))
			state=22;
		else if(isSymbol(c))
			state=24;
		else if(c=='+')
			state=12;
		else if(c=='-')
			state=15;
		else if(c=='*')
			state=18;
		else if(c=='/')
			state=19;
		else if(c=='%')
			state=20;
		else
			state=fail("unknown symbol encountered");
		break;
	case 1:c=nextchar();
		if(c=='=')
			state=2;
		else if(c=='>')
			state=3;
		else
			state=4;
		break;
	case 2:strcpy(retToken.type,"relop");
		strcpy(retToken.name,"LE");
		retToken.id=17;lexbeg=fwdptr;return;
	case 3:strcpy(retToken.type,"relop");retToken.id=18;
		strcpy(retToken.name,"NE");lexbeg=fwdptr;return;
	case 4:retract(1);
		strcpy(retToken.type,"relop");retToken.id=19;
		strcpy(retToken.name,"LT");lexbeg=fwdptr;return;
	case 5:c=nextchar();
		if(c=='=')
			state=6;
		else
			state=7;
		break;
	case 6:strcpy(retToken.type,"relop");retToken.id=20;
		strcpy(retToken.name,"GE");lexbeg=fwdptr;return;
	case 7:retract(1);
		strcpy(retToken.type,"relop");retToken.id=21;
		strcpy(retToken.name,"GT");lexbeg=fwdptr;return;
	case 8:c=nextchar();
		if(c=='=')
			state=9;
		else
			state=21;
		break;
	case 9:strcpy(retToken.type,"relop");retToken.id=22;
		strcpy(retToken.name,"EQ");lexbeg=fwdptr;return;
	case 10:c=nextchar();
		if(isalpha(c)||isdigit(c))
			state=10;
		else
			state=11;
		break;
	case 11:retract(1);
		temptok=subString(sourcecode,lexbeg,fwdptr-1);
		retToken.id=installid(temptok);
		retToken=getType(temptok);
		lexbeg=fwdptr;return;
	case 12:c=nextchar();
		if(c=='+')
			state=13;
		else
			state=14;
		break;
	case 13:strcpy(retToken.type,"arop");retToken.id=23;
		strcpy(retToken.name,"INC");lexbeg=fwdptr;return;
	case 14:retract(1);
		strcpy(retToken.type,"arop");retToken.id=24;
		strcpy(retToken.name,"PLU");lexbeg=fwdptr;return;
	case 15:c=nextchar();
		if(c=='-')
			state=16;
		else
			state=17;
		break;
	case 16:strcpy(retToken.type,"arop");retToken.id=25;
		strcpy(retToken.name,"DEC");lexbeg=fwdptr;return;
	case 17:retract(1);
		strcpy(retToken.type,"arop");retToken.id=26;
		strcpy(retToken.name,"MIN");lexbeg=fwdptr;return;
	case 18:strcpy(retToken.type,"arop");retToken.id=27;
		strcpy(retToken.name,"MUL");lexbeg=fwdptr;return;
	case 19:strcpy(retToken.type,"arop");retToken.id=28;
		strcpy(retToken.name,"DIV");lexbeg=fwdptr;return;
	case 20:strcpy(retToken.type,"arop");retToken.id=29;
		strcpy(retToken.name,"MOD");lexbeg=fwdptr;return;
	case 21:retract(1);retToken.id=30;
		strcpy(retToken.type,"arop");
		strcpy(retToken.name,"ASSIGN");lexbeg=fwdptr;return;
	case 22:c=nextchar();
		if(isdigit(c))
			state=22;
		else
			state=23;
		break;
	case 23:retract(1);retToken.id=41;
		strcpy(retToken.type,"Numeric constant");
		strcpy(retToken.name,subString(sourcecode,lexbeg,fwdptr-1));lexbeg=fwdptr;return;
	case 24:strcpy(retToken.type,"Reserved Symbol");retToken.id=isSymbol(c);
		strcpy(retToken.name,subString(sourcecode,lexbeg,fwdptr-1));lexbeg=fwdptr;return;

	}
}

}

//************

void regkeywords()
{
int i;
char keywords[][15]={"do","while","main","for","include","if","else","break","continue","int","char","float","double","void","return","switch","case"};
//17
char relop[][3]={"LE","NE","LT","GE","GT","EQ"};//17 to 22
char arop[][7]={"INC","PLU","DEC","MIN","MUL","DIV","MOD","ASSIGN"};//23 to 30
char syms[][2]={".","<",">",",","{","}","(",")","#",";"};//31 to 40

for(i=0;i<=16;i++)
{
strcpy(st[i].name,keywords[i]);
strcpy(st[i].type,"keyword");
}

for(i=17;i<=22;i++)
{
strcpy(st[i].name,relop[i-17]);
strcpy(st[i].type,"relop");
}

for(i=23;i<=30;i++)
{
strcpy(st[i].name,arop[i-23]);
strcpy(st[i].type,"arop");
}

for(i=31;i<41;i++)
{
strcpy(st[i].name,syms[i-31]);
strcpy(st[i].type,"Reserved Symbol");
}
strcpy(st[41].name,"NC");
strcpy(st[41].type,"Numeric Constant");
symbolcount=42;

}

//************

void main()
{
int i;
char c,*line;
FILE *input;
input=fopen("input.c","r");
i=0;
sourcecode=(char*)malloc(sizeof(char)*1200);
while((c=getc(input))!=EOF)
	{
	*(sourcecode+i)=c; i++;
	}
*(sourcecode+i)='\0';
regkeywords();
printf("\nline 1: ");
nextToken();
while(state!=-1)
{
printf("type: %s, name: %s, id= %d\n",retToken.type,retToken.name,retToken.id);
nextToken();
if(lexbeg>=strlen(sourcecode)||fwdptr>=strlen(sourcecode))
	state=-1;
}
printf("\nSymbol Table:\n");
for(i=0;i<=symbolcount;i++)
{
    printf("\nType: %s",st[i].type);
    printf("\tName: %s",st[i].name);
    printf("\tid=: %d",i);
}
}



Sample input (input.c) to the Lexical Analyzer

void main()
{
int a,b,c,d;
a=10;
b=30;
c=a+b;
d=a*b;
}

Operator Precedence Parsing Program in C - C Program to Implement Operator Precedence Parsing

operator precedence parser, syntax analysis operator precedence parsing, ambiguous grammar c program implementation
Sample output - Click to enlarge
Parsing (Syntax analysis) is a topic in compiler construction. Operator Precedence parsing is one of i. For example, a sample input string to the operator precedence parser is i*(i+i).
the parsing techniques for ambiguous grammars. It solves the ambiguity by using operator precedence. In this post we will see a C program which implement operator precedence parsing to check the syntax for given input string. In input string (here a mathematical expression) the identifiers are denoted by

The grammar in this program is:

E  ->  i        / E*E       / E+E       / (E)       / E^E
i for identifier.
E is the start symbol.


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

char *input;
int i=0;
char lasthandle[6],stack[50],handles[][5]={")E(","E*E","E+E","i","E^E"};
//(E) becomes )E( when pushed to stack

int top=0,l;
char prec[9][9]={

                            /*input*/

            /*stack    +    -   *   /   ^   i   (   )   $  */

            /*  + */  '>', '>','<','<','<','<','<','>','>',

            /*  - */  '>', '>','<','<','<','<','<','>','>',

            /*  * */  '>', '>','>','>','<','<','<','>','>',

            /*  / */  '>', '>','>','>','<','<','<','>','>',

            /*  ^ */  '>', '>','>','>','<','<','<','>','>',

            /*  i */  '>', '>','>','>','>','e','e','>','>',

            /*  ( */  '<', '<','<','<','<','<','<','>','e',

            /*  ) */  '>', '>','>','>','>','e','e','>','>',

            /*  $ */  '<', '<','<','<','<','<','<','<','>',

                };

int getindex(char c)
{
switch(c)
    {
    case '+':return 0;
    case '-':return 1;
    case '*':return 2;
    case '/':return 3;
    case '^':return 4;
    case 'i':return 5;
    case '(':return 6;
    case ')':return 7;
    case '$':return 8;
    }
}


int shift()
{
stack[++top]=*(input+i++);
stack[top+1]='\0';
}


int reduce()
{
int i,len,found,t;
for(i=0;i<5;i++)//selecting handles
    {
    len=strlen(handles[i]);
    if(stack[top]==handles[i][0]&&top+1>=len)
        {
        found=1;
        for(t=0;t<len;t++)
            {
            if(stack[top-t]!=handles[i][t])
                {
                found=0;
                break;
                }
            }
        if(found==1)
            {
            stack[top-t+1]='E';
            top=top-t+1;
            strcpy(lasthandle,handles[i]);
            stack[top+1]='\0';
            return 1;//successful reduction
            }
        }
   }
return 0;
}



void dispstack()
{
int j;
for(j=0;j<=top;j++)
    printf("%c",stack[j]);
}



void dispinput()
{
int j;
for(j=i;j<l;j++)
    printf("%c",*(input+j));
}



void main()
{
int j;

input=(char*)malloc(50*sizeof(char));
printf("\nEnter the string\n");
scanf("%s",input);
input=strcat(input,"$");
l=strlen(input);
strcpy(stack,"$");
printf("\nSTACK\tINPUT\tACTION");
while(i<=l)
	{
	shift();
	printf("\n");
	dispstack();
	printf("\t");
	dispinput();
	printf("\tShift");
	if(prec[getindex(stack[top])][getindex(input[i])]=='>')
		{
		while(reduce())
			{
			printf("\n");
			dispstack();
			printf("\t");
			dispinput();
			printf("\tReduced: E->%s",lasthandle);
			}
		}
	}

if(strcmp(stack,"$E$")==0)
    printf("\nAccepted;");
else
    printf("\nNot Accepted;");
}

How to Use Mathematical Functions in Math.h in GCC Compiler for C

Linux operating systems use GCC (GNU Compiler Collection). In recent versions versions of GCC, it is not enough to include the line #include<math.h> to use functions in math.h header file. The most commonly used functions in math.h are sqrt, pow, abs, sin, cos, tan, exp, log, log10, ceil, floor etc. If you use any of the functions defined  in math.h header file, even if you include the #include<math.h> pre-processor directive, the compiler may show an error. In such case you should manually link to math.h file. Suppose you are going to compile a file myfile.c which uses functions under math.h header, you may use the following commands in terminal for gcc:

gcc myfile.c -lm

or

gcc myfile.c -o outputfilename -lm

-l option is used to manually link libraries. -lm directs the compiler to manually link libm. So, if we use the math library, we have to manually link it in gcc compilers. It is said to be for the reason that earlier processors were slow and floating point capabilities were limited. It is also said that it is for the reason embedded computing components are not having much computing capabilities especially for floating point operations or some of them even do not need it. So, math.h is avoided from automatic linking.

C Programming Previous Year Question Paper for Automobile, Mechanical, Production or Metallurgy

Here i have uploaded the previous year (2014 November) question paper of Programming in C for Third semester for Automobile Engineering, Mechanical Engineering, Production Engineering or Metallurgy branches under MG university BTech course.

Course : B.Tech Engineering (degree)
University: MG university (Mahatma Gandhi university) Kottayam, Kerala
Department or branch: Automobile Engineering, Mechanical Engineering, Production Engineering or Metallurgy

Semester: Third Semester (3rd or s3)
Subject: Programming in C (CP or PSCP)

You may view online or download the question paper as pdf file from following links.

View Online in Google Docs

Download question paper in PDF format



Related Posts:

C Program to Display Prime Numbers Less than Given Number
C Program to Display Armstrong Numbers
C Program to Check Armstrong Number
C Program to Reverse a Number
C Program for Quick Sort
C Program to Search an element in array (Linear Search)
Leap Year C Program
C Program to Find Sum of Digits of a Number
C Program to Check Perfect Number
C Program to Find Transpose of Matrix
C Program to Understand Bitwise Operators

C Program to Simulate Round Robin CPU Sceduling Algorithm

The round robin CPU scheduling algorithm is simulated using C program. The time slice or time quantum is read from the user.

Program:

#include<stdio.h>
struct process{



int burst,wait,comp,f;
}p[20]={0,0};
int main(){
int
n,i,j,totalwait=0,totalturn=0,quantum,flag=1,
time=0;
printf("\nEnter The No Of Process
:");
scanf("%d",&n);
printf("\nEnter The Quantum time (in ms)
:");
scanf("%d",&quantum);
for(i=0;i<n;i++){
printf("Enter The Burst Time (in ms) For
Process #%2d :",i+1);
scanf("%d",&p[i].burst);
p[i].f=1;
}
printf("\nOrder Of Execution \n");
printf("\nProcess \tStarting\tEnding\tRemaining");
printf("\n\tTime \tTime\tTime");
while(flag==1){
flag=0;
for(i=0;i<n;i++){
if(p[i].f==1){
flag=1;
j=quantum;
if((p[i].burst-p[i].comp)>quantum){
p[i].comp+=quantum;
}
else{
p[i].wait=time-p[i].comp;
j=p[i].burst-p[i].comp;
p[i].comp=p[i].burst;
p[i].f=0;
}
printf("\nprocess # %-3d %-10d %-10d %-10d",i+1,time,time+j,p[i].burst-
p[i].comp);
time+=j;
}}}
printf("\n\n------------------");
printf("\nProcess \t Waiting Time  TurnAround Time ");
for(i=0;i<n;i++){
printf("\nProcess # %-12d%-15d%-15d",i+1,p[i].wait,p[i].wait+p[i].burst);
totalwait=totalwait+p[i].wait;
totalturn=totalturn+p[i].wait+p[i].burst;
}
printf("\n\nAverage\n------------------");
printf("\nWaiting Time : %f ms",totalwait/(float)n);
printf("\nTurnAround Time : %f ms\n\n",totalturn/(float)n);
return 0;
}


Round robin CPU scheduling algorithm simulation using C program. simulate CPU scheduling output

C Program to Simulate Priority Scheduling CPU scheduling Algorithm

The following C program implements Simulation of  priority scheduling (CPU Scheduling algorithm). Each process or job is given a priority. The priority is represented using a positive integer. The priority increases as the value of the integer decreases.

Program:

#include<stdio.h>
struct process{



int burst,wait,no,priority;
}p[20]={0,0};
int main(){
int n,i,j,totalwait=0,totalturn=0;
printf("\nEnter The No Of Process :");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter The Burst Time (in ms) For Process #%2d :",i+1);
scanf("%d",&p[i].burst);
printf("Enter The Priority For Process #%2d :",i+1);
scanf("%d",&p[i].priority);
p[i].no=i+1;
}
for(i=0;i<n;i++)
for(j=0;j<n-i-1;j++)
if(p[j].priority>p[j+1].priority)
{
p[j].burst^=p[j+1].burst^=p[j].burst^=p[j+1].burst;
p[j].no^=p[j+1].no^=p[j].no^=p[j+1].no;
//Simple way to swap 2 var’s
p[j].priority^=p[j+1].priority^=p[j].priority^=p[j+1].priority;
//printf("j");
}
printf("\nProcess \t Starting\tEnding\tWaiting\tTurnAround ");
printf("\n\t Time\tTime\tTime\tTime ");
for(i=0;i<n;i++)
{
printf("\nProcess # %-11d%-10d%-10d%-10d%10d",p[i].no,p[i].wait,p[i].wait+p[i].burst,p[i].wait,p[i].wait+p[i].burst);
p[i+1].wait=p[i].wait+p[i].burst;
totalwait=totalwait+p[i].wait;
totalturn=totalturn+p[i].wait+p[i].burst;
}
printf("\n\nAverage\n---------");
printf("\nWaiting Time : %f ms",totalwait/(float)n);
printf("\nTurnAround Time : %f ms\n\n",totalturn/(float)n);
return 0;
}

Output:
Enter The No Of Process :3
Enter The Burst Time (in ms) For Process #1 :30
Enter The Priority For Process # 1 :2
Enter The Burst Time (in ms) For Process #2 :20
Enter The Priority For Process # 2 :1
Enter The Burst Time (in ms) For Process #3 :40
Enter The Priority For Process # 3 :3

Process          Starting  Ending  Waiting  TurnAround
                          Time        Time      Time          Time
Process # 2        0             20           0                20
Process # 1       20            50          20              50
Process # 3       50            90          50              90

Average
---------
Waiting Time : 23.333333 ms
TurnAround Time : 53.333333 ms


Simulation of Shortest Job First (SJF) CPU scheduling algorithm in C Language

This is a C program to simulate Shortest Job First (SJF) CPU scheduling algorithm. In Shortest Job first CPU scheduling algorithm, the process with  shortest CPU burst time is executed first. The following program is to simulate non preemptive SJF scheduling. Preemptive SJF CPU scheduling algorithm will be discussed in another post.

#include<stdio.h>
struct process
{
int burst,wait,no;
}p[20]={0,0};

int main()
{
int n,i,j,totalwait=0,totalturn=0;
printf("\nEnter The No Of Process :");
scanf("%d",&n);
for(i=0;i<n;i++)
  {
  printf("Enter The Burst Time (in ms) For Process #%2d :",i+1);
  scanf("%d",&p[i].burst);
  p[i].no=i+1;
  }

for(i=0;i<n;i++)
  for(j=0;j<n-i-1;j++)
    if(p[j].burst>p[j+1].burst)
      {
      p[j].burst^=p[j+1].burst^=p[j].burst^=p[j+1].burst;
      p[j].no^=p[j+1].no^=p[j].no^=p[j+1].no;
      }

printf("\nProcess \t Waiting Time TurnAround Time ");
for(i=0;i<n;i++)
  {
  printf("\nProcess # %-12d%-15d%-15d",p[i].no,p[i].wait,p[i].wait+p[i].burst);
  p[i+1].wait=p[i].wait+p[i].burst;
  totalwait=totalwait+p[i].wait;
  totalturn=totalturn+p[i].wait+p[i].burst;
  }
printf("\n\nAverage\n---------");
printf("\nWaiting Time : %f ms",totalwait/(float)n);
printf("\nTurnAround Time : %f ms\n\n",totalturn/(float)n);
return 0;

}

Output:

Enter The No Of Process :3
Enter The Burst Time (in ms) For Process # 1 :20
Enter The Burst Time (in ms) For Process # 2 :30
Enter The Burst Time (in ms) For Process # 3 :10
Process          Waiting Time     TurnAround Time
Process # 3          0                           10
Process # 1        10                            30
Process # 2        30                            60

Average---------
Waiting Time : 13.333333 ms
TurnAround Time : 33.333333 ms

Related Posts:

C Program to Simulate ls Command in Linux
C Program to Simulate Round Robin CPU Scheduling Algorithm
C Program to Simulate Priority CPU Scheduling Algorithm
C Program to Simulate First Come First Serve (FCFS) CPU Scheduling Algorithm
C Program to Simulate rmdir Command or Delete Directory
C Program to Open, Read and Write Files
C Program to Create Process and Display Process ID - OS Lab Program
How to Use Fork and Exec System Calls
How to Use Exit System Call
C Program to make Parent Process Wait for Child to Terminate
C Program to Simulate GREP Command in Linux
C Program to make Child Process an Orphan Process
C Program to Show Process ID in Linux
C Program for Inter Process Communication using Pipes or Named Pipes (Chat Program)
C Program to Create a Process Using Fork System Call

Simulation of FCFS CPU Scheduling Algorithm in C

This is a C program to simulate First come first served (FCFS) CPU scheduling algorithm. First come first served algorithm serves each processes (or jobs) in the order of arrival. The process with lowest arrival time is executed first.

Program:
#include<stdio.h>
struct process
{
int burst,wait;
}p[20]={0,0};



int main()
{
int n,i,totalwait=0,totalturn=0;
printf("\nEnter The No Of Process :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter The Burst Time (in ms) For Process #%2d :",i+1);
scanf("%d",&p[i].burst);
}
printf("\nProcess \t Waiting Time\tTurnAround Time ");
printf("\n\t (in ms)\t(in ms)");
for(i=0;i<n;i++)
{
printf("\nProcess # %-12d%-15d%-15d",i+1,p[i].wait,p[i].wait+p[i].burst);
p[i+1].wait=p[i].wait+p[i].burst;
totalwait=totalwait+p[i].wait;
totalturn=totalturn+p[i].wait+p[i].burst;
}
printf("\n\nAVERAGE\n--------- ");
printf("\nWaiting Time : %f ms",totalwait/(float)n);
printf("\nTurnAround Time : %f ms\n\n",totalturn/(float)n);
return 0;
}

Output:
Enter The No Of Process :3
Enter The Burst Time (in ms) For Process # 1 :10
Enter The Burst Time (in ms) For Process # 2 :30
Enter The Burst Time (in ms) For Process # 3 :20
Process    Waiting Time     Turn Around Time
                     (in ms)                      (in ms)
Process # 1     0                               10
Process # 2    10                              40
Process # 3    40                              60

AVERAGE
---------
Waiting Time : 16.666667 ms
TurnAround Time : 36.666667 ms

C Program to Simulate the ls Command in Linux Operating system

This is a c program to do Simulation of ls Command in linux. The ls command lists all the contents of the directory including filse and sub-directories. The following c program in simulates the ls command.
#include<stdio.h>
#include<dirent.h>
main()
{
char dirname[10];
DIR*p;
struct dirent *d;
printf("Enter directory name\n");
scanf("%s",dirname);
p=opendir(dirname);
if(p==NULL)
  {
  perror("Cannot find directory");
  exit(-1);
  }
while(d=readdir(p))
  printf("%s\n",d->d_name);
}

Related Posts:

C Program to Simulate ls Command in Linux
C Program to Simulate Round Robin CPU Scheduling Algorithm
C Program to Simulate Priority CPU Scheduling Algorithm
C Program to Simulate First Come First Serve (FCFS) CPU Scheduling Algorithm
C Program to Simulate rmdir Command or Delete Directory
C Program to Open, Read and Write Files
C Program to Create Process and Display Process ID - OS Lab Program
How to Use Fork and Exec System Calls
How to Use Exit System Call
C Program to make Parent Process Wait for Child to Terminate
C Program to Simulate GREP Command in Linux
C Program to make Child Process an Orphan Process
C Program to Show Process ID in Linux
C Program for Inter Process Communication using Pipes or Named Pipes (Chat Program)
C Program to Create a Process Using Fork System Call

C Program to Simulate grep Command in Linux

This post contains C program to simulate grep command in Linux or Unix operating systems

Simulation of  grep command in Linux

#include<stdio.h>
#include<string.h>
void main()
{
char fn[10],pat[10],temp[200];
FILE *fp;
printf("Enter file name\n");
scanf("%s",fn);
printf("Enter pattern to be searched\n");
scanf("%s",pat);
fp=fopen(fn,"r");
while(!feof(fp))
{
fgets(temp,1000,fp);
if(strstr(temp,pat))
  printf("%s",temp);
}
fclose(fp);
}

Related Posts:

C Program to Simulate ls Command in Linux
C Program to Simulate Round Robin CPU Scheduling Algorithm
C Program to Simulate Priority CPU Scheduling Algorithm
C Program to Simulate Shortest Job First (SJF) CPU Scheduling Algorithm
C Program to Simulate First Come First Serve (FCFS) CPU Scheduling Algorithm
C Program to Simulate rmdir Command or Delete Directory
C Program to Open, Read and Write Files
C Program to Create Process and Display Process ID - OS Lab Program
How to Use Fork and Exec System Calls
How to Use Exit System Call
C Program to make Parent Process Wait for Child to Terminate
C Program to make Child Process an Orphan Process
C Program to Show Process ID in Linux
C Program for Inter Process Communication using Pipes or Named Pipes (Chat Program)
C Program to Create a Process Using Fork System Call

C Program to Remove (Delete) a Directory using LINUX System Calls

This is a C program to delete  or remove a directory using the system calls in Linux or Unix operating systems. The program make use of the remove() system call in Linux.

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



char fn[10];
printf("Enter source filename\n");
scanf("%s",fn);
if(remove(fn)==0)
printf("File removed\n");
else
printf("File cannot be removed\n");
}

C Program to open, read and write files and perform file copy operation usingSystem Calls in UNIX

Write a program to open, read and write files and perform file copy operation. This program show how to open, read, write and copy files using Linux or Unix system calls like open(), read() and write().

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


char buff[1000],fn1[10],fn2[10];
int fd1,fd2,n;
printf("Enter source filename\n");
scanf("%s",fn1);
printf("Enter destination file name\n");
scanf("%s",fn2);
fd1=open(fn1,O_RDONLY);
n=read(fd1,buff,1000);
fd2=open(fn2,O_CREAT|O_WRONLY);
n=write(fd2,buff,n);
close(fd1);
close(fd2);
}

C Program to Open, Read and Write a file using System Calls

This is a C program to open , read and write files using system calls in Linux (UNIX) operating systems. The system calls open(), read() and write() are used in the C program to open, read and write files in Unix/Linux operating systems.

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


char buff[100],fn[10];
int fd,n;
printf("Enter file name\n");
scanf("%s",fn);
fd=open(fn,O_RDONLY);
n=read(fd,buff,100);
n=write(1,buff,n);
close(fd);
}

Using System calls in C Program to rename a Directory in Linux

C Program to rename a directory in Unix or Linux operating systems using system call rename().

#include<stdio.h>
main()
{

char s[10],d[10];
printf("Enter source Dir Name:\n");
scanf("%s",s);
printf("Enter New Dir Name:\n");
scanf("%s",d);
if(rename(s,d)==-1)
perror("Can't be changed\n");
else
printf("%s is changed to %s\n\n",s,d);
}

How to Create process and display Process ID (pid) of Both Parent and Child

This program shows how to create process and display Process ID (pid) of Both Parent and Child processes. The process is created using the fork system call in UNIX (Linux) operating systems.

#include<stdio.h>
#include<dirent.h>
main(int argc,char **argv)
{

int pid,i;
for(i=0;i<atoi(argv[1]);i++)
{
pid=fork();
if(pid==0)
{
printf("child process id %d Parent process
id %d\n",getpid(),getppid());
}}}

How to use fork and exec System Call

Using fork and exec System calls in Linux (UNIX) operating systems. Fork system call is used to create a child process from a parent process.
#include<stdio.h>
main()
{

int pid;
pid=fork();
printf("%d\n",pid);
if(pid==0)
{
exec("/bin/date\n",NULL,NULL);
exit(0); }
else
{
printf("Parent process %d\n",pid); }}
if(sp)
while(dd=readdir(sp))
printf("--> %s\n",dd->d_name);
}
}

How to use exit() System call

C program to show how to use exit system call. The function exit() is used to exit from a process (or to terminate a process). This works both in Linux or UNIX and Windows operating systems.

#include<stdio.h>
main()
{

int pid;
pid=fork();
printf("%d\n",pid);
if(pid<0)
{
perror("Child can't be executed\n");
exit(-1);
}
else
{
printf("Child created\n");
exit(0);
}
}

How to make parent process wait till Completion of Child Process (Joining parent with child process)

How to make the parent process wait till the completion of execution of child process. The following C program makes the parent process to wait till the completion of its child process.

#include<stdio.h>
main()
{

int pid;
pid=fork();
printf("%d\n",pid);
if(pid==0)
{
printf("From child process \n");
}
else
{
wait(0);
printf("From parent process\n");
}
}

How to make Child process an Orphan Process

C program in Linux or Unix to make a child process orphan:

Making child as orphan

#include<stdio.h>
main()
{

int pid,pid1;
pid=fork();
if(pid>0)
{
printf("From parent process\n");
printf("Parent process %d \n",getpid());
}
else
{
sleep(1);
printf("From child process\n");
printf("child process %d \n",getpid());
}}

C Program to Show Process ID in Linux

This program is to show the process id (pid) in UNIX or Linx
The system call getpid() returns the process id of current process.

#include<stdio.h>
int main()
{
printf("\n Parent Process ID %d",getppid());
}

Inter Process Communication using Named Pipes - Chat Program in C

In this post, we will see a chat program using named pipes (fifo). Pipes are used for communication between processes. The named pipes are fifos. They enable two way communication unlike ordinary pipes. But they are half duplex, i.e. communication can take place only in one direction at a time. The program is in 3 parts: pipe_creation.c, leftTerminal.c and rightTerminal.c.

pipe_creation.c

#include<stdio.h>
void main()
{
int f1,f2;
f1 = mkfifo("pipeA",0666);
if(f1<0)
   printf("\npipeA was not created");
else
   printf("\npipeA created");

f2 = mkfifo("pipeB",0666);
if(f2<0)
   printf("\npipeB was not created");
else
   printf("\npipeB is created\n");
}
leftTerminal.c

#include<stdio.h> #include<fcntl.h> #include<string.h> #include<stdlib.h> void main() { char str[256]="start"; int fifo_write,fifo_read; while(strcmp(str,"end")!=0)   {   fifo_write= open("pipeA",O_WRONLY);   if(fifo_write<0)     printf("\nError opening pipe");   else     {     printf("\nEnter text:\n");     scanf("%s",str);     write(fifo_write,str,255*sizeof(char));     close(fifo_write);     }   fifo_read=open("pipeB",O_RDONLY);   if(fifo_read<0)     printf("\nError opening write pipe");   else     {     read(fifo_read,str,255*sizeof(char));     close(fifo_read);     printf("\n%s",str);     }   }

rightTerminal.c

#include<stdio.h> #include<fcntl.h> #include<string.h> #include<stdlib.h> void main() { char str[256]="start"; int fifo_read,fifo_write; while(strcmp(str,"end")!=0) { fifo_read=open("pipeA",O_RDONLY); if(fifo_read<0)    printf("\nError opening read pipe"); else    {    read(fifo_read,str,255*sizeof(char));    close(fifo_read);    printf("\n%s",str);    } fifo_write=open("pipeB",O_WRONLY); if(fifo_write<0)    printf("\nError opening write pipe"); else    {    printf("\nEnter text:\n");    scanf("%s",str);    write(fifo_write,str,255*sizeof(char));    close(fifo_write);    } } }
How to run:
Run pipe_creation.c first. Then close it. Then run leftTerm.c. Without closing it, open a new terminal window and run rightTerm.c. Start typing from leftTerm.c and then in rightTerm.c.

Output :
pipe_creation.c:
pipeA created
pipeB is created


leftTerminal.c 

Enter text:
hi

Hai
Enter text:
fine?

Ya.Sure
Enter text:
end



rightTerminal.c

hi
Enter text:
Hai

fine?
Enter text:
Ya.Sure

end
Enter text:
end


Related Posts:

C Program to Simulate ls Command in Linux
C Program to Simulate Round Robin CPU Scheduling Algorithm
C Program to Simulate Priority CPU Scheduling Algorithm
C Program to Simulate First Come First Serve (FCFS) CPU Scheduling Algorithm
C Program to Simulate rmdir Command or Delete Directory
C Program to Open, Read and Write Files
C Program to Create Process and Display Process ID - OS Lab Program
How to Use Fork and Exec System Calls
How to Use Exit System Call
C Program to make Parent Process Wait for Child to Terminate
C Program to Simulate GREP Command in Linux
C Program to make Child Process an Orphan Process
C Program to Show Process ID in Linux
C Program to Create a Process Using Fork System Call

Creating A Process in Linux (UNIX) - fork() Example Program

The system call fork() is used to  create a new process in UNIX based operating systems and Linux systems. The fork() system call creates a child process when called from a parent process. Unix will make an exact copy of the parent's address space and give it to the child. Therefore, the parent and child processes have separate address spaces. Here is a C program which uses the fork() system call to create a process during execution. The program is commented well for better understanding.

Program

/*The program (parent process) reads an array from the user.
It sorts it in descending order.


The child process created by parent process sorts it ascending order
*/

#include<stdlib.h>
#include<stdio.h>
int main()
{
  int cpid;
  int temp,a[100],n,i,j;
  printf("\nEnter number of elements : ");
  scanf("%d",&n);
  printf("Enter elements\n");
  for(i=0;i<n;i++){
     scanf("%d",&a[i]);
  }

printf("\n");
  cpid=fork(); /*Creating child process using fork() system call */

if(cpid<0)

{

printf("Cannot create a new process\n");

exit(0);

}
  if(cpid != 0)

{

/*fork returns processid of newly created process.
Therefore, the value of integer variable cpid in parent process is the process id of child process.
This block (if block) is executed only by the parent because the value of cpid is zero in child process. We use the value of variable cpid to decide which process (parent or child) should execute which part of code*/

  printf("\nThis is parent with id: %d\n",getpid());

/* The UNIX system call getpid() return the process id of process being executed.*/
     for(i=0;i<n;i++){
          for(j=0;j<n-1;j++){
                  if(a[j]<a[j+1]){
                     temp = a[j];
                     a[j] = a[j+1];
                     a[j+1] = temp;
                  }
          }
    }
 printf("Parent sorted the array in descending order\n");

}else

{

/*This block (else block) is executed only by the child process because value of cpid is zero only for child process.*/


    printf("\nThis is child with id: %d \n",getpid());
    for(i=0;i<n;i++){
          for(j=0;j<n-1;j++){
                  if(a[j]>a[j+1]){
                     temp = a[j];
                     a[j] = a[j+1];
                     a[j+1] = temp;
                  }
          }
     }
 printf("Child sorted the array in ascending order\n");

  }

/*The following part of code is executed by both the processes because it is not restricted using the value of cpid.*/

 for(i=0;i<n;i++){
    printf("%d\n",a[i]);
  }
   return 0;
}



Output:

Enter number of elements : 5
Enter elements
8
6
10
2
12


This is parent with id: 4261
Parent sorted the array in descending order
12
10
8
6
2

This is child with id: 4262
Child sorted the array in ascending order
2
6
8
10
12

Output of Linux program in C using fork() system call to create child process fork parent process start execution process id pid getpid return value
Output of the program