C while and do…while Loop

In programming, loops are used to repeat a block of code until a specified condition is met.

C programming has three types of loops.

  1. for loop
  2. while loop
  3. do…while loop

In the previous tutorial, we learned about for loop. In this tutorial, we will learn about while and do..while loop.

while loop

The syntax of the while loop is:

while (testExpression) {
  // the body of the loop 

How while loop works?

  • The while loop evaluates the testExpression inside the parentheses ().
  • If testExpression is true, statements inside the body of while loop are executed. Then, testExpression is evaluated again.
  • The process goes on until testExpression is evaluated to false.
  • If testExpression is false, the loop terminates (ends).

To learn more about test expressions (when testExpression is evaluated to true and false), check out relational and logical operators.

Flowchart of while loop

flowchart of while loop in C programming
Working of while loop

Example 1: while loop

// Print numbers from 1 to 5

#include <stdio.h>
int main() {
  int i = 1;
  while (i <= 5) {
    printf("%d\n", i);

  return 0;



Here, we have initialized i to 1.

  1. When i = 1, the test expression i <= 5 is true. Hence, the body of the while loop is executed. This prints 1 on the screen and the value of i is increased to 2.
  2. Now, i = 2, the test expression i <= 5 is again true. The body of the while loop is executed again. This prints 2 on the screen and the value of i is increased to 3.
  3. This process goes on until i becomes 6. Then, the test expression i <= 5 will be false and the loop terminates.

do…while loop


The do..while loop is similar to the while loop with one important difference. The body of do...while loop is executed at least once. Only then, the test expression is evaluated.

The syntax of the do...while loop is:

do {
  // the body of the loop
while (testExpression);

How do…while loop works?

  • The body of do...while loop is executed once. Only then, the testExpression is evaluated.
  • If testExpression is true, the body of the loop is executed again and testExpression is evaluated once more.
  • This process goes on until testExpression becomes false.
  • If testExpression is false, the loop ends.

Flowchart of do…while Loop

do while loop flowchart in C programming
Working of do…while loop

Example 2: do…while loop

// Program to add numbers until the user enters zero

#include <stdio.h>
int main() {
  double number, sum = 0;

  // the body of the loop is executed at least once
  do {
    printf("Enter a number: ");
    scanf("%lf", &number);
    sum += number;
  while(number != 0.0);

  printf("Sum = %.2lf",sum);

  return 0;


Enter a number: 1.5
Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70

Here, we have used a do...while loop to prompt the user to enter a number. The loop works as long as the input number is not 0.

The do...while loop executes at least once i.e. the first iteration runs without checking the condition. The condition is checked only after the first iteration has been executed.

do {
  printf("Enter a number: ");
  scanf("%lf", &number);
  sum += number;
while(number != 0.0);

So, if the first input is a non-zero number, that number is added to the sum variable and the loop continues to the next iteration. This process is repeated until the user enters 0.

But if the first input is 0, there will be no second iteration of the loop and sum becomes 0.0.

Outside the loop, we print the value of sum.

Source https://www.programiz.com/c-programming/c-do-while-loops

Matrix multiplication algorithm

In this section we will see how to multiply two matrices. The matrix multiplication can only be performed, if it satisfies this condition. Suppose two matrices are A and B, and their dimensions are A (m x n) and B (p x q) the resultant matrix can be found if and only if n = p. Then the order of the resultant matrix C will be (m x q).


matrixMultiply(A, B):
Assume dimension of A is (m x n), dimension of B is (p x q)
   if n is not same as p, then exit
   otherwise define C matrix as (m x q)
   for i in range 0 to m - 1, do
      for j in range 0 to q – 1, do
         for k in range 0 to p, do
            C[i, j] = C[i, j] + (A[i, k] * A[k, j])


 Live Demo

using namespace std;
int main() {
   int product[10][10], r1=3, c1=3, r2=3, c2=3, i, j, k;
   int a[3][3] = {
      {2, 4, 1},
      {2, 3, 9},
      {3, 1, 8}
   int b[3][3] = {
      {1, 2, 3},
      {3, 6, 1},
      {2, 4, 7}
   if (c1 != r2) {
      cout<<"Column of first matrix should be equal to row of second matrix";
   } else {
      cout<<"The first matrix is:"<<endl;
      for(i=0; i<r1; ++i) {
         for(j=0; j<c1; ++j)
            cout<<a[i][j]<<" ";
      cout<<"The second matrix is:"<<endl;
      for(i=0; i<r2; ++i) {
         for(j=0; j<c2; ++j)
            cout<<b[i][j]<<" ";
      for(i=0; i<r1; ++i)
         for(j=0; j<c2; ++j) {
            product[i][j] = 0;
      for(i=0; i<r1; ++i)
         for(j=0; j<c2; ++j)
            for(k=0; k<c1; ++k) {
      cout<<"Product of the two matrices is:"<<endl;
      for(i=0; i<r1; ++i) {
         for(j=0; j<c2; ++j)
            cout<<product[i][j]<<" ";
   return 0;


The first matrix is:
2 4 1
2 3 9
3 1 8
The second matrix is:
1 2 3
3 6 1
2 4 7
Product of the two matrices is:
16 32 17
29 58 72
22 44 66

Source : https://www.tutorialspoint.com/matrix-multiplication-algorithm

What is Interrupt in OS?

An interrupt is a signal emitted by hardware or software when a process or an event needs immediate attention. It alerts the processor to a high-priority process requiring interruption of the current working process. In I/O devices, one of the bus control lines is dedicated for this purpose and is called the Interrupt Service Routine (ISR).

When a device raises an interrupt at the process, the processor first completes the execution of an instruction. Then it loads the Program Counter (PC) with the address of the first instruction of the ISR. Before loading the program counter with the address, the address of the interrupted instruction is moved to a temporary location. Therefore, after handling the interrupt, the processor can continue with the process.

While the processor is handling the interrupts, it must inform the device that its request has been recognized to stop sending the interrupt request signal. Also, saving the registers so that the interrupted process can be restored in the future increases the delay between the time an interrupt is received and the start of the execution of the ISR. This is called Interrupt Latency.

What is Interrupt in OS

A single computer can perform only one computer instruction at a time. But, because it can be interrupted, it can manage how programs or sets of instructions will be performed. This is known as multitasking. It allows the user to do many different things simultaneously, and the computer turns to manage the programs that the user starts. Of course, the computer operates at speeds that make it seem like all user tasks are being performed simultaneously.

An operating system usually has some code that is called an interrupt handler. The interrupt handler prioritizes the interrupts and saves them in a queue if more than one is waiting to be handled. The operating system has another little program called a scheduler that figures out which program to control next.

Types of Interrupt

Interrupt signals may be issued in response to hardware or software events. These are classified as hardware interrupts or software interrupts, respectively.

What is Interrupt in OS

1. Hardware Interrupts

A hardware interrupt is a condition related to the state of the hardware that may be signaled by an external hardware device, e.g., an interrupt request (IRQ) line on a PC, or detected by devices embedded in processor logic to communicate that the device needs attention from the operating system. For example, pressing a keyboard key or moving a mouse triggers hardware interrupts that cause the processor to read the keystroke or mouse position.

Hardware interrupts can arrive asynchronously for the processor clock and at any time during instruction execution. Consequently, all hardware interrupt signals are conditioned by synchronizing them to the processor clock and act only at instruction execution boundaries.

In many systems, each device is associated with a particular IRQ signal. This makes it possible to quickly determine which hardware device is requesting service and expedite servicing of that device.

On some older systems, all interrupts went to the same location, and the OS used specialized instruction to determine the highest priority unmasked interrupt outstanding. On contemporary systems, there is generally a distinct interrupt routine for each type of interrupt or each interrupts source, often implemented as one or more interrupt vector tables. Hardware interrupts are further classified into two types, such as:

  • Maskable Interrupts:Processors typically have an internal interrupt mask register which allows selective enabling and disabling of hardware interrupts. Each interrupt signal is associated with a bit in the mask register; on some systems, the interrupt is enabled when the bit is set and disabled when the bit is clear, while on others, a set bit disables the interrupt. When the interrupt is disabled, the associated interrupt signal will be ignored by the processor. Signals which are affected by the mask are called maskable interrupts.
    The interrupt mask does not affect some interrupt signals and therefore cannot be disabled; these are called non-maskable interrupts (NMI). NMIs indicate high priority events that need to be processed immediately and which cannot be ignored under any circumstances, such as the timeout signal from a watchdog timer.
    To mask an interrupt is to disable it, while to unmask an interrupt is to enable it.
  • Spurious Interrupts:
    A spurious interrupt is a hardware interrupt for which no source can be found. The term phantom interrupt or ghost interrupt may also use to describe this phenomenon. Spurious interrupts tend to be a problem with a wired-OR interrupt circuit attached to a level-sensitive processor input. Such interrupts may be difficult to identify when a system misbehaves.
    In a wired-OR circuit, parasitic capacitance charging/discharging through the interrupt line’s bias resistor will cause a small delay before the processor recognizes that the interrupt source has been cleared. If the interrupting device is cleared too late in the interrupt service routine (ISR), there won’t be enough time for the interrupt circuit to return to the quiescent state before the current instance of the ISR terminates. The result is the processor will think another interrupt is pending since the voltage at its interrupt request input will be not high or low enough to establish an unambiguous internal logic 1 or logic 0. The apparent interrupt will have no identifiable source, and hence this is called spurious.
    A spurious interrupt may result in system deadlock or other undefined operation if the ISR doesn’t account for the possibility of such an interrupt occurring. As spurious interrupts are mostly a problem with wired-OR interrupt circuits, good programming practice in such systems is for the ISR to check all interrupt sources for activity and take no action if none of the sources is interrupting.

2. Software Interrupts

The processor requests a software interrupt upon executing particular instructions or when certain conditions are met. Every software interrupt signal is associated with a particular interrupt handler.

A software interrupt may be intentionally caused by executing a special instruction that invokes an interrupt when executed by design. Such instructions function similarly to subroutine calls and are used for various purposes, such as requesting operating system services and interacting with device drivers.

Software interrupts may also be unexpectedly triggered by program execution errors. These interrupts are typically called traps or exceptions.

Handling Multiple Devices

When more than one device raises an interrupt request signal, additional information is needed to decide which device to consider first. The following methods are used to decide which device to select first,

What is Interrupt in OS

  1. Polling
    In polling, the first device encountered with the IRQ bit set is to be serviced first, and appropriate ISR is called to service the same. It is easy to implement, but a lot of time is wasted by interrogating the IRQ bit of all devices.
  2. Vectored Interrupts
    In vectored interrupts, a device requesting an interrupt identifies itself directly by sending a special code to the processor over the bus. This enables the processor to identify the device that generated the interrupt. The special code can be the starting address of the ISR or where the ISR is located in memory and is called the interrupt vector.
  3. Interrupt Nesting
    In this method, the I/O device is organized in a priority structure. Therefore, an interrupt request from a higher priority device is recognized, whereas a lower priority device is not. The processor accepts interrupts only from devices/processes having priority more than it.
    Processors priority is encoded in a few bits of PS (Process Status register), and it can be changed by program instructions that write into the PS. The processor is in supervised mode only while executing OS routines, and it switches to user mode before executing application programs.

Interrupt Handling

We know that the instruction cycle consists of fetch, decode, execute and read/write functions. After every instruction cycle, the processor will check for interrupts to be processed. If there is no interrupt in the system, it will go for the next instruction cycle, given by the instruction register. If there is an interrupt present, then it will trigger the interrupt handler. The handler will stop the present instruction that is processing and save its configuration in a register and load the program counter of the interrupt from a location given by the interrupt vector table.

After processing the interrupt by the processor, the interrupt handler will load the instruction and its configuration from the saved register. The process will start its processing where it’s left. This saves the old instruction processing configuration, and loading the new interrupt configuration is also called context switching. There are different types of interrupt handlers.

  1. First Level Interrupt Handler (FLIH) is a hard interrupt handler or fast interrupt handler. These interrupt handlers have more jitter while process execution, and they are mainly maskable interrupts.
  2. Second Level Interrupt Handler (SLIH) is a soft interrupt handler and slow interrupt handler. These interrupt handlers have less jitter.

Source : https://www.javatpoint.com/what-is-interrupt-in-os

File Management in Operating System


There can be a huge amount of files in our system. The operating system is responsible for managing the files. The operating system is used to manage computer files. The File Management in the operating system manages all files with various extensions.

Before we dive into file management in the operating system, let us first recap what a file is.

A file is a collection of specific information stored in a computer system’s memory. There are various types of files in our computer-like text files, images, audio/video files, etc. All these files have different extensions. The file management system is responsible for the efficient storage, retrieval, and manipulation of files.

What is File Management System in Operating System?

File management is one of the fundamental and crucial components of an operating system. The operating system manages computer system files. Operating systems control all files with various extensions.

File management is formally defined as manipulating files in a computer system, which includes creating, modifying, and deleting files. Therefore, one of the simple but crucial features offered by the operating system is file management. The operating system’s file management function entails software that handles or maintains files (binary, text, PDF, docs, audio, video, etc.) included in computer software.

The operating system’s file system has the ability to manage both single files and groups of files that are present in a computer system. All of the files on the computer system with different extensions(such as .exe, .pdf, .txt, .docx, etc.) are managed by the operating system’s file management.

Functions of File Management System in Operating System

The file management system is also known as the file system. It is responsible for file management in any system. The various functions involved in file management are as follows:

  • It is responsible for creating new files in the computer system and placing them in specific locations.
  • It is responsible for locating the existing files in the computer system.
  • It facilitates keeping the files in separate folders known as directories. These directories allow users to quickly search for files or organize files based on their types of uses.
  • It enables users to change the data of files or the name of files in directories.

Components of File Management in Operating System

The components of the file management system in the operating system are as follows:

  • File Attribute
  • File Operations
  • File Access Permissions
  • File Systems

File Attribute

It specifies file characteristics such as type, date of last modification, size, location on disk, and so on. File attributes assist the user in comprehending the value and location of files. It is used to describe all of the information about a specific file.

File Operations

It defines the actions that can be taken on a file, such as opening and closing it.

File Access Permissions

It specifies a file’s access permissions, such as read and writes. Without permission, a file cannot be accessed.

File Systems

It defines the logical method of storing files in a computer system. FAT and NTFS are two of the most commonly used file systems.

Operations on File Systems in Operating System

The various operation on files that can be performed by a user and is facilitated by the file management in the operating system are:

  • Creating a File
  • Reading a File
  • Writing a File
  • Deleting a File
  • Truncating a File

Creating a File

In order to create a new file, there should be ample space in the file system. The new file’s directory entry must then be created. This entry should include information about the file, such as its name, location, etc.

Reading a File

The system call must specify the file’s name and location to read from a file. A read pointer should be present at the location where the read should occur. The read pointer should be updated once the read process is completed.

Writing a File

To write to a file, the system call should specify the file’s name as well as the contents to be written. A write pointer should be present at the location where the write should occur. The write pointer should be updated after the write process is completed.

Deleting a File

In order to delete a file, it must be present in the directory. When the file is deleted, all the file space is deleted so it can be reused by other files.

Truncating a File

This removes the data from the file without erasing all of its attributes. Only the file length is reset to zero, and the contents of the file are erased. The remaining characteristics remain unchanged.

Source https://www.codingninjas.com/codestudio/library/file-management-in-operating-system

What Is OS ???

An operating system (OS) is the program that, after being initially loaded into the computer by a boot program, manages all of the other application programs in a computer. The application programs make use of the operating system by making requests for services through a defined application program interface (API). In addition, users can interact directly with the operating system through a user interface, such as a command-line interface (CLI) or a graphical UI (GUI).

Why use an operating system?

An operating system brings powerful benefits to computer software and software development. Without an operating system, every application would need to include its own UI, as well as the comprehensive code needed to handle all low-level functionality of the underlying computer, such as disk storage, network interfaces and so on. Considering the vast array of underlying hardware available, this would vastly bloat the size of every application and make software development impractical.

Instead, many common tasks, such as sending a network packet or displaying text on a standard output device, such as a display, can be offloaded to system software that serves as an intermediary between the applications and the hardware. The system software provides a consistent and repeatable way for applications to interact with the hardware without the applications needing to know any details about the hardware.

As long as each application accesses the same resources and services in the same way, that system software — the operating system — can service almost any number of applications. This vastly reduces the amount of time and coding required to develop and debug an application, while ensuring that users can control, configure and manage the system hardware through a common and well-understood interface.

Once installed, the operating system relies on a vast library of device drivers to tailor OS services to the specific hardware environment. Thus, every application may make a common call to a storage device, but the OS receives that call and uses the corresponding driver to translate the call into actions (commands) needed for the underlying hardware on that specific computer. Today, the operating system provides a comprehensive platform that identifies, configures and manages a range of hardware, including processors; memory devices and memory management; chipsets; storage; networking; port communication, such as Video Graphics Array (VGA), High-Definition Multimedia Interface (HDMI) and Universal Serial Bus (USB); and subsystem interfaces, such as Peripheral Component Interconnect Express (PCIe).

Functions of an operating system

An operating system provides three essential capabilities: It offers a UI through a CLI or GUI; it launches and manages the application execution; and it identifies and exposes system hardware resources to those applications — typically, through a standardized API.

UI. Every operating system requires a UI, enabling users and administrators to interact with the OS in order to set up, configure and even troubleshoot the operating system and its underlying hardware. There are two primary types of UI available: CLI and GUI.

The architecture of an OS

The CLI, or terminal mode window, provides a text-based interface where users rely on the traditional keyboard to enter specific commands, parameters and arguments related to specific tasks. The GUI, or desktop, provides a visual interface based on icons and symbols where users rely on gestures delivered by human interface devices, such as touchpads, touchscreens and mouse devices.

The GUI is most frequently used by casual or end users that are primarily interested in manipulating files and applications, such as double-clicking a file icon to open the file in its default application. The CLI remains popular among advanced users and system administrators that must handle a series of highly granular and repetitive commands on a regular basis, such as creating and running scripts to set up new personal computers (PCs) for employees.

Application management. An operating system handles the launch and management of every application. This typically supports an array of behaviors, including timesharing multiple processes, or threads, so that various tasks can share the available processors’ time; handling interruptions that applications produce to gain a processor’s immediate attention, ensuring there is enough memory to execute the application and its corresponding data without interfering with other processes; carrying out error handling that can gracefully remove an application’s processes; and performing memory management without disrupting other applications or the OS.

An operating system can also support APIs that enable applications to utilize OS and hardware functions without the need to know anything about the low-level OS or hardware state. As an example, a Windows API can enable a program to obtain input from a keyboard or mouse; create GUI elements, such as dialog windows and buttons; read and write files to a storage device; and more. Applications are almost always tailored to use the operating system on which the application intends to run.

Additionally, an operating system can perform the following services for applications:

  • In a multitasking operating system, where multiple programs can be running at the same time, the OS determines which applications should run in what order and how much time should be allowed for each application before giving another application a turn.
  • It handles input/output (I/O) to and from attached hardware devices, such as hard disks, printers and dial-up ports.
  • It sends messages to each application or interactive user — or to a system operator — about the status of operation and any errors that may have occurred.
  • It can offload the management of batch jobs — for example, printing — so that the initiating application is freed from this work.
  • On computers that can provide parallel processing, an operating system can manage how to divide the program so that it runs on more than one processor at a time.

All major computer platforms (hardware and software) require, and sometimes include, an operating system, and operating systems must be developed with different features to meet the specific needs of various form factors.

Device management. An operating system is responsible for identifying, configuring, and providing applications with common access to underlying computer hardware devices. As the OS recognizes and identifies hardware, the OS will install corresponding device drivers that enable the OS and applications running on the OS to use the devices without any specific knowledge of the hardware or devices.

An operating system is responsible for identifying the correct printer and installing the appropriate printer drivers so that an application needs to only make calls to the printer without having to use codes or commands that are specific to that printer — that is the operating system’s job. The situation is similar for other devices, such as USB ports; networking ports; graphics devices, such as graphics processing units (GPUs); motherboard chipsets; and storage devices, such as Serial-Attached SCSI (SAS) disk adapters and disks that are formatted with a suitable file system.

The OS identifies and configures physical and logical devices for service and typically records them in a standardized structure, such as Windows Registry. Device manufacturers periodically patch and update drivers, and the OS should update them to ensure best device performance and security. When devices are replaced, the OS also installs and configures new drivers.

Operating system types and examples

Although the fundamental roles of an operating system are ubiquitous, there are countless operating systems that serve a wide range of hardware and user needs.

General-purpose operating system. A general-purpose OS represents an array of operating systems intended to run a multitude of applications on a broad selection of hardware, enabling a user to run one or more applications or tasks simultaneously. A general-purpose OS can be installed on many different desktop and laptop models and run applications from accounting systems to databases to web browsers to games. General-purpose operating systems typically focus on process (thread) and hardware management to ensure that applications can reliably share the wide range of computing hardware present.

Common desktop operating systems include the following:

  • Windows is Microsoft’s flagship operating system, the de facto standard for home and business computers. Introduced in 1985, the GUI-based OS has been released in many versions since then. The user-friendly Windows 95 was largely responsible for the rapid development of personal computing.
  • Mac OS is the operating system for Apple’s Macintosh line of PCs and workstations.
  • Unix is a multiuser operating system designed for flexibility and adaptability. Originally developed in the 1970s, Unix was one of the first operating systems to be written in the C language.
  • Linux is a Unix-like operating system that was designed to provide PC users a free or low-cost alternative. Linux has a reputation as an efficient and fast-performing system.

Mobile operating system. Mobile operating systems are designed to accommodate the unique needs of mobile computing and communication-centric devices, such as smartphones and tablets. Mobile devices typically offer limited computing resources compared to traditional PCs, and the OS must be scaled back in size and complexity in order to minimize its own resource use, while ensuring adequate resources for one or more applications running on the device. Mobile operating systems tend to emphasize efficient performance, user responsiveness and close attention to data handling tasks, such as supporting media streaming. Apple iOS and Google Android are examples of mobile operating systems.

Embedded operating system. Not all computing devices are general purpose. A huge assortment of dedicated devices — including home digital assistants, automated teller machines (ATMs), airplane systems, retail point of sale (POS) terminals and internet of things (IoT) devices — includes computers that require an operating system. The principal difference is that the associated computing device only does one major thing, so the OS is highly stripped down and dedicated to both performance and resilience. The OS should run quickly, not crash, and handle all errors gracefully in order to continue operating in all circumstances. In most cases, the OS is provided on a chip that is incorporated into the actual device. A medical device used in a patient’s life support equipment, for example, will employ an embedded OS that must run reliably in order to keep the patient alive. Embedded Linux is one example of an embedded OS.

Network operating system. A network operating system (NOS) is another specialized OS intended to facilitate communication between devices operating on a local area network (LAN). A NOS provides the communication stack needed to understand network protocols in order to create, exchange and decompose network packets. Today, the concept of a specialized NOS is largely obsolete because other OS types largely handle network communication. Windows 10 and Windows Server 2019, for example, include comprehensive networking capabilities. The concept of a NOS is still used for some networking devices, such as routers, switches and firewalls, and manufacturers may employ proprietary NOSes, including Cisco Internetwork Operating System (IOS), RouterOS and ZyNOS.

Real-time operating system. When a computing device must interact with the real world within constant and repeatable time constraints, the device manufacturer may opt to use a real-time operating system (RTOS). For example, an industrial control system may direct the operations of a sprawling factory or power plant. Such a facility will produce signals from myriad sensors and also send signals to operate valves, actuators, motors and countless other devices. In these situations, the industrial control system must respond quickly and predictably to changing real-world conditions — otherwise, disaster may result. An RTOS must function without buffering, processing latencies and other delays, which are perfectly acceptable in other types of operating systems. Two examples of RTOSes include FreeRTOS and VxWorks.

The differences between operating system types are not absolute, and some operating systems can share characteristics of others. For example, general-purpose operating systems routinely include the networking capabilities found in a traditional NOS. Similarly, an embedded operating system commonly includes attributes of an RTOS, while a mobile operating system can still typically run numerous apps simultaneously like other general-purpose operating systems.

Source https://www.techtarget.com/whatis/definition/operating-system-OS