You are on page 1of 37

Khushi Sahu 0801CA231074

LAB ASSIGNMENT 1
1. What is operating system & explain features of operating system?

Operating System is a fully integrated set of specialized programs that handle all the operations of the
computer. It controls and monitors the execution of all other programs that reside in the computer,
which also includes application programs and other system software of the computer. Examples of
Operating Systems are Windows, Linux, Mac OS, etc..
Definition:
 An Operating System (OS) is an interface between a computer user and computer hardware.
An operating system is a software which performs all the basic tasks like file management,
memory management, process management, handling input and output, and controlling
peripheral devices such as disk drives and printers.
 An Operating System (OS) is a collection of software that manages computer hardware
resources and provides common services for computer programs. The operating system is the
most important type of system software in a computer system.

What is an Operating System Used for?

 The operating system helps in improving the computer software as well as hardware. Without
OS, it became very difficult for any application to be user-friendly.
 The Operating System provides a user with an interface that makes any application attractive
and user-friendly.
 The operating System comes with a large number of device drivers that make OS services
reachable to the hardware environment and Each and every application present in the system
requires the Operating System.
 The operating system works as a communication channel between system hardware and
system software.
 The operating system helps an application with the hardware part without knowing about the
actual hardware configuration.
 It is one of the most important parts of the system and hence it is present in every device,
whether large or small device.
Functions Of Operating System
1. Memory Management –
The Primary Memory or Main Memory is controlled by the operating system. Each byte or word in
main memory has an address, and the array of bytes or words is quite big. The CPU may immediately
access main memory, which is a quick form of storage. A programme must first be loaded in the main
memory before it can be executed. The following tasks are carried out by an operating system to
manage memory: It keeps track of the primary memory, or the number of bytes of memory that each
user programme is using. the addresses of the memory that has already been assigned and the
addresses of the memory that is still available. In multiprogramming, the OS determines the order and

Page no.1
Khushi Sahu 0801CA231074

duration of memory access for each process. After a process requests memory, it allocates that
memory to that process, and when that process has finished or is engaged in I/O activity, it deallocates
that memory.

2. Security –
An Operating System aids you in achieving your goal of keeping your data secure in today's society.
An operating system's capability increases its stability. An operating system makes use of firewalls to
guard against and stop outside attacks. The system can only be used by people who have been given
permission to do so.
3. Job accounting –
Operating system keeps track of the amount of time and resources each job and user uses; this data
can be used to monitor how much of each resource is being used by a specific user or group of users.
4. Process Management -
The OS controls the order in which processes access the processor and how much processing time
each process receives in a multi-programming environment. Process scheduling is the name of this OS
feature. The following tasks are handled by an operating system in terms of processor management.
1)monitors the state of the processes.
2)The programme that carries out this function is referred to as a traffic controller.
3)gives a process access to a CPU that is a processor.
4)When a process is no longer necessary, the processor is de-allocated.
5. Device Management –
Device communication is controlled by an OS using the appropriate drivers. The operating system
handles the following tasks for device management.
1) Keeping track of all the system's linked gadgets.
2) The input/output controller is a software that is designated by the operating system as being in
charge of each device.
3) It determines which process has access to each device and how long it has that access.
4) When devices are no longer needed, it de-allocates them in an effective and efficient manner.
6. File Management –
Files are where data is saved. We can create, edit, update, and delete files with the aid of an operating
system. Additionally, it facilitates file transfers across devices. The physical entities that are stored on
the hardware are seen as files.
Directories are used to structure a file system and make it easier to navigate and use. These directories
might include additional directories and files. The following file management tasks are performed by
an operating system. It keeps track of information storage locations, user access preferences, file
status, and more. The file system refers to these resources in general.
7.Coordination between other software and users –
Between the user and the system hardware, the operating system acts as a bridge.
As needed by the user, it organises and allocates tasks to various components of the software, such as
interpreters, compilers, etc.
9. Networking –
Networking highly depends on operating systems. Distributed systems are a typical example, where a
server OS can guarantee consistency among the distributed PCs.
The operating system in such a system enables the connection of several independent and
geographically dispersed computers via a single communication channel.
10. Understanding Commands –

Page no.2
Khushi Sahu 0801CA231074

As a user, you enter commands in such a language that you understand. Because the computer
primarily understands 0s and 1s (binary language), the operating system handles command
interpretation and then directs the resources to process them.

Advantage of using Operating System:


• Allows you to hide details of hardware by creating an abstraction
• Easy to use with a GUI
• Offers an environment in which a user may execute programs/applications .
• The operating system must make sure that the computer system convenient to use.
• Operating System acts as an intermediary among applications and the hardware components
• It provides the computer system resources with easy to use format .
• Acts as an intermediator between all hardware's and software's of the system
Disadvantages of using Operating System :
• If any issue occurs in OS, you may lose all the contents which have been stored in your system.
• Operating system's software is quite expensive for small size organization which adds burden on
them.
• Example Windows It is never entirely secure as a threat can occur at any time.

2.What is Linux? Explain introduction of Linux & architecture of Linux?


The Linux Operating System is a type of operating system that is similar to Unix, and it is built
upon the Linux Kernel. The Linux Kernel is like the brain of the operating system because it
manages how the computer interacts with its hardware and resources. It makes sure everything
works smoothly and efficiently. But the Linux Kernel alone is not enough to make a complete
operating system. To create a full and functional system, the Linux Kernel is combined with a
collection of software packages and utilities, which are together called Linux distributions. These
distributions make the Linux Operating System ready for users to run their applications and perform
tasks on their computers securely and effectively. Linux distributions come in different flavors,
each tailored to suit the specific needs and preferences of users.
Linux is a powerful and flexible family of operating systems that are free to use and share. It was
created by a person named Linus Torvalds in 1991. What’s cool is that anyone can see how the
system works because its source code is open for everyone to explore and modify. This openness
encourages people from all over the world to work together and make Linux better and better. Since
its beginning, Linux has grown into a stable and safe system used in many different things, like
computers, smartphones, and big supercomputers. It’s known for being efficient, meaning it can do
a lot of tasks quickly, and it’s also cost-effective, which means it doesn’t cost a lot to use. Lots of
people love Linux, and they’re part of a big community where they share ideas and help each other
out. As technology keeps moving forward, Linux will keep evolving and staying important in the
world of computers.
Architecture of Linux:
Linux architecture has the following components:

1.Kernel: Kernel is the core of the Linux based operating system. It virtualizes the common
hardware resources of the computer to provide each process with its virtual resources. This makes
the process seem as if it is the sole process running on the machine. The kernel is also responsible
for preventing and mitigating conflicts between different processes. Different types of the kernel
are:

Page no.3
Khushi Sahu 0801CA231074

 Monolithic Kernel
 Hybrid kernels
 Exo kernels
 Micro kernels

2.System Library: Linux uses system libraries, also known as shared libraries, to implement
various functionalities of the operating system. These libraries contain pre-written code that
applications can use to perform specific tasks. By using these libraries, developers can save time
and effort, as they don’t need to write the same code repeatedly. System libraries act as an interface
between applications and the kernel, providing a standardized and efficient way for applications to
interact with the underlying system.

3.Shell: The shell is the user interface of the Linux Operating System. It allows users to interact
with the system by entering commands, which the shell interprets and executes. The shell serves as
a bridge between the user and the kernel, forwarding the user’s requests to the kernel for
processing. It provides a convenient way for users to perform various tasks, such as running
programs, managing files, and configuring the system.

4.Hardware Layer: The hardware layer encompasses all the physical components of the computer,
such as RAM (Random Access Memory), HDD (Hard Disk Drive), CPU (Central Processing Unit),
and input/output devices. This layer is responsible for interacting with the Linux Operating System
and providing the necessary resources for the system and applications to function properly. The
Linux kernel and system libraries enable communication and control over these hardware
components, ensuring that they work harmoniously together.

5.System Utility: System utilities are essential tools and programs provided by the Linux Operating
System to manage and configure various aspects of the system. These utilities perform tasks such as
installing software, configuring network settings, monitoring system performance, managing users
and permissions, and much more. System utilities simplify system administration tasks, making it
easier for users to maintain their Linux systems efficiently.

3.Perform a case study by installing and exploring various types of


operating systems on a physical or logical(virtual)machine. (Linux
installation).
Here's a step-by-step guide for installing Ubuntu Linux on a virtual machine using VirtualBox, a
popular virtualization software:

1.Download VirtualBox:
 Go to the VirtualBox website: https://www.virtualbox.org/
 Download and install VirtualBox for your operating system (Windows, macOS, Linux).

2.Download Ubuntu ISO:


 Go to the Ubuntu website: https://ubuntu.com/download
 Download the desired version of Ubuntu Desktop. Ubuntu LTS (Long Term Support) versions are
recommended for stability.

3.Create a New Virtual Machine:


 Open VirtualBox and click on the "New" button.
 Enter a name for your virtual machine and select "Linux" as the type, and "Ubuntu (64-bit)" as the
version.
 Allocate memory (RAM) for the virtual machine. At least 2GB is recommended.
 Create a new virtual hard disk and choose "VDI (VirtualBox Disk Image)" as the file type.

Page no.4
Khushi Sahu 0801CA231074

4.Configure Virtual Machine Settings:


 Select the newly created virtual machine and click on "Settings".
 Under the "System" tab, go to the "Processor" tab and allocate the number of CPU cores.
 Under the "Storage" tab, select the Ubuntu ISO file you downloaded as the optical disk in the
"Controller: IDE" section.

5.Start the Virtual Machine:


 Click on the "Start" button to launch the virtual machine.
 The Ubuntu installer should boot from the ISO file.

6.Install Ubuntu:
 Select "Install Ubuntu" from the boot menu.
 Follow the on-screen instructions to choose language, keyboard layout, and other settings.
 When prompted, choose installation type. You can select "Erase disk and install Ubuntu" for a simple
setup, or choose manual partitioning for advanced users.
 Create a user account and set up password.
 Wait for the installation to complete.

7.Restart and Login:


 Once the installation is finished, restart the virtual machine.
 Login with the username and password you created during the installation process.

8.Install VirtualBox Guest Additions (Optional but recommended):


 After logging into Ubuntu, go to the "Devices" menu in the VirtualBox window and select "Insert
Guest Additions CD image".
 Follow the on-screen instructions to install Guest Additions. This enhances the virtual machine's
performance and provides additional features.

9.Explore Ubuntu:
 Congratulations! You've successfully installed Ubuntu Linux on your virtual machine. You can now
explore the Ubuntu desktop environment, install software, and perform various tasks.
Remember, this guide is specific to VirtualBox and Ubuntu, but the general steps are similar for other
virtualization software and Linux distributions. Make sure to refer to the documentation specific to the
software and distribution you choose for installation.

4.What is comparison of all operating system?


Comparing all operating systems comprehensively is a monumental task due to the vast number of
operating systems available, each with its own unique features, strengths, and weaknesses. However, I
can provide a high-level comparison focusing on some key aspects commonly considered when
evaluating operating systems:
1.User Interface (UI):
 Windows: Known for its graphical user interface (GUI) with windows, icons, menus, and a pointer
(WIMP). It offers a familiar experience to many users.
 macOS: Offers a sleek and intuitive GUI designed specifically for Apple hardware, with features
like the Dock and Mission Control.
 Linux: Provides various desktop environments (e.g., GNOME, KDE, XFCE) with customizable
UIs, catering to different user preferences.
 Unix: Primarily command-line interfaces (CLI), though some Unix-based systems offer GUI
options.

2. Hardware Compatibility:

Page no.5
Khushi Sahu 0801CA231074

 Windows: Widely compatible with a vast array of hardware configurations due to its extensive
driver support.
 macOS: Limited to Apple hardware, ensuring tight integration and optimized performance.
 Linux: Supports a broad range of hardware, including older and specialized hardware, thanks to
extensive community-driven driver development.
 Unix: Hardware compatibility varies depending on the Unix-based system and its target hardware.

3. Software Availability:
 Windows: Offers a vast selection of commercial and free software, with extensive support for
popular applications and games.
 macOS: Provides access to a curated selection of software through the Mac App Store and third-
party developers, with a focus on quality and security.
 Linux: Offers a wide range of free and open-source software through package managers and
repositories, though support for commercial software varies.
 Unix: Software availability depends on the specific Unix variant and its ecosystem, with many
Unix-based systems focusing on server and enterprise applications.

4.Security:
 Windows: Historically criticized for security vulnerabilities, though recent versions have
improved security features such as Windows Defender and User Account Control (UAC).
 macOS: Generally considered more secure due to its Unix-based architecture, sandboxing of
applications, and stringent app store review process.
 Linux: Known for its robust security features, including user permissions, access control lists
(ACLs), and security-focused distributions like SELinux and AppArmor.
 Unix: Offers strong security foundations, particularly in multi-user environments, with features
like file permissions and access controls.

5.Customization and Flexibility:


 Windows: Provides customization options through themes, desktop backgrounds, and third-party
software, though less flexible than Linux.
 macOS: Offers limited customization compared to Linux but provides options for personalization
through system preferences and third-party tools.
 Linux: Highly customizable, allowing users to tailor the system to their preferences by selecting
different desktop environments, themes, and software packages.
 Unix: Customization capabilities vary depending on the specific Unix variant and its configuration
options.

6.Cost:
 Windows: Typically requires a license fee for commercial versions, though some versions may be
available for free for certain users (e.g., Windows 10 for education).
 macOS: Included with the purchase of Apple hardware, with periodic upgrades available at no
additional cost.
 Linux: Generally available for free, with many distributions offering free updates and support.
However, commercial support options are also available for some distributions.
 Unix: Cost varies depending on the specific Unix variant and the support services required.

This comparison provides a broad overview, but the suitability of an operating system depends on
individual needs, preferences, and use cases. Additionally, each operating system continues to evolve,
with new features and improvements shaping the landscape over time.

Page no.6
Khushi Sahu 0801CA231074

5.What are functions of operating system explain in details?


In an operating system software performs each of the function:
1. Process management:- Process management helps OS to create and delete processes. It also
provides mechanisms for synchronization and communication among processes.
2. Memory management:- Memory management module performs the task of allocation and de-
allocation of memory space to programs in need of this resources.
3. File management:- It manages all the file-related activities such as organization storage,
retrieval, naming, sharing, and protection of files.
4. Device Management: Device management keeps tracks of all devices. This module also
responsible for this task is known as the I/O controller. It also performs the task of allocation and de-
allocation of the devices.
5. I/O System Management: One of the main objects of any OS is to hide the peculiarities of that
hardware devices from the user.
6. Secondary-Storage Management: Systems have several levels of storage which includes
primary storage, secondary storage, and cache storage. Instructions and data must be stored in
primary storage or cache so that a running program can reference it.
7. Security:- Security module protects the data and information of a computer system against
malware threat and authorized access.
8. Command interpretation: This module is interpreting commands given by the and acting system
resources to process that commands.
9. Networking: A distributed system is a group of processors which do not share memory, hardware
devices, or a clock. The processors communicate with one another through the network.
10. Job accounting: Keeping track of time & resource used by various job and users.
11. Communication management: Coordination and assignment of compilers, interpreters, and
another software resource of the various users of the computer systems.

6.What are the internal commands. Explain it? Give 10 commands with
syntax and examples (with screenshots)?
Internal commands, also known as built-in commands, are commands that are directly built into the
shell (command-line interpreter) itself rather than being separate executable files located in directories
listed in the system's PATH variable. These commands are usually simple and perform basic
operations, such as file manipulation, text processing, and system configuration.
Here are 10 internal commands commonly available in Unix/Linux shells like Bash, along with their
syntax and examples:
1. cd (Change Directory):
Syntax: cd [directory]
Example: cd Documents
Description: Changes the current working directory to the specified directory.

2. pwd (Print Working Directory):


Syntax: pwd
Example: pwd
Description: Prints the current working directory.

3. echo (Echo):
Syntax: echo [arguments]
Example: echo Hello, World!

Page no.7
Khushi Sahu 0801CA231074

Description: Displays a line of text or the value of a variable.

4. history (Command History):


Syntax: history
Example: history
Description: Displays a list of previously executed commands.

5. alias (Alias):
Syntax: alias [name]='[command]'
Example: alias ll='ls -l'
Description: Creates an alias for a command or command sequence.

6. exit (Exit):
Syntax: exit
Example: exit
Description: Exits the current shell or terminal session.

7. export (Export):
Syntax: export [variable]=[value]
Example: export PATH=$PATH:/new/directory
Description: Sets the value of an environment variable.

8. unset (Unset):
Syntax: unset [variable]
Example: unset MY_VAR
Description: Removes the value of an environment variable.

9. type (Type):
Syntax: type [command]
Example: type ls
Description: Displays information about the type of command.

These are just a few examples of internal commands available in Unix/Linux shells. Each of these
commands is directly built into the shell and can be executed without referencing an external
executable file.

10. help:
Description:Display help information for shell builtins.
Syntax: help [builtin_command]
Example: help cd

Page no.8
Khushi Sahu 0801CA231074

7.What are external commands. Define it? Explain any 10 commands with
syntax and examples.
External commands refer to the commands in a command-line interface (CLI) or shell that are not
built into the shell itself but are instead separate executable programs stored in the file system. These
commands perform various tasks such as managing files, manipulating text, executing programs, etc.
Here are ten commonly used external commands in Unix/Linux systems along with their syntax and
examples:
1.ls - List directory contents
 Syntax: ls [options] [file/directory]
 Example: ls -l /home/user/Documents

2. cp - Copy files and directories


 Syntax: cp [options] source destination
 Example: cp file1.txt /path/to/destination

3.mv - Move or rename files and directories


 Syntax: mv [options] source destination
 Example: mv file1.txt newname.txt

4.rm - Remove files or directories


 Syntax: rm [options] file/directory
 Example: rm file.txt

5.mkdir - Create directories


 Syntax: mkdir [options] directory_name
 Example: mkdir new_directory

6.rmdir - Remove directories


 Syntax: rmdir [options] directory_name
 Example: rmdir old_directory

7.cat - Concatenate and display file content


 Syntax: cat [options] file(s)
 Example: cat file1.txt

Page no.9
Khushi Sahu 0801CA231074

8.grep - Search for patterns in files


 Syntax: grep [options] pattern [file(s)]
 Example: grep "keyword" file.txt

9.chmod - Change file permissions


 Syntax: chmod [options] permissions file(s)
 Example: chmod 755 script.sh

10.whoami – gives current owner name


 Syntax: whoami

These are just a few examples of external commands in Unix/Linux systems. There are many more
commands available, each serving a specific purpose in managing and interacting with the system and
its resources.

8.What are the file manipulation commands explain it? Give 5 commands
with syntax and example.
File manipulation commands are used to perform various operations on files and directories within a
Unix/Linux environment. These commands allow users to create, modify, copy, move, and delete files
and directories. Here are five common file manipulation commands along with their syntax and
examples:
1. pwd (Print Working Directory):
Syntax: pwd
Example: pwd
Description: Prints the current working directory.

1. cd (Change Directory):
Syntax: cd [directory]
Example: cd Documents
Description: Changes the current working directory to the specified directory.

3.mkdir:(Making directory/folder)
Description: Creates directories.
Syntax: mkdir [options] directory_name(s)
Example:
Create a new directory: mkdir new_directory
Create nested directories: mkdir -p parent_directory/child_directory

4.rmdir(removing a directory)
Description: Removes empty directories.
Syntax: rmdir [options] directory_name(s)
Example:
Remove an empty directory: rmdir empty_directory

5.touch(creating a file)
Description: Creates empty files or updates access and modification timestamps of existing files.
Syntax: touch [options] filename(s)
Example:

Page no.10
Khushi Sahu 0801CA231074

Create a new empty file: touch newfile.txt


Update access and modification times: touch existingfile.txt

6.cat(viewing a file)
Description: Concatenates and displays the contents of files.
Syntax: cat [options] file(s)
Example:
Display contents of a file: cat file.txt
Concatenate multiple files and display their contents: cat file1.txt file2.txt

7.rm(removing a file)
Description: Removes (deletes) files or directories.
Syntax: rm [options] file(s)/directory(s)
Example:
Remove a file: rm file.txt
Remove multiple files: rm file1.txt file2.txt
Remove a directory and its contents recursively: rm -r directory

8.cp(copying a file or directory)


Description: Copies files or directories from one location to another.
Syntax: cp [options] source(s) destination
Example:
Copy a file to another directory: cp file1.txt /path/to/destination
Copy multiple files to a directory: cp file1.txt file2.txt /path/to/destination

9.mv:(moving a file or directory)


Description: Moves or renames files or directories.
Syntax: mv [options] source destination
Example:
Move a file to another directory: mv file1.txt /path/to/destination
Rename a file: mv oldname.txt newname.txt

10.ls:
Description: Lists directory contents.
Syntax: ls [options] [file/directory]
Example:
List files in the current directory: ls
List files with detailed information: ls -l
List all files, including hidden files: ls -a

11.chmod:(change file mode)


Description: Changes file permissions.
Syntax: chmod [options] permissions file(s)
Example:
Change permissions of a file to read, write, and execute for the owner: chmod 700 file.txt
Change permissions recursively for all files in a directory: chmod -R 755 directory

These commands provide essential functionality for managing files and directories in Unix/Linux
environments.

Page no.11
Khushi Sahu 0801CA231074

LAB ASSIGNMENT 2
Program 1: Linux shell script program to create and print the values of variable.
country="India"
year=2021
echo "Country name: $country"
echo "Year: $year"

Program 2: Linux shell script program using calculator operations like +, -, *, /, %, ^, +


+, -- operator. Perform all operations and read the values from the user terminals.
echo “enter first number:”
read a
echo “enter second number:”
read b
echo “choose operation”
echo “1.addition”
echo “2.substraction”
echo “3.multiplication”
echo “4.division”
echo “5.modulus”
echo “6. exponential”
echo “7. increment”
echo “8. decrement”
read choice
case $choice in
1) echo “sum is:” $((a+b));;
2) echo “subtract is:” $((a-b));;
3) echo “multiplication is:” $((a*b));;
4) echo “division is:” $((a/b));;
5) echo “modolus is:” $((a%b));;
6) echo “exponential is:” $((a**b));;
7) echo “increment of a:” $((++a));;
8) echo “decrement of b:” $((--b));;
*) echo “invalid choice”
esac

Page no.12
Khushi Sahu 0801CA231074

Program 3: Linux shell script program to swap two numbers using third variable and
without using third variable.
Using third variable:
num1=10
num2=20
echo "Before Swapping : Num1: $num1 Num2: $num2"
num3=$num1
num1=$num2
num2=$num3
echo "After Swapping: Num1: $num1 Num2: $num2"

Without using third variable:


a=25
b=12
echo “number before swapping: $a $b”
a=$((a+b))
b=$((a-b))
a=$((a-b))
echo “number after swapping: $a $b”

Program 4: Linux shell script program to print program name using command line
argument and also Linus shell script program to execute ‘ls’ command.
echo "Script program Name: $0"

cd /
ls

Program 5: Bach shell script to find sum of digits.


echo "Enter a number"
read num
sum=0
while [ $num -gt 0 ]
do
mod=$((num % 10)) #It will split each digits
sum=$((sum + mod)) #Add each digit to sum
num=$((num / 10)) #divide num by 10.
done
echo $sum

Page no.13
Khushi Sahu 0801CA231074

Program 6: Linux shell script to display good morning, good afternoon, good evening
according to system time.
hour=$(date +%H)
if [ $hour -lt 12 ]
then
greet="Good Morning"
elif [ $hour -le 16 ]
then
greet="Good Afternoon"
elif [ $hour -lt 20 ]
then
greet="Good Evening"
else
greet="Good Night"
fi
echo "$greet"

Program 7: Linux shell script program to demonstrate the ‘$#’ variable and Linux shell
script program to print the current process id.
# Linux shell script program to print the current process id.
echo "Current process identifier: $$"

# Linux shell script program to demonstrate the "$#" variable.


echo "Total command line arguments are: $#"

Program 8: Linux shell script to demonstrate comparison operator.


a=5
b=10
if [ $a -eq $b ] then
echo "$a is equal to $b"
fi
if [ $a -ne $b ] then
echo "$a is not equal to $b"
fi
if [ $a -lt $b ] then
echo "$a is less than $b"
fi
if [ $a -gt $b ] then
echo "$a is greater than $b"
fi

Page no.14
Khushi Sahu 0801CA231074

Program 9: Linux shell script to find the number is even or odd.


echo "Enter a number"
read number
# Check if the number is divisible by 2
if [ $((number % 2)) -eq 0 ];
then
echo "$number is even."
else
echo "$number is odd."
fi

Program 10: Linux shell script to find number is prime or not.


echo "Enter a number:"
read number
# Check if the number is less than or equal to 1
if [ $number -le 1 ]; then
echo "$number is not a prime number."
exit
fi
# Check for factors from 2 to the square root of the number
is_prime=true
for (( i=2; i*i<=$number; i++ )); do
if [ $((number % i)) -eq 0 ]; then
is_prime=false
break
fi
done
# Print whether the number is prime or not
if $is_prime; then
echo "$number is a prime number."
else
echo "$number is not a prime number."
fi

Program 11: Linux shell script to find greatest of two number and three number from
user input.
echo "Enter the first number:"
read num1
echo "Enter the second number:"
read num2
echo "Enter the third number (optional, press Enter if not applicable):"
read num3
# Checking for greatest number among two
if [ "$num3" = "" ]; then
if [ "$num1" -gt "$num2" ]; then

Page no.15
Khushi Sahu 0801CA231074

echo "The greatest number is $num1"


else
echo "The greatest number is $num2"
fi
else
# Checking for greatest number among three
if [ "$num1" -gt "$num2" ] && [ "$num1" -gt "$num3" ]; then
echo "The greatest number is $num1"
elif [ "$num2" -gt "$num1" ] && [ "$num2" -gt "$num3" ]; then
echo "The greatest number is $num2"
else
echo "The greatest number is $num3"
fi
fi

Program 12: Linux shell script factorial of number from user input.
echo "Enter a number:"
read number
factorial=1
# Check if the number is less than 0
if [ $number -lt 0 ]; then
echo "Factorial is not defined for negative numbers."
exit
fi
# Calculate factorial
for (( i=1; i<=$number; i++ )); do
factorial=$((factorial * i))
done
echo "The factorial of $number is: $factorial"

Program 13: Linux to demonstrate switch case statement.


echo "Enter a fruit name (apple, banana, orange):"
read fruit
case "$fruit" in
"apple")
echo "You chose an apple." ;;
"banana")
echo "You chose a banana." ;;
"orange")
echo "You chose an orange.” ;;
*)
echo "Invalid fruit choice.” ;;
esac

Page no.16
Khushi Sahu 0801CA231074

Program 14: Linux shell script program whether year is leaping year or not?
echo "Enter a year:"
read year
# Check if the year is divisible by 4 and not divisible by 100
if [ $((year % 4)) -eq 0 ] && [ $((year % 100)) -ne 0 ]; then
echo "$year is a leap year."
# Check if the year is divisible by 400
elif [ $((year % 400)) -eq 0 ]; then
echo "$year is a leap year."
else
echo "$year is not a leap year."
fi

Program 15: Linux shell script program Armstrong no. Or not?


echo "Enter a number:"
read number
# Function to calculate the number of digits in a number
count_digits() {
echo -n $1 | wc -c
}
# Function to check if the number is an Armstrong number
is_armstrong() {
local num=$1
local num_of_digits=$(count_digits $num)
local sum=0
local temp=$num
while [ $temp -gt 0 ]; do
digit=$((temp % 10))
temp=$((temp / 10))
sum=$((sum + digit ** num_of_digits))
done
if [ $sum -eq $num ]; then
echo "$num is an Armstrong number."
else
echo "$num is not an Armstrong number."
fi
}
is_armstrong $number

Page no.17
Khushi Sahu 0801CA231074

LAB ASSIGNMENT 3

PROGRAM 1:Write a shell script to generate marksheet of a student. Take 3 subjects, calculate
and display total marks, percentage and Class obtained by the student. Take marks from the user
terminal.
# Taking input from the user
echo "Enter marks for Subject 1:"
read subject1
echo "Enter marks for Subject 2:"
read subject2
echo "Enter marks for Subject 3:"
read subject3

# Calculating total marks


total_marks=$((subject1 + subject2 + subject3))

# Calculating percentage
percentage=$(echo "scale=2; ($total_marks / 300) * 100" | bc)

# Determining class obtained


if (( $(echo "$percentage >= 80" | bc -l) )); then
class_obtained="Distinction"
elif (( $(echo "$percentage >= 60" | bc -l) )); then
class_obtained="First Class"
elif (( $(echo "$percentage >= 40" | bc -l) )); then
class_obtained="Pass Class"
else
class_obtained="Fail"
fi

# Displaying marksheet
echo "-----------------------"
echo " MARKSHEET "
echo "-----------------------"
echo "Subject 1: $subject1"
echo "Subject 2: $subject2"
echo "Subject 3: $subject3"
echo "-----------------------"
echo "Total Marks: $total_marks"
echo "Percentage: $percentage%"
echo "Class Obtained: $class_obtained"

PROGRAM 2: Write a shell script to find the largest among the 3 given numbers in UNIX / Linux.
Using looping statements.
# Taking input from the user
echo "Enter three numbers:"
read num1
read num2

Page no.18
Khushi Sahu 0801CA231074

read num3

# Finding the largest number


largest=$num1
if [ $num2 -gt $largest ]; then
largest=$num2
fi
if [ $num3 -gt $largest ]; then
largest=$num3
fi

# Displaying the result


echo "The largest number among $num1, $num2, and $num3 is: $largest"

PROGRAM 3: Write a menu driven shell script which will print the following menu and execute
the given task.
a) Display calendar of current month
b) Display today’s date and time
c) Display usernames those are currently logged in the
system
d) Display your name at given x, y position
e) Display your terminal number
f) Exit
while true; do
# Displaying the menu
echo "MENU:"
echo "a) Display calendar of current month"
echo "b) Display today’s date and time"
echo "c) Display usernames those are currently logged in the system"
echo "d) Display your name at given x, y position"
echo "e) Display your terminal number"
echo "f) Exit"
echo -n "Enter your choice: "
read choice

case $choice in
a)
# Display calendar of current month
cal
;;
b)
# Display today's date and time
date
;;
c)
# Display usernames currently logged in
who
;;
d)
# Display name at given x, y position
echo -n "Enter X position: "
read x
echo -n "Enter Y position: "
read y

Page no.19
Khushi Sahu 0801CA231074

tput cup $x $y
echo "Your Name"
;;
e)
# Display terminal number
tty
;;
f)
# Exit the program
echo "Exiting..."
exit 0
;;
*)
echo "Invalid option, please choose again."
;;
esac
done

Page no.20
Khushi Sahu 0801CA231074

PROGRAM 4: Write a shell script that displays a list of all the files in the current directory.
# Displaying list of files in current directory
echo "List of files in the current directory:"
ls

PROGRAM 5: Write a shell script that receives any number of file names as arguments checks if
every argument supplied is a file or a directory and reports accordingly. whenever the argument is
a file or directory.
# Loop through each argument
for arg in "$@"; do
# Check if the argument is a file
if [ -f "$arg" ]; then
echo "$arg is a file."
# Check if the argument is a directory
elif [ -d "$arg" ]; then
echo "$arg is a directory."
# If the argument is neither a file nor a directory
else
echo "$arg is not a valid file or directory."
fi
done

PROGRAM 6: Write a shell script to find the factorial of given integer.


# Taking input from the user
echo -n "Enter an integer: "
read num

# Checking if input is a positive integer


if [[ $num =~ ^[0-9]+$ ]]; then
if [ $num -eq 0 ]; then
result=1
else
fact=1
for (( i = 1; i <= num; i++ )); do
fact=$((fact * i))
done
result=$fact
fi
echo "Factorial of $num is $result"
else
echo "Invalid input. Please enter a positive integer."
fi

PROGRAM 7: Write a Shell script to list all of the directory files in a directory
# Check if directory argument is provided
if [ $# -eq 0 ]; then
echo "Usage: $0 <directory>"
exit 1

Page no.21
Khushi Sahu 0801CA231074

fi

# Check if the specified directory exists


if [ ! -d "$1" ]; then
echo "Error: Directory '$1' not found."
exit 1
fi

# List all files in the specified directory


echo "Files in directory '$1':"
for file in "$1"/*; do
if [ -f "$file" ]; then
echo "$(basename "$file")"
fi
done

PROGRAM 8: Write Shell Script to print multiplication table of a given number


# Taking input from the user
echo -n "Enter a number to print its multiplication table: "
read number

# Checking if input is a positive integer


if [[ $number =~ ^[0-9]+$ ]]; then
echo "Multiplication table of $number:"
for (( i = 1; i <= 10; i++ )); do
echo "$number x $i = $(($number * $i))"
done
else
echo "Invalid input. Please enter a positive integer."
fi

PROGRAM 9: Write Shell Script to calculate power of a number using while & for loop
#!/bin/bash

# Calculating power using while loop


echo -n "Enter base: "
read base
echo -n "Enter exponent: "
read exponent

if [[ $base =~ ^[0-9]+$ && $exponent =~ ^[0-9]+$ ]]; then


result=1
while [ $exponent -gt 0 ]; do
result=$((result * base))
exponent=$((exponent - 1))
done
echo "$base raised to the power of $exponent is: $result"
else
echo "Invalid input. Please enter positive integers for base and exponent."

Page no.22
Khushi Sahu 0801CA231074

fi

# Calculating power using for loop


echo -n "Enter base: "
read base
echo -n "Enter exponent: "
read exponent

if [[ $base =~ ^[0-9]+$ && $exponent =~ ^[0-9]+$ ]]; then


result=1
for ((i=1; i<=exponent; i++)); do
result=$((result * base))
done
echo "$base raised to the power of $exponent is: $result"
else
echo "Invalid input. Please enter positive integers for base and exponent."
fi

PROGRAM 10: Write Shell Script to find HCF of two numbers.


#!/bin/bash

# Taking input from the user


echo -n "Enter first number: "
read num1
echo -n "Enter second number: "
read num2

# Calculating HCF
while [ $num2 -ne 0 ]; do
remainder=$((num1 % num2))
num1=$num2
num2=$remainder
done
echo "HCF of $num1 and $num2 is: $num1"

PROGRAM 11: Write Shell Script Make directory by checking existence.


# Function to make directory if it doesn't exist
make_directory() {
if [ ! -d "$1" ]; then
mkdir "$1"
echo "Directory '$1' created successfully."
else
echo "Directory '$1' already exists."
fi
}

# Taking input from the user


echo -n "Enter directory name: "
read directory_name

# Calling function to make directory

Page no.23
Khushi Sahu 0801CA231074

make_directory "$directory_name"

PROGRAM 12: Write Shell Script Counting characters, words & lines in the file.
#!/bin/bash

# Taking input from the user


echo -n "Enter file name: "
read filename

# Checking if the file exists


if [ ! -f "$filename" ]; then
echo "Error: File '$filename' not found."
exit 1
fi

# Counting characters, words, and lines


characters=$(wc -m < "$filename")
words=$(wc -w < "$filename")
lines=$(wc -l < "$filename")

# Displaying the results


echo "File: $filename"
echo "Number of characters: $characters"
echo "Number of words: $words"
echo "Number of lines: $lines"

PROGRAM 13: Write Shell Script to print contents of an array.


# Define an array
my_array=("apple" "banana" "cherry" "date" "fig")

# Function to print contents of an array


print_array() {
echo "Contents of the array:"
for item in "${my_array[@]}"; do
echo "$item"
done
}

# Call the function to print the array


print_array

PROGRAM 14: Write Shell Script for simple calculator to perform addition subtraction
multiplication and division based on the symbol using case statements.
#!/bin/bash

# Taking input from the user

Page no.24
Khushi Sahu 0801CA231074

echo -n "Enter operator (+, -, *, /): "


read operator

# Validating the operator


case $operator in
+|-|*|/)
;;
*)
echo "Invalid operator!"
exit 1
;;
esac

echo -n "Enter first number: "


read num1
echo -n "Enter second number: "
read num2

# Performing arithmetic operations based on the operator


case $operator in
+)
result=$((num1 + num2))
;;
-)
result=$((num1 - num2))
;;
*)
result=$((num1 $operator num2))
;;
esac

# Displaying the result


echo "Result: $result"

PROGRAM 15: Write Shell Script for Add array elements - Shell Script
# Define an array
my_array=(10 20 30 40 50)

# Function to add elements of the array


add_array_elements() {
sum=0
for item in "${my_array[@]}"; do
sum=$((sum + item))
done
echo "Sum of array elements: $sum"
}

# Call the function to add array elements


add_array_elements

PROGRAM 16: Write Shell Script reverse elements in array.


# Define an array

Page no.25
Khushi Sahu 0801CA231074

my_array=("apple" "banana" "cherry" "date" "fig")

# Function to reverse elements of the array


reverse_array_elements() {
reversed_array=()
for (( i=${#my_array[@]}-1; i>=0; i-- )); do
reversed_array+=("${my_array[$i]}")
done
echo "Reversed array:"
printf '%s\n' "${reversed_array[@]}"
}

# Call the function to reverse array elements


reverse_array_elements

PROGRAM 17: Write shell script program to addition, subtraction, multiplication of two matrix.
#!/bin/bash

# Function to perform matrix addition


add_matrices() {
declare -a result
for ((i=0; i<$rows; i++)); do
for ((j=0; j<$cols; j++)); do
result[$i,$j]=$((matrix1[$i,$j] + matrix2[$i,$j]))
done
done
display_matrix result
}

# Function to perform matrix subtraction


subtract_matrices() {
declare -a result
for ((i=0; i<$rows; i++)); do
for ((j=0; j<$cols; j++)); do
result[$i,$j]=$((matrix1[$i,$j] - matrix2[$i,$j]))
done
done
display_matrix result
}

# Function to perform matrix multiplication


multiply_matrices() {
declare -a result
for ((i=0; i<$rows; i++)); do
for ((j=0; j<$cols; j++)); do
result[$i,$j]=0
for ((k=0; k<$rows; k++)); do
result[$i,$j]=$((result[$i,$j] + matrix1[$i,$k] * matrix2[$k,$j]))
done
done
done

Page no.26
Khushi Sahu 0801CA231074

display_matrix result
}

# Function to display matrix


display_matrix() {
local -n arr=$1
for ((i=0; i<$rows; i++)); do
for ((j=0; j<$cols; j++)); do
echo -n "${arr[$i,$j]} "
done
echo
done
}

# Taking input for matrix size


echo -n "Enter number of rows for matrices: "
read rows
echo -n "Enter number of columns for matrices: "
read cols

# Taking input for first matrix


echo "Enter elements of first matrix ($rows x $cols):"
for ((i=0; i<$rows; i++)); do
for ((j=0; j<$cols; j++)); do
echo -n "Enter element at position [$((i+1)),$((j+1))]: "
read num
matrix1[$i,$j]=$num
done
done

# Taking input for second matrix


echo "Enter elements of second matrix ($rows x $cols):"
for ((i=0; i<$rows; i++)); do
for ((j=0; j<$cols; j++)); do
echo -n "Enter element at position [$((i+1)),$((j+1))]: "
read num
matrix2[$i,$j]=$num
done
done

# Performing matrix operations


echo "Matrix Addition:"
add_matrices
echo "Matrix Subtraction:"
subtract_matrices
echo "Matrix Multiplication:"
multiply_matrices

Page no.27
Khushi Sahu 0801CA231074

PROGRAM 18: Write Shell program to add two numbers using functions.
#!/bin/bash

# Function to add two numbers


add() {
local num1=$1
local num2=$2
local sum=$((num1 + num2))
echo "Sum of $num1 and $num2 is: $sum"
}

# Taking input from the user


echo -n "Enter first number: "
read number1
echo -n "Enter second number: "
read number2

# Calling the add function with the user input as arguments


add $number1 $number2

PROGRAM 19: Write Shell Script to compare two strings in unix shell script.
# Taking input from the user
echo -n "Enter first string: "
read string1
echo -n "Enter second string: "
read string2

# Comparing the strings


if [ "$string1" == "$string2" ]; then
echo "The strings are equal."
else
echo "The strings are not equal."
fi

PROGRAM 20: Write a shell program to demonstrate Equal operator (=), Not Equal operator (!
=),Less than (\<),Greater than (\>) operation on two strings.
# Taking input from the user
echo -n "Enter first string: "

Page no.28
Khushi Sahu 0801CA231074

read string1
echo -n "Enter second string: "
read string2

# Demonstrating comparison operators


echo "Comparison results:"
echo "-------------------"
echo "Equal operator (=):"
if [ "$string1" = "$string2" ]; then
echo "The strings are equal."
else
echo "The strings are not equal."
fi

echo "Not Equal operator (!=):"


if [ "$string1" != "$string2" ]; then
echo "The strings are not equal."
else
echo "The strings are equal."
fi

echo "Less than operator (<):"


if [ "$string1" \< "$string2" ]; then
echo "$string1 is less than $string2."
else
echo "$string1 is not less than $string2."
fi

echo "Greater than operator (>):"


if [ "$string1" \> "$string2" ]; then
echo "$string1 is greater than $string2."
else
echo "$string1 is not greater than $string2."
fi

PROGRAM 21: Write a Program for system calls of Unix operating systems (opendir, readdir,
closedir).
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>

int main() {
DIR *directory;
struct dirent *entry;

// Open directory
directory = opendir(".");
if (directory == NULL) {
perror("Unable to open directory");
exit(EXIT_FAILURE);
}

Page no.29
Khushi Sahu 0801CA231074

// Read directory contents


printf("Contents of the directory:\n");
while ((entry = readdir(directory)) != NULL) {
printf("%s\n", entry->d_name);
}

// Close directory
closedir(directory);

return 0;
}

PROGRAM 22: Write a Program for Process system calls of Unix operating systems (fork, getpid,
exit).
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main() {
pid_t pid;

// Create a child process


pid = fork();

if (pid < 0) {
// Fork failed
perror("Fork failed");
return 1;
} else if (pid == 0) {
// Child process
printf("Child process:\n");
printf("PID: %d\n", getpid());
printf("Parent PID: %d\n", getppid());
// Child exits
exit(0);
} else {
// Parent process
printf("Parent process:\n");
printf("PID: %d\n", getpid());
printf("Child PID: %d\n", pid);
// Wait for child to finish
wait(NULL);
}
return 0;
}

Page no.30
Khushi Sahu 0801CA231074

PROGRAM 23: Write the program to implement the system calls wait ( ) and exit ( ).
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid;
int status;

// Create a child process


pid = fork();

if (pid < 0) {
// Fork failed
perror("Fork failed");
return 1;
} else if (pid == 0) {
// Child process
printf("Child process is running...\n");
// Simulating some task in the child process
sleep(3);
printf("Child process is done.\n");
// Child exits
exit(42);
} else {
// Parent process
printf("Parent process is waiting for child...\n");
// Wait for child to finish and collect its exit status
wait(&status);
if (WIFEXITED(status)) {
printf("Child process exited with status: %d\n", WEXITSTATUS(status));
}
printf("Parent process is done.\n");
}
return 0;
}

PROGRAM 24: write a program to implement the system call execl ( ).


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main() {
printf("Parent process executing...\n");

Page no.31
Khushi Sahu 0801CA231074

// Create a child process


pid_t pid = fork();

if (pid < 0) {
// Fork failed
perror("Fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Child process
printf("Child process executing...\n");

// Replace the child process image with a new program


execl("/bin/ls", "ls", "-l", NULL);
// If execl() returns, it indicates failure
perror("execl() failed");
exit(EXIT_FAILURE);
} else {
// Parent process
printf("Parent process waiting for the child...\n");
wait(NULL);
printf("Parent process done.\n");
}

return 0;
}

PROGRAM 25: write a program to implement the system call execv ( ).


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main() {
printf("Parent process executing...\n");

// Create a child process


pid_t pid = fork();

if (pid < 0) {
// Fork failed
perror("Fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Child process
printf("Child process executing...\n");

// Define arguments for the new program


char *args[] = {"/bin/ls", "-l", NULL};

// Execute a new program using execv


if (execv("/bin/ls", args) == -1) {
perror("execv() failed");
exit(EXIT_FAILURE);

Page no.32
Khushi Sahu 0801CA231074

}
} else {
// Parent process
printf("Parent process waiting for the child...\n");
wait(NULL);
printf("Parent process done.\n");
}

return 0;
}

PROGRAM 26: write a C program for I/O system calls.


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

#define BUFFER_SIZE 4096

int main() {
int input_fd, output_fd; // File descriptors for input and output files
ssize_t bytes_read, bytes_written;
char buffer[BUFFER_SIZE];

// Open the input file


input_fd = open("input.txt", O_RDONLY);
if (input_fd == -1) {
perror("Failed to open input.txt");
exit(EXIT_FAILURE);
}

// Open or create the output file


output_fd = open("output.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (output_fd == -1) {
perror("Failed to open output.txt");
close(input_fd);
exit(EXIT_FAILURE);
}

// Read from the input file and write to the output file
while ((bytes_read = read(input_fd, buffer, BUFFER_SIZE)) > 0) {
bytes_written = write(output_fd, buffer, bytes_read);
if (bytes_written != bytes_read) {
perror("Write error");
close(input_fd);
close(output_fd);
exit(EXIT_FAILURE);
}

Page no.33
Khushi Sahu 0801CA231074

if (bytes_read == -1) {
perror("Read error");
close(input_fd);
close(output_fd);
exit(EXIT_FAILURE);
}

// Close the files


if (close(input_fd) == -1) {
perror("Failed to close input file");
exit(EXIT_FAILURE);
}
if (close(output_fd) == -1) {
perror("Failed to close output file");
exit(EXIT_FAILURE);
}

printf("File copied successfully.\n");

return 0;
}

Page no.34
Khushi Sahu 0801CA231074

LAB ASSIGNMENT 4

PROGRAM 1:Write the C program to implement CPU & scheduling algorithm for first come first serve
scheduling Take user input.
#include <stdio.h>
#define MAX_PROCESS 10

void fcfs(int arrival_time[], int burst_time[], int n)


{
int completion_time[MAX_PROCESS];
float total_waiting_time = 0, total_turnaround_time = 0;
int current_time = 0;

printf("Process Execution Order: ");


for (int i = 0; i < n; i++) {
if (current_time < arrival_time[i])
current_time = arrival_time[i];

completion_time[i] = current_time + burst_time[i];

printf("%d ", i + 1);

total_waiting_time += current_time - arrival_time[i];


total_turnaround_time += completion_time[i] - arrival_time[i];

current_time = completion_time[i];
}

printf("\n\n");
printf("P_id |\tAT|\t BT|\t CT|\tTAT|\t WT|\n");
printf("----------------------------------------\n");
for (int i = 0; i < n; i++) {
int waiting_time = completion_time[i] - arrival_time[i] - burst_time[i];
printf("\t%d| \t %d| \t%d| \t %d | \t%d | \t%d | \n", i + 1, arrival_time[i], burst_time[i], completion_time[i],
completion_time[i] - arrival_time[i], waiting_time);
}

printf("\nAverage Waiting Time: %.2f\n", total_waiting_time / n);


printf("Average Turnaround Time: %.2f\n", total_turnaround_time / n);
}

int main()
{
int arrival_time[MAX_PROCESS], burst_time[MAX_PROCESS];
int n;
printf("Enter the number of processes: ");
scanf("%d", &n);
printf("Enter arrival time and burst time for each process:\n");
for (int i = 0; i < n; i++)
{
printf("Process %d: ", i + 1);
scanf("%d %d", &arrival_time[i], &burst_time[i]);
}
fcfs(arrival_time, burst_time, n);
return 0;
}

Page no.35
Khushi Sahu 0801CA231074

PROGRAM 2:Write a program to implement CPU scheduling algorithm for shortest job first Scheduling.
Take user input.
#include <stdio.h>

#define MAX_PROCESS 10

void sjf(int arrival_time[], int burst_time[], int n) {


int completion_time[MAX_PROCESS];
int remaining_time[MAX_PROCESS];
int total_waiting_time = 0, total_turnaround_time = 0;

// Copy burst times to remaining_time array


for (int i = 0; i < n; i++)
remaining_time[i] = burst_time[i];

int current_time = 0;
int completed_processes = 0;

while (completed_processes < n) {


int shortest_job = -1;
int shortest_time = 999999;

// Find the shortest remaining time job at current time


for (int i = 0; i < n; i++) {
if (arrival_time[i] <= current_time && remaining_time[i] < shortest_time && remaining_time[i] > 0) {
shortest_job = i;
shortest_time = remaining_time[i];
}
}

if (shortest_job == -1) {
current_time++;
continue;
}

// Execute the shortest job


remaining_time[shortest_job]--;
current_time++;

// If a process is completed
if (remaining_time[shortest_job] == 0) {
completion_time[shortest_job] = current_time;
completed_processes++;
total_waiting_time += completion_time[shortest_job] - arrival_time[shortest_job] -
burst_time[shortest_job];

Page no.36
Khushi Sahu 0801CA231074

total_turnaround_time += completion_time[shortest_job] - arrival_time[shortest_job];


}
}

printf("P_id\tAT\tBT\tCT\tTAT\tWT\n");
for (int i = 0; i < n; i++) {
printf("\t%d\t%d\t%d\t%d\t%d\t%d\n", i + 1, arrival_time[i], burst_time[i], completion_time[i],
completion_time[i] - arrival_time[i], completion_time[i] - arrival_time[i] - burst_time[i]);
}

printf("\nAverage Waiting Time: %.2f\n", (float)total_waiting_time / n);


printf("Average Turnaround Time: %.2f\n", (float)total_turnaround_time / n);
}

int main() {
int arrival_time[MAX_PROCESS], burst_time[MAX_PROCESS];
int n;

printf("Enter the number of processes: ");


scanf("%d", &n);

printf("Enter arrival time and burst time for each process:\n");


for (int i = 0; i < n; i++) {
printf("Process %d: ", i + 1);
scanf("%d %d", &arrival_time[i], &burst_time[i]);
}

sjf(arrival_time, burst_time, n);

return 0;
}

PROGRAM 3: Write a program to implement CPU scheduling algorithm for Shortest Job Remaining First.
Take user input.

PROGRAM 4:write a ‘C’ program to perform priority scheduling and take user input.

PROGRAM 5: write a program to implement CPU scheduling for Round Robin Scheduling.

Page no.37

You might also like