Notes Chapater 1 and 2
Notes Chapater 1 and 2
on
Operating System
Chapter 1
Operating System
An operating system is the most important software that runs on a computer. It manages the
computer's memory and processes, as well as all of its software and hardware. It also allows
you to communicate with the computer without knowing how to speak the computer's
language. Without an operating system, a computer is useless. An Operating System (OS) is a
software that acts as an interface between computer hardware components and the user.
Every computer system must have at least one operating system to run other programs.
Applications like Browsers, MS Office, Notepad Games, etc., need some environment to run and
perform its tasks.
The OS helps you to communicate with the computer without knowing how to speak the
computer’s language. It is not possible for the user to use any computer or mobile device
without having an operating system.
#Topic
Operating Systems have evolved over the years. So, their evolution through the years can be
mapped using generations of operating systems. There are four generations of operating
systems. These can be described as follows −
The First Generation ( 1945 - 1955 ): Vacuum Tubes and Plugboards
Digital computers were not constructed until the second world war. Calculating engines with
mechanical relays were built at that time. However, the mechanical relays were very slow and
were later replaced with vacuum tubes. These machines were enormous but were still very
slow.
These early computers were designed, built and maintained by a single group of people.
Programming languages were unknown and there were no operating systems so all the
programming was done in machine language. All the problems were simple numerical
calculations.
By the 1950’s punch cards were introduced and this improved the computer system. Instead of
using plugboards, programs were written on cards and read into the system.
Transistors led to the development of the computer systems that could be manufactured and
sold to paying customers. These machines were known as mainframes and were locked in air-
conditioned computer rooms with staff to operate them.
The Batch System was introduced to reduce the wasted time in the computer. A tray full of jobs
was collected in the input room and read into the magnetic tape. After that, the tape was
rewound and mounted on a tape drive. Then the batch operating system was loaded in which
read the first job from
the tape and ran it. The output was written on the second tape. After the whole batch was
done, the input and output tapes were removed and the output tape was printed.
Until the 1960’s, there were two types of computer systems i.e the scientific and the
commercial computers. These were combined by IBM in the System/360. This used integrated
circuits and provided a major price and performance advantage over the second generation
systems.
The third generation operating systems also introduced multiprogramming. This meant that the
processor was not idle while a job was completing its I/O operation. Another job was scheduled
on the processor so that its time would not be wasted.
Personal Computers were easy to create with the development of large-scale integrated circuits.
These were chips containing thousands of transistors on a square centimeter of silicon. Because
of these, microcomputers were much cheaper than minicomputers and that made it possible
for a single individual to own one of them.
The advent of personal computers also led to the growth of networks. This created network
operating systems and distributed operating systems. The users were aware of a network while
using a network operating system and could log in to remote machines and copy files from one
machine to another.
#Topic
An Operating System performs all the basic tasks like managing files, processes, and memory.
Thus operating system acts as the manager of all the resources, i.e. resource manager. Thus,
the operating system becomes an interface between user and machine.
Types of Operating Systems: Some widely used operating systems are as follows-
● It is very difficult to guess or know the time required for any job to complete. Processors
of the batch systems know how long the job would be when it is in queue
● It is sometimes costly
● The other jobs will have to wait for an unknown time if any job fails
Examples of Batch based Operating System: Payroll System, Bank Statements, etc.
● Reliability problem
● One must have to take care of the security and integrity of user programs and data
● Failure of one will not affect the other network communication, as all systems are
independent from each other
● Since resources are being shared, computation is highly fast and durable
● These systems are easily scalable as many systems can be easily added to the network
● To establish distributed systems the language which is used are not well defined yet
● These types of systems are not readily available as they are very expensive. Not only
that the underlying software is highly complex and not understood well yet
● New technologies and hardware up-gradation are easily integrated into the system
● Server access is possible remotely from different locations and types of systems
Examples of Network Operating System are: Microsoft Windows Server 2003, Microsoft
Windows Server 2008, UNIX, Linux, Mac OS X, Novell NetWare, and BSD, etc.
5. Real-Time Operating System –
These types of OSs serve real-time systems. The time interval required to process and respond
to inputs is very small. This time interval is called response time.
Real-time systems are used when there are time requirements that are very strict like missile
systems, air traffic control systems, robots, etc.
Advantages of RTOS:
● Maximum Consumption: Maximum utilization of devices and system, thus more output
from all the resources
● Task Shifting: The time assigned for shifting tasks in these systems are very less. For
example, in older systems, it takes about 10 microseconds in shifting one task to
another, and in the latest systems, it takes 3 microseconds.
● Real-time operating system in the embedded system: Since the size of programs are
small, RTOS can also be used in embedded systems like in transport and others.
● Error Free: These types of systems are error-free.
● Memory Allocation: Memory allocation is best managed in these types of systems.
Disadvantages of RTOS:
● Limited Tasks: Very few tasks run at the same time and their concentration is very less on
few applications to avoid errors.
● Use heavy system resources: Sometimes the system resources are not so good and they are
expensive as well.
● Complex Algorithms: The algorithms are very complex and difficult for the designer to write on.
● Device driver and interrupt signals: It needs specific device drivers and interrupts signals to
respond earliest to interrupts.
● Thread Priority: It is not good to set thread priority as these systems are very less prone to
switching tasks.
Examples of Real-Time Operating Systems are: Scientific experiments, medical imaging systems,
industrial control systems, weapon systems, robots, air traffic control systems, etc.
6. Multiprogramming - in an operating system as the name suggests multi means more than one
and programming means the execution of the program. when more than one program can execute
in an operating system then this is termed a multiprogramming operating system.Before the
concept of Multiprogramming, computing takes place in other way which does not use the CPU
efficiently.Earlier, CPU executes only one program at a time. In earlier day’s computing ,the problem
is that when a program undergoes in waiting state for an input/output operation, the CPU remains
idle which leads to underutilization of CPU and thus poor performance . Multiprogramming
addresses this issue and solve this issue.Multiprogramming was developed in 1950s. It was first used
in mainframe computing.The major task of multiprogramming is to maximize the utilization of
resources.
Multiprogramming is broadly classified into two types namely
Multiuser and Multitasking both are different in every aspect and multitasking is an operating
system that allows you to run more than one program simultaneously. The operating system does
this by moving each program in and out of memory one at a time. When a program runs out of
memory, it is temporarily stored on disk until it is needed again.A multi-user operating system allows
many users to share processing time on a powerful central computer on different terminals. The
operating system does this by quickly switching between terminals, each receiving a limited amount
of CPU time on the central computer. Operating systems change so rapidly between terminals that
each user appears to have constant access to the central computer. If there are many users on such
a system, the time it takes for the central computer to respond may become more apparent.
Multi-Processing Operating System is a type of Operating System in which more than one CPU is
used for the execution of resources. It betters the throughput of the System.
Advantages of Multi-Processing Operating System
It increases the throughput of the system.As it has several processors, so, if one processor fails, we can proceed
with another processor.
Disadvantages of Multi-Processing Operating System
Due to the multiple CPU, it can be more complex and somehow difficult to understand.
#Topic
● Program execution
● I/O operations
● Communication
● Error Detection
● Resource Allocation
● Protection
Program execution
Operating systems handle many kinds of activities from user programs to system programs like
printer spooler, name servers, file server, etc. Each of these activities is encapsulated as a process.
A process includes the complete execution context (code to execute, data to manipulate, registers,
OS resources in use). Following are the major activities of an operating system with respect to
program management −
I/O Operation
An I/O subsystem comprises of I/O devices and their corresponding driver software. Drivers hide the
peculiarities of specific hardware devices from the users.
An Operating System manages the communication between user and device drivers.
● I/O operation means read or write operation with any file or any specific I/O device.
● Operating system provides the access to the required I/O device when required.
A file represents a collection of related information. Computers can store files on the disk (secondary
storage), for long-term storage purpose. Examples of storage media include magnetic tape, magnetic
disk and optical disk drives like CD, DVD. Each of these media has its own properties like speed,
capacity, data transfer rate and data access methods.
A file system is normally organized into directories for easy navigation and usage. These directories
may contain files and other directions. Following are the major activities of an operating system with
respect to file management −
In case of distributed systems which are a collection of processors that do not share memory,
peripheral devices, or a clock, the operating system manages communications between all the
processes. Multiple processes communicate with one another through communication lines in the
network.
The OS handles routing and connection strategies, and the problems of contention and security.
Following are the major activities of an operating system with respect to communication −
● Both the processes can be on one computer or on different computers, but are connected
through a computer network.
Error handling
Errors can occur anytime and anywhere. An error may occur in CPU, in I/O devices or in the memory
hardware. Following are the major activities of an operating system with respect to error handling −
Resource Management
In case of multi-user or multi-tasking environment, resources such as main memory, CPU cycles and
files storage are to be allocated to each user or job. Following are the major activities of an operating
system with respect to resource management −
Protection
Considering a computer system having multiple users and concurrent execution of multiple
processes, the various processes must be protected from each other's activities.
Protection refers to a mechanism or a way to control the access of programs, processes, or users to
the resources defined by a computer system. Following are the major activities of an operating
system with respect to protection −
● The OS ensures that external I/O devices are protected from invalid access attempts.
● The OS provides authentication features for each user by means of passwords.
INTRODUCTION TO COMPUTERS
Storage Unit: The data & instruction that are entered have to be stored in the
computer. Similarly, the end results & the intermediate results also have to be
stored somewhere before being passed to the output unit. The storage unit
provides solution to all these issues. This storage unit is designed to save the
initial data, the intermediate result & the final result. This storage unit has 2
units: Primary storage & Secondary storage.
Primary Storage: The primary storage, also called as the main memory, holds the
data when the computer is currently on. As soon as the system is switched off or
restarted, the information held in primary storage disappears (i.e. it is volatile
in nature). Moreover, the primary storage normally has a limited storage
capacity, because it is very expensive as it is made up of semiconductor devices.
Secondary Storage: The secondary storage, also called as the auxiliary storage,
handles the storage limitation & the volatile nature of the primary memory. It
can retain information even when the system is off. It is basically used for
holding the program instructions & data on which the computer is not working
on currently, but needs to process them later.
Central Processing Unit: Together the Control Unit & the Arithmetic Logic Unit
are called as the Central Processing Unit (CPU). The CPU is the brain of the
computer. Like in humans, the major decisions are taken by the brain itself &
other body parts function as directed by the brain. Similarly in a computer
system, all the major calculations & comparisons are made inside the CPU. The
CPU is responsible for activating & controlling the operation of other units of
the computer system.
Hardware- This hardware is responsible for all the physical work of the
computer. Software- This software commands the hardware what to do & how
to do it.
Before moving on to any programming language, it is important to know about the various
types of languages used by the computer. Let us first know what the basic requirements of
the programmers were & what difficulties they faced while programming in that language.
COMPUTER LANGUAGES
Languages are a means of communication. Normally people interact with each other through
a language. On the same pattern, communication with computers is carried out through a
language. This language is understood both by the user and the machine. Just as every
language like English, Hindi has its own grammatical rules; every computer language is also
bounded by rules known as syntax of that language. The user is bound by that syntax while
communicating with the computer system.
Computer languages are broadly classified as:
Low Level Language: The term low level highlights the fact that it is closer to a
language which the machine understands.
The low level languages are classified as:
o Machine Language: This is the language (in the form of 0’s and 1’s, called
binary numbers) understood directly by the computer. It is machine
dependent. It is difficult to learn and even more difficult to write programs.
As you know that high level language is machine independent and assembly language
though it is machine dependent yet mnemonics that are being used to represent instructions
are not directly understandable by the machine. Hence to make the machine understand the
instructions provided by both the languages, programming language instructors are used. They
transform the instruction prepared by programmers into a form which can be interpreted &
executed by the computer. Flowing are the various tools to achieve this purpose:
Compiler: The software that reads a program written in high level language and
translates it into an equivalent program in machine language is called as compiler.
The program written by the programmer in high level language is called source
program and the program generated by the compiler after translation is called as
object program.
Assembler: The software that reads a program written in assembly language and
translates it into an equivalent program in machine language is called as assembler.
Linker: A linker or link editor is a computer program that takes one or more object
files generated by a compiler and combines them into a single executable file, library
file, or another object file.
Brief History of C
C programming language features were derived from an earlier language called “B”
(Basic Combined Programming Language – BCPL)
In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C
Programming Language” and is commonly known as K&R C.
Many of C’s ideas & principles were derived from the earlier language B, thereby
naming this new language “C”.
Taxonomy of C Language
WHY IS C POPULAR
WHY TO STUDY C
By the early 1980s, C was already a dominant language in the minicomputer world of
Unix systems. Since then, it has spread to personal computers (microcomputers) and
to mainframes.
Many software houses use C as the preferred language for producing word
processing programs, spreadsheets, compilers, and other products.
C is an extremely flexible language—particularly if it is to be used to write operating
systems.
Unlike most other languages that have only four or five levels of precedence, C has 15.
CHARECTERESTICS OF A C PROGRAM
USES
The C programming language is used for developing system applications that forms a major
portion of operating systems such as Windows, UNIX and Linux. Below are some examples of
C being used:
Database systems
Graphics packages
Word processors
Spreadsheets
Network drivers
Interpreters
STRUCTURE OF A C PROGRAM
The structure of a C program is a protocol (rules) to the programmer, which he has to follow
while writing a C program. The general basic structure of C program is shown in the figure
below.
Based on this structure, we can sketch a C program.
Example:
#include <stdio.h>
void main(void)
{ int number;
printf( "Please enter a number: " ); scanf(
"%d", &number ); printf( "You
entered %d", number ); return 0;}
Stepwise explanation:
#include
The part of the compiler which actually gets your program from the source file is
called the preprocessor.
▪ #include <stdio.h>
#include is a pre-processor directive. It is not really part of our program, but instead
it is an instruction to the compiler to make it do something. It tells the C compiler to
include the contents of a file (in this case the system file called stdio.h).
The compiler knows it is a system file, and therefore must be looked for in a special
place, by the fact that the filename is enclosed in <> characters
<stdio.h>
stdio.h is the name of the standard library definition file for all STanDard Input and
Output functions.
Your program will almost certainly want to send information to the screen and read
things from the keyboard, and stdio.h is the name of the file in which the functions
that we want to use are defined.
The function we want to use is called printf. The actual code of printf will be tied in
later by the linker.
The ".h" portion of the filename is the language extension, which denotes an include
file.
void
This literally means that this means nothing. In this case, it is referring to the function
whose name follows.
Void tells to C compiler that a given entity has no meaning, and produces no error.
main
In this particular example, the only function in the program is called main.
A C program is typically made up of large number of functions. Each of these is given
a name by the programmer and they refer to each other as the program runs.
C regards the name main as a special case and will run this function first i.e. the
program execution starts from main.
(void)
This is a pair of brackets enclosing the keyword void.
It tells the compiler that the function main has no parameters.
A parameter to a function gives the function something to work on.
{ (Brace)
This is a brace (or curly bracket). As the name implies, braces come in packs of two -
for every open brace there must be a matching close one.
Braces allow us to group pieces of program together, often called a block.
A block can contain the declaration of variable used within it, followed by a sequence
of program statements.
In this case the braces enclose the working parts of the function main.
; (semicolon)
The semicolon marks the end of the list of variable names, and also the end of that
declaration statement.
All statements in C programs are separated by ";" (semicolon) characters.
The ";" character is actually very important. It tells the compiler where a given
statement ends.
If the compiler does not find one of these characters where it expects to see one, then
it will produce an error.
scanf
In other programming languages, the printing and reading functions are a part of the
language.
In C this is not the case; instead they are defined as standard functions which are part
of the language specification, but are not a part of the language itself.
The standard input/output library contains a number of functions for formatted data
transfer; the two we are going to use are scanf (scan formatted) and printf (print
formatted).
printf
Source File- This file contains the source code of the program. The file extension of
any c file is .c. The file contains C source code that defines the main function & maybe
other functions.
Header File- A header file is a file with extension .h which contains the C function
declarations and macro definitions and to be shared between several source files.
Object File- An object file is a file containing object code, with an extension .o,
meaning relocatable format machine code that is usually not directly executable.
Object files are produced by an assembler, compiler, or other language translator,
and used as input to the linker, which in turn typically generates an executable or
library by combining parts of object files.
Executable File- The binary executable file is generated by the linker. The linker links
the various object files to produce a binary file that can be directly executed.
ELEMENTS OF C
Every language has some basic elements & grammatical rules. Before starting with
programming, we should be acquainted with the basic elements that build the language.
Character Set
Communicating with a computer involves speaking the language the computer understands.
In C, various characters have been given to communicate.
Keywords
Keywords are the words whose meaning has already been explained to the C compiler. The
keywords cannot be used as variable names because if we do so we are trying to assign a
new meaning to the keyword, which is not allowed by the computer.
There are only 32 keywords available in C. Below figure gives a list of these keywords for
your ready reference.
Identifier
1. The case of alphabetic characters is significant. Using "INDEX" for a variable is not the
same as using "index" and neither of them is the same as using "InDeX" for a variable.
All three refer to different variables.
2. As C is defined, up to 32 significant characters can be used and will be considered
significant by most compilers. If more than 32 are used, they will be ignored by the
compiler.
Data Type
In the C programming language, data types refer to a domain of allowed values & the
operations that can be performed on those values. The type of a variable determines how
much space it occupies in storage and how the bit pattern stored is interpreted. There are 4
fundamental data types in C, which are- char, int, float &, double. Char is used to store any
single character; int is used to store any integer value, float is used to store any single
precision floating point number & double is used to store any double precision floating point
number. We can use 2 qualifiers with these basic types to get more types.
Constants
A constant is an entity that doesn’t change whereas a variable is an entity that may change.
Here our only focus is on primary constant. For constructing these different types of
constants certain rules have been laid down.
Real constants are often called Floating Point constants. The real constants could be written
in two forms—Fractional form and Exponential form.
a) The mantissa part and the exponential part should be separated by a letter e.
d) The exponent must have at least one digit, which must be a positive or negative
integer. Default sign is positive.
e) Range of real constants expressed in exponential form is -3.4e38 to 3.4e38. Ex. +3.2e-
5,
Variables are names that are used to store values. It can take different values but one at a
time. A data type is associated with each variable & it decides what values the variable can
take. When you decide your program needs another variable, you simply declare (or define)
a new variable and C makes sure you get it. You declare all C variables at the top of whatever
blocks of code need them. Variable declaration requires that you inform C of the variable's
name and data type. Syntax – datatype variablename;
Eg:
int page_no;
char grade;
float salary;
long y;
Declaring Variables:
• After the opening brace of a block of code (usually at the top of a function)
• Before a function name (such as before main() in the program) Consider various
examples:
Suppose you had to keep track of a person's first, middle, and last initials. Because
an initial is obviously a character, it would be prudent to declare three character
variables to hold the three initials. In C, you could do that with the following
statement:
1. main()
{
char first, middle, last;
}
2. main()
char last;
Initialization of Variables
char grade=’A’;
Expressions
a+b – arithmetic
function call
4+21
a*(b + c/d)/20
q = 5*2 x =
++q % 3
q>3
As you can see, the operands can be constants, variables, or combinations of the two. Some
expressions are combinations of smaller expressions, called subexpressions. For example,
c/d is a subexpression of the sixth example.
An important property of C is that every C expression has a value. To find the value, you
perform the operations in the order dictated by operator precedence.
Statements
Statements are the primary building blocks of a program. A program is a series of statements
with some necessary punctuation. A statement is a complete instruction to the computer. In
C, statements are indicated by a semicolon at the end. Therefore
legs = 4
legs = 4;
is a statement.
3 + 4;
However, these statements do nothing for your program and can't really be considered
sensible statements. More typically, statements change values and call functions:
x = 25;
++x; y =
sqrt(x);
Although a statement (or, at least, a sensible statement) is a complete instruction, not all
complete instructions are statements. Consider the following statement:
x = 6 + (y = 5);
In it, the subexpression y = 5 is a complete instruction, but it is only part of the statement.
Because a complete instruction is not necessarily a statement, a semicolon is needed to
identify instructions that truly are statements.
Compound Statements (Blocks)
years
= years + 1;
}
If any variable is declared inside the block then it can be declared only at the beginning of
the block. The variables that are declared inside a block can be used only within the block.
INPUT-OUTPUT IN C
When we are saying Input that means we feed some data into program. This can be given in
the form of file or from command line. C programming language provides a set of built-in
functions to read given input and feed it to the program as per requirement.
When we are saying Output that means to display some data on screen, printer or in any file.
C programming language provides a set of built-in functions to output the data on the computer
screen. Functions printf() and scanf() are the most commonly used to display out and take
input respectively. Let us consider an example:
Explanation:
#include<stdio.h>
int main()
{ int
c=5;
printf("
Number
=%d",c
);
return
0;
}
Output Number=5
Inside quotation of printf() there, is a conversion format string "%d" (for integer). If this
conversion format string matches with remaining argument, i.e, c in this case, value of c is
displayed.
#include<stdio.h>
int main()
{ int c; printf("Enter
a number\n");
scanf("%d",&c);
printf("Number=%d",c);
return 0; }
Output Enter
a number
4
Number=4
The scanf() function is used to take input from user. In this program, the user is asked an
input and value is stored in variable c. Note the '&' sign before c. &c denotes the address of c
and value is stored in that address.
ASCII code
When character is typed in the above program, the character itself is not recorded a numeric
value (ASCII value) is stored. And when we displayed that value by using "%c", that
character is displayed.
You can display character if you know ASCII code only. This is shown by following example.
Output
Character of ASCII value 69: E
The ASCII value of 'A' is 65, 'B' is 66 and so on to 'Z' is 90. Similarly ASCII value of 'a' is 97, 'b'
is 98 and so on to 'z' is 122.
FORMATTED INPUT-OUTPUT
Data can be entered & displayed in a particular format. Through format specifications, better
presentation of results can be obtained.
EXERCISE:
1. To print out a and b given below, which of the following printf() statement will you use?
#include<stdio.h>
float a=3.14;
double b=3.14;
A. printf("%f %lf", a, b);
B. printf("%Lf %f", a, b);
C. printf("%Lf %Lf", a, b);
D. printf("%f %Lf", a, b);
2. To scan a and b given below, which of the following scanf() statement will you use?
#include<stdio.h> float a;
double b;
A. scanf("%f %f", &a, &b);
B. scanf("%Lf %Lf", &a, &b);
C. scanf("%f %Lf", &a, &b);
D. scanf("%f %lf", &a, &b);
10. In a call to printf() function the format specifier %b can be used to print binary
equivalent of an integer.
A. True
B. False
11. Point out the error in the program?
#include<stdio.h>
int main()
{ char ch;
int i;
scanf("%c", &i);
scanf("%d", &ch); printf("%c
%d", ch, i); return
0;
}
A. Error: suspicious char to in conversion in scanf()
B. Error: we may not get input for second scanf() statement
C. No error
D. None of above
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C language is rich in built-in operators and provides the following types of
operators:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Conditional operators
• Misc Operators
Arithmetic operator:
Following table shows all the arithmetic operators supported by C language. Assume
variable A holds 10 and variable B holds 20 then:
Relational Operators:
Following table shows all the relational operators supported by C language. Assume variable
A holds 10 and variable B holds 20, then:
> Checks if the value of left operand is greater than the value (A > B) is not
of right operand, if yes then condition becomes true. true.
< Checks if the value of left operand is less than the value of (A < B) is true.
right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal (A >= B) is not
to the value of right operand, if yes then condition true.
becomes true.
<= Checks if the value of left operand is less than or equal to (A <= B) is true.
the value of right operand, if yes then condition becomes
true.
Logical Operators:
These operators are used to perform logical operations on the given two variables.
Following table shows all the logical operators supported by C language. Assume variable A
holds 1 and variable B holds 0, then:
Operator Description Example
Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. Bitwise operators are
used in bit level programming. These operators can operate upon int and char but not on
float and double.
Showbits( ) function can be used to display the binary representation of any integer or
character value.
Bit wise operators in C language are; & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^
(XOR), << (left shift) and >> (right shift).
The truth tables for &, |, and ^ are as follows:
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
The Bitwise operators supported by C language are explained in the following table. Assume
variable A holds 60 (00111100) and variable B holds 13 (00001101), then:
& Binary AND Operator copies a bit to the result if it (A & B) will give 12,
exists in both operands. which is 0000 1100
^ Binary XOR Operator copies the bit if it is set in (A ^ B) will give 49,
one operand but not both. which is 0011 0001
~ Binary Ones Complement Operator is unary and (~A ) will give -61,
has the effect of ‘flipping’ bits. which is 1100 0011 in
2’s complement form.
<< Binary Left Shift Operator. The left operands A << 2 will give 240
value is moved left by the number of bits which is 1111 0000
specified by the right operand.
>> Binary Right Shift Operator. The left operands A >> 2 will give 15 which
value is moved right by the number of bits is 0000 1111
specified by the right operand.
Assignment Operators:
In C programs, values for the variables are assigned using assignment operators.
In C, ++ and – are called increment and decrement operators respectively. Both of these
operators are unary operators, i.e, used on single operand. ++ adds 1 to operand and –
subtracts 1 to operand respectively. For example:
When i++ is used as prefix(like: ++var), ++var will increment the value of var and then
return it but, if ++ is used as postfix(like: var++), operator will return the value of operand
first and then only increment it. This can be demonstrated by an example:
int c=2,d=2;
Return 0;
}
Output
4
Conditional Operators (? :)
Conditional operators are used in decision making in C programming, i.e, executes different
statements according to test condition whether it is either true or false.
If the test condition is true (that is, if its value is non-zero), expression1 is returned and if
false expression2 is returned.
y = ( x> 5 ? 3 : 4 ) ;
y=3;
else
y=4;
Misc Operators:
& Returns the address of a variable. &a; will give actual address of
the variable.
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
What is a Flowchart?
Terminal: The oval symbol indicates Start, Stop and Halt in a program’s logic flow. A pause/halt is
generally used in a program logic under some error conditions. Terminal is the first and last symbols in
the flowchart.
1. Check each element in the list by comparing it to the key.
● Input/Output: A parallelogram denotes any function of input/output type. Program instructions
that take input from input devices and display output on output devices are indicated with
parallelogram in a flowchart.
If any elem
ent is equal to the key, return its index.
Processing: A box represents arithmetic instructions. All arithmetic processes such as adding, subtracting,
multiplication and division are indicated by action or process symbol.
Decision Diamond symbol represents a decision point. Decision based operations such as yes/no question or
true/false are indicated by diamond in flowchart.
Connectors: Whenever flowchart becomes complex or it spreads over more than one page, it is useful to use
connectors to avoid any confusions. It is represented by a circle.
● Flow lines: Flow lines indicate the exact sequence in which instructions are executed. Arrows represent
the direction of flow of control and relationship among different symbols of flowchart.
Rules For Creating Flowchart :
A flowchart is a graphical representation of an algorithm.it should follow some rules while creating a flowchart
Rule 1: Flowchart opening statement must be ‘start’ keyword.
Rule 2: Flowchart ending statement must be ‘end’ keyword.
Rule 3: All symbols in the flowchart must be connected with an arrow line.
Rule 4: The decision symbol in the flowchart is associated with the arrow line.
Advantages of Flowchart:
● Flowcharts are a better way of communicating the logic of the system.
● Flowcharts act as a guide for blueprint during program designed.
● Flowcharts help in debugging process.
● With the help of flowcharts programs can be easily analyzed.
● It provides better documentation.
● Flowcharts serve as a good proper documentation.
● Easy to trace errors in the software.
● Easy to understand.
● The flowchart can be reused for inconvenience in the future.
● It helps to provide correct logic.
Disadvantages of Flowchart:
● It is difficult to draw flowcharts for large and complex programs.
● There is no standard to determine the amount of detail.
● Difficult to reproduce the flowcharts.
● It is very difficult to modify the Flowchart.
● Making a flowchart is costly.
● Some developer thinks that it is waste of time.
● It makes software processes low.
● If changes are done in software, then the flowchart must be redrawn
Example : Draw a flowchart to input two numbers from the user and display the largest of two numbers
Introduction to Algorithms
The word Algorithm means ” A set of finite rules or instructions to be followed in calculations or other problem-
solving operations ”
Or
” A procedure for solving a mathematical problem in a finite number of steps that frequently involves recursive
operations”.
Therefore Algorithm refers to a sequence of finite steps to solve a particular problem.
Use standard programming structures such as if-else, for, while, and cases the way we use them in
programming. Indent the statements if-else, for, while loops as they are indented in a program, it helps to
comprehend the decision control and execution mechanism. It also improves readability to a great extent.
Example:
IF “1”
print response
“I AM CASE 1”
IF “2”
print response
“I AM CASE 2”
Use appropriate naming conventions. The human tendency follows the approach of following what we see.
If a programmer goes through a pseudo code, his approach will be the same as per that, so the naming
must be simple and distinct.
Reserved commands or keywords must be represented in capital letters. Example: if you are writing
IF…ELSE statements then make sure IF and ELSE be in capital letters.
Check whether all the sections of a pseudo code are complete, finite, and clear to understand and
comprehend. Also, explain everything that is going to happen in the actual code.
Don’t write the pseudocode in a programming language. It is necessary that the pseudocode is simple and
easy to understand even for a layman or client, minimizing the use of technical terms.
// Documentation
/**
* file: sum.c
* author: you
* description: program to find sum.
*/
// Link
#include <stdio.h>
// Definition
#define X 20
// Global Declaration
int sum(int y);
// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}
// Subprogram
int sum(int y)
{
return y + X;
}
Output
Sum: 75
Explanation of the above Program
Below is the explanation of the above program. With a description explaining the program’s meaning and
use.
Sections Description
/**
* file: sum.c
* author: you
It is the comment section and is part of the description section of the
* description: program to
code.
find
sum.
*/
Header file which is used for standard input-output. This is the preprocessor
#include<stdio.h> section.
#define X 20 This is the definition section. It allows the use of constant X in the code.
int main() main() is the first function that is executed in the C program.
Sections Description
{…} These curly braces mark the beginning and end of the main function.
printf(“Sum: %d”, sum(y)); printf() function is used to print the sum on the screen.
int sum(int y)
{ This is the subprogram section. It includes the user-defined functions
return y + X; that are called in the main() function.
}
Note: If the compiler performs tail call optimization, then Auxiliary Space for recursive
approach can be reduced to O(1).
Bat works by repeatedly swapping the adjacent elements if they are in the wrong order.
This algorithm is not suitable for large data sets as its average and worst-case time
complexity is quite high.
Bubble Sort Algorithm
In this algorithm,
• traverse from left and compare adjacent elements and the higher one is placed at right
side.
• In this way, the largest element is moved to the rightmost end at first.
• This process is then continued to find the second largest and place it and so on until
the data is sorted.
elements at their correct positions
• Total no. of passes: n-1
• Total no. of comparisons: n*(n-1)/2
Implementation of Bubble Sort
Below is the implementation of the bubble sort. It can be optimized by stopping the algorithm
if the inner loop didn’t cause any swap.
• C
• Java
• Python3
• C#
• Javascript
• PHP