Skip to content

Programming and Operating System Concepts

An algorithm is a finite, ordered and unambiguous sequence of effective steps that accepts zero or more inputs, produces at least one output and terminates while solving a defined problem. A flowchart is a graphical representation of such logic using standard symbols joined by directed flow lines. The algorithm states what actions occur; the flowchart makes their sequence, decisions and loops visually traceable.

The essential properties of an algorithm are:

  1. Finiteness: execution ends after a finite number of steps.

  2. Definiteness: every step is precise and unambiguous.

  3. Input: it accepts zero or more supplied values.

  4. Output: it produces at least one result.

  5. Effectiveness: every operation is basic enough to be carried out in finite time.

  6. Order: the steps form a defined control sequence that solves the stated problem.

BasisAlgorithmFlowchart
FormNumbered natural-language steps or pseudocodeStandard graphical symbols and arrows
Preparation and modificationFast to write and editLogic changes may require redrawing
Main strengthPrecise detail suitable for coding and complexity analysisEasy visual communication and branch tracing
Main limitationLong logic may be difficult to visualizeLarge logic becomes crowded and page-dependent

Algorithm and flowchart compared.

A complete larger-of-two flowchart using terminal, I/O, process and decision symbols with labeled branches.

A complete larger-of-two flowchart using terminal, I/O, process and decision symbols with labeled branches.

the figure illustrates how directed arrows join terminal, input/output, process and decision symbols into executable order.

SymbolMeaning and correct use
Oval or rounded terminalStart or Stop
ParallelogramInput or output, such as Read or Print
RectangleProcess, calculation or assignment
DiamondDecision with labeled Yes/No or true/false exits
ArrowDirection and sequence of control
Small circleOn-page connector that avoids crossed or excessively long lines

Standard flowchart symbols.

START READ A, B IF A >= B THEN largest <- A ELSE largest <- B END IF PRINT largest STOP

The corresponding flowchart is terminal →\rightarrow input →\rightarrow decision. Each decision branch performs one assignment, the branches rejoin before output, and Stop has no outgoing arrow. Both representations must be tested with equal values as well as boundary inputs.

The task is to read one unsigned eight-bit word from Port A, invert every bit and write the resulting eight-bit word to Port B. Because a machine’s bitwise NOT may operate on an integer wider than eight bits, the result must be masked:

START CONFIGURE Port A as INPUT CONFIGURE Port B as OUTPUT A <- READ Port A A <- A AND 0xFF B <- (NOT A) AND 0xFF WRITE B to Port B STOP

The input mask discards any bits outside the port word; the output mask removes the high-order ones introduced when NOT is evaluated at a wider machine width. For

A=(a7 a6 a5 a4 a3 a2 a1 a0)2,A=(a_7\ a_6\ a_5\ a_4\ a_3\ a_2\ a_1\ a_0)_2,

the output field is

B=(a7‾ a6‾ a5‾ a4‾ a3‾ a2‾ a1‾ a0‾)2.B=(\overline{a_7}\ \overline{a_6}\ \overline{a_5}\ \overline{a_4}\ \overline{a_3}\ \overline{a_2}\ \overline{a_1}\ \overline{a_0})_2.

Flowchart for reading an eight-bit value from Port A, complementing it, and writing the result to Port B.

Flowchart for reading an eight-bit value from Port A, complementing it, and writing the result to Port B.

the figure uses terminal symbols for Start and Stop, parallelograms for port input/output, and a rectangle for the bitwise operation; the arrows give the exact execution order.

Data Types, Variables, Expressions and Arrays

Section titled “Data Types, Variables, Expressions and Arrays”

A data type specifies a value’s representation, storage size or range, and permitted operations. A variable is a named storage location whose value may change during execution, whereas a constant is a named value that the program must not modify after definition.

TypeStored informationExampleImportant limitation
IntegerWhole signed or unsigned numbercount = 25Fixed-width overflow
Real or floating pointApproximate fractional valuevoltage = 3.3Rounding error
CharacterOne encoded symbol’N’Encoding width varies
BooleanTrue/false conditionisReady = trueOnly logical states
StringSequence of characters"NTC"Length and encoding must be managed

Common data types and their limitations.

An expression combines operands–literals, variables or function results–with operators to produce a value. Arithmetic operators calculate, relational operators compare, logical operators combine conditions, and an assignment stores the resulting value. Parentheses should be used whenever the intended grouping might be unclear.

OrderOperator classTypical operators
1Parenthesized expression( )
2Unary operationsign and logical/bitwise NOT
3Multiplication, division and remainder*, /, %
4Addition and subtraction+, -
5Relational and equality comparison<, <=, >, >=, ==, !=
6Logical ANDAND or &&
7Logical OROR or

A common operator-precedence pattern, highest first.

Exact symbols and precedence vary by language. Under the common arithmetic rules, a+b×ca+b\times c multiplies first, while (a+b)×c(a+b)\times c adds first.

An array is an indexed collection of same-type elements, normally stored in contiguous locations. For a zero-based one-dimensional array AA with base address BB, element width ww bytes and index ii,

For a row-major two-dimensional array A[R][N]A[R][N], where each row has NN columns,

Arrays compactly represent tables, buffers and matrices. Their limitations are fixed size in many languages, costly insertion or deletion in the middle, homogeneous elements, and the need to keep every index within its valid range.

An operating system (OS) is system software that acts as an interface between users or applications and computer hardware. It abstracts devices into convenient services, allocates resources fairly and safely, and provides the controlled environment in which programs execute.

Position of the operating system between applications and hardware.

Position of the operating system between applications and hardware.

the figure places the OS between application software and hardware; users normally reach its services through applications and the user interface.

FunctionMain responsibilities
Process and CPU managementCreate and terminate processes, schedule ready work, and support synchronization and inter-process communication
Memory managementTrack and allocate RAM; provide paging, virtual memory, relocation and process protection
File and storage managementOrganize files and directories; perform create, read, write and delete operations; manage permissions, free space and recovery
Device and I/O managementControl devices through drivers, interrupts, buffering, caching and spooling
Security and protectionAuthenticate users, authorize access, isolate processes, audit actions and enforce least privilege
User and service interfaceSupply a CLI or GUI and system calls; provide networking and error-handling services to applications

Principal functions of an operating system.

Thus the OS is both a resource manager, deciding how hardware is shared, and an extended machine, hiding hardware-specific details behind convenient abstractions.

A process is a program in execution together with its current CPU state, address space and allocated resources. It moves through defined states as it is admitted, scheduled, blocked and completed.

Five-state process model and scheduler transitions.

Five-state process model and scheduler transitions.

In the figure, the long-term scheduler admits New work to Ready and the short-term scheduler dispatches a Ready process to Running. A timeout or preemption returns it to Ready; an I/O request blocks it in Waiting; event completion returns it to Ready, not directly to Running; and successful completion moves it to Terminated.

PolicyStrengthLimitation
First-Come, First-Served (FCFS)Simple and fair by arrival orderA long job can cause the convoy effect
Shortest Job First (SJF)Minimizes average waiting for a fixed ready set on one CPU when exact burst lengths are knownBurst prediction is difficult and long jobs may starve
Priority schedulingServes urgent work firstLow-priority processes may starve; aging is needed to counter this
Round RobinResponsive time sharingA very small quantum increases context-switch overhead

Common CPU scheduling policies.

For a completed process, turnaround time is always measured from arrival to completion. If SCPUS_{CPU} is its total CPU service and BB is its total blocked or I/O time, then

The common textbook formula waiting⁡=turnaround⁡−CPU burst⁡\operatorname{waiting}=\operatorname{turnaround}-\operatorname{CPU\ burst} is the special single-CPU-burst model with no blocked time. Scheduling comparisons must state whether arrival times, preemption, I/O and burst knowledge are assumed.

A thread is the smallest unit of CPU execution inside a process. Several threads in one process share that process’s memory and resources.

FeatureProcessThread
Resource ownershipOwn address space and resourcesShares its process’s resources
Creation overheadHigherLower
CommunicationRequires inter-process communicationEasier through shared memory
Failure isolationBetter isolationOne faulty thread can affect the whole process

Process and thread compared.

Operating systems use several memory-management schemes:

  • Contiguous allocation: gives each process one continuous memory block.

  • Paging: divides logical memory into fixed-size pages and physical memory into frames.

  • Segmentation: divides a program into logical segments.

  • Virtual memory: provides isolated virtual address spaces by mapping pages to physical frames; legal nonresident pages may use secondary backing storage, but virtual memory is not a physical RAM extension tier.

A file system organizes stored data into files and directories. Its key operations include create, open, read, write, close, delete and rename, together with access control, directory management, backup and recovery.

TypeDescriptionExample
Batch OSCollects jobs and executes them in batchesEarly mainframe systems
Time-sharing OSLets many users or processes share the CPU interactivelyUnix or Linux
Real-time OSResponds within strict time limitsEmbedded control systems
Distributed OSManages multiple networked computersDistributed computing systems
Mobile OSIs designed for mobile devicesAndroid or iOS

Major operating-system types.

Assembly Language: Merits, Limitations and Uses

Section titled “Assembly Language: Merits, Limitations and Uses”

Assembly language is a processor-specific low-level language in which mnemonic operation names and symbolic operands represent machine instructions. An assembler translates those statements into object or machine code, resolves labels to addresses, and reports syntax or range errors. A typical source statement has the form

opcodeoperand(s); comment

For example, MOV R1, #5 loads an immediate constant, ADD R1, R2 names an opcode and register operands, and JNZ LOOP branches to a symbolic label when the zero flag is clear.

AdvantagesDisadvantages
Direct control of registers, flags, memory and I/O portsInstruction set, registers and syntax are machine-dependent
Can be compact and permits deliberate instruction selection in measured critical routinesMore source statements and much longer development time
Direct expression of startup, interrupt and device-control operationsDifficult debugging, maintenance and team readability
Can exploit instructions unavailable in a high-level languageManual calling conventions and resource management invite errors

Merits and limitations of assembly language.

A short interrupt-service routine, for example, may save registers, read a device status port, acknowledge the interrupt and restore context with an explicit instruction sequence. Predictable worst-case latency still requires platform-specific analysis of caches, pipelines, memory waits, priorities and nested interrupts. Assembly is appropriate for boot code, context switching, tiny embedded targets and measured performance-critical sections. Compilers are normally preferred for complete applications because they support portability and optimization across large code bases.

Program development steps from problem definition through maintenance.

Program development steps from problem definition through maintenance.

the figure shows that implementation begins only after the problem and logic have been defined, and that useful software ends in documentation and continuing maintenance rather than at the first successful run.

StepPurpose
Problem definitionUnderstand exactly what must be solved
AnalysisIdentify inputs, outputs, constraints and required processing
Algorithm designPrepare the ordered step-by-step solution
Flowchart or pseudocodeRepresent and inspect logic before coding
CodingWrite the program in a selected programming language
Compilation or interpretationTranslate or execute the source and expose translation errors
TestingCheck correctness with representative, boundary and invalid data
DebuggingLocate, explain and remove errors
Documentation and maintenanceExplain design, code and use, then correct or adapt the program during its life

Program development lifecycle.

Algorithm efficiency is commonly expressed by time complexity, the growth of execution work as input size increases, and space complexity, the corresponding growth of memory use. Big-OO notation groups algorithms by dominant growth rather than machine-specific running time.

ComplexityMeaningExample
O(1)O(1)Constant timeAccess an array element by index
O(log⁡n)O(\log n)Logarithmic timeBinary search
O(n)O(n)Linear timeSequential search
O(nlog⁡n)O(n\log n)Linearithmic timeEfficient sorting
O(n2)O(n^2)Quadratic timeSimple nested-loop sorting

Common time-complexity classes.

Structured flowcharts and programs are built from three control structures.

StructureDescriptionTypical representation
SequenceSteps execute once, one after anotherConsecutive process blocks
SelectionA decision selects one pathif--else with labeled branches
IterationA body executes repeatedly while a condition controls repetitionwhile or for loop with a return arrow

Basic program control structures.

Error typeMeaningExample
Syntax errorViolates the language grammarMissing semicolon or bracket
Logical errorProgram runs but produces a wrong resultWrong formula
Runtime errorOccurs while the program executesDivide by zero or invalid memory access
Semantic errorA grammatically formed statement has an invalid meaningType mismatch

Principal programming-error types.

Debugging is the process of finding and correcting errors. Common techniques are to trace execution step by step, print or inspect intermediate values, use breakpoints and a debugger, and test boundary and invalid inputs. Testing reveals a failure; debugging locates its cause and verifies the repair.

FeatureCompilerInterpreterAssembler
InputHigh-level programHigh-level programAssembly program
Output or actionTranslates source, commonly to object/native code or intermediate bytecodeExecutes through an interpreter or runtime, possibly using parsed bytecode or JIT-compiled codeMaps mnemonics, operands and labels to object or machine representation
When translation occursPrimarily before normal execution; linking, loading or JIT stages may followProgressively or in runtime stages, not necessarily one source line at a timeBefore the assembled program executes
PerformanceDepends on generated code, runtime and workload; optimized AOT or JIT code can be fastRuntime dispatch may add overhead, but implementation and workload determine speedDepends on the emitted instruction sequence and target machine
Error reportingTranslation errors are usually found before execution; runtime failures remain possibleParsing may diagnose errors up front while dynamic failures appear during executionSyntax, symbol and encoding errors are reported during assembly

Language translators compared.

A compiler translates a high-level source program into another representation before a later execution stage. An interpreter executes program meaning under a runtime, which may itself compile bytecode or hot regions. A just-in-time (JIT) compiler combines runtime observation with compilation. An assembler maps processor-specific mnemonic statements and symbols to machine representation; these categories describe translation strategy, not a universal speed ranking.

  • Algorithm: must be finite, definite and effective, accept zero or more inputs, and produce at least one output.

  • Flowchart symbols: oval for Start/Stop, rectangle for process, diamond for decision, parallelogram for I/O, arrow for flow and small circle for an on-page connector.

  • Data: a variable can change; a constant cannot; an expression follows the language’s precedence rules.

  • Array addresses: one-dimensional B+iwB+iw; row-major two-dimensional B+(iN+j)wB+(iN+j)w.

  • Assembly: uses processor-specific mnemonics translated by an assembler and suits boot code, ISRs and small critical routines.

  • Operating system: manages CPU, memory, files, devices, security and the user/service interface.

  • Process states: New is admitted to Ready, Ready is dispatched to Running, Running may wait or be preempted, and completion terminates it.

  • Scheduling: FCFS, SJF, Priority and Round Robin; turnaround is completion minus arrival.

  • Program quality: analyze before coding, use sequence, selection and iteration, then test and debug syntax, semantic, runtime and logical errors.

  • Translators: compiler and interpreter accept high-level source; assembler accepts assembly source.