Program for FCFS CPU Scheduling | Set 1 (original) (raw)

Last Updated : 14 Jan, 2025

First come - First served (FCFS), is the simplest scheduling algorithm. FIFO simply queues processes according to the order they arrive in the ready queue. In this algorithm, the process that comes first will be executed first and next process starts only after the previous gets fully executed.

Terminologies Used in CPU Scheduling

_In this example, we have assumed the arrival time of all processes is 0, so turnaround and completion times are the same.

**Implementation

**Input : Processes along with their burst time (bt).
**Output : Waiting time, turnaround time for all processes.

  1. As first process that comes need not to wait so waiting time for process 1 will be 0 i.e. wt[0] = 0.
  2. Find **waiting time for all other processes i.e. for process i:
    wt[i] = bt[i-1] + wt[i-1] .
  3. Find **turnaround time = waiting_time + burst_time for all processes.
  4. Find **average waiting time = total_waiting_time / no_of_processes.
  5. Similarly, find **average turnaround time =
    total_turn_around_time / no_of_processes.

Code to Implement the Algorithm

C++ `

// C++ program for implementation of FCFS // scheduling #include using namespace std;

// Function to find the waiting time for all // processes void findWaitingTime(int processes[], int n, int bt[], int wt[]) { // waiting time for first process is 0 wt[0] = 0;

// calculating waiting time
for (int  i = 1; i < n ; i++ )
    wt[i] =  bt[i-1] + wt[i-1] ;

}

// Function to calculate turn around time void findTurnAroundTime( int processes[], int n, int bt[], int wt[], int tat[]) { // calculating turnaround time by adding // bt[i] + wt[i] for (int i = 0; i < n ; i++) tat[i] = bt[i] + wt[i]; }

//Function to calculate average time void findavgTime( int processes[], int n, int bt[]) { int wt[n], tat[n], total_wt = 0, total_tat = 0;

//Function to find waiting time of all processes
findWaitingTime(processes, n, bt, wt);

//Function to find turn around time for all processes
findTurnAroundTime(processes, n, bt, wt, tat);

//Display processes along with all details
cout << "Processes  "<< " Burst time  "
     << " Waiting time  " << " Turn around time\n";

// Calculate total waiting time and total turn 
// around time
for (int  i=0; i<n; i++)
{
    total_wt = total_wt + wt[i];
    total_tat = total_tat + tat[i];
    cout << "   " << i+1 << "\t\t" << bt[i] <<"\t    "
        << wt[i] <<"\t\t  " << tat[i] <<endl;
}

cout << "Average waiting time = " 
     << (float)total_wt / (float)n;
cout << "\nAverage turn around time = " 
     << (float)total_tat / (float)n;

}

// Driver code int main() { //process id's int processes[] = { 1, 2, 3}; int n = sizeof processes / sizeof processes[0];

//Burst time of all processes
int  burst_time[] = {10, 5, 8};

findavgTime(processes, n,  burst_time);
return 0;

}

C

// C program for implementation of FCFS
// scheduling #include<stdio.h> // Function to find the waiting time for all
// processes void findWaitingTime(int processes[], int n,
int bt[], int wt[]) { // waiting time for first process is 0 wt[0] = 0;

// calculating waiting time 
for (int  i = 1; i < n ; i++ ) 
    wt[i] =  bt[i-1] + wt[i-1] ; 

}

// Function to calculate turn around time void findTurnAroundTime( int processes[], int n,
int bt[], int wt[], int tat[]) { // calculating turnaround time by adding // bt[i] + wt[i] for (int i = 0; i < n ; i++) tat[i] = bt[i] + wt[i]; }

//Function to calculate average time void findavgTime( int processes[], int n, int bt[]) { int wt[n], tat[n], total_wt = 0, total_tat = 0;

//Function to find waiting time of all processes 
findWaitingTime(processes, n, bt, wt); 

//Function to find turn around time for all processes 
findTurnAroundTime(processes, n, bt, wt, tat); 

//Display processes along with all details 
printf("Processes   Burst time   Waiting time   Turn around time\n"); 

// Calculate total waiting time and total turn  
// around time 
for (int  i=0; i<n; i++) 
{ 
    total_wt = total_wt + wt[i]; 
    total_tat = total_tat + tat[i]; 
    printf("   %d ",(i+1));
    printf("       %d ", bt[i] );
    printf("       %d",wt[i] );
    printf("       %d\n",tat[i] ); 
} 
float s=(float)total_wt / (float)n;
float t=(float)total_tat / (float)n;
printf("Average waiting time = %f",s);
printf("\n");
printf("Average turn around time = %f ",t); 

}

// Driver code int main() { //process id's int processes[] = { 1, 2, 3}; int n = sizeof processes / sizeof processes[0];

//Burst time of all processes 
int  burst_time[] = {10, 5, 8}; 

findavgTime(processes, n,  burst_time); 
return 0; 

} // This code is contributed by Shivi_Aggarwal

Java

// Java program for implementation of FCFS // scheduling

import java.text.ParseException;

class GFG {

// Function to find the waiting time for all 
// processes 
static void findWaitingTime(int processes[], int n,
        int bt[], int wt[]) {
    // waiting time for first process is 0 
    wt[0] = 0;

    // calculating waiting time 
    for (int i = 1; i < n; i++) {
        wt[i] = bt[i - 1] + wt[i - 1];
    }
}

// Function to calculate turn around time 
static void findTurnAroundTime(int processes[], int n,
        int bt[], int wt[], int tat[]) {
    // calculating turnaround time by adding 
    // bt[i] + wt[i] 
    for (int i = 0; i < n; i++) {
        tat[i] = bt[i] + wt[i];
    }
}

//Function to calculate average time 
static void findavgTime(int processes[], int n, int bt[]) {
    int wt[] = new int[n], tat[] = new int[n];
    int total_wt = 0, total_tat = 0;

    //Function to find waiting time of all processes 
    findWaitingTime(processes, n, bt, wt);

    //Function to find turn around time for all processes 
    findTurnAroundTime(processes, n, bt, wt, tat);

    //Display processes along with all details 
    System.out.printf("Processes Burst time Waiting"
                   +" time Turn around time\n");

    // Calculate total waiting time and total turn 
    // around time 
    for (int i = 0; i < n; i++) {
        total_wt = total_wt + wt[i];
        total_tat = total_tat + tat[i];
        System.out.printf(" %d ", (i + 1));
        System.out.printf("     %d ", bt[i]);
        System.out.printf("     %d", wt[i]);
        System.out.printf("     %d\n", tat[i]);
    }
    float s = (float)total_wt /(float) n;
    int t = total_tat / n;
    System.out.printf("Average waiting time = %f", s);
    System.out.printf("\n");
    System.out.printf("Average turn around time = %d ", t);
}

// Driver code 
public static void main(String[] args) throws ParseException {
    //process id's 
    int processes[] = {1, 2, 3};
    int n = processes.length;

    //Burst time of all processes 
    int burst_time[] = {10, 5, 8};

    findavgTime(processes, n, burst_time);

}

} // This code is contributed by 29ajaykumar

Python

Python3 program for implementation

of FCFS scheduling

Function to find the waiting

time for all processes

def findWaitingTime(processes, n, bt, wt):

# waiting time for 
# first process is 0
wt[0] = 0

# calculating waiting time
for i in range(1, n ):
    wt[i] = bt[i - 1] + wt[i - 1] 

Function to calculate turn

around time

def findTurnAroundTime(processes, n, bt, wt, tat):

# calculating turnaround 
# time by adding bt[i] + wt[i]
for i in range(n):
    tat[i] = bt[i] + wt[i]

Function to calculate

average time

def findavgTime( processes, n, bt):

wt = [0] * n
tat = [0] * n 
total_wt = 0
total_tat = 0

# Function to find waiting 
# time of all processes
findWaitingTime(processes, n, bt, wt)

# Function to find turn around 
# time for all processes
findTurnAroundTime(processes, n, 
                   bt, wt, tat)

# Display processes along
# with all details
print( "Processes Burst time " + 
              " Waiting time " + 
            " Turn around time")

# Calculate total waiting time 
# and total turn around time
for i in range(n):

    total_wt = total_wt + wt[i]
    total_tat = total_tat + tat[i]
    print(" " + str(i + 1) + "\t\t" + 
                str(bt[i]) + "\t " + 
                str(wt[i]) + "\t\t " + 
                str(tat[i])) 

print( "Average waiting time = "+
               str(total_wt / n))
print("Average turn around time = "+
                 str(total_tat / n))

Driver code

if name =="main":

# process id's
processes = [ 1, 2, 3]
n = len(processes)

# Burst time of all processes
burst_time = [10, 5, 8]

findavgTime(processes, n, burst_time)

This code is contributed

by ChitraNayal

C#

// C# program for implementation of FCFS // scheduling using System;

class GFG {

// Function to find the waiting time for all 
// processes 
static void findWaitingTime(int []processes, int n,
                            int []bt, int[] wt) 
{
    // waiting time for first process is 0 
    wt[0] = 0;

    // calculating waiting time 
    for (int i = 1; i < n; i++) 
    {
        wt[i] = bt[i - 1] + wt[i - 1];
    }
}

// Function to calculate turn around time 
static void findTurnAroundTime(int []processes, int n,
        int []bt, int []wt, int []tat) {
    // calculating turnaround time by adding 
    // bt[i] + wt[i] 
    for (int i = 0; i < n; i++) 
    {
        tat[i] = bt[i] + wt[i];
    }
}

// Function to calculate average time 
static void findavgTime(int []processes, int n, int []bt)
{
    int []wt = new int[n];
    int []tat = new int[n];
    int total_wt = 0, total_tat = 0;

    //Function to find waiting time of all processes 
    findWaitingTime(processes, n, bt, wt);

    //Function to find turn around time for all processes 
    findTurnAroundTime(processes, n, bt, wt, tat);

    //Display processes along with all details 
    Console.Write("Processes Burst time Waiting"
                +" time Turn around time\n");

    // Calculate total waiting time and total turn 
    // around time 
    for (int i = 0; i < n; i++)
    {
        total_wt = total_wt + wt[i];
        total_tat = total_tat + tat[i];
        Console.Write(" {0} ", (i + 1));
        Console.Write("     {0} ", bt[i]);
        Console.Write("     {0}", wt[i]);
        Console.Write("     {0}\n", tat[i]);
    }
    float s = (float)total_wt /(float) n;
    int t = total_tat / n;
    Console.Write("Average waiting time = {0}", s);
    Console.Write("\n");
    Console.Write("Average turn around time = {0} ", t);
}

// Driver code 
public static void Main(String[] args)
{
    // process id's 
    int []processes = {1, 2, 3};
    int n = processes.Length;

    // Burst time of all processes 
    int []burst_time = {10, 5, 8};

    findavgTime(processes, n, burst_time);
}

}

// This code contributed by Rajput-Ji

JavaScript

`

**Output:

Processes Burst Time Waiting Time Turn-around Time
1 10 0 10
2 5 10 15
3 8 15 23

Average waiting time = 8.33333
Average turn around time = 16

**Implementation Using OOPS

C++ `

#include <bits/stdc++.h> using namespace std;

class Process { private: int at; int bt; int ct; int tat; int wt; int pid;

public: int& operator[](string var) { if (var == "at") return at; if (var == "bt") return bt; if (var == "ct") return ct; if (var == "tat") return tat; if (var == "wt") return wt; return pid; }

void update_after_ct()
{
    tat = ct - at;
    wt = tat - bt;
}

void display()
{
    printf("%d\t%d\t%d\t%d\t%d\t%d\n", pid, at, bt, ct,
           tat, wt);
}

};

float average(vector P, string var) { int total = 0; for (auto temp : P) { total += temp[var]; } return (float)total / P.size(); }

int main() { /* Input description. First line contains an integer n the next n lines contains 2 space separated integers containing values for arrival time and burst time for example: 2 0 3 1 2 */ int n; cin >> n; int counter = 0; vector P(n); for (Process& temp : P) { temp["id"] = counter++; cin >> temp["at"] >> temp["bt"]; } sort(P.begin(), P.end(), [](Process first, Process second) { return first["at"] < second["at"]; }); printf("pid\tat\tbt\tct\ttat\twt\n"); P[0]["ct"] = P[0]["at"] + P[0]["bt"]; P[0].update_after_ct(); P[0].display(); for (int i = 1; i < P.size(); i++) { if (P[i]["at"] < P[i - 1]["ct"]) { P[i]["ct"] = P[i - 1]["ct"] + P[i]["bt"]; } else { printf("curr['at'] : %d, prev['ct'] : %d\n", P[i]["at"], P[i - 1]["ct"]); P[i]["ct"] = P[i]["at"] + P[i]["bt"]; } P[i].update_after_ct(); P[i].display(); }

printf("Average waiting time : %f\n", average(P, "wt"));
return 0;

}

Java

import java.util.*;

public class Main {

// Process class to represent a process
static class Process {
    private int at; // arrival time
    private int bt; // burst time
    private int ct; // completion time
    private int tat; // turn around time
    private int wt; // waiting time
    private int pid; // process ID

    // Getter method to get a variable value of the process
    public int getVar(String var) {
        if (var.equals("at"))
            return at;
        if (var.equals("bt"))
            return bt;
        if (var.equals("ct"))
            return ct;
        if (var.equals("tat"))
            return tat;
        if (var.equals("wt"))
            return wt;
        return pid;
    }

    // Setter method to set a variable value of the process
    public void setVar(String var, int value) {
        if (var.equals("at"))
            at = value;
        else if (var.equals("bt"))
            bt = value;
        else if (var.equals("ct"))
            ct = value;
        else if (var.equals("tat"))
            tat = value;
        else if (var.equals("wt"))
            wt = value;
        else
            pid = value;
    }

    // Update the turn around time and waiting time after completion
    public void updateAfterCt() {
        tat = ct - at;
        wt = tat - bt;
    }

    // Display the process details
    public void display() {
        System.out.printf("%d\t%d\t%d\t%d\t%d\t%d\n", pid, at, bt, ct, tat, wt);
    }
}

// Calculate the average of a variable value for all processes
public static float average(ArrayList<Process> P, String var) {
    int total = 0;
    for (Process temp : P) {
        total += temp.getVar(var);
    }
    return (float) total / P.size();
}

public static void main(String[] args) {
    /*
    Input description.
    First line contains an integer n
    the next n lines contains 2 space separated integers
    containing values for arrival time and burst time for
    example:
    2
    0 3
    1 2
    */
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int counter = 0;
    ArrayList<Process> P = new ArrayList<Process>(n);
    // Create a process object for each input and add to the process list
    for (int i = 0; i < n; i++) {
        Process temp = new Process();
        temp.setVar("pid", counter++);
        temp.setVar("at", sc.nextInt());
        temp.setVar("bt", sc.nextInt());
        P.add(temp);
    }
    // Sort the process list by arrival time
    Collections.sort(P, new Comparator<Process>() {
        public int compare(Process first, Process second) {
            return first.getVar("at") - second.getVar("at");
        }
    });
    System.out.println("pid\tat\tbt\tct\ttat\twt");
    // Calculate completion time and display the details of the first process
    P.get(0).setVar("ct", P.get(0).getVar("at") + P.get(0).getVar("bt"));
    P.get(0).updateAfterCt();
    P.get(0).display();
    // Calculate completion time and display the details of the remaining processes
   for (int i = 1; i < P.size(); i++) {
       // Loop through the remaining processes
    if (P.get(i).getVar("at") < P.get(i - 1).getVar("ct")) {
        // If the process arrives before the previous process completes
        P.get(i).setVar("ct", P.get(i - 1).getVar("ct") + P.get(i).getVar("bt"));
        // Calculate completion time as the completion time of previous process plus its burst time
    } else {
        // If the process arrives after the previous process completes
        System.out.printf("curr['at'] : %d, prev['ct'] : %d\n\n", P.get(i).getVar("at"),
                P.get(i - 1).getVar("ct"));
        P.get(i).setVar("ct", P.get(i).getVar("at") + P.get(i).getVar("bt"));
        // Calculate completion time as the arrival time plus its burst time
    }
    P.get(i).updateAfterCt(); // Update the turnaround time and waiting time for the current process
    P.get(i).display(); // Display the details of the current process
}

System.out.printf("Average waiting time : %f\n", average(P, "wt"));
sc.close(); // Close the scanner

} }

Python

class processes: def init(self, id, at, bt, ct): self.id = id self.at = at self.bt = bt self.ct = ct self.tat = self.ct-self.at self.wt = self.tat-self.bt

def get(self):
    print(f"{self.id}\t{self.at}\t{self.bt}\t{self.ct}\t{self.tat}\t{self.wt}")

def turnaround(self):
    return self.tat

def waiting(self):
    return self.wt

num = int(input("Enter the Number of Processes:")) l = [] ct = 0

for i in range(num):

print(f'Process {i+1}')
at = int(input("Enter the Arrival Time:-"))
bt = int(input("Enter the Burst Time:-"))
if (len(l) == 0):
    ct = bt
    l.append(processes(i, at, bt, ct))
else:
    ct += bt
    l.append(processes(i, at, bt, ct))

print("\n")

avg_tat = 0 avg_wat = 0 print("PID\tAT\tBT\tCT\tTAT\tWT") for process in l: process.get()

for process in l: avg_tat += process.turnaround() avg_wat += process.waiting() print(f"Avg_turnaround:{avg_tat/num}\nAvg_Waitingtime:{avg_wat/num}")

pid at bt

0 0 5

1 2 3

2 6 2

3 7 3

C#

using System; using System.Collections.Generic;

class Process { private int at; private int bt; private int ct; private int tat; private int wt; private int pid;

public int this[string var]
{
    get
    {
        if (var == "at")
            return at;
        if (var == "bt")
            return bt;
        if (var == "ct")
            return ct;
        if (var == "tat")
            return tat;
        if (var == "wt")
            return wt;
        return pid;
    }
    set
    {
        if (var == "at")
            at = value;
        else if (var == "bt")
            bt = value;
        else if (var == "ct")
            ct = value;
        else if (var == "tat")
            tat = value;
        else if (var == "wt")
            wt = value;
        else
            pid = value;
    }
}

public void UpdateAfterCt()
{
    tat = ct - at;
    wt = tat - bt;
}

public void Display()
{
    Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}",
        pid, at, bt, ct, tat, wt);
}

}

class Program { static float Average(List P, string var) { int total = 0; foreach (var temp in P) { total += temp[var]; } return (float)total / P.Count; }

static void Main()
{
    /*
    Input description.
    First line contains an integer n
    the next n lines contains 2 space separated integers
    containing values for arrival time and burst time for
    example:
    2
    0 3
    1 2
    */
    int n = int.Parse(Console.ReadLine());
    int counter = 0;
    var P = new List<Process>(n);
    for (int i = 0; i < n; i++)
    {
        var temp = new Process();
        temp["id"] = counter++;
        var line = Console.ReadLine().Split();
        temp["at"] = int.Parse(line[0]);
        temp["bt"] = int.Parse(line[1]);
        P.Add(temp);
    }
    P.Sort((first, second) => first["at"].CompareTo(second["at"]));
    Console.WriteLine("pid\tat\tbt\tct\ttat\twt");
    P[0]["ct"] = P[0]["at"] + P[0]["bt"];
    P[0].UpdateAfterCt();
    P[0].Display();
    for (int i = 1; i < P.Count; i++)
    {
        if (P[i]["at"] < P[i - 1]["ct"])
        {
            P[i]["ct"] = P[i - 1]["ct"] + P[i]["bt"];
        }
        else
        {
            Console.WriteLine("curr['at'] : {0}, prev['ct'] : {1}",
                P[i]["at"], P[i - 1]["ct"]);
            P[i]["ct"] = P[i]["at"] + P[i]["bt"];
        }
        P[i].UpdateAfterCt();
        P[i].Display();
    }
    Console.WriteLine("Average waiting time : {0}", Average(P, "wt"));
}

}

` JavaScript ``

class Process { constructor() { this.at = 0; this.bt = 0; this.ct = 0; this.tat = 0; this.wt = 0; this.pid = 0; }

update_after_ct() { this.tat = this.ct - this.at; this.wt = this.tat - this.bt; }

display() { console.log(${this.pid}\t${this.at}\t${this.bt}\t${this.ct}\t${this.tat}\t${this.wt}); } }

function average(P, varName) { let total = 0; for (let i = 0; i < P.length; i++) { total += P[i][varName]; } return total / P.length; }

function main() { /* Input description. First line contains an integer n the next n lines contains 2 space separated integers containing values for arrival time and burst time for example: 2 0 3 1 2 */ const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, });

rl.question("", (n) => { const P = new Array(parseInt(n)).fill(null).map(() => new Process()); let counter = 0; rl.on("line", (line) => { const [at, bt] = line.trim().split(" "); P[counter]["pid"] = counter++; P[counter - 1]["at"] = parseInt(at); P[counter - 1]["bt"] = parseInt(bt);

  if (counter == P.length) {
    rl.close();
  }
});

rl.on("close", () => {
  P.sort((first, second) => first["at"] - second["at"]);

  console.log("pid\tat\tbt\tct\ttat\twt");
  P[0]["ct"] = P[0]["at"] + P[0]["bt"];
  P[0].update_after_ct();
  P[0].display();

  for (let i = 1; i < P.length; i++) {
    if (P[i]["at"] < P[i - 1]["ct"]) {
      P[i]["ct"] = P[i - 1]["ct"] + P[i]["bt"];
    } else {
      console.log(
        `curr['at'] : <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>P</mi><mo stretchy="false">[</mo><mi>i</mi><mo stretchy="false">]</mo><mo stretchy="false">[</mo><mi mathvariant="normal">&quot;</mi><mi>a</mi><mi>t</mi><mi mathvariant="normal">&quot;</mi><mo stretchy="false">]</mo></mrow><mo separator="true">,</mo><mi>p</mi><mi>r</mi><mi>e</mi><mi>v</mi><msup><mo stretchy="false">[</mo><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><mi>c</mi><msup><mi>t</mi><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><mo stretchy="false">]</mo><mo>:</mo></mrow><annotation encoding="application/x-tex">{P[i][&quot;at&quot;]}, prev[&#x27;ct&#x27;] : </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1.0019em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.13889em;">P</span><span class="mopen">[</span><span class="mord mathnormal">i</span><span class="mclose">]</span><span class="mopen">[</span><span class="mord">&quot;</span><span class="mord mathnormal">a</span><span class="mord mathnormal">t</span><span class="mord">&quot;</span><span class="mclose">]</span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">p</span><span class="mord mathnormal">re</span><span class="mord mathnormal" style="margin-right:0.03588em;">v</span><span class="mopen"><span class="mopen">[</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span></span></span></span></span><span class="mord mathnormal">c</span><span class="mord"><span class="mord mathnormal">t</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.7519em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span></span></span></span></span><span class="mclose">]</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>{P[i - 1]["ct"]}`
      );
      P[i]["ct"] = P[i]["at"] + P[i]["bt"];
    }
    P[i].update_after_ct();
    P[i].display();
  }

  console.log(`Average waiting time : ${average(P, "wt")}`);
});

}); }

main();

``

PID AT BT CT TAT WT
0 0 10 10 10 0
1 10 5 15 5 0
2 15 8 23 8 0

Avg_turnaround:7.666666666666667
Avg_Waitingtime:0.0