0% found this document useful (0 votes)
32 views45 pages

PPS Notes Unit 1 & Unit 2 - Dr. Aditya Kumar

The document provides an overview of computer systems, detailing the five basic operations of computers: input, storing, processing, output, and controlling. It discusses the components of a computer, including input and output devices, storage units, and the central processing unit (CPU), as well as the classification of computers and operating systems. Additionally, it outlines the evolution of computers through various generations, highlighting key technological advancements.

Uploaded by

surajshukla8795
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views45 pages

PPS Notes Unit 1 & Unit 2 - Dr. Aditya Kumar

The document provides an overview of computer systems, detailing the five basic operations of computers: input, storing, processing, output, and controlling. It discusses the components of a computer, including input and output devices, storage units, and the central processing unit (CPU), as well as the classification of computers and operating systems. Additionally, it outlines the evolution of computers through various generations, highlighting key technological advancements.

Uploaded by

surajshukla8795
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Lecture Notes-Unit Wise

Programming for Problem Solving (PPS)


Dr. Aditya Kumar
Unit – 1: (Introduction to Programming)

Topic: Introduction to components of a computer system: Memory, processor, I/O


Devices, storage

INTRODUCTION TO COMPUTERS
Any programming language is implemented on a computer. Right from its inception, to the present
day, all computer system (irrespective of their shape & size) perform the following 5 basic
operations. It converts the raw input data into information, which is useful to the users.

1. Input: It is the process of entering data & instructions to the computer system.
2. Storing: The data & instructions are stored for either initial or additional processing, as & when
required.
3. Processing: It requires performing arithmetic or logical operation on the saved data to convert itinto
useful information.
4. Output: It is the process of producing the output data to the end user.
5. Controlling: The above operations have to be directed in a particular sequence to be completed.
Based on these 5 operations, we can sketch the block diagram of a computer.

Block Diagram of a Computer

Input Unit:
We need to first enter the data & instruction in the computer system, before any computation
begins. This task is accomplished by the input devices. (The data accepted is in a human readable
form. The input device converts it into a computer readable form.
Input device: The input device is the means through which data and instructions enter in a
computer.
1. Camera - most cameras like this are used during live conversations. The camera transmits a
picture from one computer to another, or can be used to record a short video.
.

2. Compact Disc (CD) - CDs store information. The CD can then be put into another computer,
and the information can be opened and added or used on the second computer. Note: A CD-R or CD-
RW can also be used as an OUTPUT device.

3. Keyboard - The keyboard is a way to input letters or numbers into different applications or
programs. A keyboard also has special keys that help operate the computer.

4. Mouse - The mouse is used to open and close files, navigate web sites, and click on a lot of
commands (to tell the computer what to do) when using different applications.

5. Microphone - A microphone is used to record sound. The sound is then saved as a sound file
on the computer.

6. Scanner - A scanner is used to copy pictures or other things and save them as files on the
computer.

7. Joystick - A joystick is used to move the cursor from place to place, and to click on various
items in programs. A joystick is used mostly for computer games.

8. Bar Code Scanner - A bar code scanner scans a little label that has a bar code on it. The
information is then saved on the computer. Bar code scanners are used in libraries a lot.

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.
Magnetic Disk
The Magnetic Disk is Flat, circular platter with metallic coating that is rotated beneath
read/write heads. It is a Random access device; read/write head can be moved to any location on the
platter.
Floppy Disk
These are small removable disks that are plastic coated with magnetic recording
material. Floppy disks are typically 3.5″ in size (diameter) and can hold 1.44 MB of data. This
portable storage device is a rewritable media and can be reused a number of times. Floppy disks are
commonly used to move files between different computers. The main disadvantage of floppy disks
is that they can be damaged easily and, therefore, are not very reliable.

Hard disk.
A hard disk consists of one or more rigid metal plates coated with a metal oxide
material that allows data to be magnetically recorded on the surface of the platters. The hard disk
platters spin at a high rate of speed, typically 5400 to 7200 revolutions per minute (RPM).Storage
capacities of hard disks for personal computers range from 10 GB to 120 GB (one billion bytes are
called a gigabyte).

CD:
Compact Disk (CD) is portable disk having data storage capacity between 650-700 MB. It can hold
large amount of information such as music, full-motion videos, and text etc. It contains digital
information that can be read, but cannot be rewritten. Separate drives exist for reading and writing
DGI Greater Noida

CDs. Since it is a very reliable storage media, it is very often used as a medium for distributing
large amount of information to large number of users. In fact today most of the software is
distributed through CDs.
DVD
Digital Versatile Disk (DVD) is similar to a CD but has larger storage capacity and enormous
clarity. Depending upon the disk type it can store several Gigabytes of data (as opposed to around
650MB of a CD). DVDs are primarily used to store music or movies and can be played back on
your television or the computer too. They are not rewritable media. It‘s also termed DVD (Digital
Video Disk)

Memory Organization in Computer


A memory unit is the collection of storage units or devices together. The memory unit stores the
binary information in the form of bits. Generally, memory/storage is classified into 2 categories:
• Volatile Memory: This loses its data, when power is switched off.
• Non-Volatile Memory: This is a permanent storage and does not lose any data when power
is switched off.

Memory Hierarchy

The total memory capacity of a computer can be visualized by hierarchy of components. The
memory hierarchy system consists of all storage devices contained in a computer system from
the slow Auxiliary Memory to fast Main Memory and to smaller Cache memory.

Auxillary memory access time is generally 1000 times that of the main memory, hence it is at
the bottom of the hierarchy.
The main memory occupies the central position because it is equipped to communicate directly
with the CPU and with auxiliary memory devices through Input/output processor (I/O).
When the program not residing in main memory is needed by the CPU, they are brought in from
auxiliary memory. Programs not currently needed in main memory are transferred into auxiliary
memory to provide space in main memory for other programs that are currently in use.
The cache memory is used to store program data which is currently being executed in the CPU.
Approximate access time ratio between cache memory and main memory is about 1 to 7~10

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 isresponsible
for activating & controlling the operation of other units of the computer system.
Arithmetic Logic Unit:
The actual execution of the instructions (arithmetic or logical operations) takes place over
here. The data & instructions stored in the primary storage are transferred as & when required. No
processing is done in the primary storage. Intermediate results that are generated in ALU are
temporarily transferred back to the primary storage, until needed later. Hence, data may move from
the primary storage to ALU & back again to storage, many times, before the processing is done.
Control Unit:
This unit controls the operations of all parts of the computer but does not carry out any
actual data processing.It is responsible for the transfer of data and instructions among other units of
the computer.It manages and coordinates all the units of the system.It also communicates with
Input/Output devices for transfer of data or results from the storage units.

OutputUnit:
The job of an output unit is just the opposite of an input unit. It accepts the results produced by the
computer in coded form. It converts these coded results to human readable form. Finally, it displays
the converted results to the outside world with the help of output devices ( Eg :monitors, printers,
projectors etc..).
Output device:
Device that lets you see what the computer has accomplished.
1. Monitor - A monitor is the screen on which words, numbers, and graphics can be seem. The
monitor is the most common output device.

2. Compact Disk - Some compact disks can be used to put information on. This is called
burning information to a CD. NOTE: A CD can also be an input device.

3. Printer - A printer prints whatever is on the monitor onto paper. Printers can print words,
numbers, or pictures.

4. Speaker - A speaker gives you sound output from your computer. Some speakers are built
into the computer and some are separate.

5. Headphones - Headphones give sound output from the computer. They are similar to
speakers, except they are worn on the ears so only one person can hear the output at a time.
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. Together, the hardware &
software form the computer system. This software is further classified as system software &
application software.

System Software-
System software are a set of programs, responsible for running the computer, controlling various
operations of computer systems and management of computer resources. They act as an interface
between the hardware of the computer & the application software. E.g.: Operating System.
Application software
is a set of programs designed to solve a particular problem for users. It allows the end user to do
something besides simply running the hardware. E.g.: Web Browser, Gaming Software, etc.

Computer Classification:
Computers can be generally classified by size and power as follows, though there is considerable
overlap:
a. Personal computer: a small, single-user computer based on a microprocessor. In addition to
the microprocessor, a personal computer has a keyboard for entering data, a monitor fordisplaying
information, and a storage device for saving data.
b. Workstation: a powerful, single-user computer. A workstation is like a personal computer,
but it has a more powerful microprocessor and a higher-quality monitor.
c. Minicomputer: a multi-user computer capable of supporting from 10 to hundreds ofusers
simultaneously.
d. Mainframe: a powerful multi-user computer capable of supporting many hundreds or
thousands of users simultaneously.
e. Supercomputer: an extremely fast computer that can perform hundreds of millions of
instructions per second.
For Reference Only **Digital Computer-A brief History
Each generation of computer is characterized by a major technological development that
fundamentally changed the way computers operate, resulting in increasingly smaller, cheaper,
more powerful and more efficient and reliable devices.
First Generation (1940-1956) Vacuum Tubes
• The first computers used vacuum tubes for circuitry and magnetic drums for memory, and
were often enormous, taking up entire rooms.
• They were very expensive to operate and in addition to using a great deal of electricity,
generated a lot of heat, which was often the cause of malfunctions.
• First generation computers relied on machine language, the lowest-level programming
language understood by computers, to perform operations, and they could only solve oneproblem
at a time.
• Input was based on punched cards and paper tape, and output was displayed on printouts.
• The UNIVAC and ENIAC Computers are examples of first-generation computing devices.
Second Generation (1956-1963) Transistors
• Transistors replaced vacuum tubes and ushered in the second generation of computers. The
transistor was far superior to the vacuum tube, allowing computers to become smaller, faster,
cheaper, more energy-efficient and more reliable than their first-generation predecessors.
• Second-generation computers still relied on punched cards for input and printouts for output.
• Second-generation computers moved from cryptic binary machine language to symbolic, or
assembly, languages, which allowed programmers to specify instructions in words. High-level
programming languages were also being developed at this time, such as early versions of COBOL
and FORTRAN.
• The first computers of this generation were developed for the atomic energy industry.
Third Generation (1964-1971) Integrated Circuits
• The development of the integrated circuit was the hallmark of the third generation of
computers.
• Transistors were miniaturized and placed on silicon chips, called semiconductors, which
drastically increased the speed and efficiency of computers.
• Instead of punched cards and printouts, users interacted with third generation computers
through keyboards and monitors and interfaced with an operating system, which allowed the device
to run many different applications at one time with a central program that monitored thememory.
• Computers for the first time became accessible to a mass audience because they were smaller
and cheaper than their predecessors.
Fourth Generation (1971-Present) Microprocessors
• The microprocessor brought the fourth generation of computers, as thousands of integrated
circuits were built onto a single silicon chip.
• The Intel 4004 chip, developed in 1971, located all the components of the computer—from the
central processing unit and memory to input/output controls—on a single chip.
• As these small computers became more powerful, they could be linked together to form
networks, which eventually led to the development of the Internet.
• Fourth generation computers also saw the development of GUIs, the mouse and handheld
devices.
Fifth Generation (Present and Beyond) Artificial Intelligence
• Fifth generation computing devices, based on artificial intelligence, are still in development,
though there are some applications, such as voice recognition, that are being used today.
• The use of parallel processing and superconductors is helping to make artificial intelligence a
reality.
.

Topic: Operating system –functions and services

Notes
Definition: An operating system (OS) is a collection of software that manages computer hardware
resources and provides common services for computer programs.
Definition:(1)As an interface (2) As an environment (3) As a system software

Operating System functions:


1. Process Management 2.Main Memory management 3.I/O device management
4. File Management 5.Secondary storage management 6.Network Management
7. System Protection 8.Command interpretation

Classification of operating systems:


(i) Batch System:
(a) Program, its related data and relevant control command should be submitted together, in the form of
a job.
(b) No interaction between the users and the executing programs, very simple, transfer control
automatically.
(c) Scheduling of jobs is in the order of FCFS
(d) Memory management is done by Master/Slave concept.
(e) No need of concurrency control.
(f) Good for the programs which have long execution time.

(ii) Interactive System:


An operating system that allows users to run interactive programs. Pretty much all operating
systems that are on PCs are interactive OS.

(iii) Time Sharing System:


1. Time sharing (multitasking) is a logical extension of multiprogramming. The CPU executes multiple
jobs by switching among them, but the switches occur so frequently that the users can interact with
each program while it is running
2. CPU bound is divided into different time slots depending upon the number of users using the system.
3. There must be some CPU scheduling, memory management scheme, synchronization and
communication schemes.

(iv) Real Time System:


1. This type of operating systems are used to control Scientific devices and similar small instruments
where memory and resources are crucial. These type of devices have very limited or no end user
utilities , so more effort should go into making the OS really memory efficient and fast (less coding),
so as to minimize the execution time ,in turn saving on power as well. E x: VHDL, 8086 etc.
2. Provide quick response time and thus to meet a scheduling deadline (time constraint).3. Resource
utilization is secondary concern to these systems.
4. Applicable to Rocket launching, flight control, robotics.5. Types (a) soft RTS (b) hard RTS

(v) Multiprocessor system:


1. Multiprocessor System consists of a set of processors that shares a set of physical memory
blocks over an interconnection network.
2. Controls and manage the hardware and software resources such that user can view the entire
system as a powerful uniprocessor system.
.

3. Design is too complex.


4. Parallel or tightly coupled systems.

(vi) Multiuser System:


1. Multi-user is a term that defines an operating system or application software that allows
concurrent access by multiple users of a computer.
2. Time-sharing systems are multi-user systems. Most batch processing systems for mainframe
computers may also be considered "multi-user", to avoid leaving the CPU idle while it waits for I/O
operations to complete.

Common services provided by an operating system −


• Program execution
• I/O operations
• File System manipulation
• Communication
• Error Detection
• Resource Allocation
• Protection

**Additional Informations about OS-

DOS (Disk Operating System)


1. Microsoft Disk operating system, MS-DOS is a non-graphical command line operating system
derived from 86-DOS that was created for IBM compatible computers. MS-DOS originally written
by Tim Paterson and introduced by Microsoft in August 1981 and was last updated in 1994 .
2. Today, MS-DOS is no longer used; however, the command shell, more commonly known as the
Windows command line is still used by many users. In the picture to the right, is an example of what
a MS-DOS window more appropriately referred to as the Windows command line looks like under
Microsoft Windows.
3. DOS (an acronym for Disk Operation System) is a tool which allows you to control the operation
of the IBM PC. DOS is software which was written to control hardware.
Essential DOS Commands and Concepts
1. Change the Default Drive
To change the default drive, simply type the letter of the choice. The new default will be listed in
subsequent DOS prompts.
2. CHDIR (CD) Change Directory Command
Once you have located the directory you want, you may move from directory to directory using the CD
command (change directory)
3. COPY Command
The COPY command can be used both to copy files from disk to disk or to create a second copy of a file
on a single disk. (There are many more uses of the COPY command, but only the basic operation is
discussed here.)
4. DIR (Directory) Command
The DIRECTORY command lists the names and sizes of all files located on a particular disk.
5. DIR Options
Two little characters, '*' and '?', will make your life with computers much easier. Their use is illustrated
below.
6. ERASE Command
The ERASE command deletes specified files.
.

7. FORMAT Command
You must format new disks before using them on the IBM computers. The format command checks a
diskette for flaws and creates a directory where all the names of the diskette's files will be stored.
8. MKDIR (MD) Make Directory Command
This command creates a new directory.
9. RENAME (REN) Command
The RENAME command permits users to change the name of a file without making a copy of it.
10. RMDIR (RD) Remove Directory Command
This command removes a directory. It is only possible to execute this command if the directory you
wish to remove is empty.
11. Stop Execution (Ctrl-Break)
If you wish to stop the computer in the midst of executing the current command, you may use the key
sequence Ctrl-Break. Some other commands are: DATE, TIME, VER, CLS, and COPYCON.

Microsoft Windows
• Windows is a meta family of graphical operating systems developed, marketed, and sold by
Microsoft.
• Active Windows families include Windows NT, Windows Embedded and Windows Phone;
these may encompass subfamilies, e.g. Windows Embedded Compact (Windows CE) or
Windows Server. Defunct Windows families include Windows 9x; Windows 10 Mobile is an
active product, unrelated to the defunct family Windows Mobile.
• Microsoft introduced an operating environment named Windows on November 20, 1985, as a
graphical operating system shell for MS-DOS in response to the growing interest in graphical
user interfaces (GUIs).
• Version history-Windows 1.0, Windows 2.0, and Windows 2.1x➔Windows 3.x➔Windows
9x➔Windows NT➔ Windows XP➔Windows Vista➔Windows 7➔Windows 8 and
8.1➔Windows 10➔
Basic Features of Windows Operating System-
1) Windows Easy Transfer 2) Windows Anytime Upgrade3) Windows Basics 4) Searching and
Organizing 5) Parental Controls 6) Ease of Access Center 7) Default Programs 8) Remote Desktop
Connection
Linux
• The Unix operating system was conceived and implemented in 1969 at AT&T's Bell
Laboratories in the United States by Ken Thompson, Dennis Ritchie, Douglas McIlroy, and Joe
Ossanna.
• Linux Operating System has primarily three components
• Kernel − Kernel is the core part of Linux. It is responsible for all major activities of this
operating system. It consists of various modules and it interacts directly with the
underlying hardware. Kernel provides the required abstraction to hide low level hardware
details to system or application programs.
• System Library − System libraries are special functions or programs using which
application programs or system utilities accesses Kernel's features. These libraries
implement most of the functionalities of the operating system and do not requires kernel
module's code access rights.
• System Utility − System Utility programs are responsible to do specialized, individual
level tasks.
.

Basic Features
Following are some of the important features of Linux Operating System.
• Portable − Portability means software 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.
• Security − Linux provides user security using authentication features like password
protection/ controlled access to specific files/ encryption of data.
Architecture
The architecture of a Linux System consists of the following layers −
• Hardware layer − Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc).
• Kernel − It is the 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. The
shell takes commands from the user and executes kernel's functions.
• Utilities − Utility programs that provide the user most of the functionalities of an
operating systems.

Android
What is Android-One of the most widely used mobile OS these days is ANDROID. Android
is a software bunch comprising not only operating system but also middleware and key
applications. Android Inc was founded in Palo Alto of California, U.S. by Andy Rubin,
Rich miner, Nick sears and Chris White in 2003. Later Android Inc. was acquired by
Google in 2005. After original release there have been number of updates in the original
version of Android

Features & Specifications
Android is a powerful Operating System supporting a large number of applications in Smart
Phones. These applications make life more comfortable and advanced for the users.
Android applications are written in java programming language.
Android is available as open source for developers to develop applications which can be
further used for selling in android market.
For software development, Android provides Android SDK (Software development kit).

Applications
These are the basics of Android applications:
• Android applications are composed of one or more application components (activities,
services, content providers, and broadcast receivers)
• Each component performs a different role in the overall application behavior, and each
one can be activated individually (even by other applications)
• The manifest file must declare all components in the application and should also declare
all application requirements, such as the minimum version of Android required and any
hardware configurations required
• Non-code application resources (images, strings, layout files, etc.) should include
alternatives for different device configurations (such as different strings for different
languages)
Topic: Concept of assembler, compiler, interpreter, loader and linker

• A language that is acceptable to a computer system is called a computer language or programming


language and the process of creating a sequence of instructions in such a language is called
programming or coding.
• A program is a set of instructions, written to perform a specific task by the computer. A set of large
program is called software. To develop software, one must have knowledge of a programming
language.
• Before moving on to any programming language, it is important to know about the various types of
languages used by the computer.

COMPUTER LANGUAGES
• Languages are a means of communication. Normally people interact with each otherthrough
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:


• 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.
• Assembly Language: This is the language where the machine codes comprising of 0‘sand
1‘s are substituted by symbolic codes (called mnemonics) to improve their understanding. It
is the first step to improve programming structure. Assembly language programming is
simpler and less time consuming than machine level programming, it is easier to locate and
correct errors in assembly language than in machine language programs. It is also machine
dependent. Programmers must have knowledge of the machine on which the program will
run.

• High Level Language: Low level language requires extensive knowledge of the hardware
since it is machine dependent. To overcome this limitation, high level language has been
evolved which uses normal English, which is easy to understand to solve any problem. High
level languages are computer independent and programming becomes quite easy and simple.
Various high level languages are given below:
• BASIC (Beginners All Purpose Symbolic Instruction Code): It is widely used, easy to learn
general purpose language. Mainly used in microcomputers in earlier days.
• COBOL (Common Business Oriented language): A standardized language used for
commercial applications.
• FORTRAN (Formula Translation): Developed for solving mathematical and scientific
problems. One of the most popular languages among scientific community.
• C: Structured Programming Language used for all purpose such as scientific application,
commercial application, developing games etc.
.

• C++: Popular object oriented programming language, used for general purpose.

PROGRAMMING LANGUAGE TRANSLATORS


• 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.

Interpreter: it also executes instructions written in a high level language. Both complier & interpreter
have the same goal i.e. to convert high level language into binary instructions, but their method of
execution is different. The complier converts the entire source code into machine level program,
while the interpreter takes 1 statement, translates it, executes it & then again takes the next statement.

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.
.

Topic: Idea of Algorithm: Representation of Algorithm, Flowchart, Pseudo code


with examples, From algorithms to programs, source code.

Algorithm
• Characteristics of algorithm: Input, output, definiteness, finiteness, effectiveness.
• Algorithm is a step-by-step solution to a problem. Example: one algorithm for adding
two digit numbers is "add the units, add the tens and combine the answers"
• "Algorithm" is named after the 9th century Persian mathematician Al-Khwarizmi.
Example: For factorial
1. Start
2. Input number N (for which we want to calculate factorial.)
3. Let M=1 and F=1.
4. F=F*M.
5. Is M=N?
6. If NO then M=M+1 and go to step 3.
7. If YES then output F
8. End
Flow Chart:
A flowchart is a type of diagram that represents an algorithm or process, showing the steps as
boxes of various kinds, and their order by connecting these with arrows. This diagrammatic
representation can give a step-by-step solution to a given problem.

Example: For factorial.

Advantages Of Using FLOWCHARTS: -


• Communication: - Flowcharts are better way of communicating the logic of a system to
all concerned.
• Effective analysis: - With the help of flowchart, problem can be analyzed in more
effective way.
.

• Proper documentation: - Program flowcharts serve as a good program documentation,


which is needed for various purposes.
• Efficient Program Maintenance: - The maintenance of operating program becomes easy
with the help of flowchart. It helps the programmer to put efforts more efficiently on that
part

Disadvantages Of Using FLOWCHARTS: -


1. Complex logic: - Sometimes, the program logic is quite complicated. In that case,
flowchart becomes complex and clumsy.
2. Alterations and Modifications: - If alterations are required the flowchart may require re-
drawing completely.
3. Reproduction: - As the flowchart symbols cannot be typed, reproduction of flowchart
becomes a problem.
4. The essentials of what is done can easily be lost in the technical details of how it is done.

Examples of Algorithm and Flowchart (Random)-For hint


1. Draw flowchart to find the largest among three different numbers entered by user.
.

2.Draw a flowchart to find all the roots of a quadratic equation ax2+bx+c=0

3.Draw a flowchart to find the Fibonacci series till term≤1000.

Example : Calculate the Interest of a Bank Deposit


Algorithm:
▪ Step 1: Read amount,
▪ Step 2: Read years,
▪ Step 3: Read rate,
▪ Step 4: Calculate the interest with formula "Interest=Amount*Years*Rate/100
▪ Step 5: Print interest,
.

Flowchart:

Example : Determine and Output Whether Number N is Even or Odd


Algorithm:
▪ Step 1: Read number N,
▪ Step 2: Set remainder as N modulo 2,
▪ Step 3: If remainder is equal to 0 then number N is even, else number N is odd,
▪ Step 4: Print output.
Flowchart:
DGI Greater Noida

Example : Determine Whether A Student Passed the Exam or Not:


Algorithm:
▪ Step 1: Input grades of 4 courses M1, M2, M3 and M4,
▪ Step 2: Calculate the average grade with formula "Grade=(M1+M2+M3+M4)/4"
▪ Step 3: If the average grade is less than 60, print "FAIL", else print "PASS".
Flowchart:
DGI Greater Noida

Topic: Programming Basics: Structure of C program, Syntax , errors

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:
/* This program accepts a number & displays it to the user*/
#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. 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
The printf function is the opposite of scanf. It takes text and values from within the program and sends
it out onto the screen. Just like scanf, it is common to all versions of C and just like scanf, it is
described in the system file stdio.h.The first parameter to a printf is the format string, which contains
text, value descriptions and formatting instructions.

FILES USED IN A C PROGRAM


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.

Types of error
a) Syntax Errors: Errors in syntax (grammar) of the program.
b) Semantic Errors: Errors in the meaning of the program.
c) Logical Errors: Errors in logic of the program. Compiler cannot diagnose these kinds of errors.
d) Runtime Errors: i) Insufficient memory ii)Floating exception
e) Compile Errors: i) parse error ii)implicit declaration iii) no matching function iv)Unsatisfied
symbols v)incomplete type vi)cannot call member function vii)bad argument viii)cannot
allocate an object
,j
m
Special Character !@#$%^&*

White space Tab or new lines or space

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
In the programming language C, an identifier is a combination of alphanumeric characters, the
first being a letter of the alphabet or an underline, and the remaining being any letter of the
alphabet, any numeric digit, or the underline.
Two rules must be kept in mind when naming identifiers.
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 consideredsignificant
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.

There are 2 types of qualifiers-


Sign qualifier- signed & unsigned
Size qualifier- short & long
The data types in C can be classified as follows:

Type Storage size Value range

Char 1 byte -128 to 127

unsigned char 1 byte 0 to 255

Integrity 2 or 4 bytes 32,768 to 32,767 or -2,147,483,648 to 2,147,483,647

nsigned integrity 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

Short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

long 4 bytes -2,147,483,648 to 2,147,483,64

unsigned long 4 bytes 0 to 4,294,967,295

Type Storage size Value range Precision

float 4 bytes 1.2E-38 to 3.4E+38 6 decimal places

double 8 bytes 2.3E-308 to 1.7E+308 15 decimal places

long double 10 bytes .4E-4932 to 1.1E+4932 19 decimal places


.

Constants
A constant is an entity that doesn‘t change whereas a variable is an entity that may change constants
can be divided into two major categories: Primary Constants, Secondary Constants

Rules for Constructing Integer Constants:


• An integer constant must have at least one digit.
• It must not have a decimal point.
• It can be either positive or negative.
• If no sign precedes an integer constant it is assumed to be positive.
• No commas or blanks are allowed within an integer constant
• The allowable range for integer constants is -32768to 32767.
Ex.: 426, +782,-8000, -7605

Rules for Constructing Real Constants:


• Real constants are often called Floating Point constants. The real constants could be written
in two forms—Fractional form and Exponential form.
• A real constant must have at least one digit.
• It must have a decimal point.
• It could be either positive or negative.
• Default sign is positive.
• No commas or blanks are allowed within a real constant. Ex. +325.34, 426.0, -32.76, -
48.5792

Rules for constructing real constants expressed in exponential form:


• The mantissa part and the exponential part should be separated by a letter e.
• The mantissa part may have a positive or negative sign.
• Default sign of mantissa part is positive.
.

• The exponent must have at least one digit, which must be a positive or negative integer.
Default sign is positive.
• Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.
• Ex. +3.2e-5, 4.1e8, -0.2e+3, -3.2e-5

Rules for Constructing Character Constants:


A character constant is a single alphabet, a single digit or a single special symbol enclosed within
single inverted commas.
The maximum length of a character constant can be 1 character.
Ex.: ‗M‘, ‗6‘, ‗+‘

VARIABLES
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. Variable declaration requires that you inform C of the variable's name and data type.
Syntax – data type variable name;
Eg:int page_no;
char grade;
float salary;
long y;
Declaring Variables:
There are two places where you can declare a variable:
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:

Initialization of Variables
When a variable is declared, it contains undefined value commonly known as garbage value. If
we want we can assign some initial value to the variables during the declaration itself. This
is called initialization of the variable.
Eg-int pageno=10;

Expressions
An expression consists of a combination of operators, operands, variables & function calls. An
expression can be arithmetic, logical or relational. Here are some expressions:
a+b – arithmetic operation
a>b- relational operation a
== b - logical operation
func (a,b) – function call

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. a semicolon is needed to identify
instructions that truly are statements.

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.
DGI Greater Noida

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:

#include <stdio.h> //This is needed to run printf() function.


int main()
{ printf("C Programming"); //displays the content inside quotation return 0;
}
Output:C Programming
Explanation:
Every program starts from main() function.
printf() is a library function to display output which only works if #include<stdio.h>is included
at the beginning.
Here, stdio.h is a header file (standard input output header file) and #include is command to
paste the code from the header file when necessary. When compiler encounters
printf()function and doesn't find stdio.h header file, compiler shows error.
return 0; indicates the successful execution of the program.

Input- Output of integers in C


#include<stdio.h>
int main()
{int c=5;
printf("Number=%d",c);
return 0;
}
Output:Number=5

Input - Output of characters


#include <stdio.h>
int main()
{char var1;
printf("Enter character: ");
scanf("%c",&var1);
printf("You entered %c.",var1);
return 0;
}
Output:Enter character: g You entered g.

FORMATTED INPUT-OUTPUT
Data can be entered & displayed in a particular format. Through format specifications, better
presentation of results can be obtained.

Variations in Output for integer & floats:


#include<stdio.h>
int main()
{printf("Case 1:%6d\n",9876);
/* Prints the number right justified within 6 columns */
printf("Case 2:%3d\n",9876);
DGI Greater Noida

/* Prints the number to be right justified to 3 columns but, there are 4 digits so number is not
right justified */
printf("Case 3:%.2f\n",987.6543);
/* Prints the number rounded to two decimal places */
printf("Case 4:%.f\n",987.6543);
/* Prints the number rounded to 0 decimal place, i.e, rounded to integer */
printf("Case 5:%e\n",987.6543);
/* Prints the number in exponential notation (scientific notation) */
return 0;
}
Output
Case 1: 9876
Case 2:9876
Case 3:987.65
Case 4:988
.

Topic: Storage classes

• Generally there are two kinds of locations in a computer where such a value can be present, these are
Memory and CPU registers. The storage class of a particular variable determines in which of the
above two locations the variable‘s value is stored.
• There are four properties by which storage class of a variable can be recognized. These are scope,
default initial value, scope and life.
• A variable‘s storage class reveals the following things about a variable
(i) Where the variable is stored.
(ii) What is the initial value of the variable if the value of the variable is not specified?
(iii) What is the scope of the variable (To which function or block the variable is available).
(iv) What is the life of particular variable (Up to what extent the variable exists in a program).

• In c there are four types of storage class. They are: 1. Auto 2. Register 3.
Static 4. Extern
• Storage class is modifier or qualifier of data types which decides: In which area of memory
a particular variable will be stored? What is scope of variable? What is visibility of variable?

Visibility of a variable in c: Visibility means accessibility. Up to witch part or area of a


program, we can access a variable, that area or part is known as visibility of that variable.
For example: In the following figure yellow color represents visibility of variable a.

Scope of a variable in c: Meaning of scope is to check either variable is alive or dead. Alive
means data of a variable has not destroyed from memory. Up to which part or area of the
program a variable is alive, that area or part is known as scope of a variable. There are four
type of scope in c:
1. Block scope.
2. Function scope.
3. File scope.
3. Program scope.

Automatic Storage Class


Syntax to declare automatic variable is:
auto datatype variablename;
Example:
auto int i;
Features of Automatic Storage Class are as follows
Storage: Memory
Default Initial Value: Garbage Value
.

Scope: Local to the block in which the variable is defined


Life: Till the control remains within the block in which the variable is defined
by default every variable is automatic variable
The following program illustrates the work of automatic variables.
void test();
void main()
{
test();
test();
test();
}
void test()
{
auto int k=10;
printf(―%d\n‖,k);
k++;
}
Output:
10
10
10
In the above program when the function test() is called for the first time ,variable k is created and
initialized to 10. When the control returns to main(), k is destroyed. When function test() is called
for the second time again k is created , initialized and destroyed after execution of the function. Hence
automatic variables came into existence each time the function is executed and destroyed when
execution of the function completes.

Register Storage Class


Syntax to declare register variable is:
register datatype variablename;
Features of Register Storage Class are as follows:
Storage: CPU Registers
Default Initial Value: Garbage Value
Scope: Local to the block in which the variable is defined
Life: Till the control remains within the block in which the variable is defined
For example loop counters are declared as register variables, which are defined as follows:
int main()
{
register int a;
for(a=0;i<50000;i++)
printf(―%d\t‖,a);
return 0;

In the above program, variable a was used frequently as a loop counter so the variable a is defined as a
register variable. Register is a not a command but just a request to the compiler to allocate the memory
for the variable into the register. If free registers are available than memory will be allocated in to the
registers. And if there are no free registers then memory will be allocated in the RAM only (Storage
is in memory i.e. it will act as automatic variable).
Every type of variables can be stored in CPU registers. Suppose the microprocessor has 16 bit registers
then they can‘t hold a float or a double value which requires 4 and 8 bytes respectively.
DGI Greater Noida

But if you use register storage class for a float or double variable then you will not get any error message
rather the compiler will treat the float and double variable as be of automatic storage class(i.e. Will
treat them like automatic variables).

Static Storage Class


Syntax to declare static variable is:
static datatype variablename;
Example:
static int i;
Features of Static Storage Class are as follows
Storage: Memory
Default Initial Value: Zero
Scope: Local to the block in which the variable is defined
Life: Value of the variable continues to exist between different function calls
Now look at the previous program with k is declared as static instead of automatic.
void test();
void main()
{
test();
test();
test();
}
void test()
{
static int k=10;
printf(―%d\n‖,k);
k++;
}

Output:10 11 12
Here in the above program the output is 10, 11, 12, because if a variable is declared as static then it is
initialized only once and that variable will never be initialized again. Here variable k is declared as
static, so when test() is called for the first time k value is initialized to 10 and its value is incremented
by 1 and becomes 11. Because k is static its value persists. When test() is called for the second time
k is not reinitialized to 10 instead its old value 11 is available. So now 11 is get printed and it value
is incremented by 1 to become 12. Similarly for the third time when test() is called 12(Old value) is
printed and its value becomes 13 when executes the statement ‗k++;‘

So the main difference between automatic and static variables is that static variables are initialized to
zero if not initialized but automatic variables contain an unpredictable value(Garbage Value) if not
initialized and static variables does not disappear when the function is no longer active , their value
persists, i.e. if the control comes back to the same function again the static variables have the same
values they had last time.

General advice is avoid using static variables in a program unless you need them, because their values
are kept in memory when the variables are not active which means they occupies space in memory
that could otherwise be used by other variables.

External Storage Class


Syntax to declare static variable is:
DGI Greater Noida

extern datatype variablename;


Example:
extern int i;
Features of External Storage Class are as follows
Storage: Memory
Default Initial Value: Zero
Scope: Global
Life: Till the program‘s execution doesn‘t come to an end
External variables differ from automatic, register and static variables in the context of scope, external
variables are global on the contrary automatic, register and static variables are local. External
variables are declared outside all functions, therefore are available to all functions that want to use
them.
If the program size is very big then code may be distributed into several files and these files are compiled
and object codes are generated. These object codes linked together with the help of linker and
generate ―.exe‖ file. In the compilation process if one file is using global variable but it is
declared in some other file then it generate error called undefined symbol error. To overcome this we
need to specify global variables and global functions with the keyword extern before using theminto
any file. If the global variable is declared in the middle of the program then we will get undefined
symbol error, so in that case we have to specify its prototype using the keyword extern.

So if a variable is to be used by many functions and in different files can be declared as external variables.
The value of an uninitialized external variable is zero. The declaration of an external variable declares
the type and name of the variable, while the definition reserves storage for the variable as well as
behaves as a declaration. The keyword extern is specified in declaration but not in definition. Now
look at the following four statements

1. auto int a;
2. register int b;
3. static int c;
4. extern int d;
Out of the above statements first three are definitions where as the last one is a declaration. Suppose
there are two files and their names are File1.c and File2.c respectively. Their contents are as follows:
File1.c
int n=10;
void hello()
{
printf(―Hello‖);
}
File2.c
extern int n;
extern void hello();
void main()
{printf(―%d‖, n);
hello();}
In the above program File1.obj+ File2.obj=File2.exe and in File2.c value of n will be 10.
.

Module – 2: (Arithmetic expressions & Conditional Branching)

Topic: 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 associability.

OPERATORS-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, Increment and decrement operators, Conditional
operators, Misc Operators

Arithmetic operator: Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A – B will give -10

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2

Modulus Operator and remainder of after an integer

% B % A will give 0
Division

++ Increments operator increases integer value by one A++ will give 11

-- Decrements operator decreases integer value by one A–will give 9


.

Relational Operators:
Assume variable A holds 10 and variable B holds 20, then:
Operator Description Example

== Checks if the values of two operands are equal or not, if yes (A == B) is not
then condition becomes true. true.

!= Checks if the values of two operands are equal or not, if (A != B) is true.


values are not equal then condition becomes true.

> 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 to (A >= B) is not
the value of right operand, if yes then condition becomes true.
true.

<= Checks if the value of left operand is less than or equal to the (A <= B) is true.
value of right operand, if yes then condition becomes true.

Logical Operators:
Assume variable A holds 1 and variable B holds 0, then:
Operator Description Example

Called Logical AND operator. If both the operands are (A && B) is

&&
nonzero, then condition becomes true. false.

Called Logical OR Operator. If any of the two operands is

|| (A || B) is true.
non-zero, then condition becomes true.

Called Logical NOT Operator. Use to reverses the logical

!(A && B) is

! state of its operand. If a condition is true then Logical NOT


true.
operator will make false.
.

Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. These operators can operate upon int
and char but not on float and double..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:
P Q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume variable A holds 60 (00111100) and variable B holds 13 (00001101), then:


Operator Description Example

& 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 OR Operator copies a bit if it exists in either (A | B) will give 61,


operand. which is 0011 1101

^ 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 has (~A ) will give -61, which
the effect of ‗flipping‘ bits. is 1100 0011 in 2‘s
complement form.

<< Binary Left Shift Operator. The left operands value A << 2 will give 240
is moved left by the number of bits specified by the which is 1111 0000
right operand.

>> Binary Right Shift Operator. The left operands A >> 2 will give 15
value is moved right by the number of bits specified which is 0000 1111
by the right operand.
.

Assignment Operators:
In C programs, values for the variables are assigned using assignment operators.
There are following assignment operators supported by C language:
Operator Description Example

= mple assignment operator, Assigns values from right side C = A + B will


operands to left side operand assign value of A +
B into C

+= d AND assignment operator, It adds right operand to the C += A is


left operand and assign the result to left operand equivalent to C = C
+A

-= Subtract AND assignment operator, It subtracts right C -= A is


operand from the left operand and assign the result to left equivalent to C = C
Operand –A

*= Multiply AND assignment operator, It multiplies right C *= A is


operand with the left operand and assign the result to left equivalent to C = C
Operand *A

/= Divide AND assignment operator, It divides left operand C /= A is


ith the right operand and assign the result to left operand equivalent to C = C
/A

%= odulus AND assignment operator, It takes modulus using C %= A is


two operands and assign the result to left operand equivalent to C = C
%A

<<= Left shift AND assignment operator C <<= 2 is same as


C = C << 2

>>= Right shift AND assignment operator C >>= 2 is same as


C = C >> 2

&= Bitwise AND assignment operator C &= 2 is same as


C=C&2

^= bitwise exclusive OR and assignment operator C ^= 2 is same as C


=C^2

|= bitwise inclusive OR and assignment operator C |= 2 is same as C


=C|2
.

Increment/Decrement OPERATOR
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:
Let a=5 and b=10
a++; //a becomes 6
a--; //a becomes 5
++a; //a becomes 6
--a; //a becomes 5
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:
#include <stdio.h>
int main()
{int c=2,d=2;
printf(―%d\n‖,c++); //this statement displays 2 then, only c incremented by 1 to 3.
Printf(―%d‖,++c); //this statement increments 1 to c then, only c is displayed.
Return 0;
}
Output:2 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.
Syntax of conditional operators;
conditional_expression?expression1:expression2
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 ) ;➔this statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y.

Misc Operators:
There are few other operators supported by c language.
Operator Description Example

sizeof() It is a unary operator which is used in sizeof(a), where a is integer, will


finding the size of data type, constant, return 4.
arrays, structure etc.

& Returns the address of a variable. &a; will give actual address of
the variable.

* Pointer to a variable. *a; will pointer to a 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.
Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* &sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift <<>> Left to right

Relational <<= >>= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right


Type casting

• Type casting /type conversion is a way to convert a variable from one data type to another
data type. For example, if you want to store a long value into a simple integer then you
can typecast long to int.
• You can convert values from one type to another explicitly using the cast operator. There
are two types of type casting in c languages that are implicit conversions and Explicit
Conversions.
• New data type should be mentioned before the variable name or value in brackets which
to be typecast.
C TYPE CASTING EXAMPLE PROGRAM:
In the below C program, 7/5 alone will produce integer value as 1.So, type cast is done
before division to retain float value (1.4).
#include <stdio.h>
int main ()
{
float x;
x = (float) 7/5;
printf(―%f‖,x);
}
Output:
1.400000
WHAT IS TYPE CASTING IN C LANGUAGE?
Converting an expression of a given type into another type is known as type casting. It is best
practice to convert lower data type to higher data type to avoid data loss. Data will be
truncated when the higher data type is converted to lower. For example, if a float is
converted to int, data which is present after the decimal point will be lost.
There are two types of type casting in c language.
TYPES OF TYPECASTING IN C
Types of type casting in C Programming
Implicit Conversion
Explicit Conversion
1. IMPLICIT CONVERSION
Implicit conversions do not require any operator for converted. They are automatically
performed when a value is copied to a compatible type in the program.

#include<stdio.h>
#include<conio.h>
void main()
{
int i=20;
double p;
clrscr();
p=i; // implicit conversion
printf(―implicit value is %d‖,p);
getch();}

Output:-
implicit value is 20.
.

2. EXPLICIT CONVERSION
In C language, Many conversions, especially those that imply a different interpretation of the
value, require an explicit conversion.
Example :-
#include<stdio.h>
#include<conio.h>
void main()
{
int i=20;
short p;
clrscr();
p = (short) i; // Explicit conversion
printf(―Explicit value is %d‖,p);
getch();
}
Output:-
Explicit value is 20.

Usual Arithmetic Conversion


The usual arithmetic conversions are implicitly performed to cast their values in a common
type, C uses the rule that in all expressions except assignments, any implicit type
conversions made from a lower size type to a higher size type as shown below:
.

Type Casting In C Language


DIFFERENCE BETWEEN TYPE CASTING AND TYPE CONVERSION
BASIS FOR TYPE CASTING TYPE CONVERSION
COMPARISO
N
Definition When a user can convert the one Type Conversion is that which
data type into other then it is automatically converts the one
called as the type casting. data type into another.
Implemented Implemented on two Implemented only when two data
‗incompatible‘ data types. types are ‗compatible‘.
Operator For casting a data type to another, No operator required.
a casting operator ‗()‘ is
required.
Implemented It is done during program It is done explicitly while
designing. compiling.
Conversion type Narrowing conversion. Widening conversion.
Example int x; int x=3;
byte y; float y;
…y= (byte) x; y=a; // value in y=3.000.

Inbuilt Typecast Functions In C:


There are many inbuilt type casting functions available in C language which performs data
type conversion from one type to another.

S.No Typecast Function Description


1 atof() Convert string to Float
2 atoi() Convert string to int
3 atol() Convert string to long
4 itoa() Convert int to string
5 ltoa() Convert long to string
.

Topic: Conditional Branching: Applying if and switch statements, nesting if and else,
use of break and Default with switch.

If, if-else, Case switch statements


CONTROL STATEMENTS
Control statements enable us to specify the order in which the various instructions in the program are to
be executed. They define how the control is transferred to other parts of the program. Control
statements are classified in the following ways:

a) If statement
Syntax:
if(boolean_expression)
{ /* statement(s) will execute if the Boolean expression is true */
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If boolean expression evaluates to false then the first set of code after the end of the if
statement (after the closing curly brace) will be executed. C programming language assumes any
non-zero and non-null values as true and if it is either zero or null then it is assumed as false value.
Flow Diagram:

Example:
.

#include <stdio.h>
int main ()
{ int a = 10;
if( a < 20 )
{ Printf("a is less than 20\n" );
}
Printf("value of a is : %d\n", a);
}
When the above code is compiled and executed, it produces following result:
a is less than 20;
value of a is : 10

(b) if –else statement


Syntax: The syntax of an if...else statement in C programming language is:
if(boolean_expression)
{ /* statement(s) will execute if the boolean expression is true */
}
else
{ /* statement(s) will execute if the boolean expression is false */
}
If the Boolean expression evaluates to true then the if block of code will be executed otherwise
else block of code will be executed programming language assumes any non-zero and non-null
values as true and if it is either zero or null then it is assumed as false value.
Flow Diagram:

Example:
#include <stdio.h>
main ()
{ int a = 100;
if( a < 20 )
{ Printf("a is less than 20\n" );
}
else
{ Printf("a is not less than 20\n" );
} Printf("value of a is : %d\n", a);}
.

When the above code is compiled and executed, it produces following result:
a is not less than 20;
value of a is : 100

(c) Nested if-else statement


The syntax for a nested if statement is as follows:
if( boolean_expression 1)
{ /* Executes when the Boolean expression 1 is true */
if(boolean_expression 2)
{ /* Executes when the Boolean expression 2 is true */
}
}
Example:
#include <stdio.h>
main ()
{ int a = 100;
int b = 200;
if( a == 100 )
{ if( b == 200 )
{ printf("Value of a is 100 and b is 200\n" );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
}
When the above code is compiled and executed, it produces following result:
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200

(d) A switch statement


Allows a variable to be tested for equality against a list of values. Each value is called a case, and
the variable being switched on is checked for each switch case. Syntax:
switch(expression)
{ case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */

/* you can have any number of case statements */


default : /* Optional */
statement(s);
}
The following rules apply to a switch statement:
• You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
.

• The constant-expression for a case must be the same data type as the variable in the switch,
and it must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
• A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.
Flow Diagram:

Example:
main ()
{ char grade = 'B';
switch(grade)
{ case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
} printf("Your grade is %c\n", grade );
}
When the above code is compiled and executed, it produces following result:
Well done
Your grade is
B.

45

You might also like