0% found this document useful (0 votes)
13 views24 pages

Os Viva

Uploaded by

afrin nisha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views24 pages

Os Viva

Uploaded by

afrin nisha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 24

CHILD:

This C program uses fork() to create a new process. Here's a step-by-step


explanation:

#include <stdio.h>
This preprocessor directive includes the standard input/output header file. It
allows the use of functions like printf().

#include <sys/types.h>
This header defines data types used in system calls, including pid_t for process
IDs.

#include <unistd.h>
This header provides access to the POSIX API, including functions like fork().

int main()
The main() function is the entry point of the program.

fork();
This is the critical system call in the program. The fork() function creates a new
process by duplicating the calling process. It returns:

0 to the child process.


The child's process ID (a positive integer) to the parent process.
-1 if the creation of the child process fails.
After fork() is called, there are now two processes (the parent and the child) that
continue executing from the next statement. These two processes have separate
memory spaces but are executing the same program.

printf("Hello world!\n");
This function prints "Hello world!" to the standard output (usually the terminal).
Since both the parent and child processes are running this statement, "Hello
world!" will be printed twice—once by the parent and once by the child.

However, because of the way process scheduling works, the exact order of the
printed messages is not guaranteed. You might see both messages back-to-back, or
there could be an interleaving of outputs if more statements are added.

return 0;
This terminates the main() function, returning a value of 0 to indicate successful
completion of the program.

In summary:
The fork() system call creates a new process.
Both the parent and child processes execute the printf() function, so "Hello
world!" is printed twice.

ORPHAN:
This C program demonstrates an orphan process—a child process that continues to run
even after its parent process terminates. Let's walk through it line by line:

1. #include<stdio.h>
This includes the Standard Input/Output library, which allows using functions like
printf() for output to the console.
2. #include<sys/types.h>
This header defines various types used in system calls, particularly pid_t, which
represents process IDs.

3. #include<unistd.h>
This header provides access to the POSIX API, including the fork() and sleep()
system calls used in process management.

4. int main()
This is the entry point of the program where the execution starts.

5. printf ("Demonstration-orphan process\n");


This line prints "Demonstration-orphan process" to the console, signaling the start
of the program.

6. int pid=fork();
Here, the fork() system call is used to create a new process. The return value of
fork() is stored in the variable pid:

In the parent process, fork() returns the child’s process ID, a positive integer.
In the child process, fork() returns 0.
7. if (pid>0)
This condition checks if pid is greater than 0, meaning the code is running in the
parent process (since only the parent gets the child’s PID as a return value).

Inside the parent process:


printf("In parent process");: This line will print "In parent process" to the
console.
After this, the parent process finishes, which creates an orphan scenario because
the child process is still running.
8. else if (pid==0)
This condition checks if pid equals 0, meaning the code is now running in the child
process.

Inside the child process:


sleep(5);: The sleep(5) function makes the child process sleep (pause) for 5
seconds. This delay allows the parent process to terminate first, making the child
an orphan process.

printf("in child process");: After the 5-second sleep, the child process will print
"in child process" to the console.

At this point, the child process continues to run even though its parent has
finished. After the parent terminates, the child process becomes an orphan and is
adopted by the init or systemd process (depending on the operating system).

9. return 0;
This signals the end of the main() function, returning 0 to indicate that the
program executed successfully.

Explanation of the Orphan Process:


An orphan process occurs when a child process continues running after its parent
process has finished.
In this case, the parent process terminates first after printing "In parent
process".
The child process, after waiting for 5 seconds, prints "in child process". During
this time, the child process is an orphan and is re-parented by the init or systemd
process.
ZOMBIE:
This C program demonstrates the creation of a zombie process, which occurs when a
child process terminates but its parent process has not yet acknowledged its
termination using wait(). Let's go through the code line by line:

1. #include<stdlib.h>
This header file includes functions for performing general functions like memory
allocation, process control, conversions, etc. It allows the use of exit() to
terminate a process.

2. #include<sys/types.h>
This header defines types like pid_t used in system calls for working with process
IDs.

3. #include<unistd.h>
This includes the POSIX API for system calls like fork() and sleep() used in this
program.

4. #include<stdio.h>
This header file allows for input/output operations, such as printing to the
console using printf().

5. int main()
This is the entry point of the program where execution starts.

6. int child_pid;
Declares an integer variable child_pid, which will store the process ID returned by
the fork() system call.

7. child_pid=fork();
The fork() system call creates a new child process.
The return value of fork() is stored in child_pid.
In the parent process, fork() returns the child's process ID (a positive integer).
In the child process, fork() returns 0.
8. printf("process created");
This prints "process created" to the console in both the parent and the child
process, because both processes continue to execute this line after fork() is
called. However, there might be only one print visible, depending on how the
processes are scheduled.

9. if(child_pid>0)
This checks if child_pid is greater than 0, meaning the code is currently executing
in the parent process.

Inside the parent process:


sleep(2);: The parent process sleeps for 2 seconds. During this time, the child
process will likely terminate first, leaving the parent unaware of its child's
termination, which creates a zombie process.
After the sleep, the parent process will eventually terminate, but before it does,
the child process becomes a zombie.
10. else
This branch is executed in the child process, where child_pid == 0.

Inside the child process:


printf("zombie process created");: This prints "zombie process created" to the
console, indicating that the child process is about to terminate.
exit(0);: The exit(0) function terminates the child process with a status of 0
(indicating successful completion).
At this point, the child process becomes a zombie because it has terminated, but
the parent has not yet called wait() to read the child's exit status.
11. return 0;
This returns 0 from the main() function, signaling the successful termination of
the parent process (after 2 seconds).

What is a Zombie Process?


A zombie process is a process that has terminated but still occupies an entry in
the process table because its parent has not yet read its exit status using wait().
It remains in this state until the parent process calls wait() or terminates.
In this program, the child process terminates after printing "zombie process
created", but since the parent does not call wait(), the child becomes a zombie.
The zombie state persists until the parent process itself terminates.
Program Flow:
The parent and child processes are created using fork().
Both processes print "process created".
The child process terminates quickly after printing "zombie process created",
becoming a zombie.
The parent process sleeps for 2 seconds and then terminates without acknowledging
the child's termination, leaving the child as a zombie until the parent terminates.

ROUND ROBIN:
This C program simulates the Round Robin (RR) Scheduling Algorithm used in process
scheduling. Let's go through the code step by step:

1. #include<stdio.h>
This includes the Standard Input/Output library, which allows using functions like
printf() and scanf() for console input/output operations.

2. #include<conio.h>
This includes the Console Input/Output library, which provides console input/output
functions like getch(). This library is specific to certain compilers (like Turbo
C), and it's not necessary for standard C programs in modern environments.

3. void main()
This is the entry point of the program. In C, int main() is more standard, but void
main() works in some environments.

4. int i, NOP, sum=0, count=0, y, quant, wt=0, tat=0, at[10], bt[10], temp[10];
i: A loop variable.
NOP: Number of processes.
sum: Keeps track of the total time as processes are executed.
count: Used to track if a process has completed execution in the current round.
y: A copy of NOP to track the remaining processes.
quant: The time quantum for the round-robin scheduling.
wt: Total waiting time of all processes.
tat: Total turnaround time of all processes.
at[10]: Array to store the arrival times of up to 10 processes.
bt[10]: Array to store the burst times of up to 10 processes.
temp[10]: Temporary array to store the remaining burst times of the processes.
5. printf(" Total number of process in the system: ");
This prompts the user to enter the total number of processes in the system.
6. scanf("%d", &NOP);
This reads the number of processes from the user and stores it in the variable NOP.

7. y = NOP;
This assigns the value of NOP to y. This is used to track the remaining processes
as y decreases when processes are completed.

8. for(i=0; i<NOP; i++)


This loop iterates over each process and gathers the arrival time and burst time.

9. printf("\n Enter the Arrival and Burst time of the Process[%d]\n", i+1);
This prompts the user to enter the arrival time and burst time for each process,
starting from Process 1.

10. scanf("%d", &at[i]);


This reads the arrival time for the current process from the user and stores it in
the at[] array.

11. scanf("%d", &bt[i]);


This reads the burst time for the current process from the user and stores it in
the bt[] array.

12. temp[i] = bt[i];


The burst time of each process is copied into the temp[] array. This array will
keep track of the remaining burst time as processes are executed.

13. printf("Enter the Time Quantum for the process: ");


This prompts the user to enter the time quantum for round-robin scheduling, which
is the maximum time a process can run before it is preempted (if it's not
completed).

14. scanf("%d", &quant);


This reads the time quantum value from the user.

15. printf("\n Process No \t\t Burst Time \t\t TAT \t\t Waiting Time ");
This prints the table header for displaying process information such as Process
Number, Burst Time, Turnaround Time (TAT), and Waiting Time.

16. for(sum=0, i=0; y!=0; )


This loop continues as long as there are unfinished processes (y != 0). The sum
keeps track of the current time.

17. if(temp[i] <= quant && temp[i] > 0)


This condition checks if the current process's remaining burst time is less than or
equal to the time quantum, and if the burst time is greater than 0. If so, the
process will finish its execution within this quantum.

18. sum = sum + temp[i];


This adds the remaining burst time of the current process to the total time sum.

19. temp[i] = 0;
This sets the remaining burst time of the current process to 0, indicating that it
has finished.

20. count=1;
This indicates that the current process has finished execution.

21. else if(temp[i] > 0)


This condition checks if the remaining burst time of the process is greater than
the time quantum. If true, the process will be preempted after the quantum.

22. temp[i] = temp[i] - quant;


This reduces the remaining burst time of the process by the time quantum.

23. sum = sum + quant;


This adds the time quantum to the total time sum.

24. if(temp[i]==0 && count==1)


This checks if the process has finished execution (temp[i] == 0) and if it had
finished in the current round (count == 1).

25. y--;
This decrements the number of remaining processes (y), indicating that one more
process has completed.

26. printf("\nProcess No[%d] \t\t %d \t\t\t %d \t\t\t %d", i+1, bt[i], sum-at[i],
sum-at[i]-bt[i]);
This prints the process number, burst time, turnaround time (sum - at[i]), and
waiting time (sum - at[i] - bt[i]).

27. wt = wt + sum - at[i] - bt[i];


This accumulates the waiting time for the current process.

28. tat = tat + sum - at[i];


This accumulates the turnaround time for the current process.

29. count = 0;
This resets the count variable for the next iteration.

30. if(i == NOP-1)


This checks if the last process has been reached in the current round.

31. i = 0;
If the last process has been reached, the loop resets i to 0 to start the next
round.

32. else if(at[i+1] <= sum)


This checks if the arrival time of the next process is less than or equal to the
current total time sum.

33. i++;
If the next process has arrived, the loop proceeds to the next process.

34. else { i = 0; }
If the next process hasn't arrived yet, the loop resets i to 0 to continue
checking.

35. avg_wt = wt * 1.0 / NOP;


This calculates the average waiting time by dividing the total waiting time by the
number of processes.

36. avg_tat = tat * 1.0 / NOP;


This calculates the average turnaround time by dividing the total turnaround time
by the number of processes.

37. printf("\n Average Turn Around Time: \t%f", avg_wt);


This prints the average waiting time.
38. printf("\n Average Waiting Time: \t%f", avg_tat);
This prints the average turnaround time.

39. getch();
This waits for the user to press a key before closing the program. It's specific to
older environments like Turbo C and is not required in modern C programs.

Summary:
This program simulates Round Robin Scheduling, where:

Each process is assigned a time quantum to execute.


If the process finishes within the quantum, it completes; otherwise, it is
preempted and placed back in the queue.
The program calculates and prints each process's turnaround time (TAT) and waiting
time (WT), along with their averages.

FCFS:
This C program implements First-Come, First-Served (FCFS) scheduling for processes,
calculating the waiting time (WT) and turnaround time (TAT) for each process. Let's
go through the code step by step:

1. #include<stdio.h>
This includes the Standard Input/Output library, which allows using functions like
printf() and scanf() for console input/output operations.

2. #include<conio.h>
This includes the Console Input/Output library, which provides console I/O
functions like getch(). This is optional and mainly used in older environments like
Turbo C.

3. int main()
This is the entry point of the program.

4. int pid[15];
An array pid[] is declared to store the process IDs for up to 15 processes.

5. int bt[15];
An array bt[] is declared to store the burst times (execution times) for up to 15
processes.

6. int n;
This variable n is used to store the number of processes.

7. printf("enter the number of process:");


This prints a prompt asking the user to enter the number of processes.

8. scanf("%d",&n);
This reads the number of processes (n) from the user.
9. printf("enter process id for all processes:");
This prompts the user to enter the process IDs.

10. for(int i=0;i<n;i++) { scanf("%d",&pid[i]); }


This loop iterates n times, allowing the user to input the process IDs for all
processes, storing them in the pid[] array.

11. printf("enter burst time of all the process:");


This prompts the user to enter the burst times of the processes.

12. for(int i=0;i<n;i++) { scanf("%d",&bt[i]); }


This loop iterates n times, allowing the user to input the burst times for each
process and stores them in the bt[] array.

13. int i, wt[n];


The variable i is declared for loop iteration, and the wt[] array is declared to
store the waiting times of each process.

14. wt[0]=0;
The waiting time for the first process is always 0, as it doesn't have to wait for
any prior process to finish.

15. for(i=1;i<n;i++) { wt[i]=bt[i-1]+wt[i-1]; }


This loop calculates the waiting time for each process using the formula:

wt[i] = bt[i-1] + wt[i-1]


The waiting time of the current process is the burst time of the previous process
plus the waiting time of the previous process.
16. printf("process id burst time waiting time turnaround time \n");
This prints the table header for displaying process information, such as Process
ID, Burst Time, Waiting Time, and Turnaround Time (TAT).

17. float twt=0.0; float tat=0.0;


These two variables, twt (total waiting time) and tat (total turnaround time), are
initialized to store cumulative values of waiting time and turnaround time,
respectively.

18. for(i=0;i<n;i++)
This loop iterates over all processes to calculate and print individual waiting and
turnaround times.

19. printf("%d \t \t", pid[i]);


This prints the process ID for the current process.

20. printf("%d \t \t", bt[i]);


This prints the burst time for the current process.

21. printf("%d \t \t", wt[i]);


This prints the waiting time for the current process.

22. printf("%d \t \t", bt[i] + wt[i]);


This prints the turnaround time for the current process, calculated as burst time +
waiting time.

23. twt += wt[i];


This accumulates the total waiting time by adding the waiting time of the current
process to twt.

24. tat += (wt[i] + bt[i]);


This accumulates the total turnaround time by adding the turnaround time of the
current process to tat.

25. float att, awt;


These variables att and awt are declared to store the average turnaround time and
average waiting time.

26. awt = twt / n;


This calculates the average waiting time by dividing the total waiting time (twt)
by the number of processes (n).

27. att = tat / n;


This calculates the average turnaround time by dividing the total turnaround time
(tat) by the number of processes (n).

28. printf("avg,waiting time=%f \n", awt);


This prints the average waiting time.

29. printf("avg,turnaround time=%f", att);


This prints the average turnaround time.

Explanation of Terms:
Waiting Time (WT):
The time a process has to wait before it gets the CPU.
Calculated as WT[i] = sum of burst times of previous processes.
Turnaround Time (TAT):
The total time taken from the submission of a process to its completion.
Calculated as TAT[i] = WT[i] + BT[i].
Example:
Suppose you input:

Number of processes: 3
Process IDs: 1, 2, 3
Burst times: 5, 8, 12
The output will be:

css
Copy code
Process ID Burst Time Waiting Time Turnaround Time
1 5 0 5
2 8 5 13
3 12 13 25

Average Waiting Time = (0 + 5 + 13) / 3 = 6.00


Average Turnaround Time = (5 + 13 + 25) / 3 = 14.33
This program is a simple implementation of FCFS Scheduling and calculates the
waiting time and turnaround time for each process.

SJF:
This C program implements Shortest Job First (SJF) scheduling in non-preemptive
mode, where processes are sorted by their burst times (execution times). Here's a
detailed breakdown of the code, step by step:

1. #include <stdio.h>
This includes the Standard Input/Output library for using printf() and scanf()
functions for console operations.

2. int main()
The main() function is the entry point of the program.

3. Variable Declarations:
c
Copy code
int bt[20], p[20], wt[20], tat[20], i, j, n, total = 0, pos, temp;
float avg_wt, avg_tat;
bt[20]: Array to store the burst times of up to 20 processes.
p[20]: Array to store the process IDs.
wt[20]: Array to store the waiting times.
tat[20]: Array to store the turnaround times.
i, j: Loop counters.
n: Number of processes.
total: Accumulates the total waiting and turnaround times for average calculation.
pos: Used for tracking the position of the shortest burst time in the selection
sort algorithm.
temp: Temporary variable used for swapping values during sorting.
avg_wt, avg_tat: Variables to store the average waiting time and average turnaround
time.
4. User Input:
c
Copy code
printf("Enter number of processes: ");
scanf("%d",&n);
This part asks the user to input the number of processes (n).

5. Input Burst Times:


c
Copy code
printf("\nEnter burst times:\n");
for (i = 0; i < n; i++) {
printf("p[%d]: ", i + 1);
scanf("%d", &bt[i]);
p[i] = i + 1;
}
The loop collects the burst time for each process.
The process ID is stored in p[i], where p[i] = i + 1 assigns process numbers
starting from 1.
6. Sorting Burst Times (SJF Scheduling):
c
Copy code
for (i = 0; i < n; i++) {
pos = i;
for (j = i + 1; j < n; j++) {
if (bt[j] < bt[pos])
pos = j;
}
temp = bt[i];
bt[i] = bt[pos];
bt[pos] = temp;
temp = p[i];
p[i] = p[pos];
p[pos] = temp;
}
The outer loop goes through each process.
The inner loop finds the process with the shortest burst time and swaps it with the
current process.
Both burst times (bt[i]) and process IDs (p[i]) are swapped, ensuring the order of
processes is based on burst time.
7. Calculate Waiting Time:
c
Copy code
wt[0] = 0; // First process has no waiting time
for (i = 1; i < n; i++) {
wt[i] = 0;
for (j = 0; j < i; j++)
wt[i] += bt[j];
total += wt[i]; // Accumulate total waiting time
}
The waiting time for the first process is 0 because it doesn't wait.
For each subsequent process, the waiting time is calculated by summing up the burst
times of all previous processes.
The total variable accumulates the total waiting time to calculate the average
later.
8. Calculate Turnaround Time:
c
Copy code
total = 0; // Reset total for turnaround time calculation
for (i = 0; i < n; i++) {
tat[i] = bt[i] + wt[i]; // Turnaround time = burst time + waiting time
total += tat[i]; // Accumulate total turnaround time
}
The turnaround time for each process is calculated by adding its burst time and
waiting time.
The total variable accumulates the total turnaround time for average calculation.
9. Average Waiting Time & Turnaround Time:
c
Copy code
avg_wt = (float)total / n; // Average waiting time
total = 0; // Reset total for turnaround time
avg_tat = (float)total / n; // Average turnaround time
The average waiting time and average turnaround time are computed by dividing the
total waiting/turnaround times by the number of processes.
10. Display Results:
c
Copy code
printf("\nProcess\t Burst Time\t Waiting Time\t Turnaround Time\n");
for (i = 0; i < n; i++) {
printf("p[%d]\t %d\t\t %d\t\t %d\n", p[i], bt[i], wt[i], tat[i]);
}
This prints the table with:

Process ID
Burst Time
Waiting Time
Turnaround Time for each process.
11. Display Average Times:
c
Copy code
printf("\nAverage Waiting Time: %.2f", avg_wt);
printf("\nAverage Turnaround Time: %.2f", avg_tat);
This prints the average waiting time and average turnaround time with two decimal
places.
Summary of Important Terms:
Waiting Time (WT):

The time a process waits before getting the CPU.


Calculated as the sum of the burst times of previous processes.
Turnaround Time (TAT):

The total time from process submission to completion.


Calculated as TAT = WT + BT.
Shortest Job First (SJF):

A CPU scheduling algorithm that selects the process with the shortest burst time
next.
Non-preemptive SJF executes each process fully before moving to the next.

SEMAPHORE:
This program demonstrates multithreading using POSIX threads (pthreads) and
semaphores to synchronize access to a shared variable between two threads. Here's a
line-by-line explanation:

1. Including Necessary Headers:


c
Copy code
#include <pthread.h> // For creating and managing threads
#include <stdio.h> // For standard input/output functions
#include <semaphore.h> // For using semaphores
#include <unistd.h> // For the sleep() function
pthread.h: Contains the functions for creating and managing threads.
semaphore.h: Used to handle semaphores for synchronizing access to shared
resources.
unistd.h: Contains sleep() function to pause execution of a thread.
2. Function Declarations:
c
Copy code
void* fun1(void* arg);
void* fun2(void* arg);
These are the two thread functions (fun1 and fun2) which will manipulate the shared
variable.

3. Global Variables:
c
Copy code
int shared = 1; // A global shared variable
sem_t s; // A semaphore to control access to the shared variable
shared: A global variable that both threads will access and modify.
sem_t s: A semaphore that will be used to ensure that the two threads do not access
shared simultaneously, preventing a race condition.
4. Main Function:
c
Copy code
int main() {
sem_init(&s, 0, 1); // Initialize the semaphore with an initial value of 1
sem_init(&s, 0, 1) initializes the semaphore s with an initial value of 1. This
allows one thread to enter the critical section while the other waits.
0: Specifies that the semaphore is shared between threads (not processes).
1: The initial value of the semaphore.
c
Copy code
pthread_t thread1, thread2; // Declare two thread identifiers
pthread_t thread1, thread2: Declare two threads, thread1 and thread2.
c
Copy code
pthread_create(&thread1, NULL, fun1, NULL);
pthread_create(&thread2, NULL, fun2, NULL);
pthread_create creates two threads:
thread1 will execute the fun1 function.
thread2 will execute the fun2 function.
c
Copy code
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join is used to wait for the threads thread1 and thread2 to finish before
proceeding. This ensures that the main function does not terminate before both
threads complete execution.
c
Copy code
printf("Final value of shared is %d \n", shared);
This prints the final value of the shared variable after both threads have
completed their work.
c
Copy code
sem_destroy(&s); // Destroy the semaphore to free resources
return 0;
}
sem_destroy(&s) destroys the semaphore, freeing its resources.
5. Thread Function fun1:
c
Copy code
void* fun1(void* arg) {
int x;
sem_wait(&s); // Wait (decrement) semaphore to enter critical section
sem_wait(&s) is called to lock the semaphore (decrement its value). If the
semaphore is already locked by another thread, this thread will block until it can
acquire the lock.
c
Copy code
x = shared; // Read the shared variable
printf("Thread 1 reads the value as %d \n", x);
x = shared copies the current value of the shared variable shared into the local
variable x.
The current value is printed.
c
Copy code
x++;
printf("Local updation by thread 1: %d \n", x);
sleep(1); // Simulate some processing time
x++ increments the local copy of shared.
sleep(1) pauses the thread for 1 second to simulate some processing time.
c
Copy code
shared = x; // Update the global shared variable
printf("Value of shared variable updated by thread 1 is: %d \n", shared);
The global shared variable is updated with the new value of x.
The updated value of shared is printed.
c
Copy code
sem_post(&s); // Signal (increment) semaphore to leave critical section
return NULL;
}
sem_post(&s) increments the semaphore value, allowing other threads to access the
critical section.
return NULL ends the function.
6. Thread Function fun2:
c
Copy code
void* fun2(void* arg) {
int y;
sem_wait(&s); // Wait (decrement) semaphore to enter critical section
Similar to fun1, sem_wait(&s) locks the semaphore, blocking other threads.
c
Copy code
y = shared; // Read the shared variable
printf("Thread 2 reads the value as %d \n", y);
y = shared reads the current value of shared and stores it in the local variable y.
The value is printed.
c
Copy code
y++;
printf("Local updation by thread 2: %d \n", y);
sleep(1); // Simulate some processing time
y++ increments the local copy of the shared variable.
The thread is paused for 1 second.
c
Copy code
shared = y; // Update the global shared variable
printf("Value of shared variable updated by thread 2 is: %d \n", shared);
The global shared variable is updated with the incremented value y.
The updated value is printed.
c
Copy code
sem_post(&s); // Signal (increment) semaphore to leave critical section
return NULL;
}
sem_post(&s) releases the semaphore, allowing other threads to access the shared
variable

SHELL SCRIPT:
FACTORIAL OF GV NUM USING FOR LOOP:
This is a Bash script to calculate the factorial of a number entered by the user.
Let me explain the script line by line:

1. Prompting for Input:


bash
Copy code
echo "Enter a number"
read num
echo "Enter a number": This prints the message asking the user to input a number.
read num: This reads the user input and stores it in the variable num.
2. Initial Setup for Factorial Calculation:
bash
Copy code
fact=1
fact=1: This initializes the variable fact with a value of 1. The variable fact
will hold the final factorial value.
3. For Loop to Calculate the Factorial:
bash
Copy code
for ((i=1; i<=num; i++))
do
fact=$((fact * i))
done
for ((i=1; i<=num; i++)): This is a loop that iterates from i=1 to i=num.
The double parentheses ((...)) indicate arithmetic evaluation and looping in Bash.
fact=$((fact * i)): On each iteration, the value of fact is updated by multiplying
the current value of fact by i. This calculates the factorial of the number step by
step.
4. Output the Result:
bash
Copy code
echo "Factorial of $num: $fact"
echo "Factorial of $num: $fact": This prints the final result of the factorial
calculation, showing both the number entered by the user ($num) and the calculated
factorial ($fact).
Example:
If you input 5, the output will be:

mathematica
Copy code
Enter a number
5
Factorial of 5: 120
Explanation of the Factorial Calculation:
For num = 5, the loop goes through:
Iteration 1: fact = 1 * 1 = 1
Iteration 2: fact = 1 * 2 = 2
Iteration 3: fact = 2 * 3 = 6
Iteration 4: fact = 6 * 4 = 24
Iteration 5: fact = 24 * 5 = 120
The final value of fact after the loop is 120, which is the factorial of 5.

LENGTH OF THE GIVEN STRING :


This Bash script calculates the length of the string "operating system lab" and
prints it. Let's break it down:

1. String Declaration:
bash
Copy code
str="operating system lab"
str="operating system lab": This initializes the variable str with the value
"operating system lab", which is the string whose length you want to calculate.
2. Length Calculation:
bash
Copy code
length=${#str}
length=${#str}: This syntax calculates the length of the string stored in the
variable str. The ${#str} expression returns the number of characters in the
string.
3. Printing the Result:
bash
Copy code
echo "Length of '$str' is $length"
echo "Length of '$str' is $length": This prints the string "Length of 'operating
system lab' is" followed by the length stored in the length variable.
Example Output:
For the string "operating system lab", the output would be:

csharp
Copy code
Length of 'operating system lab' is 20
Explanation:
The string "operating system lab" has 20 characters, including spaces, so the
script correctly calculates and outputs the length as 20.

REVERSE OF GV STR USING WHILE LOOP:


Let's break down the provided shell script step by step. This script reverses a
given number using a while loop.

Step-by-Step Explanation
Print a Message:

bash
Copy code
echo "Reverse the given number using while loop"
This line outputs a message to the console informing the user about the purpose of
the script.

Prompt for Input:

bash
Copy code
echo "Enter a number"
This line prompts the user to enter a number that they want to reverse.

Read Input:

bash
Copy code
read num
The read command takes input from the user and stores it in the variable num.

Initialize Reverse Variable:

bash
Copy code
reverse=0
This line initializes a variable reverse to 0. This variable will hold the reversed
number as we compute it.

While Loop:

bash
Copy code
while [ $num -gt 0 ]; do
This begins a while loop that continues as long as num is greater than 0.

Calculate Remainder:

bash
Copy code
remainder=$(($num % 10))
Inside the loop, this line calculates the remainder when num is divided by 10. This
gives the last digit of the number. The $(...) syntax executes the expression
inside and stores the result in remainder.

Update Reversed Number:

bash
Copy code
reverse=$(($reverse * 10 + $remainder))
This line updates the reverse variable by multiplying it by 10 (shifting the
existing digits to the left) and adding the remainder (the last digit of num). This
builds the reversed number step by step.

Update Original Number:

bash
Copy code
num=$(($num / 10))
This line removes the last digit from num by dividing it by 10. It prepares num for
the next iteration of the loop.

End of While Loop:

bash
Copy code
done
This marks the end of the while loop. The loop will repeat until num becomes 0.

Output the Result:

bash
Copy code
echo "Reversed number is: $reverse"
Finally, this line outputs the reversed number stored in the reverse variable.

Summary
The script effectively takes a number from the user, reverses it digit by digit
using a while loop, and prints the reversed number. The key operations involve
calculating the remainder and updating both the reverse and num variables until all
digits are processed.

If you have any questions about specific parts of the code or if you want to
explore more examples, feel free to ask!

REVERSE THE GV STR:


Let's break down the provided shell script step by step. This script reverses a
given string using a for loop in bash.

Step-by-Step Explanation
Initialize the String:

bash
Copy code
s="operating system lab"
This line defines a variable s and assigns it the string "operating system lab".

Calculate String Length:

bash
Copy code
strlen=${#s}
Here, ${#s} is used to get the length of the string s, and the result is stored in
the variable strlen.

Initialize Reversed String Variable:

bash
Copy code
revstr=""
This line initializes an empty string variable revstr, which will be used to store
the reversed version of s.

For Loop:

bash
Copy code
for((i=$strlen-1;i>=0;i--)); do
This line starts a for loop that begins at the last index of the string (strlen -
1) and decrements i until it reaches 0. This allows the loop to iterate over each
character of the string in reverse order.

Extract and Append Characters:

bash
Copy code
revstr+=${s:$i:1}
Inside the loop, this line extracts a single character from s at the index i using
${s:$i:1} and appends it to revstr. The += operator is used to concatenate the
character to the end of revstr.

End of For Loop:

bash
Copy code
done
This marks the end of the for loop. The loop will continue until all characters
have been processed.

Output the Result:

bash
Copy code
echo "Original string: $s"
echo "Reversed string: $revstr"
Finally, these lines output the original string and the reversed string. The
variable s holds the original string, while revstr contains the reversed version.

Summary
The script effectively takes a string, reverses it character by character using a
for loop, and prints both the original and reversed strings. The key operations
involve calculating the length of the string and iterating over its characters in
reverse order to build the reversed string.

Example Output
For the string "operating system lab", the output would be:

c
Copy code
Original string: operating system lab
Reversed string: bal metsys gnitaro
If you have any questions about specific parts of the code or if you'd like to see
variations or more examples, feel free to ask!

STRING CONTAINS ONLY ALPHABET


Let's break down the provided shell script step by step. This script checks whether
a given string contains only alphabetic characters (both uppercase and lowercase).

Step-by-Step Explanation
Prompt for Input:

bash
Copy code
echo "Enter a string"
This line prints a message to the console asking the user to enter a string.

Read Input:

bash
Copy code
read string
The read command takes input from the user and stores it in the variable string.

Regular Expression Check:

bash
Copy code
if [[ $string =~ ^[a-zA-Z]+$ ]]; then
This line uses a conditional statement to check if the string matches a specific
pattern:

[[ ... ]] is a bash conditional expression.


$string is the variable containing the user's input.
=~ is the operator used for regex matching in bash.
^[a-zA-Z]+$ is the regex pattern:
^ asserts the start of the string.
[a-zA-Z] matches any uppercase or lowercase alphabetic character.
+ indicates that there should be one or more of these characters.
$ asserts the end of the string.
This pattern effectively checks if the entire string consists only of alphabetic
characters.

If Condition True:

bash
Copy code
echo "String contains only alphabets"
If the condition is true (i.e., the string contains only letters), this line prints
a message indicating that the string is valid.

If Condition False:

bash
Copy code
else
echo "String does not contain only alphabets"
fi
If the condition is false (i.e., the string contains characters other than
letters), this block executes and prints a message indicating that the string is
invalid.

Summary
The script effectively prompts the user for a string and checks whether it contains
only alphabetic characters using a regular expression. It outputs a message
indicating the validity of the string based on the check.

Example Output
If the user inputs HelloWorld:

sql
Copy code
String contains only alphabets
If the user inputs Hello123:

arduino
Copy code
String does not contain only alphabets

SUBJECT DETAILS:
Let's break down the provided shell script step by step. This script collects and
prints details about a subject for a specific paper.

Step-by-Step Explanation
Print Header:

bash
Copy code
echo "III BSC CS-SBE Paper"
This line outputs a header indicating the title or context of the information that
will follow, in this case, "III BSC CS-SBE Paper".

Prompt for Subject Code:

bash
Copy code
echo "Enter the subject code: "
read code
The first echo command prompts the user to enter the subject code.
The read code command takes the user's input and stores it in the variable code.
Prompt for Subject Name:

bash
Copy code
echo "Enter the subject name: "
read name
Similarly, this echo command prompts the user for the subject name.
The read name command captures the input and stores it in the variable name.
Print Paper Details:

bash
Copy code
echo "\nSBE Paper Details:"
echo "Subject Code: $code"
echo "Subject Name: $name"
The first line intends to print a label "SBE Paper Details:", but the \n will not
work as intended in echo. To include a new line, you can either use echo -e (which
enables interpretation of backslash escapes) or just separate the two echo
commands:
bash
Copy code
echo -e "\nSBE Paper Details:"
or
bash
Copy code
echo ""
echo "SBE Paper Details:"
The next two lines print the subject code and subject name using the variables
$code and $name, respectively.
Summary
The script prompts the user to enter a subject code and subject name, then prints
those details as part of the "SBE Paper Details." The final output will summarize
the entered information.

TWO STR ARE EQUAL OR NOT:


Let’s break down the provided shell script step by step. This script checks whether
two input strings are equal.

Step-by-Step Explanation
Prompt for Input:

bash
Copy code
echo "Enter two strings to check whether they are equal"
This line prints a message to inform the user that they will be prompted to enter
two strings for comparison.

Read First String:

bash
Copy code
read -p "String 1: " str1
The read command here uses the -p option to prompt the user with "String 1: ".
The input is captured and stored in the variable str1.
Read Second String:

bash
Copy code
read -p "String 2: " str2
This line also uses the read command with the -p option to prompt the user for the
second string with "String 2: ".
The input is stored in the variable str2.
String Comparison:

bash
Copy code
if [ "$str1" == "$str2" ]; then
This line starts an if statement to compare the two strings.
The condition checks whether str1 is equal to str2 using ==.
The double quotes around the variables ensure that the comparison works even if the
strings contain spaces or are empty.
If Condition True:

bash
Copy code
echo "Both strings are equal"
If the condition evaluates to true (the strings are equal), this line executes and
prints a message indicating that the strings are equal.
If Condition False:

bash
Copy code
else
echo "Both strings are not equal"
fi
If the condition evaluates to false (the strings are not equal), this block
executes and prints a message indicating that the strings are not equal.
Summary
The script prompts the user for two strings, compares them, and outputs whether
they are equal or not.

Example Output
Assuming the user inputs:

String 1: hello
String 2: hello
The output will be:

sql
Copy code
Both strings are equal
If the user inputs:

String 1: hello
String 2: world
The output will be:

sql
Copy code
Both strings are not equal
Suggested Improvement
To make the string comparison more robust and compatible with different shells, you
might consider using = instead of ==, which is more widely supported in POSIX-
compliant shells:

bash
Copy code
if [ "$str1" = "$str2" ]; then
[22/10/2024 11:21 AM] : Here are some common abbreviations used in C programming,
particularly with the stdio.h library:

stdio.h Functions:

1. printf - Print Formatted


2. scanf - Scan Formatted
3. getchar - Get Character
4. putchar - Put Character
5. fgets - Get Formatted Text (string)
6. fputs - Put Formatted Text (string)
7. fopen - File Open
8. fclose - File Close
9. fread - File Read
10. fwrite - File Write

Data Types:

1. int - Integer
2. char - Character
3. float - Floating-point number
4. double - Double-precision floating-point number

Operators:

1. = - Assignment
2. == - Equal to
3. != - Not equal to
4. > - Greater than
5. < - Less than
6. >= - Greater than or equal to
7. <= - Less than or equal to
8. + - Addition
9. - - Subtraction
10. * - Multiplication
11. / - Division
12. % - Modulus (remainder)

Control Structures:

1. if - If statement
2. else - Else statement
3. for - For loop
4. while - While loop
5. do - Do-while loop
6. switch - Switch statement
7. case - Case statement
8. break - Break statement
9. continue - Continue statement

Other:

1. main - Main function


2. return - Return statement
3. void - Void data type (no return value)

These abbreviations are commonly used in C programming and can help improve code
readability and writing efficiency.
[22/10/2024 11:21 AM] : The full form of stdio.h is:

Standard Input/Output Header


[22/10/2024 11:22 AM] : conio.h is derived from:

- con: Console
- io: Input/Output
- .h: Header file
[22/10/2024 11:23 AM] : The name sys/types.h is derived from:

- sys: System (referring to system-level programming)


- types: Data types (referring to the file's purpose)
- .h: Header file (a file that contains function declarations and macro
definitions)
[22/10/2024 11:23 AM] : The name unistd.h is derived from:

- uni: Unix
- std: Standard
- .h: Header file
[22/10/2024 11:24 AM] : The name stdlib.h is derived from:

- std: Standard
- lib: Library
- .h: Header file

You might also like