Unit I
Unit I
Introduction to components of a computer system: Memory, processor, I/O Devices, storage, operating
system, Concept of assembler, compiler, interpreter, loader and linker.
Idea of Algorithm: Representation of Algorithm, Flowchart, Pseudo code with examples, From algorithms
to programs, source code.
Programming Basics: Structure of C program, writing and executing the first C program, Syntax and logical
errors in compilation, object and executable code. Components of C language. Standard I/O in C,
Fundamental data types, Variables and memory locations, Storage classes.
Arithmetic expressions and precedence: Operators and expression using numeric and relational operators,
mixed operands, type conversion, logical operators, bit operations, assignment operator, operator
precedence and associativity.
Conditional Branching: Applying if and switch statements, nesting if and else, use of break and default with
switch.
Iteration and loops: use of while, do while and for loops, multiple loop variables, use of break and
continue statements. Functions: Introduction, types of functions, functions with array, passing parameters
to functions, call by value, call by reference, recursive functions.
Arrays: Array notation and representation, manipulating array elements, using multi-dimensional arrays.
Character arrays and strings, Structure, union, enumerated data types, Array of structures, Passing arrays
to functions.
Basic Algorithms: Searching &Basic Sorting Algorithms (Bubble, Insertion and Selection), Finding roots of
equations, Notion of order of complexity.
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 1|Page
Module – 1: (Introduction to Programming)
Introduction to components of a computer system: Memory, processor, I/O Devices, storage, operating system,
Concept of assembler, compiler, interpreter, loader and linker.
Idea of Algorithm: Representation of Algorithm, Flowchart, Pseudo code with examples, From algorithms to
programs, source code.
Programming Basics: Structure of C program, writing and executing the first C program, Syntax and logical errors
in compilation, object and executable code. Components of C language. Standard I/O in C, Fundamental data
types, Variables and memory locations, Storage classes.
Basics of Computer
What is a computer?
The term ‘computer’ is derived from the word ‘compute’ which means to calculate.
Definition
“A computer is an electronic device that processes data and converts it into information that is useful to people.”
OR
“A computer is an electronic device capable of performing arithmetic and logical operations. It can also store a
large volume of information.”
Example: Names of students and their marks in different subjects listed in random order.
Example: When the names of students are arranged in alphabetical order, total and average marks are
calculated & presented in a tabular form, it is information.
• Input It is the process of capturing or acquiring the information, or it is the process of accepting data or
information.
• Output It is the process by which the useful information is made available to the user by displaying it or
by printing a hard copy of it.
• Storing It is the process of storing or retaining the data or information or instruction, so that the user
can retain and retrieve it whenever required.
• Controlling It is the process of directing the manner and sequence in which all the operations are to be
performed.
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 2|Page
Figure shows the block diagram of a computer. It shows the functional components with flow of data and
instructions between them.
• Control Unit
• Memory Unit
• Input Unit
• Output Unit
1. The Control Unit Controls all the activities of the Computer. It sends commands and control signals and
finds the sequence of instruction to be executed.
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 3|Page
2. Memory Unit stores instruction and data and provides them to the various other units as and when
required. It is basically the working memory of the computer system. This memory unit is volatile,
i.e. it is temporary memory and nothing can be stored here permanently. The information is stored
in the main memory as long the computer is switched on or as long as it is required by the
computer.
3. ALU Consists of circuits for arithmetic operations (+,-,*, /) and logical operations (<,>,>=, <=, ==, !=)
4. Input device is used for transferring data from the users’ end to the computer.
5. Output Device is used to transfer processed information from the computer to the user in a way
required by the user.
Storage Devices:
1. Floppy disk
2. Hard disk
3. Compact disk
Memory
RAM: It is a temporary storage medium in a computer. The data to be processed by the computer are transferred
from a storage device or a keyboard to RAM results from an executed program are also stored in RAM. The data
stored will be erased when the computer is off.
ROM (Read only Memory): This is a non-volatile or data storage medium which stores start up programs
(operating systems). This essentially stores the BIOS (Basic Input Operating System)
Note: Basically, Computer System components communicate it binaries as (0’s & 1’s, 0 refers OFF state, 1 refer ON
state)
Secondary memory
Secondary storage, secondary memory or external memory, is a non-volatile memory (does not lose stored data
when the device is powered down) that is not directly accessible by the CPU, because it is not accessed via the
input/output channels (it is an external device).
Hard disk
A magnetic disk on which you can store computer data. The term hard is used to distinguish it from a soft, or
floppy, disk. Hard disks hold more data and are faster than floppy disks. A hard disk, for example, can store
anywhere from 10 to more than 100 gigabytes, whereas most floppies have a maximum storage capacity of 1.4
megabytes.
A single hard disk usually consists of several platters. Each platter requires two read/write heads, one for each
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 4|Page
side. All the read/write heads are attached to a single access arm so that they cannot move independently. Each
platter has the same number of tracks, and a track location that cuts across all platters is called a cylinder. For
example, a typical 84-megabyte hard disk for a PC might have two platters (four sides) and 1,053 cylinders.
Advantages of computers:
1. High speed: Computers have the ability to perform routine tasks at a greater speed than human beings. They
can perform millions of calculations in seconds.
2. Accuracy: Computers are used to perform tasks in a way that ensures accuracy.
3. Storage: Computers can store large amount of information. Any item of data or any instruction stored in the
memory can be retrieved by the computer at lightning speeds.
4. Automation: Computers can be instructed to perform complex tasks automatically (which increases the
productivity).
5. Diligence: Computers can perform the same task repeatedly & with the same accuracy without getting tired.
6. Versatility: Computers are flexible to perform both simple and complex tasks.
7. Cost effectiveness: Computers reduce the amount of paper work and human effort, thereby reducing
costs.
Limitations of computers:
1. Computers need clear & complete instructions to perform a task accurately. If the instructions are not clear
& complete, the computer will not produce the required result.
Hardware: Hardware refers to the physical elements of a computer. This is also sometime called the machinery
or the equipment of the computer. Examples of hardware in a computer are the keyboard, the monitor, the
mouse and the central processing unit (CPU).
Example: input and output devices, processors, circuits and the cables etc.
Software: commonly known as programs or apps, consists of all the instructions that tell the hardware how to
perform a task. These instructions come from a software developer in the form that will be accepted by the
platform (operating system + CPU) that they are based on. For example, a program that is designed for the
Windows operating system will only work for that specific operating system. Compatibility of software will
vary as the design of the software and the operating system differ
Operating System
• A program that acts as an intermediary between a user of a computer and the computer hardware.
• 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.
• OS controls execution of programs to prevent errors and improper use of the computer.
• OS manages all resources and decides between conflicting requests for efficient and fair resource use.
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 5|Page
Functions of an Operating System
COMMUNICATIO MEMORY
N MANAGEMENT
• Provide an interface between the computer hardware and the programmer that simplifies and makes
feasible for coding, creation, debugging and execution of application programs.
• Provide access to the compiler for translating the user program from high level language to machine
language.
Device Management
File Management
Memory Management
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 6|Page
• Controls transfer of programs in and out of memory.
• Control the allocation and use of the computing system's memory among the various users and tasks.
Handling Users
• Maintain security and access rights of users with the help of password or access right information.
Command Interpretation
• Read, check, interpret and execute user commands like copy, print, rename, dir, type, delete, etc. ·
• Compute the resource allocation time for different users, keep record of login and logout times for users
etc.
Security ·
• Provide data security among various users and prevent unauthorized access to any of the resources.
Communication
• The disk operating system (DOS) may seem out of date, it is still widely used and deserves to be included
in this discussion.
• DOS originally came with the appearance of the IBM PC, which was the first personal computer.
• DOS came with two versions. The first was PC DOS, which IBM released with its computer. The other was
Microsoft’s version of DOS, known as MS-DOS (Microsoft DOS), which was used on millions of IBM-
compatible PCs or clones.
MS-DOS Commands
Disk Commands
1. FORMAT: Prepares a disk so that MS-DOS can use it. Formatting a disk erases all the information on the
disk, so be careful. Example: FORMAT A:
2. CHKDSK: Checks for problems and repairs corrupted disks. A disk can sometimes get corrupted when, for
example, the power is turned off while a program is still running. Example: CHKDSK C:
3. DISKCOPY: Duplicates diskettes. Use this command to copy important diskettes, like newly purchased
programs. Example: DISKCOPY A: B:
Linux is one of popular version of UNIX operating System. It is open source as its source code is freely available. It
is free to use. Linux was designed considering UNIX compatibility. It's functionality list is quite similar to that of
UNIX.
Basic Features
Following are some of the important features of Linux Operating System.
• Portable - Portability means softwares can works on different types of hardware in same way. Linux
kernel and application programs supports their installation on any kind of hardware platform.
• Open Source - Linux source code is freely available and it is community-based development project.
Multiple teams work in collaboration to enhance the capability of Linux operating system and it is
continuously evolving.
• Multi-User - Linux is a multiuser system means multiple users can access system resources like memory/
ram/ application programs at same time.
• Multiprogramming - Linux is a multiprogramming system means multiple applications can run at same
time.
• Hierarchical File System - Linux provides a standard file structure in which system files/ user files are
arranged.
• Shell - Linux provides a special interpreter program which can be used to execute commands of the
operating system. It can be used to do various types of operations, call application programs etc.
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 8|Page
• Security - Linux provides user security using authentication features like password protection/ controlled
access to specific files/ encryption of data.
• Hardware layer - Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc).
• Kernel - Core component of Operating System, interacts directly with hardware, provides low level
services to upper layer components.
• Shell - An interface to kernel, hiding complexity of kernel's functions from users. Takes commands from
user and executes kernel's functions.
• Utilities - Utility programs giving user most of the functionalities of an operating systems
We can use cd command for changing directories suppose you are in the ‘asia’Directory and now you want to go
its subdirectory named ‘india’, you type ‘cd india’
We use ls command to see a list of the files and directories located in current directory. Suppose you are in the
named ‘websites’ and you type ls, a list will appear that shows the content of websites directory.
ls –lt (shows newest or last modified file and directory first) ls –a (shows
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 9|Page
After issuing pwd command you’ll see the complete path of the directory you are currently in. This command is
very helpful when you forget which directory you’ve changed.
4. cp -r /Source Of Copy /Destination Of Copied Data Using “*” we can copy everything under /websites/
Directory.
7. cat (read text files) Using cat command we can read text file contents without opening it.
8. grep ( grep searches inside files and then print out them on shell window)
Suppose i have huge name list save in this “NameList.txt” file. I want to search name “Haider” from this list then i
use grep command to search specific word from this whole file Like
Machine language
• Machine language is the basic low-level programming language designed to be recognized by a computer.
• Actually, the language is written in a binary code of 0s and 1s that represent electric impulses or off and
on electrical states respectively. A group of such digits is called an instruction and it is translated into a
command that the central processing unit or CPU understands.
• More specifically, instructions are organized in patterns of 0s and 1s in various lengths such as 16, 24, 32,
and 64 digits or bits, representing specific tasks such as storing or transferring data.
• An instruction is made up of two parts: the operator or opcode and the operand. The first few bits of an
instruction are the "operator or opcode," whose role is to specify the kind of operation that needs to be
performed. The rest of the bits are the "operand," whose role is to indicate the location where the
operation is to be performed.
Assembly Language
• An assembly language is a low-level programming language for microprocessors and other programmable
devices.
• It is not just a single language, but rather a group of languages.
• Assembly language implements a symbolic representation of the machine code needed to program a
given CPU architecture.
• Assembly language is the most basic programming language available for any processor. With assembly
language, a programmer works only with operations that are implemented directly on the physical CPU.
• Assembly languages generally lack high-level conveniences such as variables and functions, and they are
not portable between various families of processors.
• It has the same structures and set of commands as machine language, but it allows a programmer to use
names instead of numbers.
• This language is still useful for programmers when speed is necessary or when they need to carry out an
operation that is not possible in high-level languages.
• A high-level language is a computer programming language that isn't limited by the computer, designed
for a specific job, and is easier to understand.
• It is more like human language and less like machine language.
• Programs written in a high-level language must be translated into machine language by a compiler or
interpreter.
• The first high-level languages were introduced in the 1950's. Today, there are many high-level languages
in use, including BASIC, C, C++, Cobol, FORTRAN, Java, Pascal, Perl, PHP, Python, Ruby, and Visual Basic.
• Assembler is a software or a tool that translates Assembly language to machine code. So, an assembler is
a type of a compiler and the source code is written in Assembly language.
• Assembly is a human readable language but it typically has a one to one relationship with the
corresponding machine code.
• Therefore, an assembler is said to perform isomorphic (one to one mapping) translation.
• Advanced assemblers provide additional features that support program development and debugging
processes. For example, the type of assemblers called macro assemblers provides a macro facility.
Compiler
• A compiler is a piece of code that translates the high-level language into machine language.
• When a user writes a code in a high-level language such as C, Java and wants it to execute, a specific
compiler which is designed for C is used before it will be executed.
• The compiler scans the entire program first and then translates it into machine code which will be
executed by the computer processor and the corresponding tasks will be performed.
• Shown in the figure is basic outline of the compilation process, here program written in higher level
language is known as source program and the converted one is called object program.
Loader
• Loader is a program that loads machine codes of a program into the system memory.
• In Computing, a loader is the part of an Operating System that is responsible for loading programs.
• It is one of the essential stages in the process of starting a program. Because it places programs into
memory and prepares them for execution.
• Loading a program involves reading the contents of executable file into memory.
• Once loading is complete, the operating system starts the program by passing control to the loaded
program code.
• All operating systems that support program loading have loaders. In many operating systems the loader is
permanently resident in memory.
Linker
• In high level languages, some built in header files or libraries are stored.
• These libraries are predefined and these contain basic functions which are essential for executing the
program.
• These functions are linked to the libraries by a program called Linker. If linker does not find a library of a
function then it informs to compiler and then compiler generates an error.
• The compiler automatically invokes the linker as the last step in compiling a program.
• Not built in libraries, it also links the user defined functions to the user defined libraries. Usually a longer
program is divided into smaller subprograms called modules. And these modules must be combined to
execute the program.
• The process of combining the modules is done by the linker.
Properties of algorithm
• The steps used in algorithm must be unambiguous and precisely defined.
• The uncertainty about the instruction to be executed next, should be avoided.
• The steps used in algorithm should be finite and the algorithm should be terminated, that is, it cannot
be open-ended.
• The execution of the algorithm should conclude after a finite number of steps.
• The algorithm must be general enough to deal with any situation.
Example: Let us write an algorithm to calculate the addition of two given numbers.
Algorithm
Step 1: Start
Display C.
Step 5: Stop
Algorithm
B,C
Step2: If A > B is True, then check whether A > C, if yes then A is greatest otherwise C is greatest
Step3: If A > B is False, then check whether B > C, if yes then B is greatest otherwise C is greatest
Step4: Stop
Flow Chart
• A flowchart depicts pictorially the sequence in which instructions are carried out in an algorithm.
• Pictorial representation of an algorithm is called flowchart.
• Flow charts are used not only as aids in developing algorithms but also to document algorithms.
• Flowcharts are used in analyzing, designing, documenting or managing a process or program in various
fields.
• When better communication is needed between people involved with the same process.
• To document a process.
iii. Rectangles are used to indicate any processing operation such as storage and Arithmetic.
iv. Decision based on a question. The question is written in the diamond. More than one arrow goes out of
the diamond, each one showing the direction the process takes for a given answer to the question. (Often
the answers are “ yes” and “ no.”)
v. Rectangles with rounded ends are used to indicate the beginning or end points of a procedure.
vi. A circle is used to join different parts of a flowchart. This is called a connector.
Flowchart Disadvantages
• Hard to modify
• Need special software
• Structured design elements nota all implemented.
Understanding Pseudocode
• Pseudocode makes creating programs easier.
• Programs can be complex and long; preparation is the key. For years, flowcharts were used to map out
programs before writing one line of code in a language.
• However, they were difficult to modify and with the advancement of programming languages, it was
difficult to display all parts of a program with a flowchart
Examples of Pseudocode
1. To create a program to add 2 numbers together and then display the result.
Start Program
Enter two numbers, A, B
Add the numbers together
Print Sum
End Program
2. To compute the area of a rectangle
Get the length, l, and width, w
Compute the area = l*w
Display the area
3. If student's grade is greater than or equal to 60
Print "passed"
else
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 14 | P a g e
Print "failed"
4. Find the biggest of three (3) Numbers
BEGIN
NUMBER num1, num2, num3
INPUT num1
INPUT num2
INPUT num3
IF num1>num2 AND num1>num3 THEN
OUTPUT num1+ "is higher"
ELSE IF num2 > num3 THEN
OUTPUT num2 + "is higher"
ELSE
OUTPUT num3+ "is higher"
ENDIF
END
Source Code
• Source code is the list of human readable instructions that a programmer writes after in programming
language.
• Source code is run through compiler to turn it into machine code, also called object code that a computer
can understand and execute.
• Object code consists of primarily of ones and zeros, so is not human readable.
• Source code is the program written in particular programming language like C, Java etc.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int r;
int A;
printf(“Enter Radius”);
scanf(“%d”,&r);
A=3.14*r*r;
printf(“\nArea =%f”,A);
getch();
}
Documentation Section
Link Section
Definition Section
Global Declaration Section
main()
{
Declaration Section
Executable part
}
Subprogram section
Function 1
Documentation Section: It consists of a set of comment lines giving the name of the program and other details.
Link Section: It provides instructions to the compiler to link functions from the system library. C program depends
upon some header files for function definition that are used in the program. Each header file has extension ‘.h’. The
header files are included at the beginning of the program in the C language. These files should be included using
#include directive as given below
Example:
#include
(This will find header file in standard directory)
Definition Section: It defines all symbolic constants.
Global Declaration Section: There are some variables and those variables are declared in this section that is outside
of all functions.
main() function: Every C program must have one main() function section. int main(void): This is the function
definition for main().Parenthesis followed to main is to tell the user again that main() is a function. Int main(void)
function return an integer.
void main(void): This function takes no arguments and return nothing.
Declaration and Executable Part: It is user defined function. The Opening braces sometimes called logical start and
Closing braces known as logical end of the program.
-Declaration Part declares all the variables used in the executable part. There should be at least one statement in
the executable part which contains instructions to perform certain task. The declaration and executable part must
appear between the opening and closing braces. All statements in the declaration part should end with the
semicolon.
Subprogram Section: contains all the user defined functions that are called in the main function.
EXAMPLE PROGRAM:
Syntax Errors:
• Errors that occur when you violate the rules of writing 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
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 16 | P a g e
• Missing semicolon like this:
// C program to illustrate
// syntax error
#include<stdio.h>
void main()
{
int x = 10;
printf("%d", x) // semicolon missed
}
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.
• Here are some examples of mistakes which lead to logical errors:
o using the wrong variable name
o indenting a block to the wrong level
o using integer division instead of floating-point division
o getting operator precedence wrong
o making a mistake in a boolean expression
o off-by-one, and other numerical errors
Components of C Language
Character Set: The characters that can be used to form words and expressions depends upon the computer to
which the program is run
The Characters in C are
1. Letters:
a. Uppercase Letters: A,B,C…
b. Lowercase Letters: a, b, c…
2. Digits: 0,1,2…9
3. Special Characters: @#$% ..etc.
4. White Space Characters:
i. Blank space Character
ii. Horizontal tab space character ‘\t’
iii. New line character ‘\n’
C Tokens:
Individual words and punctuation marks are characters. In a C program the smallest individual units are known as
C tokens. C language has six types of tokens.
Keywords in C Programming
2. Identifiers: These are the names of variables, functions and arrays. They are the user defined
3. Constants: constants in “C” are applicable to the values which not change during the execution of a
program.
Integer Constants:
• Sequence of number 0-9 without decimal points, fractional part or any other symbols.
• It requires two or four bytes, can be +ve, -ve or Zero the number without a sign is as positive. Eg: -10, +20,
40
Character Constants
Single character constants: A single character constants are given within a pair of single quote mark. Eg : ‘a’,
‘8’ etc.
String Constant: These are the sequence of character within double quote marks Eg : “Straight”, “India”, “4”
4. Variables:
void datatype:
• A void type has no value this is usually used to specify the return type of function;
• This function does not return any value to calling function.
Example: void main()
{
}
Storage Class:
• A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program.
• There are following storage classes which can be used in a C Program
• auto
• register
• static
• extern
auto - Storage Class: auto is the default storage class for all local variables.
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 21 | P a g e
void main()
{
int Count;
auto int Month;
}
The example above defines two variables with the same storage class. auto can only be used within functions, i.e.
local variables.
register - Storage Class:
• register is used to define local variables that should be stored in a register instead of RAM.
• This means that the variable has a maximum size equal to the register size (usually one word) and can’t have
the unary '&' operator applied to it (as it does not have a memory location).
void main()
{
register int Miles;
}
• Register should only be used for variables that require quick access - such as counters.
• It should also be noted that defining 'register' goes not mean that the variable will be stored in a register.
• It means that it MIGHT be stored in a register - depending on hardware and implementation restrictions.
#include<stdio.h>
static int Count;
int Road;
void main()
{
printf("%d\n", Road);
}
• static variables can be 'seen' within all functions in this source file. At link time, the static variables defined
here will not be seen by the object modules that are brought in.
• static can also be defined within a function. If this is done the variable is initialised at run time but is not
reinitialized when the function is called. This inside a function static variable retains its value during various
calls.
void func(void);
static count=10; /* Global variable - static is the default */
#include<stdio.h>
void main()
{
while (count--)
{
func();
}
}
void func( void )
{
static i = 5;
i++;
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 22 | P a g e
printf("i is %d and count is %d\n", i, count);
}
Output:
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
extern - Storage Class
• extern is used to give a reference of a global variable that is visible to ALL the program files. When you use
'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that
has been previously defined.
• When you have multiple files and you define a global variable or function which will be used in other files
also, then extern will be used in another file to give reference of defined variable or function. Just for
understanding extern is used to declare a global variable or function in another files.
File 1: main.c
int count=5;
main() PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura First Year (CS-A and CS-B) 20 | Page
{
write_extern();
}
File 2: write.c
void write_extern(void);
extern int count;
void write_extern(void)
{
printf("count is %i\n", count);
}
Here extern keyword is being used to declare count in another file.