You are on page 1of 25

PPS

Disks
Generally, a disk is a round plate on which data can be encoded. There are two basic
types of disks: magnetic disks and optical disks.

Magnetic Disks
On magnetic disks, data is encoded as microscopic magnetized needles on the disk's
surface. You can record and erase data on a magnetic disk any number of times, just as
you can with a cassette tape. Magnetic disks come in a number of different forms:

 floppy Disk: A typical 5¼-inch floppy disk can hold 360K or 1.2MB (megabytes).
3½-inch floppies normally store720K, 1.2MB or 1.44MB of data. Floppy disks or
obsolete today, and are found on older computer systems.
 Hard Disk: Hard disks can store anywhere from 20MB to more than 1-TB
(terabyte). Hard disks are also from 10 to 100 times faster than floppy disks.
 Removable Cartridge: Removable cartridges are hard disks encased in a metal
or plastic cartridge, so you can remove them just like a floppy disk. Removable
cartridges are very fast, though usually not as fast as fixed hard disks.
Optical Disks
Optical disks record data by burning microscopic holes in the surface of the disk with a
laser. To read the disk, another laser beam shines on the disk and detects the holes by
changes in the reflection pattern.

Optical disks come in three basic forms:

 CD-ROM: Most optical disks are read-only. When you purchase them, they are
already filled with data. You can read the data from a CD-ROM, but you cannot
modify, delete, or write new data.
 WORM: Stands for write-once, read-many. WORM disks can be written on once
and then read any number of times; however, you need a special WORM disk
drive to write data onto a WORM disk.
 erasable optical (EO): EO disks can be read to, written to, and erased just like
magnetic disks.
 The machine that spins a disk is called a disk drive. Within each disk drive is one
or more heads (often called read/write heads) that actually read and write data.
Memory
A memory is just like a human brain. It is used to store data and instructions. Computer
memory is the storage space in the computer, where data is to be processed and
instructions required for processing are stored. The memory is divided into large
number of small parts called cells. Each location or cell has a unique address, which
varies from zero to memory size minus one. For example, if the computer has 64k
words, then this memory unit has 64 * 1024 = 65536 memory locations. The address of
these locations varies from 0 to 65535.
Memory is primarily of three types −
 Cache Memory
 Primary Memory/Main Memory
 Secondary Memory
Cache Memory
Cache memory is a very highspeed semiconductor memory which can speed up the
CPU. It acts as a buffer between the CPU and the main memory. It is used to hold those
parts of data and program which are most frequently used by the CPU. The parts of
data and programs are transferred from the disk to cache memory by the operating
system, from where the CPU can access them.
Advantages
The advantages of cache memory are as follows −

 Cache memory is faster than main memory.


 It consumes less access time as compared to main memory.
 It stores the program that can be executed within a short period of time.
 It stores data for temporary use.

Disadvantages
The disadvantages of cache memory are as follows –
 Cache memory has limited capacity.
 It is very expensive.
Primary Memory (Main Memory)
Primary memory holds only those data and instructions on which the computer is
currently working. It has a limited capacity and data is lost when power is switched off. It
is generally made up of semiconductor device. These memories are not as fast as
registers. The data and instruction required to be processed resides in the main
memory. It is divided into two subcategories RAM and ROM.
1. Random Access Memory (RAM) –
 It is also called as read write memory or the main memory or the primary
memory.
 The programs and data that the CPU requires during execution of a program are
stored in this memory.
 It is a volatile memory as the data loses when the power is turned off.
 RAM is further classified into two types- SRAM (Static Random Access
Memory) and DRAM (Dynamic Random Access Memory).

2. Read Only Memory (ROM) –


 Stores crucial information essential to operate the system, like the program
essential to boot the computer.
 It is not volatile.
 Always retains its data.
 Used in embedded systems or where the programming needs no change.
 Used in calculators and peripheral devices.
 ROM is further classified into 4 types- ROM, PROM, EPROM, and EEPROM.
Types of Read Only Memory (ROM) –
1. PROM (Programmable read-only memory) – It can be programmed by user.
Once programmed, the data and instructions in it cannot be changed.
2. EPROM (Erasable Programmable read only memory) – It can be
reprogrammed. To erase data from it, expose it to ultra violet light. To reprogram
it, erase all the previous data.
3. EEPROM (Electrically erasable programmable read only memory) – The
data can be erased by applying electric field, no need of ultra violet light. We can
erase only portions of the chip.

Characteristics of Main Memory


 These are semiconductor memories.
 It is known as the main memory.
 Usually volatile memory.
 Data is lost in case power is switched off.
 It is the working memory of the computer.
 Faster than secondary memories.
 A computer cannot run without the primary memory.
Secondary Memory
This type of memory is also known as external memory or non-volatile. It is slower than
the main memory. These are used for storing data/information permanently. CPU
directly does not access these memories, instead they are accessed via input-output
routines. The contents of secondary memories are first transferred to the main memory,
and then the CPU can access it. For example, disk, CD-ROM, DVD, etc.
Characteristics of Secondary Memory
 These are magnetic and optical memories.
 It is known as the backup memory.
 It is a non-volatile memory.
 Data is permanently stored even if power is switched off.
 It is used for storage of data in a computer.
 Computer may run without the secondary memory.
 Slower than primary memories.
Processor
A processor, or "microprocessor," is a small chip that resides in computers and other
electronic devices. Its basic job is to receive input and provide the appropriate output.
While this may seem like a simple task, modern processors can handle trillions of
calculations per second.
The central processor of a computer is also known as the CPU, or "central processing
unit." This processor handles all the basic system instructions, such as processing
mouse and keyboard input and running applications. Most desktop computers contain a
CPU developed by either Intel or AMD, both of which use the x86 processor
architecture. Mobile devices, such as laptops and tablets may use Intel and AMD CPUs,
but can also use specific mobile processors developed by companies like ARM or
Apple.
Modern CPUs often include multiple processing cores, which work together to process
instructions. While these "cores" are contained in one physical unit, they are actually
individual processors. In fact, if you view your computer's performance with a system
monitoring utility like Windows Task Manager (Windows) or Activity Monitor (Mac OS
X), you will see separate graphs for each processor. Processors that include two cores
are called dual-core processors, while those with four cores are called quad-core
processors. Some high-end workstations contain multiple CPUs with multiple cores,
allowing a single machine to have eight, twelve, or even more processing cores.
Where a program is stored and executed
Programs are stored on secondary storage devices such as hard disks. When you
install a program on your computer, the program is actually copied to your hard disk.
But when you execute a program, the program is copied (loaded) from your hard disk to
the main memory, and that copy of the program is executed.
Operating System
An Operating System (OS) is an interface between a computer user and computer
hardware. An operating system is a software which performs all the basic tasks like file
management, memory management, process management, handling input and output,
and controlling peripheral devices such as disk drives and printers.

Some popular Operating Systems include Linux Operating System, Windows Operating
System, VMS, OS/400, AIX, z/OS, etc.

Definition
An operating system is a program that acts as an interface between the user and the
computer hardware and controls the execution of all kinds of programs.

Following are some of important functions of an operating System.

 Memory Management
 Processor Management
 Device Management
 File Management
 Security
 Control over system performance
 Job accounting
 Error detecting aids
 Coordination between other software and users
Compilers
Compiler, Computer software that translates (compiles) source code written in a high-
level language (e.g., C++) into a set of machine-language instructions that can be
understood by a digital computer’s CPU. Compilers are very large programs, with error-
checking and other abilities. Some compilers translate high-level language into an
intermediate assembly language, which is then translated (assembled) into machine
code by an assembly program or assembler. Other compilers generate machine
language directly.

Introduction to Programming Languages

A computer is a device that can accept human instruction, processes it and responds to
it or a computer is a computational device which is used to process the data under the
control of a computer program. Program is a sequence of instruction along with data.

The basic components of a computer are:

 Input unit
 Central Processing Unit (CPU)
 Output unit

The CPU is further divided into three parts-

 Memory unit
 Control unit
 Arithmetic Logic unit

A program is a set of instructions given to a computer to perform a specific operation. or


computer is a computational device which is used to process the data under the control
of a computer program. While executing the program, raw data is processed into a
desired output format. These computer programs are written in a programming
language which are high level languages. High level languages are nearly human
languages which are more complex than the computer understandable language which
are called machine language, or low level language. So after knowing the basics, we
are ready to create a very simple and basic program. Like we have different languages
to communicate with each other, likewise, we have different languages like C, C++, C#,
Java, python, etc to communicate with the computers. The computer only understands
binary language (the language of 0’s and 1’s) also called machine-understandable
language or low-level language but the programs we are going to write are in a high-
level language which is almost similar to human language.
Characteristics of a programming Language –
 A programming language must be simple, easy to learn and use, have good
readability and human recognizable.
 Abstraction is a must-have Characteristics for a programming language in which
ability to define the complex structure and then its degree of usability comes.
 A portable programming language is always preferred.
 Programming language’s efficiency must be high so that it can be easily
converted into a machine code and executed consumes little space in memory.
 A programming language should be well structured and documented so that it is
suitable for application development.
 Necessary tools for development, debugging, testing, maintenance of a program
must be provided by a programming language.
 A programming language should provide single environment known as Integrated
Development Environment (IDE).
 A programming language must be consistent in terms of syntax and semantics.
Algorithm
The word Algorithm means “a process or set of rules to be followed in calculations or
other problem-solving operations”. Therefore Algorithm refers to a set of
rules/instructions that step-by-step define how a work is to be executed upon in order to
get the expected results.
It can be understood by taking an example of cooking a new recipe. To cook a new
recipe, one reads the instructions and steps and execute them one by one, in the given
sequence. The result thus obtained is the new dish cooked perfectly. Similarly,
algorithms help to do a task in programming to get the expected output.
The Algorithm designed are language-independent, i.e. they are just plain instructions
that can be implemented in any language, and yet the output will be the same, as
expected.
Characteristics of Algorithm
 Clear and Unambiguous: Algorithm should be clear and unambiguous. Each of
its steps should be clear in all aspects and must lead to only one meaning.
 Well-Defined Inputs: If an algorithm says to take inputs, it should be well-
defined inputs.
 Well-Defined Outputs: The algorithm must clearly define what output will be
yielded and it should be well-defined as well.
 Finite-ness: The algorithm must be finite, i.e. it should not end up in an infinite
loops or similar.
 Feasible: The algorithm must be simple, generic and practical, such that it can
be executed upon will the available resources. It must not contain some future
technology, or anything.
 Language Independent: The Algorithm designed must be language-
independent, i.e. it must be just plain instructions that can be implemented in any
language, and yet the output will be same, as expected.
How to design an Algorithm
In order to write an algorithm, following things are needed as a pre-requisite:
 The problem that is to be solved by this algorithm.
 The constraints of the problem that must be considered while solving the
problem.
 The input to be taken to solve the problem.
 The output to be expected when the problem the is solved.
 The solution to this problem, in the given constraints.
Algorithm Flowchart
Pseudo code
 It’s simply an implementation of an algorithm in the form of annotations and informative
text written in plain English. It has no syntax like any of the programming language and
thus can’t be compiled or interpreted by the computer.
Examples:
1.. If student's grade is greater than or equal to 60

Print "passed"
else
Print "failed"
Variables
A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and
layout of the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C is case-sensitive. Based on the basic types explained in
the previous chapter, there will be the following basic variable types –
1. Char: Typically a single octet (one byte). It is an integer type.
2. Int: The most natural size of integer for the machine.
3. Float: A single-precision floating point value.
4. Double: A double-precision floating point value.
5. Void: Represents the absence of type.
Data Types
Data types in c refer to an extensive system used for declaring variables or functions of
different types. The type of a variable determines how much space it occupies in
storage and how the bit pattern stored is interpreted.

The types in C can be classified as follows −


1. Basic Types: They are arithmetic types and are further classified into: (a) integer
types and (b) floating-point types.
2. Enumerated types: They are again arithmetic types and they are used to define
variables that can only assign certain discrete integer values throughout the
program.
3. The type void: The type specifier void indicates that no value is available.
4. Derived types: They include (a) Pointer types, (b) Array types, (c) Structure
types, (d) Union types and (e) Function types.
Errors
Error is an illegal operation performed by the user which results in abnormal working of
the program.
Programming errors often remain undetected until the program is compiled or executed.
Some of the errors inhibit the program from getting compiled or executed. Thus errors
should be removed before compiling and executing.
The most common errors can be broadly classified as follows.
Syntax errors: Errors that occur when you violate the rules of writing C/C++ syntax
are known as syntax errors. This compiler error indicates something that must be fixed
before the code can be compiled. All these errors are detected by compiler and thus are
known as compile-time errors.
Most frequent syntax errors are:
 Missing Parenthesis (})
 Printing the value of variable without declaring it
 Missing semicolon like this:

Run-time Errors: Errors which occur during program execution(run-time) after


successful compilation are called run-time errors. One of the most common run-time
error is division by zero also known as Division error. These types of error are hard to
find as the compiler doesn’t point to the line at which the error occurs.

Linker Errors: These error occurs when after compilation we link the different object
files with main’s object using Ctrl+F9 key (RUN). These are errors generated when the
executable of the program cannot be generated. This may be due to wrong function
prototyping, incorrect header files. One of the most common linker error is writing Main
() instead of main ().

Logical Errors: On compilation and execution of a program, desired output is not


obtained when certain input values are given. These types of errors which provide
incorrect output but appears to be error free are called logical errors. These are one of
the most common errors done by beginners of programming.
These errors solely depend on the logical thinking of the programmer and are easy to
detect if we follow the line of execution and determine why the program takes that path
of execution.

Semantic errors: This error occurs when the statements written in the program are not
meaningful to the compiler.
Arrays
An array is a collection of items stored at contiguous memory locations. The idea is to
store multiple items of the same type together. This makes it easier to calculate the
position of each element by simply adding an offset to a base value, i.e., the memory
location of the first element of the array (generally denoted by the name of the array).
The base value is index 0 and the difference between the two indexes is the offset.

For simplicity, we can think of an array a fleet of stairs where on each step is placed a
value (let’s say one of your friends). Here, you can identify the location of any of your
friends by simply knowing the count of the step they are on.
Remember: “Location of next index depends on the data type we use”.

The above image can be looked at as a top-level view of a staircase where you are at
the base of the staircase. Each element can be uniquely identified by their index in the
array (in a similar way as you could identify your friends by the step on which they were
on in the above example).
Advantages of using arrays: 
 
 Arrays allow random access of elements. This makes accessing elements by
position faster.
 Arrays have better cache locality that can make a pretty big difference in
performance.

Disadvantages of using arrays:

You can’t change the size i.e. once you have declared the array you can’t change its
size because of static memory allocated to it.
Now if take an example of implementation of data structure Stack using array there are
some obvious flaw.
Let’s take the POP operation of the stack. The algorithm would go something like this.

1. Check for the stack underflow


2. Decrement the top by 1
Call by value in C
 In call by value method, the value of the actual parameters is copied into the
formal parameters. In other words, we can say that the value of the variable is
used in the function call in the call by value method.
 In call by value method, we cannot modify the value of the actual parameter by
the formal parameter.
 In call by value, different memory is allocated for actual and formal parameters
since the value of the actual parameter is copied into the formal parameter.
 The actual parameter is the argument which is used in the function call whereas
formal parameter is the argument which is used in the function definition.
Call by Value Example: Swapping the values of the two variables
1. #include <stdio.h>  
2. void swap(int , int); //prototype of the function   
3. int main()  
4. {  
5.     int a = 10;  
6.     int b = 20;   
7.     printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing th
e value of a and b in main  
8.     swap(a,b);  
9.     printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of act
ual parameters do not change by changing the formal parameters in call by value, a = 10, b 
= 20  
10. }  
11. void swap (int a, int b)  
12. {  
13.     int temp;   
14.     temp = a;  
15.     a=b;  
16.     b=temp;  
17.     printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal para
meters, a = 20, b = 10   
18. }  

Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

Call by reference in C
 In call by reference, the address of the variable is passed into the function call as
the actual parameter.
 The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.
 In call by reference, the memory allocation is similar for both formal parameters
and actual parameters. All the operations in the function are performed on the
value stored at the address of the actual parameters, and the modified value gets
stored at the same address.
Call by reference Example: Swapping the values of the two variables
1. #include <stdio.h>  
2. void swap(int *, int *); //prototype of the function   
3. int main()  
4. {  
5.     int a = 10;  
6.     int b = 20;   
7.     printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing th
e value of a and b in main  
8.     swap(&a,&b);  
9.     printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of ac
tual parameters do change in call by reference, a = 10, b = 20  
10. }  
11. void swap (int *a, int *b)  
12. {  
13.     int temp;   
14.     temp = *a;  
15.     *a=*b;  
16.     *b=temp;  
17.     printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal pa
rameters, a = 20, b = 10   
18. }  

Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

No Call by value Call by reference


.

1 A copy of the value is passed into the An address of value is passed into the function
function

2 Changes made inside the function is limited Changes made inside the function validate outside
to the function only. The values of the of the function also. The values of the actual
actual parameters do not change by parameters do change by changing the formal
changing the formal parameters. parameters.

3 Actual and formal arguments are created at Actual and formal arguments are created at the
the different memory location same memory location

Linear Search
Linear search in C to find whether a number is present in an array. If it's present, then at
what location it occurs. It is also known as a sequential search. It is straightforward and
works as follows: we compare each element with the element to search until we find it
or the list ends. Linear search for multiple occurrences and using a function.

Linear Search Program

#include <stdio.h>
int main()
{
  int array[100], search, c, n;

  printf("Enter number of elements in array\n");


  scanf("%d", &n);

  printf("Enter %d integer(s)\n", n);

  for (c = 0; c < n; c++)
    scanf("%d", &array[c]);

  printf("Enter a number to search\n");


  scanf("%d", &search);

  for (c = 0; c < n; c++)
  {
    if (array[c] == search)    /* If required element is found */
    {
      printf("%d is present at location %d.\n", search, c+1);
      break;
    }
  }
  if (c == n)
    printf("%d isn't present in the array.\n", search);

  return 0;
}

Output
Binary Search
Binary search in C language to find an element in a sorted array. If the array isn't sorted,
you must sort it using a sorting technique such as merge sort. If the element to search is
present in the list, then we print its location. The program assumes that the input
numbers are in ascending order.
Binary Search Program
#include <stdio.h>
int main()
{
  int c, first, last, middle, n, search, array[100];

  printf("Enter number of elements\n");


  scanf("%d", &n);

  printf("Enter %d integers\n", n);

  for (c = 0; c < n; c++)
    scanf("%d", &array[c]);

  printf("Enter value to find\n");


  scanf("%d", &search);

  first = 0;
  last = n - 1;
  middle = (first+last)/2;

  while (first <= last) {
    if (array[middle] < search)
      first = middle + 1;
    else if (array[middle] == search) {
      printf("%d found at location %d.\n", search, middle+1);
      break;
    }
    else
      last = middle - 1;

    middle = (first + last)/2;
  }
  if (first > last)
    printf("Not found! %d isn't present in the list.\n", search);

  return 0;
}

Output

Bubble Sort
Bubble sort in C to arrange numbers in ascending order, you can modify it for
descending order and can also sort strings. The bubble sort algorithm isn't efficient as
its average-case complexity is O(n2) and worst-case complexity is O(n2). There are
many fast sorting algorithms like Quicksort, heap-sort, and others. Sorting simplifies
problem-solving in computer programming.
Bubble Sort Program
#include <stdio.h>

int main()
{
  int array[100], n, c, d, swap;

  printf("Enter number of elements\n");


  scanf("%d", &n);
  printf("Enter %d integers\n", n);

  for (c = 0; c < n; c++)
    scanf("%d", &array[c]);

  for (c = 0 ; c < n - 1; c++)
  {
    for (d = 0 ; d < n - c - 1; d++)
    {
      if (array[d] > array[d+1]) /* For decreasing order use < */
      {
        swap       = array[d];
        array[d]   = array[d+1];
        array[d+1] = swap;
      }
    }
  }

  printf("Sorted list in ascending order:\n");

  for (c = 0; c < n; c++)
     printf("%d\n", array[c]);

  return 0;
}

Output

Insertion Sort
Insertion sort in C: C program for insertion sort to sort numbers. This code implements
insertion sort algorithm to arrange numbers of an array in ascending order. With a little
modification, it will arrange numbers in descending order. Best case complexity of
insertion sort is O(n), average and the worst case complexity is O(n2).
Insertion Sort Program
#include <stdio.h>

int main()
{
  int n, array[1000], c, d, t, flag = 0;

  printf("Enter number of elements\n");


  scanf("%d", &n);

  printf("Enter %d integers\n", n);

  for (c = 0; c < n; c++)
    scanf("%d", &array[c]);

  for (c = 1 ; c <= n - 1; c++) {
    t = array[c];

    for (d = c - 1 ; d >= 0; d--) {
      if (array[d] > t) {
        array[d+1] = array[d];
        flag = 1;
      }
      else
        break;
    }
    if (flag)
      array[d+1] = t;
  }

  printf("Sorted list in ascending order:\n");

  for (c = 0; c <= n - 1; c++) {
    printf("%d\n", array[c]);
  }

  return 0;
}

Output
Quick Sort
Quicksort is a divide and conquer algorithm. The steps are: 1) Pick an element from the
array, this element is called as pivot element. 2) Divide the unsorted array of elements
in two arrays with values less than the pivot come in the first sub array, while all
elements with values greater than the pivot come in the second sub-array (equal values
can go either way). This step is called the partition operation. 3) Recursively repeat the
step 2(until the sub-arrays are sorted) to the sub-array of elements with smaller values
and separately to the sub-array of elements with greater values. The same logic we
have implemented in the following C program.
Quick Sort Program
#include<stdio.h>
void quicksort(int number[25],int first,int last){
int i, j, pivot, temp;

if(first<last){
pivot=first;
i=first;
j=last;

while(i<j){
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}

temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);

}
}

int main(){
int i, count, number[25];

printf("How many elements are u going to enter?: ");


scanf("%d",&count);

printf("Enter %d elements: ", count);


for(i=0;i<count;i++)
scanf("%d",&number[i]);

quicksort(number,0,count-1);

printf("Order of Sorted elements: ");


for(i=0;i<count;i++)
printf(" %d",number[i]);

return 0;
}

Output

C program to find roots of a quadratic equation


It calculates the roots of a quadratic equation. Coefficients are assumed to be integers,
but roots may or may not be real. For a quadratic equation ax^2+ bx + c = 0 (a≠0),
discriminant (b*b-4*a*c) decides the nature of roots.
Roots of Quadratic Equation
#include <stdio.h>
#include <math.h>
int main()
{
  int a, b, c, d;
  double root1, root2;

  printf("Enter a, b and c where a*x*x + b*x + c = 0\n");


  scanf("%d%d%d", &a, &b, &c);

  d = b*b - 4*a*c;

  if (d < 0) { //complex roots
    printf("First root = %.2lf + i%.2lf\n", -b/(double)
(2*a), sqrt(-d)/(2*a));
    printf("Second root = %.2lf - i%.2lf\n", -b/(double)
(2*a), sqrt(-d)/(2*a));
  }
  else { //real roots
    root1 = (-b + sqrt(d))/(2*a);
    root2 = (-b - sqrt(d))/(2*a);

    printf("First root = %.2lf\n", root1);


    printf("Second root = %.2lf\n", root2);
  }

  return 0;
}

Output
Enter a, b and c where ax^2+bx+c=0
1 -2 1
First Root = 1.00
Second Root = 1.00

You might also like