The greatest mistake you can make in life is to be continually fearing you will make one

Friday 26 February 2010

Type Conversion and Type casting in C

  • Type conversion occurs when the expression has data of mixed data types. 
  • example of such expression include converting an integer value in to a float value, or assigning the value of the expression to a variable with different data type.
  • In type conversion, the data type is promoted from lower to higher because converting higher to lower involves loss of precision and value.
  • For type conversion, C following some General rules explained below

    1. Integer types are lower than floating point types
    2. Signed types are lower than unsigned types
    3. Short whole number types are lower than longer types
    4. double>float>long>int>short>char
     
  • While Programming consider the following points

    1. An arithmetic operation between an integer and integer always yields an integer result.
    2. An operation between a float and float always yields a float result
    3. An operation between an integer and float always yields a float result. In this operation the integer is first promoted to a float and then the operation is performed. the net result is a float.
      int/int=int
      float/int=float
      int/float=float
      float/float=float
    4. If the expression contains one operand as double data type and another operand as some other lower data type then the other operand is also converted to double and the result will be double.
      double operator (float(or)long(or)int(or)short)=>double
    5.  If the expression contains long and unsigned integer data types, the unsigned integer is converted to unsigned long and the result will be unsigned long.
    6. Character and short data are promoted to integer
    7. Unsigned char and unsigned short are converted to unsigned integer.

Forced Conversion:
  • Forced conversion occurs when we are converting the value of the larger data type to the value of the smaller data type or smaller data type to the larger data type.
  • For example,consider the following assignment statement
    int a;
    float b;
    a=5.5;
    b=100;
    In the first statement a=5.5 ;a is declared as int so the float value 5.5 cannot be stored in a.In such a case float is demoted to an int and then its value is stored. hence 5 is stored in a.
    In the second statement b=100;since b is a float variable 100 is promoted to 100.000000 and then stored in b.
  • In general, the value of the expression is promoted or demoted depending on the type of variable on left hand side of =.
    consider the following statement
    float x,y,z;
    int result;
    result=x*y*z/100+32/8-3*1.5;
    In the above statement some operands are ints where as others are floats. During evaluation of the expression the ints would be promoted to floats and the result of the expression would be a float. But when this float value is assigned to result,it is again demoted to an int and then stored in result.
  • Forced conversion may decrease the precision.
  • Type casting is the prefered method of forced conversion
Type Casting (or) Explicit Type conversion:
  • Explicit type conversions can be forced in any expression , with a unary operator called a cast.
  • Syntax is
        (type-name) expression;
  • Example
    int n;
    float x;
    x=(float)n;
    The above statement will convert the value of n to a float value before assigning to x.but n is not altered
  • Type casting does not change the actual value of the variable but the resultant value may be put in temporary storage.
  • The cast operator has the same high precedence as other unary operators.
  • The Typecasting should not be used in some places.such as
  1. Type cast should not be used to override a const or volatile declaration.overriding these type modifiers can cause the program to fail to run correctly.
  2. Type cast should not be used to turn a pointer to one type of structrure or data type in to another.
  • Example of type casting using pointers
#include<stdio.h>
main()
{
    void *temp; //void pointer
    char c='a',*ch="hello";
    int i=10;
    temp=&c;
    printf("char=%c\n",*(char *)temp);
    temp=ch;
    printf("string=%s\n",(char *)temp);
    temp=&i;
    printf("i=%d\n",*(int *)temp);
    return 0;
}
output
char=a
string=hello
i=10       here temp is a void pointer.temp is used to typecast to anyother pointer

Thursday 25 February 2010

C Constants


  • A constant value is the one which does not change during the execution of a program
  • Constants are classified as shown in the picture

Integer Constant:
  • An integer constant must have atleast one digit.
  • It can be either positive or negative.If no sign precedes then it is assumed to be positive(unsigned).
  • No decimal point,commas or blanks are allowed in an integer constant
  • The range of integer constant depends upon the compiler. For a 16 bit compiler like Turbo C or Turbo C++ the range is -32768 to 32767
  •  Example 100,-200,+500
  • If an integer is too big to fit in to an integer range then it will taken as a long. A long constant is written with a terminal l (or) L. Example 123456789L
  • Unsigned constants are written with a terminal u (or) U.
  • Unsigned long constants are written with a terminal ul (or) UL.
  • The value of an integer can be specified in octal or hexadecimal instead of decimal. A leading 0(zero) on an integer constant means octal. A leading 0x (or) 0X on an integer constant means hexadecimal.
  • For example decimal 32 can be written as 040 in octal and 0x20 in hexadecimal.
  • unsigned(u) and long(l) can also be applied to octal and hexadecimal constants. for example 0xFUL is an unsigned long constant with decimal value 15.
Real Constant (or) Floating Point Constant
  • A real constant must have atleast one digit.
  • It must have a decimal point. No commas or blanks are allowed.
  • It could be either positive or negative. Default sign is positive.
  • It can be written in a fractional form(123.4) or an exponential form(1e-2).In exponential form the part appearing before 'e' is called mantissa and the part following 'e' is called exponent.
  • The suffixes f (or) F indicate a float constant.l or L indicate a long double.
  • Example: +123.45,500.0,-300.25,10e-5,-200e-25 
Character Constant
  • A character constant is an integer, written as a single alphabet,a single digit or a single special symbol enclosed within single quotes.
  • Example 'A','5','z','='
  • The value of  a character constant is the numeric value of the character in the machines character set.
  • The maximum length of a character constant can be 1 character.
  • Escape sequences are character constants.They look like 2 characters but they are single character only.Example: \n->newline and \t->horizontal tab
String Constant
  • Sequence of 0 or more characters surrounded by double quotes
  • Example "I am a String",empty string " "
  • The double quotes are not part of the string but used to delimit the string
  • String constants can be concatenated at compile time. for example "hello" "world" is equivalent to "hello world". This is useful for spliting long strings across several source lines.
  • The string constant is an array of characters. The internal representation of a string has a null character '\0' at the end.
  • strlen() function returns the number of characters in a string excluding '\0'
Enumeration Constant
  • An enumeration is a list of constant integer values. Example: enum bool{yes,no};
  • The first name in an enum has value 0, the next one has 1 and so on unless explicit values are specified.
  • If not all the values are specified, unspecified values continue the value from the last specified value.
  • Enumeration provide a convenient way to associate constant values with names.
  • Enumeration is an alternative to #define. In enum the values automatically defined.and easy to define large number of constants





    Wednesday 24 February 2010

    C Question of the Day -Enum

    1.What is the output of the following program?
    #include<stdio.h>
    int main()
    {
        enum measure {left=10,right,top=100,bottom};
        printf("left=%d\tright=%d\ttop=%d\tbottom=%d\n",left,right,top,bottom);
        return 0;
    }

    Solution
    left=10 right=11 top=100 bottom=101
    left is assigned to10.so next to left ie right is automatically assigned to 12.top is explicitly assigned to 100 so next to top ie bottom becomes 101

     2.What is the output of the following program?
    #include<stdio.h>
    int main()
    {
        enum student1 {Anand=0,Ashok,Alex} Boys;
        enum student2 {skippy=0,slowvy,Ashok} Girls;
        Girls=slowvy;
        switch(Girls)
        {
            case Skippy:
                printf("Skippy\n");
                break;
            case Slowy:
                printf("Slowy\n");
                break;
            case Ashok:
                printf("Ashok\n");
                break;
            default:
                break;
        }
         return 0;
    }
    Solution

    Compiler Error
    The program is failed to compile because 'Ashok' is both in the enumeration list

    3.What is the output of the following program?
    #include<stdio.h>
    #define FALSE 1
    int main()
    {
        enum Boolian{FALSE=0,TRUE};
        enum Boolian b;
        printf("False=%d\n",FALSE);
        printf("True=%d\n",TRUE);
        return 0;
    }
    Solution

    Compiler Error
    The program is failed to compile because the preprocessor will try to change the 'FALSE' to 1 in the enum statement

    4.What is the output of the following program?
    #include<stdio.h>
    enum Boolian {FALSE=0,TRUE}b;
    #define FALSE 1
    int main()
    {
        enum Boolian b;
        printf("False=%d\n",FALSE);
        printf("True=%d\n",TRUE);
        return 0;
    }
    Solution

    False=1 True=1
    This program will compile but the #define statement will make FALSE as 1.so FALSE and TRUE both have a value of 1

    5.What is the output of the following program?
    #include<stdio.h>
    enum {false,true};
    int main()
    {
        int x=1;
        do
        {
            printf("x=%d\t",x);
            x++;
            if(x<10)
                continue;
        }while(false);
        return 0;
    }
    Solution
    x=1

    6.What is the output of the following program?
    #include<stdio.h>
    int main()
    {
        float f=5,g=10;
        enum {i=10,j=20,k=50};
        printf("%d\n",++k);
        printf("%f\n",f<<2);
        pritf("%lf\n",f%g);
        return 0;
    }
    Solution

    Line no 6: Error Lvalue required
    Line no7: Cannot apply left shift to float
    Line no8:Cannot apply mod to float
    Explanation:
    Enumeration constants cannot be modified, so you cannot apply ++
    Bit wise operators and % operators cannot be applied on float values
    7.What is the output of the following program?
    #include<stdio.h>
    typedef enum errorType{warning,error,exception}error;
    int main()
    {
        error e;
        e=1;
        printf("e=%d\n",e);
        return 0;
    }
    Solution
    Compiler error:Multiple declaration for error
    Explanation:
    The name error is used in 2 places. first it is a enumeration constant with value 1.
    The second one is it is a type name(due to typedef) for enum error type.The compiler cannot distinguish the meaning of error so it produce a error message

    Enum Example programs in C

    Program 1:
    Program to find whether week day or week end using enum
    #include<stdio.h>
    int main()
    {
        enum Day {Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday};
        enum Day today;
        int x;
        printf("please enter the day of the week(0 to 6)\n");
        scanf("%d",&x);
        today=x;

        if(today==Sunday || today==Saturday)
            printf("Enjoy! Its the weekend\n");
        else
            printf("Week day.do your work\n");
        return 0;
    }

    Output
    Please enter the day of the week(0 to 6)
    0
    Enjoy! Its the Weekend


    Program 2:
    Program to find the month 
    #include<stdio.h>
    int main()
    {
        enum months {Jan=1,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec};
        enum months month;
        printf("month=%d\n",month=Feb);//Assign integer value
        return 0;
    }
    Output
    month=2

    Program 3:
    Program to return the number of days in a month using enum
    #include<stdio.h>
    int main()
    {
        enum months {Jan=31,Feb=28,Mar=31,Apr=30,May=31,Jun=30,Jul=31,Aug=31,Sep=30,Oct=31,Nov=30,Dec=31};
        enum months month;
        printf("days=%d\n",month=Feb);
        return 0;
    }
    Output
    days=28


     

    Tuesday 23 February 2010

    C Data Types and Sizes

    • In a C program, the programmer has to tell the system before, the type of numbers or characters he is using in his program. These specification of data is called data type.
    • C language data types can be classified in to 3 types as shown in figure


    Primary Data type:

    NoData TypeFull formRange of Values
    1charCharacter-128 to 127
    2intInteger-32768 to +32767
    3floatsingle precision floating point3.4e-38 to 3.4e+38
    4doubleDouble precision floating point1.7e-308 to 1.7e+308
    5voidVoid
    • void data type used in functions to specify the return value or the arguments.
    • There are number of qualifiers such as short,long,signed,unsigned can be applied to these primary data types.
    • The possible qualifiers for the basic type are shown in the table
    NoData TypeQualifier
    1charSigned,Unsigned
    2intshort,long,signed,unsigned
    3floatNo qualifier
    4doublelong
    5voidNo qualifier

    • Each compiler is free to choose appropriate size for its own hardware with restrictions that short and int are atleast 16 bits and longs are atleast 32 bits and size of short < int < long.
    • qualifier signed or unsigned may be applied to char or any integer.
    • unsigned numbers are always positive or zero and obey the laws of arithmetic modulo 2n, where n is the number of bits in the type.For example char is 8 bits so unsigned char variables have values between 0 and 28 ie values between 0 and 255.
    Data Type16 bit machine32 bit machine
    size(bytes)RangeSize(bytes)Range
    Char or Signed Char1-128 to 1271-128 to 127
    Unsigned Char10 to 25510 to 255
    Short int or Signed short int1-128 to 1272-32768 to 32767
    unsigned short int10 to 25520 to 65535
    int or Signed int2-32768 to 327674-2147483648 to 2147483647
    Unsigned int20 to 6553540 to 4294967295
    Long int or Signed long int4-2147483648 to 21474836474-2147483648 to 2147483647
    Unsigned long int40 to 429496729540 to 4294967295
    Float43.4e-38 to 3.4e+3843.4e-38 to 3.4e+38
    Double81.7e-308 to 1.7e+30881.7e-308 to 1.7e+308
    Long Double103.4e-4932 to 3.4e+493216

    • If we do not specify either signed or unsigned, most compiler will assume the type to be signed.           so signed int x; can be written as int x;
    • short and long can be used alone as type specifiers. 
                short=short int
                long=long int
                Short int x; can be wriiten as short x;

    • signed and unsigned can also be used alone as type specifiers. 
                signed int=signed
                unsigned int=unsigned
                unsigned  int x; can be wriiten as unsigned x;

    Monday 22 February 2010

    C Question of the Day 5

    1.What is the output of the following program?
    #include<stdio.h>
    int main()
    {
        int x=0,y=1;
        if(x=0)
        {
            printf("True\n");
        }
        else
        {
            printf("False\n");
        }
        return 0;
    }
    Solution
    False
    if(x=0) then x value is assigned to zero. now if(x=0) becomes if(0). The rule is if(n) becomes true when n is any positive or negative number except zero. so the condition is failed. so the else part is executed. The answer is false


    2.What is the output of the following program?
    #include<stdio.h>
    int main()
    {
        int x=1;
        x=5+5*x++;
        printf("x=%d\n",x);
        return 0;
    }
    Solution
    x=11
    When Postfix(x++) operation is used with variable in expression then the expression is evaluated first with original value then the variable is incremented.
    x=5+5*1=>x=5+5=>10
    now x will be incremented by one.x=10+1=>x=11


    3.What is the output of the following program?
    #include<stdio.h>
    int main()
    {
        int x=1,y;
        y=5+5*x++;
        printf("x=%d\t y=%d\n",x,y);
        return 0;
    }
    Solution

    x=2  y=10

    Saturday 20 February 2010

    C Question of the Day 4

    1.What is the output of the following program?
    #include<stdio.h>
    int main()
    {
        int a=10,b=20,c=30;
        c=a==b;
        printf("c=%d",c);
        return 0;
    }
    Solution
    c=0
    == is a relational operator.if the 2 operand is equal it returns 1(true) else return false.here a is not equal to b. so a==b returns 0. and 0 is stored in c. so the result is c=0


    2.What is the output of the following program?
    #include<stdio.h>
    int main()
    {
        int a=1,b=2;
        switch(a)
        {
            case 1:
                    printf("GOOD\n");
                    break;
            case b:
                    printf("BAD\n");
                    break;
        }
        return 0;
    }
    Solution
    Compiler Error: case label does not reduce to an integer constant
    The case statement can have only constant expressions ie we cannot use variable names directly in to a case statement. so an error happen.But enumerated types can be used in case statements

    3.What is the output of the following program?
    #include<stdio.h>
    int main()
    {
        int x;
        printf("ans=%d",scanf("%d",&x)); //value 10 is given as input here
        return 0;
    }
    Solution
    ans=1
    The scanf function returns number of items successfully read.
    Here 10 is given as input which should have been scanned successfully. So number of items read is 1

    Binay Tree

    Introduction:
    • A binary tree is a tree in which no node can have more than two children.These children are described as left child and right child of the parent node.
    • A binary tree T is defined as a finite set of nodes such that



      1. T is empty (ie) T has no nodes called the null tree or empty tree.
      2. There is a specially designated node called the root of the tree, and the remaining nodes are partitioned in to two disjointed sets T1 and T2,each of which is a binary tree.T1 is called the left subtree and T2 is called the right subtree.
    • Example of a binary tree is shown in figure 1

    • In the above binary tree A is the root node of the binar tree.B is the left child of A and C is the right child of A. So A is the parent node of B and C. B and C are the children of A.
    • If a node has no child then its called a leaf node. In the above example nodes D,H,I,F,J are leaf nodes
    • For a binary tree the maximum number of nodes at level i will be 2i considering root node is at level 0.
    • If K is the depth of the tree then the maximum number of nodes that the tree can have is 2K-1
    Strictly binary tree:
    • The tree is said to be strictly binary tree, if every non-leaf node in a binary tree has non-empty left and right sub trees
    • (ie) every node in the strictly binary tree contains either no children or 2 children.
    • figure 1 is not a strictly binary tree because node G has only one child
    • A strictly binary tree with n leaves always contains 2n-1 nodes. The strictly binary tree in the below figure has 5 leaves such as D,E,F,H,I. here n=5.so the tree has 2*5-1 ie 9 nodes.The tree contains 9 nodes only.So in strictly binary tree given the number of leaves we can easily find the totla number of nodes in the tree.
    • Strictly binary tree is also called 2-tree or extended binary tree.












      • The main application of a 2-tree is to represent any algebraic expression such as [E=(a+b)/((c-d)*e)]using binary operation.

      Problems based on Tree

      Problem 1:
      List out some of the application of tree data structure?
      Answer
      1. Manipulation of Arithmetic expression
      2. Symbol Table construction
      3. Syntax analysis
      Problem 2
      In a tree construction which is the suitable efficient data structures?
      (a) Array
      (b) Linked list
      (c) Stack
      (d) Queue
      (e) None

      Answer:
      (b) Linked list

      Problem 3 
      How many different trees are possible with 10 nodes?
      Answer
      In general If there are n nodes then there exist 2n-n different trees
      here n=10
      so 210-10==>1024-10=1014
      So there are 1014 different possible trees available.

      Problem 4
      How many differnt trees are possible with 3 nodes and show the possible trees?
      Answer
      here n=3
      2n-n=23-3=8-3=5
      So a tree with 3 nodes have the maximum combination of 5 different trees.
      The different possible trees are shown below


      Problem 5
      Consider the tree shown in figure

      1. Which node is the root node?
      2. Which nodes are Leaves?
      3. What is the depth of the tree?
      4. What is the degree of the tree?
      5. For each node in the tree
                (A) Name the parent node
                (B) List the children
                (C) List the siblings
                (D) Compute the depth
                (E) Compute the height

      Answer

      C Question of the Day 3

      1.What is the output of the following program?
      #include<stdio.h>> 
      int main()
      {
          float x;
          (int)x=100;
          printf("x=%d",x);
          return 0;
      }
      Solution

      error: lvalue required as left operand of assignment
      After using any operator on operand it always return some integer value. type casting operator is also doing the same thing. so (int)x is converted in some integer value(garbage value). we cannot assign any constant value to another constant value in c.
      (int)x=100==>2345332=100.
      2345332 is a garbage value.
      So the program results an error

      2.What is the output of the following program?
      #include<stdio.h>>
      int main()
      {
          int x;
          x=sizeof(!7.5);
          printf("x=%d",x);
          return 0;
      }
      Solution

      x=4
      ! is a unary negation operator.It returns either 0 or 1.
      ! converts a non zero operand in to 0 and a zero operand in to a 1.
      so !7.5 returns 0.since 0 is a integer number and size of integer data type is 4 bytes in a 32 bit compiler

      3.What is the output of the following program?
      #include<stdio.h>
      int main()
      {
          int x;
          x=012+0x46+20;
          printf("x=%d",x);
          return 0;
      }
      Solution

      x=100
      012 is a octal number.The decimal value of 012=1*8+2=10.
      0x46 is a hexadecimal value.The decimal value of 0x46=4*16+6=70.
      so the total value of x=10+70+20=100









      error: lvalue required as left operand of assignment
      After using any operator on operand it always return some integer value. type casting operator is also doing the same thing. so (int)x is converted in some integer value(garbage value). we cannot assign any constant value to another constant value in c.
      (int)x=100==>2345332=100.
      2345332 is a garbage value.
      So the program results an error 

      Friday 19 February 2010

      C Question of the Day 2

      1.What is the output of the following program?
      #include<stdio.h>>
      int main()
      {
          int x=100;
          printf("x=%d\nsizeof(x++)=%d\nx=%d\n",x,sizeof(x++),x);
          return 0;
      }
      Solution
      x=100
      sizeof(x++)=4
      x=100
      The x value is not incremented after the x++ operation.because the increment operation performed inside the sizeof operator doesn't change the value of x.
      The 'sizeof' operator is used to determine the amount of space anydata-element/datatype occupies in memory


      2.What is the output of the following program?
      #include<stdio.h>>
      int main()
      {>
          int x=10;
          printf("x1=%d\n",printf("x2=%d\n",printf("x3=%d\n",x)));
          return 0;
      }
      Solution

      x3=10
      x2=6
      x1=5
      The output function printf returns the number of characters printed.






      x=100
      sizeof(x++)=4
      x=100
      The x value is not incremented after the x++ operation.because the increment operation performed inside the sizeof operator doesn't change the value of x.
      The 'sizeof' operator is used to determine the amount of space anydata-element/datatype occupies in memory

      Thursday 18 February 2010

      C Question of the Day 1

      1.What is the output of the following program?
      #include<stdio.h>
      int main()
      {
          int i=10,j=20;
          j=i++ + ++i;
          printf("%d %d",i,j);
          return 0;
      }
      Solution
      As per C standard, there is no such rule to evaluate either right or left hand side of operator + on priority.Hence the statements like i+++++i should be avoided in programming


      2.What is the output of the following program?
      #include<stdio.h>
      int main()
      {
          float x;
          x=50/100;
          printf("x=%f",x);
          return 0;
      }
      Solution
      x=0.000000
      The expected output is 0.500000.because dividing an integer by an integer resulting a integer value. so 50/100 provide 0. but x is a float so the result is 0.000000
      int/int=int
      int/float=float
      float/int=float
      float/float=float



      3. What is the output of the following program?
      #include<stdio.h>
      int main()
      {
          int x;
          x=10,20,30;
          printf("x=%d",x);
          return 0;
      }
      Solution
      x=10


      4. What is the output of the following program?
      #include<stdio.h>
      int main()
      {
          int a=10,b=20,c=30;
          printf("%d%d%d");
          return 0;
      }
      Solution
      -973480632 -973480616 0
      Garbage value is printed

      5.What is the output of the following program?
      #include<stdio.h>
      int main()
      {
          int x=10;
          if(!!x)
              printf("!x=%d",!x);
          else
              printf("x=%d",x);
          return 0;
      }
      Solution
      !x=0
      ! is a unary negation operator.! converts a non zero operand in to 0 and a zero operand in to a 1



      !x=0

      Tuesday 16 February 2010

      CPU Scheduling

      What is CPU scheduling?
      • Determining which processes run when there are multiple runnable processes. 
      • Cpu scheduling is very important for system productivity and performance.
      • Necessary in multiprogramming environment.  
      What are possible process states? 
      • Running - process is running on CPU.
      • Ready - ready to run, but not actually running on the CPU.
      • Waiting - waiting for some event like IO to happen. 
      Role of Dispatcher?
      • Dispatcher is a component of OS that is used to switch between processes. 
      • It will stop the process,save the context of the stopped process,Load context of new process and resume the new process. 
      what is Dispatch latency? 
      • Time taken for the dispatcher to stop one process and start another running process. 
       Role of CPU scheduler? 
      • Whenever the CPU becomes idle a ready process must be selected for execution. The scheduler selects one process from the list of processes in memory that are ready to execute and allocates the cpu to one of the ready process.


      CPU Scheduling algorithm with source code
       
            This is the tested code for CPU scheduling algorithm. This code will cover First Come First Serve(FCFS),Shortest Job First(SJF),Shortest Job First with preemption,Shortest Job First with Nonpreemption,Priority schduling and RoundRobin schduling.

      This code consist of 3 files.
      copy and save the contents in to 3 separate files specified below

      1.Header file-save the content below from "//Header file for Cpu scheduling" to
      "// Implementation file for Cpu scheduling" as cpuh.h

      2.Implementation file-save the content from "// Implementation file for Cpu scheduling" to
      " //Application file for cpu Scheduling" as cpua.cpp

      3.The content below the line " //Application file for cpu Scheduling" save as cpub.cpp

      now compile both cpua.cpp,cpub.cpp and run cpub.cpp

      Code :

      // Header file for Cpu scheduling

      //------ > cpuh.h
      #include"iostream.h"
      #include"stdio.h"
      #include"conio.h"

      class cpuschedule
      {
          int n,Bu[20];
          float Twt,Awt,A[10],Wt[10],w;
          public:
          //Getting the No of processes & burst time
          void Getdata();
          //First come First served Algorithm
          void Fcfs();
          //Shortest job First Algorithm
          void Sjf();
          //Shortest job First Algorithm with Preemption
          void SjfP();
          //Shortest job First Algorithm with NonPreemption
         void SjfNp();
          //Round Robin Algorithm
          void RoundRobin();
          //Priority Algorithm
          void Priority();
      };

       // Implementation file for Cpu scheduling

      #include "cpuh.h"
      //Getting no of processes and Burst time
      void cpuschedule::Getdata()
      {
           int i;
           cout<<"Enter the no of processes:";
           cin>>n;
           for(i=1;i<=n;i++)
          {
               cout<<"Enter The BurstTime for Process p"<< i << "= ";
               cin>>Bu[i];
          }
      }

      //First come First served Algorithm
      void cpuschedule::Fcfs()
      {
           int i,B[10];
           Twt=0.0;
           for(i=1;i<=n;i++)
          {
               B[i]=Bu[i];
               cout<<"Burst time for process p"<< i <<"= ";
               cout<<B[i];
           }
           Wt[1]=0;
           for(i=2;i<=n;i++)
          {
                 Wt[i]=B[i-1]+Wt[i-1];
           }

            //Calculating Average Weighting Time
            for(i=1;i<=n;i++)
                  Twt=Twt+Wt[i];
            Awt=Twt/n;
            cout<< "Total Weighting Time=" << Twt;
            cout<<"Average Weighting Time=" << Awt <<" ";
      }

      //Shortest job First Algorithm
      void cpuschedule::Sjf() {
           int i,j,temp,B[10];
           Twt=0.0;
           for(i=1;i<=n;i++)
          {
               B[i]=Bu[i];
               cout<< "Burst time for process p" << i << "= ";
               cout<<B[i];
          }
          for(i=n;i>=1;i--)
         {
              for(j=1;j<=n;j++)
             {
                 if(B[j-1] > B[j])
                {
                      temp=B[j-1];
                      B[j-1]=B[j];
                      B[j]=temp;
                }
             }
          }

           Wt[1]=0;
           for(i=2;i<=n;i++)
          {
                Wt[i]=B[i-1]+Wt[i-1];
          }
          //calculating Average Weighting Time
          for(i=1;i<=n;i++)
              Twt=Twt+Wt[i];
          Awt=Twt/n;
          cout<< "Total Weighting Time=" << Twt;
          cout<< "Average Weighting Time=" << Awt <<" ";
      }

       //Shortest job First Algorithm with NonPreemption

      void cpuschedule::SjfNp()
      {
           int i,B[10],Tt=0,temp,j;
           char S[10];
           float A[10],temp1,t;
           Twt=0.0;
           w=0.0;
           for(i=1;i<=n;i++)
          {
                B[i]=Bu[i];
                cout<< "Burst time for process p" << i << "= ";
                cout<<B[i];
                S[i]='T';
                Tt=Tt+B[i];
                cout<< "Enter the Arrival Time for" << i << "th process= ";
                cin>>A[i];
           }
           for(i=n;i>=1;i--)
          {
               for(j=3;j<=n;j++)
              {
                    if(B[j-1] > B[j])
                   {
                         temp=B[j-1];
                         temp1=A[j-1];
                         B[j-1]=B[j];
                         A[j-1]=A[j];
                         B[j]=temp;
                         A[j]=temp1;
                    }
                }
          }
          for(i=1;i<=n;i++)
          {
           cout<< "p" << i << " " << B[i] << " " <<A[i];
           }

           //For the 1st process
           Wt[1]=0;
           w=w+B[1];
           t=w;
           S[1]='F';
           while(w<Tt)
           {
                i=2;
                while(i<=n)
               {
                     if(S[i]=='T'&&A[i]<=t)
                    {
                        Wt[i]=w;
                         cout<< "WT" << i << "=" << Wt[i];
                         S[i]='F';
                         w=w+B[i];
                         t=w;
                         i=2;
                     }
                     else
                         i++;
               }
          }
          for(i=1;i<=n;i++)
          cout<< "Wt" << i << "==" << Wt[i];
          //calculating average weighting Time
          for(i=1;i<=n;i++)
             Twt=Twt+(Wt[i]-A[i]);
          Awt=Twt/n;
          cout<< "Total Weighting Time=" << Twt << " ";
          cout<< "Average Weighting Time=" << Awt << " ";
      }

      //Priority Algorithmvoid cpuschedule::Priority()
      {
           int i,B[10],P[10],j;
           w=0.0;
           int max;
          Twt=0.0;
          max=1;
          for(i=1;i<=n;i++)
         {
              B[i]=Bu[i];
              cout<< "Burst time for process p" << i << "= ";
              cout<<B[i];
              cout<< "Enter the priority for process P" << i << "= ";
              cin>>P[i];
              if(max < P[i])
                  max=P[i];
          }
          j=1;
          while(j<=max)
          {
               i=1;
               while(i <= n)
              {
                   if(P[i]==j)
                  {
                       Wt[i]=w;
                       w=w+B[i];
                   }
                   i++;
              }
              j++;
           }

           //calculating average weighting Time
           for(i=1;i<=n;i++)
               Twt=Twt+Wt[i];
           Awt=Twt/n;
           cout<< "Total Weighting Time=" << Twt <<" ";
           cout<< "Average Weighting Time=" << Awt << " ";
      }

      //Shortest job First Algorithm with Preemption
      void cpuschedule::SjfP()
      {
           int i,j,m,Wt[10],k,B[10],A[10],Tt=0,Wtm[10],temp;
           char S[20],start[20];
           int max=0,Time=0,min;
           float Twt=0.0,Awt;
           for(i=1;i<=n;i++)
          {
               B[i]=Bu[i];
               cout<< "Burst time for process P" << i << "= " << B[i];
               if(B[i]>max)
                   max=B[i];
               Wt[i]=0;
               S[i]='T';
               start[i]='F';
               Tt=Tt+B[i];
               cout<< "Enter the Arrival Time for" << i << "th process= ";
               cin>>A[i];
               if(A[i]>Time)
                   Time=A[i];
           }
           //cout<< "Max=" << max;
           int w=0,flag=0,t=0;
           i=1;
           while(t<Time)
          {
               if(A[i]<=t && B[i]!=0)
              {
                   if(flag==0)
                  {
                       Wt[i]=Wt[i]+w;
                        cout<< "Wt["<< i << "]=" << Wt[i];
                  }
                  B[i]=B[i]-1;
                  if(B[i]==0)
                      S[i]='F';
                  start[i]='T';
                  t++;
                  w=w+1;
                  if(S[i]!='F')
                 {
                       j=1;flag=1;
                       while(j<=n && flag!=0)
                       {
                             if(S[j]!='F' && B[i]>B[j] && A[j]<=t && i!=j )
                            {
                                   flag=0;
                                   Wt[i]=Wt[i]-w;
                                    i=j;
                            }
                            else
                           {
                                flag=1;
                           }
                           j++;
                       }
                   }
                   else
                   {
                        i++;
                        j=1;
                        while(A[j] <= t &&j <= n)
                        {
                             if(B[i]>B[j] && S[j]!='F')
                            {
                                flag=0;
                                i=j;
                             }
                             j++;
                       }
                   }
              }
              else
                   if(flag==0)
                            i++;
           }
            cout<< "Printing remaining burst time";
            for(i=1;i<=n;i++)
                 cout<< "B["<< i <<"]=" << B[i];
            cout<< " ";
            while(w<Tt)
           {
               min=max+1;
               i=1;
              while(i<=n)
              {
                  if(min>B[i] && S[i]=='T')
                 {
                       min=B[i];
                       j=i;
                  }
                  i++;
              }
              i=j;
              if(w==Time && start[i]=='T')
             {
                  w=w+B[i];
                  S[i]='F';
             }
             else
            {
                 Wt[i]=Wt[i]+w;
                 w=w+B[i];
                 S[i]='F';
            }
         }
          cout<< "Weight info";
          for(i=1;i<=n;i++)
              cout<< "WT["<< i <<"]=" << Wt[i];
          cout<< "after subtracting arrival time";
          for(i=1;i<=n;i++)
          {
                Wt[i]=Wt[i]-A[i];
                 cout<< "WT["<< i <<"]=" << Wt[i];
          }
          //Calculating Average Weighting time
          for(i=1;i<=n;i++)
               Twt=Twt+Wt[i];
          Awt=Twt/n;
          cout<< "Average Weighting Time=" << Awt;
      }

      //Round Robin Algorithm
      void cpuschedule::RoundRobin()
      {
          int i,j,tq,k,B[10],Rrobin[10][10],count[10];
          int max=0;
          int m;
          Twt=0.0;
          for(i=1;i<=n;i++)
         {
             B[i]=Bu[i];
             cout<< "Burst time for process p" << i <<"= ";
             cout<<B[i];
             if(max<B[i])
                max=B[i];
             Wt[i]=0;
          }
          cout<< "Enter the Time Quantum=";
          cin>>tq;
          //TO find the dimension of the Rrobin array
          m=max/tq+1;

          //initializing Rrobin array
          for(i=1;i<=n;i++)
         {
              for(j=1;j<=m;j++)
             {
                 Rrobin[i][j]=0;
             }
          }
          //placing value in the Rrobin array
          i=1;
          while(i<=n)
          {
              j=1;
              while(B[i]>0)
              {
                   if(B[i]>=tq)
                  {
                       B[i]=B[i]-tq;
                       Rrobin[i][j]=tq;
                       j++;
                  }
                  else
                 {
                      Rrobin[i][j]=B[i];
                      B[i]=0;
                      j++;
                  }
              }
              count[i]=j-1;
              i++;
          }
          cout<< "Display";
          for(i=1;i<=n;i++)
         {
              for(j=1;j<=m;j++)
             {
                  cout<<"Rr["<< i <<","<< j <<"]="<< Rrobin[i][j];
                  cout<<" ";
              }
              cout<<" ";
          }
          //calculating weighting time
          int x=1;
          i=1;
          while(x<=n)
          {
               for(int a=1;a<x;a++)
              {
                 Wt[x]=Wt[x]+Rrobin[a][i];
               }
               i=1;
               int z=x;
               j=count[z];
               k=1;
               while(k<=j-1)
              {
                   if(i==n+1)
                  {
                       i=1;
                       k++;
                  }
                  else
                  {
                        if(i!=z)
                       {
                            Wt[z]=Wt[z]+Rrobin[i][k];
                       }
                       i++;
                  }
               }
               x++;
           }
           for(i=1;i<=n;i++)
                cout<<"Weighting Time for process P"<< i <<"="<<Wt[i];

           //calculating Average Weighting Time
           for(i=1;i<=n;i++)
               Twt=Twt+Wt[i];
           Awt=Twt/n;
           cout<<"Total Weighting Time="<<Twt;
           cout<<"Average Weighting Time="<<Awt<<" ";
      }

      //Application file for cpu Scheduling

      #include "cpuh.h"

      void main()
      {
           int ch,cho;
           cpuschedule c;
           do
           {
                cout<<" MENU";
                cout<<"1.Getting BurstTime";
                cout<<"2.FirstComeFirstServed";
                cout<<"3.ShortestJobFirst";
                cout<<"4.RoundRobin";
                cout<<"5.Priority";
                cout<<"6.EXIT";
                cout<<"Enter your choice";
                cin>>ch;
                switch(ch)
               {
                   case 1:
                            c.Getdata();
                            break;
                   case 2:
                            cout<<"FIRST COME FIRST SERVED SCHEDULING";
                            c.Fcfs();
                            break;
                    case 3:
                             cout<<"SHORTEST JOB FIRST SCHEDULING";
                             do
                             {
                                   cout<<"1.SJF-Normel";
                                   cout<<"2.SJF-Preemptive";
                                   cout<<"3.SJF-NonPreemptive";
                                   cout<<"Enter your choice";
                                   cin>>cho;
                                   switch(cho)
                                  {
                                       case 1:
                                                c.Sjf();
                                                break;
                                       case 2:
                                                c.SjfP();
                                                break;
                                       case 3:
                                                c.SjfNp();
                                                break;
                                    }
                               }while(cho<=3);
                               break;
                      case 4:
                               cout<<"ROUND ROBIN SCHEDULING";
                               c.RoundRobin();
                               break;
                      case 5:
                               cout<<"PRIORITY SCHEDULING";
                               c.Priority();
                               break;
                      case 6:
                               break;
                  }
            }while(ch<=5);
      }