Author: admin

  • Java – Scope of a Variable

    What is scope of a variables in Java?

    Scope refers to the visibility of variables. In other words, a scope is a section of a program, and the scope of variables refers to the section of the program where the variables are visible.

    Variables are declared and used within that region. Also variable declared within the block cannot be accessed outside that block.

    Before understanding the variable’s scope, lets us see some certain rules to declare the variables:

    • The first character must be a letter.
    • A variable name can consist of letters A-Z, a-z, digits 0-9, and two special characters such as underscore(_) and the dollar sign($).
    • Blank spaces cannot be used in variable names.
    • Java keywords cannot be used as variable names.
    • Variable names are case-sensitive.

    Types of Variables in Java:

    • local variable
    • instance variable
    • static variable

    Let’s learn the scope of these each variable with an example:

    1. Local Variable:

    A variable that is declared within the body of the method or constructor is called a local variable. This variable is used only within that block or method where it was created other classes cannot access it. And is destroyed after exiting the method or block.

    Initialization of Local Variables is necessary.

    Example of local variable:

      public class Employees
      { 
        public void EmployeeInfo() 
        { 
          // local variable age 
          int age = 0;
          String name = "Prashant";
            
          age = age + 30; 
          System.out.println("Employee age is : " + age); 
          System.out.println("Employee name is : " + name ); 
        } 
      
        public static void main(String args[]) 
        { 
          Employees emp = new Employees(); 
          emp.EmployeeInfo(); 
        } 
      }

    Output:

     Employee age is : 30
     Employee name is : Prashant

    2. Instance Variable:

    These are the non-static variable that is declared within the class but outside the method or constructor. With the creation of Objects, Instance Variable is created and destruction of an object destroys the variables.

    And can be accessed only by creating objects. Initialization of Instance Variable is not necessary as it is 0 by default.

    Example of Instance variable:

     public class Employees
     {
        // this instance variable  
        String name;
        int age;
    
        public Employees (String EmployeeName)
        {
          name = EmployeeName;
        }
    
        public void EmpAge(int EmployeeAge)
        {
          age = EmployeeAge;
        }
    
        public void Display()
        {
          System.out.println("Employee name: " + name ); 
          System.out.println("Employee  age :" + age); 
        }
    
        public static void main(String args[])
        {
          Employees r = new Employees("Prashant");
          r.EmpAge(20);
          r.Display();
        }
     }

    Output:

    Employee name: Prashant
    Employee  age :20

    3. Static variable:

    These variables are also known as class Variables. These are declared just like Instance Variable that within the class but outside the constructor or method but the difference is that static variable is declared using static keyword.

    Unlike the Instance variable, only one static variable is created its value remains the same for all objects no matter how many objects the user creates. Here initialization is not mandatory, it is 0 by default.

    Example of Static variable:

     public class Employees
     {
        //static variable
        static int id = 1101;
    
      public static void main(String[] args)
      {
        
        Employees emp = new Employees();
    
       // Call static variable using object reference variable
        int a = emp.id;
    
        
        System.out.println("Employee ID: ");
        System.out.println(Employees.id);
      }
     }

    Output:

    Employee ID: 
    1101

  • Java – Operator & Expression

    Operators are used to perform operations on variables and values or to manipulate them. The operation is performed with two operand and operators to provide what action need to perform.

    Example:

    int a = 10 + 5;

    In the above example, 10 and 5 are operands and + is the operation performed between these two operands.

    Java provides numbers of operation and these are grouped into the following:

    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Logical Operators
    • Relational (comparison) operators
    • Bitwise Operators
    • Ternary Operator

    1. Arithmetic Operators: 

    They are used to perform basic arithmetic operations. They perform on primitive data types.
    They are:

    * : Multiplication
    Multiplies two values
    Example: x * y;

    / : Division
    Divides one value from another
    Example: x / y;

    % : Modulo
    Returns the division remainder
    Example: x % y;

    + : Addition
    Adds together two values
    Example: x + y;

    – : Subtraction
    Subtracts one value from another
    Example: x - y;

    Example: Click Here


    2. Assignment Operators: 

    The assignment operator is used to assigning a value to any variable. This operator assigns the value of the right-hand side of an operator to the left-hand side. Various assignment operator in Java:

    These are the short version formed by combining the two operators.

    For example Instead of writing, int a = a+3, we can write a+= 5.

    • Assignment operator: ‘=’ This operator assigns the value on the right to the variable on the left.
      a = 20; B = 30; Ch = 'cha';
    • Add AND assignment operator: ‘+=’ This operator first adds the current value of the variable on the left to the value on the right and then assigns the result to the variable on the left.
      c+=7; a+=b;
    • Subtract AND assignment operator: ‘-=’ This operator first subtracts the current value of the variable on the left from the value on the right and then assigns the result to the variable on the left.
      c-=7; a-=b;
    • Multiply AND assignment operator: ‘*=’ This operator first multiplies the current value of the variable on the left to the value on the right and then assigns the result to the variable on the left.
      c*=7; a*=b;
    • Divide AND assignment operator: ‘/=’ This operator first divides the current value of the variable on the left by the value on the right and then assigns the result to the variable on the left.
      c/=7; a/=b;
    • Modulus AND assignment operator: ‘%=’ It takes modulus using two operands and assigns the result to the left operand.
      C %= A is equivalent to C = C % A ;
    • Right shift AND assignment operator: ‘>>=’ This operator is used for Right shift Operation.
      C >>= 2 ;
    • Left shift AND assignment operator: ‘<<=’ This operator is used for Left shift Operation.
      C <<= 2 ;
    • Bitwise AND assignment operator: ‘&=’ This operator is used for Bitwise AND Operations.
      C &= 2;
    • Bitwise exclusive OR and assignment operator: ‘^=’ This operator is used for Bitwise exclusive OR Operations.
      C ^= 2;
    • Bitwise inclusive OR and assignment operator: ‘|=’ This operator is used for Bitwise inclusive OR.
      C |= 2;

    Example: Click Here


    3. Increment and Decrement Operators: 

    The ++ and the – – are Java’s increment and decrement operators. ++ is used to increase the value by 1 and — is used to decrease the value by 1. There are two kinds of Increment and Decrement Operators.

    They are:

    • Post-Increment or Post-Decrement:
      First, the value is used for operation and then incremented or decremented. Represented like a++ or a–.
    • Pre-Increment Pre-Decrement:
      Here First the value is incremented or decremented then used for the operation. Represented like ++a or –a.

    Example: Click Here


    4. Logical Operators:

    Logical Operators are used in conditional statements and loops for evaluating a condition with binary values. All of the binary logical operators combine two boolean values that are true and false to form a result value.

    Logical Operators with their description:

    Operator Description Example
    && (logical AND) If both the operands are non-zero, then the condition becomes true. (X && Y) is false
    || (logical OR) If any of the two operands are non-zero, then the condition becomes true. (X || Y) is true
    ! (logical NOT)Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(X && Y) is true

    Example: Click Here


    5. Relational (comparison) operators:

    Comparison operators are used to comparing two values and return boolean results. These operators are used to check for relations like equality, greater than, less than between two values. They are used with a loop statement and also with if-else statements.

    Following are the relational operators in Java:

    OperatorNameExample
    ==Equal to.A == B
    !=Not equal.A != B
    >Greater than.A > B
    <Less than.A < B
    >=Greater than or equal to.A >= B
    <=Less than or equal to.A <= B

    Example: Click Here


    6. Bitwise operators: 

    Bitwise operator works on bits and performs a bit-by-bit operation. There are six Bitwise Operators and can be applied to the integer types, long, int, short, char, and byte.

    • Bitwise AND: ‘&’
      Binary AND Operator copies a bit to the result if it exists in both operands.
    • Bitwise OR: ‘|’
      Binary OR Operator copies a bit if it exists in either operand.
    • Bitwise XOR: ‘^’
      Binary XOR Operator copies the bit if it is set in one operand but not both.
    • Binary Left Shift: ‘<<’
      The left operands value is moved left by the number of bits specified by the right operand.
    • Binary Right Shift: ‘>>’
      The left operand’s value is moved right by the number of bits specified by the right operand.
    • Bitwise complement: ‘~’
      Binary Ones Complement Operator is unary and has the effect of ‘flipping’ bits.
    • zero-fill right shift: ‘>>>’
      The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.

    Example: Click Here


    7. Ternary operators: 

    Ternary Operator is also known as the Conditional operator. It is used to evaluate Boolean expressions. We can say that it is a short version of the if-else statement. But here instead of operating on to operand, it operates on three operands, and therefore the name ternary.

    Syntax:

    variable num1 = (expression) ? value if true : value if false;

    Example: Click Here


    What are Precedence and Associativity?

    Precedence and Associativity are the rules that are used to determine the operators with the highest priority in evaluating an equation that contains different operations.

    For example:

     x = 10 + 5 * 2;   

    In this example, x is assigned as 20, not 30 that’s because operator * has higher precedence than +, and hence it first gets multiplied (5*2) and then the multiplied value is added to 10.

    In the following table, the precedence of an operator decreases from top to down:

    CategoryOperatorAssociativity
    Postfix>() [] . (dot operator)Left to right
    Unary>++ – – ! ~Right to left
    Additive>+ –Left to right
    Relational>> >= < <=Left to right
    Equality>== !=Left to right
    Bitwise AND>&Left to right
    Bitwise OR>|Left to right
    Bitwise XOR>^Left to right
    Logical AND>&&Left to right
    Logical OR>||Left to right
    Conditional?:Right to left
    Assignment>= += -= *= /= %= >>= <<= &= ^= |=Right to left

  • Java – Operator Precedence and Associativity

    What are Precedence and Associativity?

    Precedence and Associativity are the rules that are used to determine the operators with the highest priority in evaluating an equation that contains different operations.

    For example:

     x = 10 + 5 * 2;   

    In this example, x is assigned as 20, not 30 that’s because operator * has higher precedence than +, and hence it first gets multiplied (5*2) and then multiplied value is added to 10.


    In the following table, the precedence of an operator decreases from top to down:

    CategoryOperatorAssociativity
    Postfix>() [] . (dot operator)Left to right
    Unary>++ – – ! ~Right to left
    Additive>+ –Left to right
    Relational>> >= < <=Left to right
    Equality>== !=Left to right
    Bitwise AND>&Left to right
    Bitwise OR>|Left to right
    Bitwise XOR>^Left to right
    Logical AND>&&Left to right
    Logical OR>||Left to right
    Conditional?:Right to left
    Assignment>= += -= *= /= %= >>= <<= &= ^= |=Right to left

  • Java Variables

    What is Variable in Java?

    The variable is the basic unit of storage which holds the value while the program is executed. We can also say that it is a name given to the memory location. A variable is defined by data-types provided by Java.

    It may be string, int, float, char, and boolean.

    Declaring a Variable in Java:

    Certain rules are needed to be followed before declaring the variables:

    • The first character must be a letter.
    • A variable name can consist of letters A-Z, a-z, digits 0-9, and two special characters such as underscore(_) and dollar Sign($).
    • Blank spaces cannot be used in variable names.
    • Java keywords cannot be used as variable names.
    • Variable names are case-sensitive.

    Syntax to declare Variables:

    data_type variable_name = value;

    Here, data_type means one of the Java data-types mentioned above. variable_name is the name that must be assigned to it, you can give any name suitable for it. The equal sign(=) is an assignment Operator used to assign the value of R.H.S. to L.H.S.

    Example: Demonstration of assigning value to different data-types

     int num = 20;
     String name = "Daniel";
     float floatNum = 7.98f;
     char alphabet = 'D';
     boolean bool = true;

    Types of Variables in Java:

    • local variable
    • instance variable
    • static variable

    Following declaration help us to understand the position of each of these three variables:

     class Example
     {  
      int Num1 = 30;//instance variable  
    
      static int Num2 = 40;//static variable 
      
      void method_Name()
      {  
      int num3 = 60;//local variable  
      }  
     }

    1. Local Variable:

    A variable that is declared within the body of the method or constructor is called a local variable. This variable is used only within that block or method where it was created other classes cannot access it. And is destroyed after exiting the method or block. Initialization of Local Variables is necessary.

    Example of Local variable in Java:

      public class Employees
      { 
        public void EmployeeInfo() 
        { 
          // local variable age 
          int age = 0;
          String name = "Prashant";
            
          age = age + 30; 
          System.out.println("Employee age is : " + age); 
          System.out.println("Employee name is : " + name ); 
        } 
      
        public static void main(String args[]) 
        { 
          Employees emp = new Employees(); 
          emp.EmployeeInfo(); 
        } 
      }

    Output of local variable in Java:

     Employee age is : 30
     Employee name is : Prashant

    2. Instance Variable:

    These are the non-static variable that is declared within the class but outside the method or constructor. With the creation of Objects, Instance Variable is created and destruction of an object destroys the variables. And can be accessed only by creating objects. Initialization of Instance Variable is not necessary as it is 0 by default.

    Example of Instance variable in Java:

     public class Employees
     {
        // this instance variable  
        String name;
        int age;
    
        public Employees (String EmployeeName)
        {
          name = EmployeeName;
        }
    
        public void EmpAge(int EmployeeAge)
        {
          age = EmployeeAge;
        }
    
        public void Display()
        {
          System.out.println("Employee name: " + name ); 
          System.out.println("Employee  age :" + age); 
        }
    
        public static void main(String args[])
        {
          Employees r = new Employees("Prashant");
          r.EmpAge(20);
          r.Display();
        }
     }

    Output of Instance variable in Java:

    Employee name: Prashant
    Employee  age :20

    3. Static variable:

    These variables are also known as class Variables. These are declared just like Instance Variable that within the class but outside the constructor or method but the difference is that static variable is declared using static keyword. Unlike Instance variable, only one static variable is created its value remains the same for all objects no matter how many objects user creates. Here initialization is not mandatory, it is 0 by default.

    Example of Static variable in Java:

     public class Employees
     {
        //static variable
        static int id = 1101;
    
      public static void main(String[] args)
      {
        
        Employees emp = new Employees();
    
       // Call static variable using object reference variable
        int a = emp.id;
    
        
        System.out.println("Employee ID: ");
        System.out.println(Employees.id);
      }
     }

    Output of Static variable in Java:

    Employee ID: 
    1101

  • Comparison between JDK, JRE and JVM

    This post contains the difference between JDK, JRE, and JVM. Let’s understand the difference between them first.
    JVM: Java Virtual Machine
    JDK: Java Development Kit
    JRE: Java Runtime Environment

    Comparison between JDK, JRE, and JVM

    JDK

    It stands for Java Development Kit. It is the tool necessary to compile, document and package Java programs. It contains JRE + development tools and is an implementation of any one of the following Java Platforms released by Oracle:

    1. Standard Edition Java Platform
    2. Enterprise Edition Java Platform
    3. Micro Edition Java Platform

    JRE

    It stands for Java Runtime Environment. JRE refers to a runtime environment in which Java bytecode can be executed and used for developing java applications with set of libraries.

    It’s an implementation of the JVM and is physically exists.

    JVM

    JVM stands for Java Virtual Machine, which is an abstract machine that provides a runtime environment to run Java programs. JVM is the specification that must be implemented in the computer system.

    There are three notations in JVM:

    • Specification
    • Implementation
    • Runtime Instance.

  • Java – Basic Syntax

    The syntax of the Java programming language is the set of rules for writing the java programs and defining its interpretation. Java program is the collection of classes and objects that communicate with each other via. method. It is the program structure.

    There are certain features that are omitted such as operator overloading or unsigned integer types, also there are no global functions or variables, but there are data members which are regarded as global variables.

    Before starting programs, it is very important to remember the following points.

    1. Case Sensitivity:

    Java is case sensitive, which means identifier Hello, heLlO and hello, all have a different meaning in Java.

    2. Class Names:

    Class names should always begin with Upper Case. If more than one word is used to form the name of the class, then each inner word’s first letter should be in Upper Case.

    Example: class MyFirstJavaLesson, class StudentsDetails, etc.

    3. Method Names:

    All method names should begin with a Lower Case letter. If more than one word is used to form the name of the method, then each inner word’s first letter should be in Upper Case.

    Example: public void myFirstMethod(), public void myStudentDetails() etc.

    Note: public static void main(String args[]):
    All Java program processing begins from the main() method which is a mandatory part of every Java program.

    4. Program File Name:

    The name of the program file should always match the class name. While saving the file, it should be saved with the class name and append ‘.java’ to the end of the name. Note that if it doesn’t match with the class name then the program will not work.

    Example: consider that ‘MyFirstJavaCode’ is the class name. Then the file should be saved with the name ‘MyFirstJavaProgram.java’.

    JAVA Basic Example to print “Hello World”:

    This the very basic way to write a program. The program below print “Hello World”.

    public class JavaBasic //JavaProgram is the class name
     {
      public static void main(String args[]) //main() method
      {
        System.out.println("Hello World"); //Prints hello world
      }
     }

    This shows the format for writing java code in code editor. This is the basic one. To learn more on how to write java with function and multiple classes, navigate through our website and learn more.


  • Java Introduction

    Java is a popular general-purpose, high level, modern programming language, and computing platform. It is fast, reliable, secure, and dynamic, with the ability to fit the needs of virtually any type of application.

    It is Platform Independent, which means the user only needs to write a program once and it can be run on a number of different platforms such as Windows, Mac OS, and the various versions of UNIX

    It was created by James Gosling from Sun Micro-systems (Sun) in 1991. It was first publicly released in 1995 with the version of Java (Java 1.0). According to Oracle, Java runs on 3 billion devices worldwide

    Nowadays, Java is used almost in every field that is desktop to web applications, mobile applications, in gaming consoles, cell phones to the Internet, data connection, servers, and many more.

     Main Features of Java:

    • Object-Oriented
    • Platform Independent
    • Simple and secure
    • Portable
    • Robust
    • Dynamic
    • Multi-threaded
    • High Performance
    • Compiled and Interpreted
    • Distributed.

    JAVA Basic Example to print “Hello World”:

    public class JavaBasic //JavaProgram is the class name
        {
         public static void main(String args[]) //main() method
         {
            System.out.println("Hello World"); //Prints hello world
         }
        } 

    Let’s understand briefly on each of the features.

    1. Object-Oriented:

    Java is an object-oriented programming language. OOP divides the program into a number of objects and makes it simpler. This Object has some data and behavior which is used inflow of data from one function to another. Users can easily extend java as it is based on Object Model. Therefore understanding OOP is an important step to learn Java Programming.

    Basic concepts of OOPs are:

    • Object
    • Class
    • Inheritance
    • Polymorphism
    • Abstraction
    • Encapsulation

    2. Platform Independent:

    Unlike other programming languages such as C, C++, etc, which require a specific platform to be compiled whereas Java is compiled into byte-code and this byte-code is Platform Independent.

    This means Java is only required to write-once and can be run on any platform such as Windows, Linux, Mac OS, etc. This byte-code is interpreted by the Java Virtual Machine (JVM).

    3. Simple and secure:

    Java is very easy to learn, clean, and easy to understand. Java language is a simple programming language because of its C++ syntax.

    Java is also best known for the security that it provides and enables us to develop virus-free systems. it is secured because java programs run inside the virtual machine sandbox.

    4. Portable:

    As mentioned above, the byte-code is Platform Independent and can be carried to any other platform for execution of Java program that makes Java code portable.

    5. Robust:

    Robust means strong. Java is strong and reliable because of its ability for early checking for errors, mainly on a compilation error and run-time checking.

    6. Dynamic:

    Since Java is designed to adapt to a transformed environment, it makes java dynamic. it is considered to be more dynamic than C or C++. Java supports the dynamic loading of classes and compilation and garbage collection.

    7. Multi-threaded:

    This feature in Java allows Java to perform more than one task at once by defining multiple threads for maximum utilization of CPU. The advantage of the use of Multi-threaded is that it does not require to occupy space in memory for each thread instead it shares the common memory space.

    8. High Performance:

    Java-enabled High performance by introducing JIT- Just In Time compiler, that is the compiler only compiles the code or method that is called, making the compilation process faster and consume less-time.

    9. Compiled and Interpreted:

    Java has both Compiled and Interpreted feature where the compilation feature allows to create byte code after compilation. And after, the byte codes are converted into Machine Language with the help of the Interpreter. Hence both the features are required for the execution of Java Code.

    10. Distributed:

    Java is distributed because it allows users/developers to create distributed applications that are designed to run on computer networks. RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are used for creating distributed applications.

    In other words, this feature allows the user to access the files from any machine that is connected to each other on the internet.

    These are some of the features of java.


  • Dining Philosophers problem in C

    In this article, you will learn about the C program to solve Dining Philosophers problem.

    The Dining Philosophers Problem:

    Let there be 5 philosophers (for example) sitting around a round table for dinner. Each philosopher needs two forks to eat but there are only 5 forks (equal to the number of philosophers around the table).

    A philosopher may eat if he/she can pick up two adjacent forks. But the 5 philosophers cannot eat at the same time because they can have only 1 fork on one hand and empty on the other and not able to eat. After that, each of them waits for the adjacent philosopher to finish which leads to a deadlock situation and each of the philosophers starve.

    The problem is to create a behaviour (algorithm) for the philosophers such that each philosopher would not starve and able to alternate between eating and thinking.

    Program for Dining Philosophers Problem in C

    #include <stdio.h>
    #define n 5	//Number of philosophers around the table
    
    int completedPhilosophers = 0, i;
    
    struct fork
    {
      int taken;
    }
    
    ForkAvail[n];
    
    struct philosp
    {
      int left;
      int right;
    }
    
    Philostatus[n];
    
    void goForDinner(int philID)
    {
     	//same like threads concept here cases implemented
      if (Philostatus[philID].left == 10 && Philostatus[philID].right == 10)
        printf("Philosopher %d completed his dinner\n", philID + 1);
     	//if already completed dinner
      else if (Philostatus[philID].left == 1 && Philostatus[philID].right == 1)
      {
       	//if just taken two forks
        printf("Philosopher %d completed his dinner\n", philID + 1);
    
        Philostatus[philID].left = Philostatus[philID].right = 10;	//remembering that he completed dinner by assigning value 10
        int otherFork = philID - 1;
    
        if (otherFork == -1)
          otherFork = (n - 1);
    
        ForkAvail[philID].taken = ForkAvail[otherFork].taken = 0;	//releasing forks
        printf("Philosopher %d released fork %d and fork %d\n", philID + 1, philID + 1, otherFork + 1);
        completedPhilosophers++;
      }
      else if (Philostatus[philID].left == 1 && Philostatus[philID].right == 0)
      {
       	//left already taken, trying for right fork
        if (philID == (n - 1))
        {
          if (ForkAvail[philID].taken == 0)
          {
           	//KEY POINT OF THIS PROBLEM, THAT LAST PHILOSOPHER TRYING IN reverse DIRECTION
            ForkAvail[philID].taken = Philostatus[philID].right = 1;
            printf("Fork %d taken by philosopher %d\n", philID + 1, philID + 1);
          }
          else
          {
            printf("Philosopher %d is waiting for fork %d\n", philID + 1, philID + 1);
          }
        }
        else
        {
         	//except last philosopher case
          int dupphilID = philID;
          philID -= 1;
    
          if (philID == -1)
            philID = (n - 1);
    
          if (ForkAvail[philID].taken == 0)
          {
            ForkAvail[philID].taken = Philostatus[dupphilID].right = 1;
            printf("Fork %d taken by Philosopher %d\n", philID + 1, dupphilID + 1);
          }
          else
          {
            printf("Philosopher %d is waiting for Fork %d\n", dupphilID + 1, philID + 1);
          }
        }
      }
      else if (Philostatus[philID].left == 0)
      {
       	//nothing taken yet
        if (philID == (n - 1))
        {
          if (ForkAvail[philID - 1].taken == 0)
          {
           	//KEY POINT OF THIS PROBLEM, THAT LAST PHILOSOPHER TRYING IN reverse DIRECTION
            ForkAvail[philID - 1].taken = Philostatus[philID].left = 1;
            printf("Fork %d taken by philosopher %d\n", philID, philID + 1);
          }
          else
          {
            printf("Philosopher %d is waiting for fork %d\n", philID + 1, philID);
          }
        }
        else
        {
         	//except last philosopher case
          if (ForkAvail[philID].taken == 0)
          {
            ForkAvail[philID].taken = Philostatus[philID].left = 1;
            printf("Fork %d taken by Philosopher %d\n", philID + 1, philID + 1);
          }
          else
          {
            printf("Philosopher %d is waiting for Fork %d\n", philID + 1, philID + 1);
          }
        }
      }
      else {}
    }
    
    int main()
    {
      for (i = 0; i < n; i++)
        ForkAvail[i].taken = Philostatus[i].left = Philostatus[i].right = 0;
    
      while (completedPhilosophers < n)
      {
        /*
        Actually problem of deadlock occur only they try to take at same time
        This for loop will say that they are trying at same time. 
        And remaining status will print by go for dinner function
        */
        for (i = 0; i < n; i++)
          goForDinner(i);
        printf("\nTill now number of philosophers who completed dinner are: %d", completedPhilosophers);
      }
    
      return 0;
    }

    The output of the Dining philosopher problem in c programming:

  • Round Robin Scheduling in C

    This article contains the implementation of the Round Robin Scheduling in C Programming with the explanation, an example, it’s advantages and disadvantages.

    If we consider large management or organization with multi-users and with a time-sharing system, in such cases response time plays a vital role in the achievements of various objectives. So, Process Scheduling is a key component for such management.

    Let us understand the Round Robin Scheduling program in C

    What is Round Robin Scheduling?

    The Round robin algorithm is a pre-emptive process scheduling algorithm used by the machine for scheduling the CPU utilization. Here, each process is allotted to a fixed time called time slice or time quantum in a cyclic way. A process enables the job scheduler that saves the current progress of the job moves to the next job present in the queue. Each process must complete the job within the given time-quantum else an interrupt may occur. The context-switching saves the current state of the process.


    What is Round Robin Scheduling Algorithm?

    • Here, every job is arranged in a FIFO(First Come First Server) order.
    • When the first process arrives, it is sent for execution. But if it couldn’t complete the execution in a given amount of time quantum that is allotted to it, then an automated timer generates an interrupt.
    • After that, the process is stopped and then send back to the end of the queue. Although the state is saved and stored so that it can be resumed where it was interrupted.
    • The process is resumed and the schedulers select the next process from the queue sent it to the processor for execution.
    • Each process is executed in a similar way and checked for the time quantum.
    • The steps are repeated for every process until the processes are over.

    Compute Times involved in Round Robin Scheduling:

    • Completion Time: Time at which process completes its execution.
    • Turn Around Time: Time Difference between completion time and arrival time.
      Turn Around Time = Completion Time – Arrival Time
    • Waiting Time(W.T): Time Difference between turn around time and burst time.
      Waiting Time = Turn Around Time – Burst Time

    Advantages:

    • It is simple, easy to use and the overhead in decision-making is low.
    • Due to the fair share of CPU, Starvation issues or convoy effect do not occur.
    • Due to the queue system, equal priority is given to all the jobs which cannot be seen in other algorithms.
    • Each process can be rescheduled after a given fixed time slot or quantum period.

    Disadvantages:

    • Due to its dependency on quantum value, the efficiency of the system is decreased.
    • An increase in the quantum value might make the system unresponsive.
    • There is no special priority for the most important process, every process is scheduled.

    Example: Round Robin Scheduling in C Programming

    #include <stdio.h>
    
    int main()
    {
       int i, total = 0, x, limit, counter = 0, t_quantum;
       int wait_time = 0, turnaround_time = 0, arrival_time[10], burst_time[10], temp[10];
    
       float average_wait_time, average_turnaround_time;
    
       printf("\nEnter Total Number of Processes: ");
       scanf("%d", &limit);
       x = limit;
    
       for (i = 0; i < limit; i++)
       {
          printf("\nProvide the details for Process[%d]\n", i + 1);
          printf("Arrival Time:\t");
          scanf("%d", &arrival_time[i]);
          printf("Burst Time:\t");
          scanf("%d", &burst_time[i]);
          temp[i] = burst_time[i];
       }
    
       printf("\nEnter Time Quantum:\t");
       scanf("%d", &t_quantum);
    
       printf("\nProcess ID\t\tBurst Time\t Turnaround Time\t Waiting Time\n");
       for (total = 0, i = 0; x != 0;)
       {
          if (temp[i] <= t_quantum && temp[i] > 0)
          {
             total = total + temp[i];
             temp[i] = 0;
             counter = 1;
          }
          else if (temp[i] > 0)
          {
             temp[i] = temp[i] - t_quantum;
             total = total + t_quantum;
          }
    
          if (temp[i] == 0 && counter == 1)
          {
             x--;
             printf("\nProcess[%d]\t\t%d\t\t %d\t\t\t %d", i + 1, burst_time[i], total - arrival_time[i], total - arrival_time[i] - burst_time[i]);
    
             wait_time = wait_time + total - arrival_time[i] - burst_time[i];
    
             turnaround_time = turnaround_time + total - arrival_time[i];
             counter = 0;
          }
    
          if (i == limit - 1)
          {
             i = 0;
          }
          else if (arrival_time[i + 1] <= total)
          {
             i++;
          }
          else
          {
             i = 0;
          }
       }
    
       average_wait_time = wait_time *1.0 / limit;
       average_turnaround_time = turnaround_time *1.0 / limit;
    
       printf("\n\nAverage Waiting Time:\t%f", average_wait_time);
       printf("\nAvg Turnaround Time:\t%f\n", average_turnaround_time);
    
       return 0;
    }

    Output of above Round Robin Algorithm in C:


  • Bit Stuffing Program in C

    This post contains the implementation of Bit Stuffing in C programming. Learn about bit-stuffing and with source code for Bit Stuffing in c.

    What is Bit Stuffing?

    Bit Stuffing is the technique of insertion of one or more extra bits (0) into data. These are the noninformation bits as a way to provide signaling information to a receiver.

    On the receiver end, the stuffed 0 bit is removed and the original value is retrieved.

    This bit (0) is added after every 5 consecutive 1’s bit frame sequence as shown in a program below.


    C Program for Bit Stuffing

    In the following source code of C programming in bit stuffing, while loop is used.

    Firstly, the user needs to input the number of frame sizes than the bit string and the 0 is stuffed after every 5 consecutive 1’s execution.

    Implementation of Bit stuffing Using C.

    #include <stdio.h>
    #include <conio.h>
    #include <string.h>
    
    void main()
    {
      int x[50], y[50], n;
      int i, j, k, count = 1;
    
      printf("Enter size of a bit string:");
      scanf("%d", &n);
    
      printf("Enter the bit string(0's &1's):");
      for (i = 0; i < n; i++)
      {
        scanf("%d", &x[i]);
      }
    
      i = 0;
      j = 0;
    
      while (i < n)
      {
        if (x[i] == 1)
        {
          y[j] = x[i];
    
         	//count is less than 5 as 0 is inserted after every 
         	//5 consecutive 1's
          for (k = i + 1; x[k] == 1 && k < n && count < 5; k++)
          {
            j++;
            y[j] = x[k];
            count++;
    
            if (count == 5)
            {
              j++;
              y[j] = 0;
            }
    
            i = k;
          }
        }
        else
        {
          y[j] = x[i];
        }
    
        i++;
        j++;
      }
    
     	//Displaying final result
      printf("Result of Bit Stuffing:");
      for (i = 0; i < j; i++)
      {
        printf("%d", y[i]);
      }
    
      getch();
    }

    The output of Bit Stuffing Program in C:

    bit stuffing in c program