0% found this document useful (0 votes)
46 views124 pages

CP Module 1 Material

The document provides an overview of computers, including their definition, characteristics, generations of development, and classifications. It discusses how computers accept data as input, process it, and provide output. The five generations of computers are described from the first generation using vacuum tubes to the current fifth generation focused on artificial intelligence. Computers are also classified based on their operating principles, applications, and size.

Uploaded by

sunstngamers
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)
46 views124 pages

CP Module 1 Material

The document provides an overview of computers, including their definition, characteristics, generations of development, and classifications. It discusses how computers accept data as input, process it, and provide output. The five generations of computers are described from the first generation using vacuum tubes to the current fifth generation focused on artificial intelligence. Computers are also classified based on their operating principles, applications, and size.

Uploaded by

sunstngamers
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/ 124

Dr.

Mahalingam College of Engineering and Technology, Pollachi – 642003


19CSSC2001 C Programming
23ADT001 C Programming
Unit-1 – INTRODUCTION

The term computer is derived from the word compute. The word
compute means to calculate. A computer is an electronic machine that
accepts data from the user, processes the data by performing calculations
and operations on it, and generates the desired output results.

Digital Computer uses distinct values to represent the data internally.


All information is represented using the digits 0s and 1s.
Analog computer is another kind of a computer that represents data as
variable across a continuous range of values.

Characteristics of Computer:

Speed: The computer can process data very fast, at the rate of millions of
instructions per second.

Accuracy: Level of accuracy depends on the instructions and type of


machine being used. Faulty instruction for data processing may lead to
faulty results.

Diligence: When used for a longer period of time, It can perform long and
complex calculations with the same speed and accuracy from the start till
the end.
Reliability: It is measurement of performance of a computer, which is
measured against pre determined standards for operation without any
failure.

Storage Capability: Large volumes of data and information can be stored


in the computer and also retrieved whenever required.
A limited amount of data can be stored, temporarily, in the primary
memory.
Secondary storage devices like floppy disk and compact disk can store a
large amount of data permanently.

Versatility: Computer is versatile in nature. It can perform multiple tasks


simultaneously.
Resource sharing: computers are capable to connect with each other.

GENERATION OF COMPUTERS

The computer has evolved from a large—sized simple calculating machine


to a smaller but much more powerful machine. The evolution of computer
to the current state is defined in terms of the generations of computer.
Each generation of computer is designed based on a new technological
development, resulting in better, cheaper and smaller computers that are
more powerful, faster and efficient than their predecessors. Currently,
there are five generations of computer.

• 1st Generation(1940-1956) : Vacuum Tubes

• 2nd Generation(1956 -1963) : Transistors

• 3rd Generation(1964 to Early 1970s) : Integrated Circuits

• 4th Generation(Early 1970s Till Date) : Microprocessors

• 5th Generation(Present & Beyond) : Artificial Intelligence

First Generation:

Hardware Technology The first generation of computers used vacuum


tubes for circuitry and magnetic drums for memory. The input to the
computer was through punched cards and paper tapes. The output was
displayed as printouts.

Software Technology The instructions were written in machine


language. Machine language uses 0s and 1s for coding of the instructions.
The first generation computers could solve one problem at a time.

Computing Characteristics The computation time was in milliseconds.

Physical Appearance These computers were enormous in size and


required a large room for installation.

Application They were used for scientific applications as they were the
fastest computing device of their time.

Examples UNIVersal Automatic Computer (UNIVAC), Electronic


Numerical Integrator and Calculator (ENIAC), and Electronic Discrete
Variable Automatic Computer (EDVAC).

The first generation computers used a large number of vacuum tubes and
thus generated a lot of heat. They consumed a great deal of electricity and
were expensive to operate. The machines were prone to frequent
malfunctioning and required constant maintenance. Since first generation
computers used machine language, they were difficult to program.

Second Generation:

Hardware Technology Transistors replaced the vacuum tubes of the


first generation of computers. Transistors allowed computers to become
smaller, faster, cheaper, energy efficient and reliable. The second
generation computers used magnetic core technology for primary memory.
They used magnetic tapes and magnetic disks for secondary storage. The
input was still through punched cards and the output using printouts.
They used the concept of a stored program, where instructions were stored
in the memory of computer.

Software Technology The instructions were written using the assembly


language. Assembly language uses mnemonics like ADD for addition and
SUB for subtraction for coding of the instructions. High-level
programming languages, such as early versions of COBOL and
FORTRAN were also developed during this period.

Computing Characteristics The computation time was in microseconds.

Physical Appearance Transistors are smaller in size compared to


vacuum tubes, thus, the size of the computer was also reduced.

Application The cost of commercial production of these computers was


very high, though less than the first generation computers. The transistors
had to be assembled manually in second generation computers.

Examples PDP-8, IBM 1401 and CDC 1604.

Second generation computers generated a lot of heat but much less than
the first generation computers. They required less maintenance than the
first generation computers.

Third Generation:
Hardware Technology The third generation computers used the
Integrated Circuit (IC) chips. Consist of single chip with many
components such as transistors, resistors & capacitors fabricated on it.
Punched cards & printouts are replaced by keyboards & monitors &
interfaced with operating system. Magnetic disks were used for secondary
storage.

Software Technology The keyboard and the monitor were interfaced


through the operating system. Operating system allowed different
applications to run at the same time. High-level languages were used
extensively for programming, instead of machine language and assembly
language.

Computing Characteristics The computation time was in nanoseconds.

Physical Appearance The size of these computers was quite small


compared to the second generation computers.

Application Computers became accessible to mass audience. Computers


were produced commercially, and were smaller and cheaper than their
predecessors.

Examples IBM 370, PDP 11.

The third generation computers used less power and generated less heat
than the second generation computers. The cost of the computer reduced
significantly, as individual components of the computer were not required
to be assembled manually. The maintenance cost of the computers was also
less compared to their predecessors.
Fourth Generation:

Hardware Technology
 They use the Large Scale Integration (LSI) and the Very Large Scale
Integration (VLSI) technology. Thousands of transistors are integrated on
a small silicon chip using LSI technology. VLSI allows hundreds of
thousands of components to be integrated in a small chip. ULSI increased
that number into millions.
 Uses an extension of third generation technology of this generation is
based on IC But these have been made readily available because of
development of the microprocessor (Circuit containing millions of
transistors).
 Magnetic core memories were substituted by semiconductor memories
resulted in RAM.
 Secondary memories –hard disk became economical, smaller & bigger in
capacity.

Software Technology Development of Graphical User Interface (GUIs),


mouse, hand held devices happened

Computing Characteristics The computation time is in picoseconds.

Physical Appearance They are smaller than the computers of the


previous generation. Some can even fit into the palm of the hand.

Application They became widely available for commercial purposes.


Personal computers became available to the home user.

Examples The Intel 4004 chip was the first microprocessor

The microprocessor has resulted in the fourth generation computers being


smaller and cheaper than their predecessors. The fourth generation
computers are also portable and more reliable.
They generate much lesser heat and require less maintenance compared to
their predecessors.GUI (Graphical User Interface) and pointing devices
facilitate easy use and learning on the computer. Networking has resulted
in resource sharing and communication among different computers.
Fifth Generation (Present and Next):

 The goal of fifth generation computing is to develop computers that are


capable of learning and self-organization. The fifth generation computers
use Super Large Scale Integrated (SLSI) chips that are able to store
millions of components on a single chip.
 These computers have large memory requirements.
 This generation of computers uses parallel processing that allows
several instructions to be executed in parallel, instead of serial execution.
Parallel processing results in faster processing speed. The Intel dual core
microprocessor uses parallel processing.
 The fifth generation computers are based on Artificial Intelligence (AI).
They try to simulate the human way of thinking and reasoning. Artificial
Intelligence includes areas like Expert System (ES), Natural Language
Processing (NLP), speech recognition, voice recognition, robotics, etc.

CLASSIFICATION OF COMPUTER

Based on operating principles/Type:

Analog computers: represent data in the form of continuous electrical


signals having a specific magnitude.
Digital computers: store and process data in the digital form.
Hybrid computers: A combination of analog computer and digital
computer because it encompasses the best features of both.

Based on applications:
General purpose computers: can work in all environments.
Special purpose computers: can perform only a specified task.

Based on size and capability:


Microcomputers: Designed to be used by individuals.
Mini Computers: Can handle more data and more input and output than
micro computers.
Mainframe Computers: A very large computer.
Super Computers: The fastest type of computer that can perform
complex operations at a very high speed.
Classification by
Size & capability

Micro Mini Mainframe Super

Desktop Laptop Hand-held

Micro-computer

 It is defined as a computer that has microprocessor as its CPU.

 Microcomputers are small, low-cost and single-user digital computer.


They consist of CPU, Input unit, output unit, storage unit and the
software.
 PCs today are powered by three types of operating systems—
Windows (7, 8 or 10), Mac OS X (Apple) and Linux.

Desktop Computer or Personal Computer (PC):


 It consists of three units—keyboard, monitor, and a system unit
containing the CPU, memory, hard disk drive, etc.
 Used at home
 Used in Educations Institutions and Organizations as nodes
 Can perform typical activities like documentation, playing games,
surfing web to more complex activities as programming, design, DTP
etc.

Laptops (Notebook):
 Same as PCs in functionality
 More Compact, Portable
 Less Power requirement, operated on battery/s
 Less capacity compared to PCs
 Maintenance and actually are costlier compared to PCs
 Theft prone
Netbook:
 These are smaller notebooks optimized for low weight and low cost,
and are designed for accessing web-based applications.

Tablet Computer:
 It has features of the notebook computer but it can accept input from
a stylus or a pen instead of the keyboard or mouse.
 It is a portable computer.

Handheld Computer or Personal Digital Assistant (PDA)


 It is a small computer that can be held on the top of the palm.
 It is small in size.
 Instead of the keyboard, PDA uses a pen or a stylus for input.
 They have a limited memory and are less powerful.
 PDAs can be connected to the Internet via a wireless connection
 PDAs have merged into mobile phones to create smart phones.

Minicomputers

 It is a medium sized computer they have high processing speed , high


storage capacity and more powerful than microcomputer
 Minicomputer is usually designed to serve multiple users
simultaneously. It can support 4–200 users simultaneously.
 Minicomputers lie between mainframe and microcomputers.
 They are also called midrange computers and users can access the
minicomputer through their PCs or terminal.
 They are maintained by some organization
 Ex. PDP – 11, IBM (8000 series)

Mainframe Computer
 Mainframe computers are multi-user, multi-programming and high
performance computers.
 They operate at a very high speed, have very large storage capacity
and can handle the workload of many users.
 Mainframe computers are large and powerful systems generally used
in centralized databases.
 It can support hundreds or thousands of users using the feature of
time sharing supported by systems like Linux.
 Mainframes can concurrently run multiple programs even with a
single CPU. The processor speed in a mainframe is measured in
MIPS (million instructions per second).
 The user accesses the mainframe computer via a terminal that may
be a dumb terminal, an intelligent terminal or a PC. A dumb
terminal cannot store data or do processing of its own. It has the
input and output device only. An intelligent terminal has the input
and output device, can do processing, but, cannot store data of its
own. The dumb and the intelligent terminal use the processing power
and the storage facility of the mainframe computer.
 Mainframe computers are used in organizations like banks or
companies, where many people require frequent access to the same
data, on-line processing of large number of transactions & require
computer systems which have massive data storage & processing
capabilities.
 Some examples of mainframes are CDC 6600 and IBM ES000 series.

Super Computers
 Supercomputers are the fastest and the most expensive machines.
 They have high processing speed compared to other computers.
 The speed of a supercomputer is generally measured in FLOPS
(Floating point Operations per Second).
 Some of the faster supercomputers can perform trillions of
calculations per second. A supercomputer uses multiple CPUs for
parallel data processing, which means portions of the same program
are handled independently by multiple processors.
 Supercomputers are used for highly calculation-intensive tasks, such
as, weather forecasting, Analysis of geological data, climate research
(global warming), molecular research, biological research, nuclear
research and aircraft design.
 They are also used in major universities, military agencies and
scientific research laboratories.
 Some examples of supercomputers are IBM Roadrunner, IBM Blue
gene and Intel ASCI red.
 PARAM is a series of supercomputer assembled in India by C-DAC
(Center for Development of Advanced Computing), in Pune. PARAM
Padma is the latest machine in this series. The peak computing
power of PARAM Padma is 1 Tera FLOP (TFLOP).

BASIC ORAGANIZATION OF A COMPUTER

The computer system

Computer is an electronic device that accepts data as input, processes the


input data by performing mathematical and logical operations on it, and
gives the desired output.
 Hardware consists of the mechanical parts that make up the
computer as a machine. The hardware consists of physical devices
the computer. The devices are required for input, output, storage and
processing of the data. Keyboard, monitor, hard disk drive, floppy
disk drive, printer, processor and motherboard are some of the
hardware devices.
 Software is a set of instructions that tells the computer about the
tasks to be performed and how these tasks are to be performed.
Program is a set of instructions, written in a language understood by
the computer, to perform a specific task.
A set of programs and documents are collectively called software. The
hardware needs to be instructed about the task to be performed.
Software instructs the computer about the task to be performed. The
hardware carries out these tasks.
 Data are isolated values or raw facts, which by themselves have no
much significance. The data is provided as input to the computer,
which is processed to generate some meaningful information.
 Users are people who write computer programs or interact with the
computer.
Components of computer hardware
The computer system hardware comprises of three main components:
1. Input/output (I/O) Unit,
2. Central Processing Unit (CPU), and
3. Memory Unit.
The I/O unit consists of the input unit and the output unit. CPU performs
calculations and processing on the input data, to generate the output. The
memory unit is used to store the data, the instructions and the output
information.
(1). Input/output Unit:
Input unit

 The user interacts with the computer via the I/O unit. The Input unit
accepts data from the user, into a form that is understandable by the
computer. Input devices are classified as follows
 Human data entry devices
Input devices that require data to be entered manually to the computer are
identified as human data entry devices.
 Keyboard
 Pointing devices—mouse, trackball, joystick, digitizing tablet
 Pick devices—light pen, touch screen
 Source data entry devices
Source data entry devices do not require data to be typed-in, keyed-in or
pointed to a particular location.
 Audio input—speech recognition
 Video input—digital camera
 Scanner—hand-held scanner, flat-bed scanner
 Optical Scanner—OCR, OMR, MICR, barcode reader
Output unit
 Output devices provide output to the user, which is generated after
processing the input data.
 The processed data, presented to the user via the output devices
could be text, graphics, audio or video.
 Output devices are classified as follows
 Hard Copy Devices
The output obtained in a tangible form on a paper or any surface is called
hard copy output.
 Printer
 Plotter
 Computer Output on Microfilm (microfiche)
 Soft Copy Devices
The output obtained in an intangible form on a visual display, audio unit or
video unit is called soft copy output.
 Monitor
 Visual Display Terminal
 Video Output
 Audio Response

(2). Central Processing Unit


 Central Processing Unit (CPU) or the processor is also often
called the brain of computer. The CPU is fabricated as a single
Integrated Circuit (IC) chip, and is also known as the
microprocessor.
 CPU consists of Arithmetic Logic Unit (ALU) and Control Unit (CU).
In addition, CPU also has a set of registers which are temporary
storage areas for holding data, and instructions.
 CPU executes the stored program instructions, i.e. instructions and
data are stored in memory before execution. For processing, CPU gets
data and instructions from the memory. It interprets the program
instructions and performs the arithmetic and logic operations
required for the processing of data. Then, it sends the processed data
or result to the memory.
Arithmetic Logic Unit
ALU consists of two units—arithmetic unit and logic unit.
 The arithmetic unit performs arithmetic operations on the data that
is made available to it. Some of the arithmetic operations supported
by the arithmetic unit are—addition, subtraction, multiplication and
division.
 Logic unit performs comparisons of numbers, letters and special
characters. Logic operations include testing for greater than, less than
or equal to condition.
Control Unit
 It acts as a supervisor and, controls and coordinates the activity of the
other units of computer. CU is responsible for organizing the
processing of data and instructions.
 CU coordinates the input and output devices of a computer. It directs
the computer to carry out stored program instructions by
communicating with the ALU and the registers.
 CU tells when to fetch the data and instructions, what to do, where to
store the results, the sequencing of events during processing etc.
 CU uses the instructions in the Instruction Register (IR) to decide
which circuit needs to be activated. When a program is run, the
Program Counter (PC) register keeps track of the program instruction
to be executed next.
 CU also holds the CPU’s Instruction Set, which is a list of all
operations that the CPU can perform.
Registers
 Registers store data, instructions, addresses and intermediate results
of processing.
 Registers are high-speed storage areas within the CPU, but have the
least storage capacity. Registers are not referenced by their address,
but are directly accessed and manipulated by the CPU during
instruction execution.
 Registers store data, instructions, addresses and intermediate results
of processing. Registers are often referred to as the CPU’s working
memory.
 The data and instructions that require processing must be brought in
the registers of CPU before they can be processed.
Central Processing Unit

Control Arithmeti
Unit c Logic
Unit

Registers

 Accumulator (ACC) stores the result of arithmetic and logic


operations.
 Instruction Register (IR) contains the current instruction most
recently fetched.
 Program Counter (PC) contains the address of next instruction to be
processed.
 Memory Address Register (MAR) contains the address of next location
in the Memory to be accessed.
 Memory Buffer Register (MBR) temporarily stores data from memory
or the data to be sent to memory.
 Data Register (DR) stores the operands and any other data.
The number of registers and the size of each (number of bits) register in a
CPU help to determine the power and the speed of a CPU. The size of
register, also called word size, indicates the amount of data with which the
computer can work at any given time. The size of a register may be 8, 16,
32 or 64 bits. 32-bit processor and 64-bit processor are the terms used to
refer to the size of the registers.

(3). Memory Unit


The memory unit consists of cache memory, primary memory and
secondary memory.
Primary memory or main memory of the computer is used to store the data
and instructions during execution of the instructions. Random Access
Memory (RAM) and Read Only Memory (ROM) are the primary memory.
In addition to the main memory, there is another kind of storage device
known as the secondary memory. Secondary memory is non-volatile and is
used for permanent storage of data and programs. A program or data that
has to be executed is brought into the RAM from the secondary memory.
Cache Memory
 The time taken to move the data between RAM and CPU registers is
large. This affects the speed of processing of computer, and results in
decreasing the performance of CPU.
 Cache memory is a very high speed memory placed in between RAM
and CPU.
 Cache memory is a storage buffer that stores the data that is used
more often, temporarily, and makes them available to CPU at a fast
rate.
 The computer also supports cache memory to hold those portions of a
program that are frequently used by the CPU. This fast but small
memory is available as a buffer between the CPU and RAM. When
executing a program, the CPU first looks for the instruction and data
in the cache. If it finds them there (cache hit), access of the slower
RAM is avoided. If the data is not found in the cache (cache miss), the
operating system places it there.
 Cache memory is very expensive, so it is smaller in size. Generally,
computers have cache memory of sizes 256 KB to 2 MB.

Primary Memory
 Primary memory is the main memory of computer. It is used to store
data and instructions during the processing of data. Primary memory
is semiconductor memory.
 Primary memory is of two kinds—Random Access Memory (RAM) and
Read Only Memory (ROM).
 RAM is volatile. It stores data when the computer is on. The
information stored in RAM gets erased when the computer is turned
off. RAM provides temporary storage for data and instructions.
 ROM is non-volatile memory, but is a read only memory. The storage
in ROM is permanent in nature, and is used for storing standard
processing programs that permanently reside in the computer. ROM
comes programmed by the manufacturer.
 RAM stores data and instructions during the execution of instructions.
The data and instructions that require processing are brought into the
RAM from the storage devices like hard disk. CPU accesses the data
and the instructions from RAM, as it can access it at a fast speed than
the storage devices connected to the input and output unit.
 The input data that is entered using the input unit is stored in RAM,
to be made available during the processing of data. Similarly, the
output data generated after processing is stored in RAM before being
sent to the output device. Any intermediate results generated during
the processing of program are stored in RAM.
 RAM provides a limited storage capacity, due to its high cost.

Secondary Memory
 The secondary memory stores data and instructions permanently. The
information can be stored in secondary memory for a long time
(years), and is generally permanent in nature unless erased by the
user. It is a non-volatile memory.
 It provides back-up storage for data and instructions. Hard disk drive,
floppy drive and optical disk drives are some examples of storage
devices.
 The data and instructions that are currently not being used by CPU,
but may be required later for processing, are stored in secondary
memory.
 Secondary memory has a high storage capacity than the primary
memory.
 Secondary memory is also cheaper than the primary memory.
 It takes longer time to access the data and instructions stored in
secondary memory than in primary memory.
 Magnetic tape drives, disk drives and optical disk drives are the
different types of storage devices.
Instruction
 A computer program is a set of instructions that describe the steps to
be performed for carrying out a computational task. The program and
the data, on which the program operates, are stored in main memory,
waiting to be processed by the processor. This is also called the stored
program concept.
 A processor has a set of instructions that it understands, called as
instruction set.
 The primary responsibility of a computer processor is to execute a
sequential set of instructions that constitute a program. CPU executes
each instruction in a series of steps, called instruction cycle.
Fetching: The processor fetches the instruction from the memory.
The fetched instruction is placed in the Instruction Register.
Program Counter holds the address of next instruction to be
fetched and is incremented after each fetch.
Decoding: The instruction that is fetched is broken down into
parts or decoded. The instruction is translated into commands so
that they correspond to those in the CPU’s instruction set. The
instruction set architecture of the CPU defines the way in which
an instruction is decoded.
Executing: The decoded instruction or the command is executed.
CPU performs the operation implied by the program instruction.
For example, if it is an ADD instruction, addition is performed.
Storing: CPU writes back the results of execution, to the
computer’s memory.
 A CPU performance is measured by the number of instructions it
executes in a second, i.e., MIPS (million instructions per second), or
BIPS (billion instructions per second).
 Part of the computer that are responsible for processing or converting
data into meaningful information.
 Processor
 Buses
 System Clock
Processor
 CPU referred to as a Processor Performs processing and control
activities performed by different parts of computer.
Buses
 Electrical pathway that transfer data and instructions among
different parts of computer.
 Main memory is directly/indirectly connected to the processor via a
bus.
 Data Bus - Data bus is Bidirectional because the Microprocessor
can read data from memory or write data to the memory.
 Address Bus - Address bus is Unidirectional because the
microprocessor is addressing a specific memory location.
 Control Bus – Control the activities all the software's and
hardware’s
System Clock – Clock used to synchronizing the activities performed by
the computer.
Factors that affect the performance of the computer
Registers - The bigger the size, the more quickly it can process data.
RAM - Larger the RAM size when the computer is switched on, the
operating system, device drivers, the active files and running programs are
loaded into RAM is very fast.
System Clock- Higher clock frequencies mean more clock ticks per
second. A CPUs performance is measured by the number of instructions it
executes in a second
Bus - The data bus width affects the speed of computer.
Cache memory – Size (amount of cache memory) and level L1, L2 and L3.
Larger the size of cache, the better it is. PCs nowadays have a L1 cache of
256KB and L2 cache of 1MB.

Computer Language
Low-Level Languages:
• Supports low level tasks such as transferring data from memory to
disk, or rendering text onto a display.
• Low level language is machine dependent i.e. a program written for
one type of computer does not work on other computers.
Machine Language –
• First Generation Language Instructions are represented by
combinations of 0’s and 1’s.
• Machine languages are the only languages understood by computers.
Assembly Language –
• Second Generation Language. Machine language instructions are
replaced with simple pneumonic abbreviations (e.g. ADD, MUL, DIV
etc…).
• Computer can’t execute it directly. Programs need to translate into
machine language to run. Assembler translates assembly language
into Machine codes.

High-Level Languages:
• Any language that is independent of the machine such as C, C++,
and Java.
• High level languages uses English like statements and mathematical
notations.
SOFTWARE

Set of computer programs which include instructions, used for performing


a particular task using hardware.
 Software tells hardware: what to do? How to do?
 Software is a collection of code that drives a computer to perform a
related group of tasks.
 It comprises one or more programs, supported by libraries and
configuration files that programs need to access. Software may reside
in a ROM, RAM, secondary storage (the hard disk) or may be loaded
from a network.
Computer software can be broadly divided into two types:
 System software - This is the software run by the computer to
manage the hardware connected to it. Users don’t have much control
over its functioning, but their own programs (application software)
use the services offered by system software whenever required.
 Application software - Software of this type relates to a specific
application, say, and one that makes hotel bookings or creates special
effects in movies. The vast majority of programmers are engaged in
developing application software.

System Software
 System software is "Background" software that helps the computer
manage its own internal resources.
 It enables the application software to interact with the computer
hardware. E.g. Operating System, Device Drivers, Utility Software,
and Translators etc...
 Most system software is run by the computer on startup, first from a
ROM and then from the hard disk. The others are invoked when
programs need them, say, for printing a report. In some cases, a user
may also directly use a program of this type. System software
includes but is not restricted to the following:

 Basic Input Output System (BIOS) - This is a small program that


checks the hardware devices and peripherals at boot time and then
loads the operating system.
 Operating system - This is the central system software that
manages both the hardware and programs running on the computer.
Because all programs need its services, the operating system remains
in memory as long as the computer is up. MS-DOS, MS-Windows,
UNIX, Linux, Mac OS etc…
 Device driver - Every hardware needs special software that knows
how to handle it. Programs access a device driver by making a call to
the operating system.
 Compilers and associated programs - This category of system
software is special because it is invoked by users. A programmer
invokes a compiler program to convert the source code written by
them to machine code.
 Utility Software - Used to analyze, configure and maintain the
computer system. (Antivirus software, backup software and disk
cleaners, clean up tools, defragmentation tool etc…)
When a program run by a user (application software) needs to access
hardware (say, a printer), it makes a call to system software to get the job
done. For this reason, the BIOS and operating system are loaded into
memory before users can run their programs.

Application Software

It is Collection of programs written to specific applications. The


Smartphone industry even has a smart name for it; they call it “apps.”
 Office software - Word processing, spreadsheet and presentations.
 Database software - This software package, commonly known as
Data Base Management System (DBMS), allows data having a
uniform structure to be stored in a database.
 Communications software - Computer networking led to the
development of software that allowed users to communicate with one
another. E.g. Email, Skype and Whatsapp.
 Entertainment software - Gaming software remains extremely
popular and challenging for software developers. The VideoLAN
(VLC) software serves as a one-stop shop for playing most audio and
video formats.
 Anti-virus software - A virus is a small program designed by a
person with malicious intent. Antivirus software essential to protect
from malicious software’s or virus.
 Special-purpose software - desktop publishing, computer-aided
design/manufacturing (CAD/CAM) and distance learning.

Software Development Life Cycle:

Software Development Life Cycle (SDLC) is a process used by the software


industry to design, develop and test high quality software's.
The SDLC aims to produce high-quality software that meets or exceeds
customer expectations, reaches completion within times and cost
estimates.
• It offers a basis for project planning, scheduling, and estimating.
• Provides a framework for a standard set of activities and deliverables
• It is a mechanism for project tracking and control.
• Increases visibility of project planning to all involved stakeholders of
the development process
• Increased and enhance development speed. Improved client relations.
• Helps you to decrease project risk and project management plan
overhead.
Stage1: planning and requirement analysis
 Requirement Analysis is the most important and fundamental stage
in SDLC.
 Getting input from all stakeholders, including customers,
salespeople, industry experts, and programmers.
 Learn the strengths and weaknesses of the current system with
improvement as the goal.
Stage 2: defining
 The team determines the cost and resources required for
implementing the analyzed requirements.
 It also details the risks involved and provides sub-plans for softening
those risks.
Stage 3: designing
 All stakeholders then review this plan and offer feedback and
suggestions.
Stage 4: coding
 At this stage, the actual development starts.
 It’s important that every developer sticks to the agreed blueprint.
 Proper guidelines in place about the code style and practices.
Stage 5: testing
 In this stage, we test for defects and deficiencies. We fix those issues
until the product meets the original specifications.
 Verify if the code meets the defined requirements.
Software deployment
 Deploy the software to the production environment so users can start
using the product.
 Testing or staging environment - This allows any stakeholders to
safely play with the product before releasing it to the market.
Maintenance
 Bug fixing - bugs are reported because of some scenarios which are
not tested at all
 Upgrade - Upgrading the application to the newer versions of the
Software
 Enhancement - Adding some new features into the existing software
PROBLEM SOLVING

In order to solve a problem by the computer, one has to pass though


certain stages or steps. They are
1) Understanding the problem
2) Analyzing the problem
3) Developing the solution
4) Coding and implementation.
To design a program, a programmer must determine three basic
steps
 The instructions to be performed.
 The sequence in which those instructions are to be performed.
 The data required to perform those instructions.

A program is set of instructions to instruct the computer to perform a task.


The instructions are three types,
1) Instructions to accept the data.
2) Instructions that will process the data.
3) Instructions to provide the output to user.
Problem development lifecycle
1) Problem analysis - Understand the problem to be solved.
Determines the various ways in which the problem can be solved,
and decides upon a single solution which will be followed to solve a
problem.
2) Program design – The selected solution represented in three forms
 An algorithm – English like explanation of the solution.
 A flowchart – Diagrammatic representation of the solution.
 A pseudo code – Pseudo code uses the structured programming
constructs called keyword statements.
3) Program Development
 The Pseudo code is coded using suitable programming
language. Like C, C++, and java.
 The coded program is compiled for any syntax errors then
errors removed during compilation.
 The successfully complied program is now ready for solution.
 The executed program generates the output which may be
correct or incorrect. The program is tested with various inputs,
to see that it generates the desired results. The semantic errors
are removed to get the correct results.
 The successfully tested program is ready for use.
4) Program Documentation and Maintenance
 The program is properly documented, The program may
require updating, fixing of errors etc, during the maintenance
phase.

Properties of a good program

Integrity: Integrity refers to the accuracy of the calculations.


Clarity: Overall readability of the program.
Simplicity: The clarity and accuracy of the program are usually enhanced
by keeping things as simple as possible.
Efficiency: Concerned with execution speed and efficient memory
utilization.
Modularity: Large program broken into series of identifiable small
subtask or module. It enhances the accuracy and clarity of the program.
Generality: Program should be general. It should read the values of
certain key parameters rather than fixed values.

Program Logic
• Logic is a just an idea or a blue print for a part of a program which
consists of set of instructions to solve the given problem.
• Logic of the program consists of the statements which will be then
converted into programming language statements that will be
executed by the computer in order to solve the problem.
Problem formulation:
Top down analysis: Subdivide the large problem into several small tasks
or parts for ease of analysis.
Two essential ideas in top down analysis:
Subdivision of a problem
Hierarchy of tasks
Four steps in top down analysis:
Step 1: Define the complete scope of the problem to determine the basic
requirement for its solutions.
Input: what data is required to be processed by the program?
Process: What must be done with the input data? What type of processing
is required?
Output: What information should the program produce? In what form
should it be presented?
Step 2: Based on the definition of the problem, divide the problem into two
or more parts/tasks.
Step 3: Define the scope of ease of these tasks and subdivide them further
if necessary, divide into two or more smaller tasks.
Step 4: Repeat step 3 at lowest level describes a simple tasks, which
cannot be broken further.

Algorithms
An algorithm is a
 well organized,
 Set of step-by-step instructions that perform a specific task or
operation
 Natural language NOT programming language
It helps the programmer in breaking down the solution of a problem into a
number of sequential steps.
Features:
 Finiteness. An algorithm must always terminate after a finite
number of steps.
 Definiteness. Each step of an algorithm must be precisely defined;
the actions to be carried out must be rigorously and unambiguously
specified for each case.
 Input. An algorithm has zero or more inputs, i.e., quantities which
are given to it initially before the algorithm begins.
 Output. An algorithm has one or more outputs i.e, quantities which
have a specified relation to the inputs.
 Effectiveness. An algorithm is also generally expected to be
effective. This means that all of the operations to be performed in the
algorithm must be sufficiently basic that they can in principle be done
exactly and in a finite length of time.
Properties of an algorithm:
 No ambiguity
 No uncertainty about which instruction to be executed next(written
in sequence)
 Conclude after a finite number of steps(algorithm will terminate)
 General enough to deal with any contingency
Factors used to measure the algorithm:
 Time
 Memory
 Accuracy
 Sequence etc,.
Flowcharts:
 It is the pictorial representation of an algorithm in which steps are
drawn in the form of different shapes of boxes and the logical flow is
indicated by interconnecting arrows.
 Boxes represent operations
 Arrows represent sequence in which operations are implemented
 Primary purpose : help programmer in understanding the logic
 Flowchart=Blue print of building

Flowchart Symbols:

 Terminal symbol
It is used to represent the start, end of the program logic.

 Input/output
It is used for input or output.

 Process Symbol
It is used to represent the calculations, data movements,
initialization ope rations etc,.

 Decision Symbol
It is used to denote a decision to be made at that point
 Flow lines
It is used to connect the symbols

 Connectors
It is used to connect the flow lines.

 Loop
It is used to denote loops involved in the process.

Guidelines for preparing flowcharts:


 It should be clear and easy to follow
 Standard symbols should be used.
 The flow lines should not intersect each others.
 In case of complex flowcharts use the connectors symbols.
 Direction of flow of procedure is from left to right or top to bottom
 It must have one logical start and end.
 Only one flow line should enter the process symbol and only one flow
line should come out from a process symbol.

 Only one flow line used with the terminal symbol.


 Only one flow line should enter the decision symbol and two or three
flow lines may leave from the decision symbol.

Benefits of Flowcharts:
 Makes logic clear
 Communication: Flowcharts are better way of communicating the
logic of a system
 Effective analysis: Problem can be analyzed in more effective way.
 Proper documentation: Flowcharts serve as a good program
documentation
 Efficient Coding: Flowcharts act as a guide or blueprint during the
systems analysis and program development phase.
 Proper testing and Debugging: Flowchart helps in debugging
process.
 Efficient Program Maintenance: The maintenance of operating
program becomes easy with the help of flowchart.

Limitations of Using Flowcharts:


 Complex logic: Sometimes, the program logic is quite complicated.
In that case, flowchart becomes complex and clumsy.
 Difficult to modify: Alterations and Modifications- If alterations
are required the flowchart may require re-drawing completely.
 No update: Programs are updated regularly
Pseudo code
 Pseudo means imitation and code means instruction.
 It is formal design tool.
 It is an outline of a program ,written in a form that can be easily
converted in a real programming statements
 It is also called PDL-Program Design Language(Uses plain
English statements to represent computer programs)
Keywords used:
 Input : READ,OBTAIN,GET and PROMPT
 Output :PRINT,DISPLAY and SHOW
 Compute: COMPUTE,CALCULATE and DETERMINE
 Initialize :SET and INITIALIZE
 Add one : INCREMENT

Guideline for writing Pseudo code:


 Simple English
 Understandable
 Concise
 Each instruction in separate line & each statement express one
action
 Capitalize the keyword.
 Top to bottom, with on entry and one exit
 Easy transition from design to coding in programming language

BUILDING BLOCKS OF ALGORITHM


 Algorithm can be constructed from basic building blocks namely
Statements
State
control flow
functions
 Statement is a single action in a computer.
In a computer statements might include some of the following actions
Input data-information given to the program
Process data-perform operation on a given input
Output data-processed result
 State - Transition from one process to another process under
specified condition within a time is called state.
 Control Flow –
The process of executing the individual statements in a given order is
called control flow.
The control can be executed in three ways
Sequence
Selection
Iteration

Sequence

All the instructions are executed one after another is called sequence
execution.
Example: Add two numbers
Step 1: Start
Step 2: get a,b
Step 3: Calculate c=a+b
Step 4: Display c
Step 5: Stop

Selection

 A selection statement causes the program control to be transferred to


a specific part of the program based upon the condition.
 If the conditional test is true, one part of the program will be
executed, otherwise it will execute the other part of the program.

Example: Greatest among two numbers


Step 1: Start
Step 2: Read a, b . /* a, b two numbers */
Step 3: If a>b then /*Checking */
Display “a is the largest number”.
Else
Display “b is the largest number”.
Step 4: Stop.
Iteration
In some programs, certain set of statements are executed again and
again based upon conditional test. i.e. executed more than one time.
This type of execution is called looping or repetition or iteration.

Example: Write an algorithm to print all natural numbers up


to n
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step5: Print i value and increment i value by 1
Step 6: go to step 4
Step 7: Stop
 Functions
 Function is a subprogram which consists of block of code (set of
instructions) that performs a particular task.
 For complex problems, the problem is been divided into smaller and
simpler tasks during algorithm design.

Mainfunction()

Step 1: Start
Step 2: Call the function add()
Step 3: Stop

Sub function add()

Step1:Function start
Step2:Get a,b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return
Examples:
Algorithm Flowchart Pseudocode
Addition of two numbers
Step1: Start READ a,b
Step2: Read two C=a+b
numbers say a, b WRITE C
Step3: Add the value of STOP
a with b and store the
result in c.
Step4: Display the
value of c
Step5: Stop

Odd or even
Step 1:Start START
Step 2: read a Number READ number
Step 3:if (Number%2) IF number MOD 2=0 THEN
is 0,Print/Show as DISPLAY “ Even Number”
even number else ELSE
show as odd number DISPLAY “Odd Number”
Step 4: Stop END IF
STOP
Largest number among 3 numbers
Step1: Start READ a, b, c
Step2: Read the IF (a>b) and (a>c) THEN
value of a, b, c WRITE a is largest
Step3: Check if ELSE IF (b>c) THEN
(a>b) and (a>c) WRITE b is largest
then, print a is ELSE
largest WRITE c is largest
else check if (b>c) ENDIF
then, print b is STOP
largest
else
print c is largest
Step4: Stop

Finding the area of a circle


Step1: Start Begin
Step2: Read the READ r
value of r COMPUTE area=3.14*r*r
Step3: Calculate PRINT area
area stop
Step4: Print area
Step5: Stop
Finding the year is leap year or not
Step1: Start READ year
Step2: Read the IF year % 4 ==0 THEN
value of year WRITE It is a Leap year
Step3: ELSE
IF year % 4 ==0 WRITE It is not a Leap
THEN year
print It is a Leap ENDIF
year Stop
ELSE
print It is not a
Leap year
Step4: Stop

Finding the Sum of the digits


Step1: Start READ the value of n and
Step2: set i =0, sum=0
Read the value of n WHILE (n>0) do
and set sum = 0 r=n%10
Step3: sum=sum + r
While n>0 do n=n/10
r=n%10 ENDWHILE
sum=sum + r Repeat the loop until
n=n/10 condition fails
else Goto step5 WRITE sum
Step4: Goto step 3 Stop
Step5: Print the
value of sum
Step6: Stop
Finding the Reverse of a Number
Step1: Start READ the value of n and
Step2: Read the value set i =0, sum=0
of n and set sum = 0 WHILE (n>0) do
Step3: While n>0 do r=n%10
r=n%10 sum=sum *10 + r
sum=sum *10 + r n=n/10
n=n/10 ENDWHILE
else Goto step5 Repeat the loop until
Step4: Goto step 3 condition fails
Step5: print the value WRITE sum
of sum stop
Step6: Stop

Finding the Armstrong Number


Step1: Start READ the value of n and
Step2: Read the value set a =n, sum=0
of n ,set a = n,sum = 0 WHILE (n>0) do
Step3: While n>0 do r=n%10
r=n%10 sum=sum + r*r*r
sum=sum + r*r*r n=n/10
n=n/10 ENDWHILE
else Goto step5 Repeat the loop until
Step4: Goto step 3 condition fails
Step5: If a = sum then IF a=sum THEN
Print Armstrong WRITE Armstrong
Number Number
Else ELSE
Print It is Not an WRITE It is not an
Armstrong Number Armstrong Number
Endif ENDIF
Step6: Stop Stop
Finding the Fibonacci series
Step1: Start READ the value of n and
Step2: Read the value set f=0 ,f1=-1, f2=1
of n and set f=0,f1=- WHILE (f<n) do
1, f2=1 f=f1+f2
Step3: While (f<n) do f1=f2
f=f1+f2 f2=f
f1=f2 WRITE f
f2=f ENDWHILE
Print f Repeat the loop until
else Goto step5 condition fails
Step4: Goto step 3 stop
Step5: Stop

Finding the Sum of odd number between 1 to n


Step1: Start READ the value of n and
Step2: Read the value set sum=0,i=1
of n and set WHILE (i<=n) do
sum=0,i=1 sum=sum+i
Step3: While (i<=n) i=i+2
do ENDWHILE
sum=sum+i Repeat the loop until
i=i+2 condition fails
else Goto step5 WRITE sum
Step4: Goto step 3 stop
Step5: Print sum
Step6: Stop
Finding the Sum of even number between 1 to n
Step1: Start READ the value of n and
Step2: Read the value set sum=0,i=0
of n and set WHILE (i<=n) do
sum=0,i=0
Step3: While (i<=n) sum=sum+i
do i=i+2
sum=sum+i ENDWHILE
i=i+2 Repeat the loop until
else Goto step 5 condition fails
Step4: Goto step 3 WRITE sum
Step5: Print sum stop
Step6: Stop

Conversion of Binary number to Decimal


Step1: Start READ the value of n and
Step2: Read the value set i =0, sum=0
of n & set i = 0, sum = 0 WHILE (n>0) do
Step3: While n>0 do r=n%10
r=n%10 sum=sum + r*pow(2,i)
sum=sum + r*pow(2,i) n=n/10
n=n/10 i=i+1
i=i+1 ENDWHILE
else Goto step5 Repeat the loop until
Step4: Goto step 3 condition fails
Step5: print the value WRITE sum
of sum stop
Step6: Stop
Conversion of Celsius to Fahrenheit
Step1: Start Set Fahrenheit
Step2: Read the value READ the Celsius
of Celsius COMPUTE Fahrenheit =
Step3: Fahrenheit = (1.8* Celsius) + 32
(1.8* Celsius) + 32 PRINT Fahrenheit
Step4: Print stop
Fahrenheit
Step5: Stop

Conversion of Fahrenheit to Celsius


Step1: Start Set Celsius
Step2: Read the value READ the Fahrenheit
of Fahrenheit COMPUTE Celsius
Step3:Calculate Celsius =(Fahrenheit – 32)/1.8
=(Fahrenheit – 32)/1.8 PRINT Celsius
Step4: Print Celsius stop
Step5: Stop

Finding the Factorial


Step1: Start READ the value of n and
Step2: Read the value set i =1
of n and set i =1 WHILE (i <= n) do
Step3: While i <= n do fact =fact * i
fact =fact * i i=i+1
i=i+1 ENDWHILE
else Goto step5 Repeat the loop until
Step4: Goto step 3 condition fails
Step5: print the value WRITE fact
of fact stop
Step6: Stop
Swapping two variables
Step1: Start READ the value of a, b
Step2: Read the value To swap use
of a, b c=a
Step3: c = a a=b
a=b b=c
b=c WRITE a, b
Step4: Print the value stop
of a and b
Step5: Stop

Swapping two variables without using another variable


Step1: Start READ the value of a, b
Step2: Read the value To swap use
of a, b a=a+b
Step3: a = a + b b=a-b
b=a-b a=a-b
a=a-b WRITE a, b
Step4: Print the value stop
of a and b
Step5: Stop
UNIT 2 - C PROGRAMMING BASICS

History of C

Ken Thompson created the B language in 1969 from martin Richard’s BCPL (Basic
Combined Programming Language). He used assembly language and B to produce the initial
versions of the UNIX operating system. BCPL and B were type less languages in which
variables were simply words in memory. Dennis Ritchie of Bell Laboratories latter converted
B into C by retaining most of B’s syntax in 1972 and wrote the first compiler, In 1978,
Kernighan and Ritchie wrote a book entitled ‘ The C programming Language’ that become the
language definition almost a decade. By mid 1980s, popularity of C becomes wide spread.
Numerous C compilers were written for computers of all sizes.

What is C?

C is a general-purpose, block-structured, procedural, case-sensitive, free-flow, portable and


high-level programming language developed by Dennis Ritchie at the Bell Telephone
Laboratories. The selection of ‘C’ as the name of a programming language seems to be an odd
choice but it was named C because it evolved from earlier languages Basic Combined
Programming Language (BCPL) and B.

Why Learn C?
C is a core language: In computing, C is a general-purpose, cross-platform, block structured
procedural, imperative computer programming language. A number of common and popular
computer languages are based on C. Having learnt C, it will be much easier to learn languages
that are largely or in part based upon C. Such languages include C++, Java, and Perl.
C is a small language: C has only thirty-two keywords and only about twenty of them are in
common use. This makes it relatively easy to learn compared to bulkier languages.
C is quick: We can write codes which run quickly, and the program can be very ‘close to the
hardware’. This implies that you can access low-level facilities in your computer quite easily,
without the compiler or run-time system stopping you from doing something potentially
dangerous.
C is portable: C programs written on one system can be run with little or no modification on
other systems. If modifications are necessary, they can often be made by simply changing a
few entries in a header file accompanying the main program.

Key features or characteristics of C language:


• General-purpose programming language
• Middle level language, which means it combines the features of high-level language
with the functionality of an assembly language
• Structured programming language ,procedural language
• Simple and easy to use
• Vast collection of keywords, operators, built-in functions and data types
• Portable and can be used in different environments
• Used as an interface to other more visual languages
• It is very flexible
• It is fast
• It is modular, i.e. can be divided into small modules
• It is easily available
• It is easy to debug, as it detects syntax errors quickly and easily and displays the errors
along with the line numbers of the code and the error message

Assembler, Compiler and Interpreter

A program is a set of instructions for performing a particular task. These instructions are just
like English words. The computer interprets the instructions as 1’s and 0’s. A program can be
written in assembly language as well as in high-level language. This written program is called
the source program. The source program is to be converted to the machine language, which is
called an object program. A translator is required for such a translation.
Program translator translates source code of programming language into machine language
instruction code. Generally, computer programs are written in languages like COBOL, C,
BASIC and ASSEMBLY LANGUAGE, which should be translated into machine language
before execution.
Programming language translators are classified as follows.
(i) Assembler
(ii) Compiler
(iii) Interpreter
Assembler: An assembler translates the symbolic codes of programs of an assembly language
into machine language instructions. The assembler programs translate the low-level language
o the machine code.

Mnemonic
Assembler Machine code
language

Compiler: Compilers are the translators, which translate all the instructions of the program
into machine codes, which can be used again and again The program, which is to be
translated, is called the source program and after translation the object code is generated.
The source program is input to the compiler. The object code is output for the secondary
storage device. The entire program will be read by the compiler first and generates the object
code.
Interpreter: Interpreters also come in the group of translators. It helps the user to execute the
source program with a few differences as compared to compilers. The source program is just
like English statements in both interpreters and compilers. The interpreter generates object
codes for the source program. Interpreter reads the program line by line, whereas in compiler
the entire program is read by the compiler, which then generates the object codes. Interpreter
directly executes the program from its source code.

Mnemonic Compilers/Inte
Machine codes
language rpreters

Compiling and linking the Program or Life cycle of a program

Compiling involves preprocessing, compilation, assembly, and linking.


Editing the Program
Before writing a program, you need to first identify its input and output and then develop the
program logic. Once you have the algorithm or flowchart ready, key in the source code using
editing software. Most of the C compilers come with an editor for writing the source code.
This editor is specially designed for writing the source code of C programs. It makes the
writing of the C source code easier. They highlight various parts of the program in different
colors. This makes the source code more readable. This source code is saved in on the disk as
an ASCII text file with an extension .c. For example sum.c
The Three-Phase Compilation Process
The Preprocessing

This program acts on lines that begin with a #. They occur mostly at the beginning of a
program and are called preprocessor directives. A directive may insert the contents of a header
file at that location (like #include <stdio.h>) or perform a substitution (like #define PI 3.142)
in the program itself. Preprocessing It processes include-files, conditional compilation
instructions, and macros. The C preprocessor is used to modify the program according to the
preprocessor directives in the source code.

Compilation
It is the second step of the compiling process. The process of converting of the source code
into machine code/Object code is called compiling. The program that is used to convert the
source code into machine code is called compiler. The compiler examines each program
statement contained in the source program and checks it to ensure that it conforms to the
syntax and semantics of the language. The compiler creates object code and saves it in a new
file on the disk. The file name has an extension .obj.

Before creating the object code, the compiler scans the source code for errors. If there are
errors in the source code, it does not compiler the source code and indicates the error. All the
errors must be removed from the source code before creating the object code of the program.

Assembly
It is the third stage of compilation. It takes the assembly source code and produces an
assembly listing with offsets. The assembler output is stored in an object file. After the
program has been translated into an equivalent assembly language program, the next step in
the compilation process is to translate the assembly language statements into actual machine
instructions.

Linking
A C program may contain predefined routines and functions. These functions are contained in
separate files and these files are part of the C compilers and are called library files or runtime
libraries.

In this step the necessary libraries are linked to the object code and executable file of the
program is created. The functions are the part of the standard C library, provided by every C
compiler. The program may use other source programs that were previously processed by the
compiler. These functions are stored as separate object files which must be linked to the object
file. Linker handles this linking. The process of compiling and linking a program is often
called building.
The linker also detects errors and does not create the executable file. These errors are removed
in the source code and new object file is created. The new object file is then linked to libraries
to create executable file. The executable file created with .exe extension.

Executing the Program


The program actually runs on the system. When run the program the system loader loads the
file into computer memory and executes it. The executable file of the program may also
contain certain errors and these errors can produce wrong output or they may halt the system.
These errors are located and removed from the source code is again compiled to create
executable file.

When the program is executed, each of the statements of the program is sequentially executed.
If the program requests any data from the user, known as input, the program temporarily
suspends its execution so that the input can be entered. Or, the program might simply wait for
an event, such as a mouse being clicked, to occur. Results that are displayed by the program,
known as output, appear in a window, sometimes called the console. Or, the output might be
directly written to a file on the system.
Errors
If all goes well, the program performs its intended task. If the program does not produce the
desired results, it is necessary to go back and reanalyze the program. Three types of errors
may occur:
Compile errors: These are given by the compiler and prevent the program from running.
Linking errors: These are given by the linker or at run time and end the program. The linker
can also detect and report errors, for example, if part of the program is missing or a
nonexistent library component is referenced.
Run-time errors: These are given by the operating system.

Debugging

Removing errors from a program is called debugging. Any type of error in a program is
known as a bug. During debugging, an attempt is made to remove all the known problems or
bugs from the program.
A debugger is a program that enables the programmer to run another program step-by-step
and examine the value of that program’s variables.
The programming language are designed to support certain kind of data, such as numbers,
characters, strings, to get useful output known as result/information. Data consists of digits,
alphabets and symbols.
Execution Flow (Simple description)

1) C program (source code) is sent to preprocessor first. The preprocessor is


responsible to convert preprocessor directives into their respective values. The
preprocessor generates an expanded source code.

2) Expanded source code is sent to compiler which compiles the code and converts it
into assembly code.

3) The assembly code is sent to assembler which assembles the code and converts it into
object code. Now a simple.obj file is generated.

4) The object code is sent to linker. Linker links it to the library such as header files.
Then it is converted into executable code. A simple.exe file is generated.

5) The executable code is sent to loader which loads it into memory and then it is
executed. After execution, output is sent to console.

BASIC STRUCTURE OF A C PROGRAM

C is a structured programming language. Every C program contains a number of building


blocks. These building blocks should be written in a correct order and procedure, to execute
without any errors. It is known as functions.
Documentation section
We can give comments about the program, creation or modified date, author name etc in this
section. The characters or words or anything which are given between “/*” and “*/”, won’t
be considered by C compiler for compilation process. These will be ignored by C compiler
during compilation. Example: /* comment line1 comment line2 comment 3 */
Comment section
Comment section is used to convey a message and improve readability of a program.
Comments contains author name, date of development and program details they are not part
of executable programs.
Two types of comments
1. Single line comments: A single line comments starts with two forward slashes(//) and
terminated with the end of line
Example: //sum of two numbers
2. Multi line comments: A multi line comments starts with /* and terminated with */.It is
used when multiple lines of comments are included.
/* this is multi line comments */

Link Section/Preprocessor Directive Section


Header files that are required to execute a C program are included in this section
1. The preprocessor directive always starts with a pound symbol (i.e. #).
2. The pound symbol # should be the first non-white space character in a line.
3. The preprocessor directive is terminated with a new line character and not with a
semicolon.
4. Preprocessor directives are executed before the compiler compiles the source code.
Include header file section
Each header file by default is extended with .h
Header file should be included using #include directive as
# include <stdio.h> or
#include “stdio.h”

Definition Section
In this section, variables are defined and values are set to these variables.

Global Declaration Section


Global variables are defined in this section. When a variable is to be used throughout the
program, can be defined in this section. This section declares some variables that are used in
more than one function and variables can be accessed anywhere within the program.

Function prototype declaration section


Function prototype gives much information about a function like return type, parameter
names used inside the function.

Main function
Every C program is started from main function and this function contains two major sections
called declaration section and executable section.
int main(void) -The int main(void) is a function that takes no arguments and returns a value
of type int.
void main(void) and void main()
The program execution begins with the opening brace “{“and ends with a closing brace “}”
Declaration Part: The declaration part declares the entire local variables that are used in
executable part. Local variable scope is limited to that function where the local variables are
declared.
Executable part
This part includes the statements following the declaration of variables

User defined function section


User can define functions in this section as per requirement which perform particular task as
per the user requirement. User defined functions which are called by main function and each
user defined function contains the return type, function name and argument list.
Each function has two parts header of the function and Body of the function.
Header of the function syntax: [return_type] function_name ([argument list]
Body of the function consists of a set of statements enclosed with in curly braces. It consists
of executable and non executable statements.
Include header file section
Global declaration section
/*comments*/
main () /*function name*/
{
/*comments*/
//Declaration part
//Executable part
}
User defined functions
{
// statements
}

/*
Documentation section
C programming basics & structure of C programs
Author: fresh2refresh.com
Date : 01/01/2012
*/

#include <stdio.h> /* Link section */


# define pi 3.14 //definition section
int total = 0; /* Global declaration section */
int sum (int, int); /* Function declaration section */
int main () /* Main function */
{
printf ("This is a C basic program \n");
total = sum (1, 1);
printf ("Sum of two numbers : %d \n", total);
return 0;
}

int sum (int a, int b) /* User defined function */


{
return a + b; /* definition section */
}
Programming Rules
 Every program should have main () function.
 Statements should be terminated by a semi-colon. At some places, a comma operator
is permitted.
 All statements should be written in lowercase letters. Generally, uppercase letters are
used only for symbolic constants.
 Blank spaces may be inserted between the words. This leads to improvement in the
readability of the statements. However, this is not applicable while declaring a
variable, keyword, constant and function.
 The opening and closing braces should be balanced.

COMPILERS AND INTERPRETERS


• A program is a set of instructions performing a particular task.

• The program can be written in assembly language as well as high level language. This
is source program.

• The source program is to be converted to the machine language which is called object
program.

S.N Compiler Interpreter


o.
Interpreter takes one statement then
Compiler translates the entire program
1 translates it and executes it and then takes
in one go and then executes it
another statement
Compiler generates the error report after Interpreter will stop the translation after it
2
the translation of entire program gets the first error
Compiler takes a larger amount of time
Interpreter takes lesser time in the same
3 in analyzing and processing the high
process
level language code
Overall execution time of a code is
4 Overall execution time of code is faster
slower
1. C CHARACTER SET
 A Character set defines the valid characters that can be used in a source program or
interpreted when program is running.
 The set characters that can be used to write a source program is called a source
character set. It is used to construct the statements in the program.
 The set of characters that are available when program is being executed is called
execution character set. These characters are employed at the time of execution
i.e. they have effects only when the program is being executed.

Alphabets

Digits

White spaces and


escape sequences
Special characters
C character set
ASCII Code: ASCII stands for American Standard Code for Information Interchange, is
the code of two types. One uses 7 bits and other uses 8 bits. The 7-bit code represents 128
different characters and the 8-bit code represents 256 characters. For example, the
character A is represented in 7-bit code as 10000012(decimal 65).

2. DELIMITERS
The language C uses special kind of symbol, which are called delimiters.

3. C TOKENS
The smallest individual units of a program are known as tokens. The C programs can be
written using the tokens and its syntax rules.
KEYWORDS

 Keywords are reserved words whose meaning has already been explained to the
compiler and that has a particular meaning the programming language.
 There are 32 keywords available in C and must written in lower case.

CONSTANTS

 A constant is an entity whose value remains the same throughout the execution of a
program. Constants are assigned to variables.
 It can be placed on the right side of the assignment operator. Ex: X=3; 3 is a constant.
Numerical Constants

Integer Constants: These constants are represented with whole numbers. They require a
minimum of 2 bytes and a maximum of 4 bytes of memory.

(a) Numerical constants are represented with numbers. At least one digit is needed for
representing the number.
(b) The decimal point, fractional part, or symbols are not permitted. Neither blank spaces nor
commas are permitted
(c) Integer constant could be either positive or negative or may be zero.
(d) A number without a sign is assumed as positive.

Some valid examples: 10, 20, +30, –15, etc.


Some invalid integer constants: 2.3, .235, $76, 3 ^6, etc.

They can also be represented in octal or hexadecimal number system based on the
requirement. The octal numbers are 0, 1, 2, 3, 4, 5, 6, and 7 and the hexadecimal numbers are
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,A, B, C, D, E, and F.

Examples of octal and hexadecimal numbers:


Octal numbers – 027, 037, 072
Hexadecimal numbers – 0X9, 0Xab, 0X4

Real Constants: Real constants are often known as floating point constants. Real constants
can be represented in exponential or fractional form.
The following concepts are essential to follow the real numbers:
(a) The decimal point is permitted.
(b) Neither blank spaces nor commas are permitted.
(c) Real numbers could be either positive or negative.
(d) The number without a sign is assumed as positive.

Examples of real numbers are 2.5, 5.521, 3.14, etc.

The real constants can be written in exponential notation, which contains fractional and
exponential parts.
For example, the value 2456.123 can be written as 2.4561 X e+3. The part that precedes e is
called mantissa and the part that follows it is an exponent. In this example, 2.4561 is the
mantissa and +3 is the exponent.
The following points must be noted while constructing a real number in exponential form:

(a) The real number should contain a mantissa and an exponent.


(b) The letter ‘e’ separates the mantissa and the exponent and it can be written in lower or
uppercase.
(c) The mantissa should be either a real number represented in decimal or integer form.
(d) The mantissa may be either positive or negative.
(e) The exponent should be an integer that may be positive or negative.
Some valid examples are 5.2e2,–2, 5.0e–5, 0.5e–3, etc.

Character Constant

Single Character Constants: A character constant is a single character. It can also be


represented with single digit or a single special symbol or white space enclosed within a pair
of single quote marks or character constants are enclosed within single quotation marks.
Example:
‘a’, ‘8’, ‘-’ printf (“%c %d”, 65, ‘B’) will display character ‘A’ and 66.

String Constants: String constants are a sequence of characters enclosed within double quote
marks. The string may be a combination of all kinds of symbols.
Example: “Hello”, “India”, “444”, “a”.

IDENTIFIERS

Identifier is a name of an object. A symbolic name is used to refer to a variable, constant,


function, structure, union etc. This process is done with identifiers. In other words, identifiers
are the names of variables, functions, arrays, etc.
Identifiers are user-defined names. They are generally defined in lowercase letters. However,
the uppercase letters are also permitted. The underscore (_) symbol can be used as an
identifier.
• E.g.: Student_Name, StudentName, student_name, student1, _student1.
#define N 10
#define a 15 here ‘N’ and ‘a’ are user defined identifiers.
Rules for defining identifier:
• First character must be alphabetic (either uppercase or lowercase) or an underscore.
• Identifier name in C can have letters, digits, or underscores.
• Only the first 31 characters of an identifier are significant and are recognized by the
compiler.
• Special character (except underscore), blank space and comma cannot be use in an
identifier name.
• Cannot use a keywords or reserved word (e.g. main, include, printf & scanf etc.).
• No space are allowed between the identifiers etc,
• C is case sensitive, e.g. My_name  my_name.
Variables: Variables is an entity used to store values whose value can vary during the
program execution. It has memory location and can store single value at a time. A variable is a
data name used for storing a data value. Example: height, average, sum, avg12
Declaration statement: Every identifier need to be declared before it is used.
Syntax: [storage_class_specifier] [type_qualifier][type modifier] type_ identifier=[value];
Terms enclosed with [] optional. Type identifier and ; is important.
Common syntax: datatype variable1,variable2…variable;
int variable;
static int variable;
static unsigned int variable;
static const unsigned int variable;
example: int variable =20; int a=20;

Program to declare and initialize variables and display outputs.


void main()
{
int age=20;
float height=5.4;
char gender=‘M’;
clrscr();
printf(“Age :%d \nHeight : %g \nGender : %c”,age,height,sex);
}
OUTPUT:
Age: 20
Height: 5.4
Gender: M

int Float Character string

• int a; • float a; • char a; • char a[5];


• a=10; • a=10.5; • a=‘x’ • a=“hello”;

Data types

The data type defines the possible values that an identifier can have and the valid operations
that can be applied on it. The memory requirement for each data will be determined by the
possible range of values for the data type.
C data
type

Basic/Primitiv valueless User


Derived
e datatype defined
Datatype
data type

Pointers Structure
Integer(int) void Union
Functions
Character Enumeratio
(char) Arrays
n
Float Typedef
double
long doube

Basic Data Type:

Integer Data Type


 A number without a fraction part : integral number.
 C supports three different sizes of the integer data type :
 short int
 int
 long int
Character data type:

• Characters are generally stored using 8 bits (1 Byte) of the internal storage.

Floats and Doubles: single precision (float) and double precision (double) floating points

 A floating-point type is a number with a fractional part, e.g. 56.78


 Floating point numbers are stored using 4 Byte.
 Types :- Float , Double , long double
Integer and Float Number Representations

Integer Representation

The signed integer has signs positive


or negative. The signs are represented in the computer in the binary format as 1 for − (minus)
and 0 for + (plus) or vice versa. The sign bit is always coded as leftmost bit.

+7 is represented as 0 0000111

The signed negative integers can be represented in any one of the following forms:
(a) signed—magnitude form
(b) signed—1’s complement form
(c) signed—2’s complement form

In the signed magnitude form, the sign of the number is represented as 1 and the magnitude
by equivalent
binary form.
Example:
−7 is represented as 1 0000111
In the signed 1’s complement form, the sign of the integer is indicated by 1 and the
magnitude is shown in 1’s complement form as follows,
−7 is represented as 1 1111000
In the above signed − 2’s complement form, the sign is indicated by 1 and magnitude by 2’s
complement form as follows,
−7 is represented by 1 1111001

Floating-Point Representation

The system of the number representation that keeps track of the position of binary and decimal
point is better than the fixed-point representation. This system is called floating-point
representation.
The real number 454.45 can be written as 4.5445 × 102 or 0.45445 × 103 .
0.45445 3
Mantissa Exponent

Void
 The void type has no values and no operations.
 Both the set of values and the set of operations are empty.
DERIVED DATA TYPE
• These data types are derived from the basic data types.
1. Array type
2. Pointer type
3. Function type
USER DEFINED DATA TYPE
• The c language provides flexibility to the user to create new data types.
• These newly created data types are called as user defined data types.
1. Structure
2. Union

//program to display given data

#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
float b=10.88;
char c=‘$’;
char d[5]=“hello”;
clrscr();
printf(“Integer value : %d\n”,a);
printf(“Float value : %f\n”,b);
printf(“Character : %c\n”,c);
printf(“String : %s”,d);
getch();

Different between declaration and definition:


Declaration only introduces the name of an identifier along with its type to the compiler
before it is used. During declaration, no memory space is allocated to an identifier.
Definition of an identifier means the declaration of an identifier plus reservation of space for it
in the memory.
Type qualifiers, Type modifiers and Type conversion
Type qualifiers: it doesn’t affect the range of values and the arithmetic properties of the
declared object. They are used to indicate the special properties of data within an object.
Const qualifier: - Declaring an object const the value will not changed during execution.
void main()
{
const int num=12;
++num;
}
The above program code will not be executed and end with error message. Here,
a constant variable attempted to modify its value.

Volatile qualifier: - Declaring an object as volatile means the object has some special
properties relevant to optimization.
void main()
{
volatile int x;
volatile const int y=10;
clrscr();
printf(“Enter an integer:”);
scanf(“%d”,&x);
printf(“Entered integer is :%d”,x);
x=3;
printf(“\nChanged value of x is :%d”,x);
printf(“\nValue of y:%d”,y);
/* y=8;*/
getche();
}
OUTPUT:
Enter an integer:5
Entered integer is :5
Changed value of x is :3

Value of y:10
x is initialized with keyword volatile and y is with volatile constant. Value
of x can be changed but volatile const cannot be changed. ‘Cannot modify
a const value’.
Type modifiers:
It modifies the base type to yield new type. It modifies the range and arithmetic
properties of the base type (Key words are signed, unsigned, short, long).
Type Conversion
In C, it is possible to convert one data type to another.
Explicit type conversion- programmer needs the result in certain data type. For
example division of 5 with 2 should return float value.
Implicit type conversion- In C automatically ‘lower’ data type is promoted to ‘upper’
data type. For example, data type char or short is converted to int.
In case an expression contains one of the operands as unsigned operands and another
non -unsigned, the latter operand is converted to unsigned.
Initializing Variables
Variables declared can be assigned or initialized using assignment operator ‘=’. The
declaration and initialization can also be done in the same line.
Static initialization
Syntax:
variable_name = constant; or data_type variable_name= constant;
Example:
int y =2 ; where y is an integer variable.

Dynamic Initialization

The initialization of variable at run time is called dynamic initialization. Dynamic refers
to the process during execution.

void main()
{
int r=2;
float area=3.14*r*r;
clrscr();
printf(“Area=%g”,area);
}

OUTPUT:
Area=12.56

In the above program, area is calculated and assigned to variable area. The expression is
solved
at a run time and assigned to area at a run time. Hence, it is called dynamic
initialization.
RULES FOR DEFINING VARIABLES

 Capital letters A-Z, lowercase letters a-z, digits 0-9, and the underscore character

 First character can be a letter or underscore without spaces.

 Usually only the first 32 characters are significant

 There can be no embedded blanks

 Variable name should not be a C Keyword

 Identifiers are case sensitive eg., SUM ,sum are different

 Variable name should not start with a digit

 The variable names may be a combination of upper and lower characters

OPERATORS AND EXPRESSION

Expression: - An expression is a sequence of operands and operators that specifies the


computations of a value. Example: X=a+b.

Operands: - An operand is an entity on which an operation is to be performed. An operand


can be a variable name, a constant, a function call or a macro name.

Example: X=a+b; Where X, a, b are the operands.

Operators: - An operator is a symbol that specifies an operation to be performed on operands.

Example: X=a+b; Where + is an operator.

Operator Precedence:
Precedence means priority. Every operator in C has assigned precedence (priority). An
expression may contain a lot of operators. The operations on the operands are carried out
according to the priority of the operators. The operators having higher priority are evaluated
first and then lower priority.
 The parenthesized sub-expressions are evaluated first.
 If the parentheses are nested, the innermost sub-expression is evaluated first.
 The precedence rules are applied to determine the order of application of operators
while evaluating sub-expressions.
 The associativity rule is applied when two or more operators of the same precedence
appear in the sub-expression.
 BODMAS – Brackets->of->Division->Multiplication->Addition->Subtraction.
# include <stdio.h>
# include <conio.h>  In this program, in the expression j = a
main () + b c, first multiplication operation is
{ performed followed by addition
int a=1,b=2,c=3,j; operation;
clrscr();  Hence, value of j is 7. In the second
j=a+b*c; expression, the parentheses give first
printf (“\n j=%d”,j); priority to the addition operation.
j=(a+b)*c;  Hence, addition of ‘a’ and ‘b’ is
printf (“\n j=%d”,j); performed first and followed by
} multiplication is performed.
OUTPUT:
j=7
j=9

Associativity

Associativity means the direction of execution.

Left to right: In this type, expression, evaluation starts from left to right direction.
Example: 12 4 / 8 % 2
In the above expression, all operators are having the same precedence, and so associativity
rule is followed (i.e. direction of execution is from left to right).
= 48 / 8 % 2
=6%2
= 0 (The above modulus operation provides remainder 0)
(ii) Right to left: In this type, expression, evaluation starts from right to left direction.
Example: a=b=c
In the above example, assignment operators are used. The value of c is assigned to b and then
to a. Thus, evaluation is from right to left.

CLASSIFICATION OF OPERATORS
The operators in C classified based on
1. The number of operands on which an operator operates.
2. The role of an operator.

Classification based on number of operands

i. Unary operators
ii. Binary operators
iii. Ternary operators
Unary operators

A unary operator operates on only one operand.

C Operation Operator Example Explanation


Positive + a = +3 The first assigns positive 3 to a then
increment
Negative/Minus - b = -a First decrement then second assigns
the negative value of a to b.
Increment ++ i++ i++ is equivalent to i = i + 1
Decrement -- i-- i-- is equivalent to i = i-1
Ampersand & &a Assigns value to a
Logical negation ! !a Negate the value
Size of sizeof Sizeof(2) Results the size of value

Binary operators : A binary operator operates on two operands.


Example: 8+3. Here + is the binary operator it operates on 8 and 3.

C Operation Operator Example:


Addition + A=a + b
Subtraction - B=a-b
Multiplication * C=a*b
Division / C=a/b
Modulus % C=a%b
Ternary operator
A ternary operator operates on three operands. The only ternary operator in C language is
conditional operator (? :).

Classification based on role of an operator.


1. Arithmetic operators
 The unary plus operator can appear only towards the left side of its operand. Ex : +5
 The unary minus operator can appear only towards the left side of its operand. Ex : -5
 Increment operator
The increment operator can appear towards the left side or towards the right side of its
operand.
If the increment operator appears towards the left side of its operand, it is known as the
pre increment operator. Ex: ++a. The pre increment operation increments a value by 1
and then assigns value to ‘a’.
If the increment operator appears towards the right side of its operand it is known as the
post increment operator. Ex: a++. The post increment operation assigns the value to ‘a ‘
then increments the value by 1.

#include<stdio.h>
main() a=3, b=3, c=3, d=2
{ Reasons:
int a=2, b=2,c,d; • The value of a is incremented and
c=++a; then it is assigned to c as a is pre
d=b++; incremented
printf(“a=%d, b=%d, c=%d, d=%d”,a,b,c,d); • The value of b is assigned to d
} before it is incremented as b is post-
incremented

 Decrement operator
The decrement operator can appear towards the left side or towards the right side of its
operand.
If the decrement operator appears towards the left side of its operand, it is known as the
pre decrement operator. Ex: --a. The pre decrement operation decrements a value by 1
and then assigns value to ‘a’.
If the decrement operator appears towards the right side of its operand it is known as the
post decrement operator. Ex: a--. The post decrement operation assigns the value to ‘a ‘
then decrements the value by 1.
a=1, b=1, c=1, d=2
Reasons:
#include<stdio.h>
• The value of a is decremented
main()
and then it is assigned to c as a is
{
pre decremented
int a=2, b=2,c,d;
• The value of b is assigned to d
c=−−a;
before it is decremented as b is
d=b−−;
post-decremented
printf(“a=%d, b=%d, c=%d, d=%d”,a,b,c,d);
}

 Division operator
The division operator is used to find the quotient.
The sign of the result of evaluation of the division operator depends upon the sign of
both the numerator as well as the denominator.
If both are positive, the result will be positive. If both are negative, the result will be
positive. If either of the two is negative, the result will be negative.
For example: 4/3=1, −4/3=−1, 4/−3=−1 and −4/−3=1.

Sign of the result of division


#include<stdio.h>
operator:
main() 4/3=1, −4/3=−1
{ 4/-3=-1, −4/−3=1
printf(“Sign of the result of division operator:\n”); Remark:
printf(“4/3=%d, -4/3=%d\n”,4/3,-4/3); • The sign of the result of
printf(“4/-3=%d, -4/-3=%d”,4/-3,-4/-3); evaluation of the division
} operator depends upon the sign
of the numerator as well as the
denominator

 Modulus operator
Modulus operator is used to find the remainder.
The operands of modulus operator must be of integer type. It cannot have floating point
type operands.
The sign of modulus operator depends only upon the sign of numerator.

#include<stdio.h>
Compilation error “Illegal use of
main()
floating point in the function main”
{ Reason:
int a; • Operands of modulus operator should
a=2%3.0; be of integer type
b=15%2; What to do?
c=12%2; • Write 3 instead of 3.0 or type cast 3.0
to int by writing (int) 3.0
printf(“The value of a is %d”,a);
The result will be a=2
printf(“The value of b is %d”,b); b=1;
printf(“The value of c is %d”,c); c=0;
}
include <stdio.h>
int main()
Output
{
int a = 9,b = 4, c; a+b = 13
c = a+b;
a-b = 5
printf("a+b = %d \n",c);
c = a-b; a*b = 36
printf("a-b = %d \n",c);
c = a*b; a/b = 2
printf("a*b = %d \n",c); Remainder when a divided by b=1
c=a/b;
printf("a/b = %d \n",c);
c=a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
2. Relational operators
Relational operators are used to compare two quantities/variables (their operands).
There should be no white-space character between two symbols of a relational operator.
The result of relational operator is a Boolean constant.
The relational operator forms a condition.

// C Program to demonstrate the working of relational operators


#include <stdio.h>
int main() {
int a = 5, b = 5; Output
printf("%d == %d = %d \n", a, b, a == b); // true 5 == 5 = 1
printf("%d > %d = %d \n", a, b, a > b); //false
printf("%d < %d = %d \n", a, b, a < b); //false 5>5=0
printf("%d != %d = %d \n", a, b, a != b); //false
5<5=0
printf("%d >= %d = %d \n", a, b, a >= b); //true
printf("%d <= %d = %d \n", a, b, a <= b); //true 5 != 5 = 0
return 0; }
5 >= 5 = 1

5 <= 5 = 1
void main()
{
OUTPUT:
clrscr();
Condition: Return Values
printf(“\nCondition : Return Values\n” );
10!=10 : 0
printf(“\n10!=10 : %5d”,10!=10);
10==10 : 1
printf(“\n10==10 : %5d”,10==10);
10>=10 : 1
printf(“\n10>=10 : %5d”,10>=10);
10<=100: 1
printf(“\n10<=100: %5d”,10<=100);
10!=9 : 1
printf(“\n10!=9 : %5d”,10!=9);
}
3. Logical Operators
The logical relationship between the two expressions is tested with logical operators. After
checking the conditions, it provides logical true (1) or false (0) status. The operands could be
constants, variables and expressions.

Logical operators operate according to the truth tables

void main()
{ OUTPUT:
clrscr(); Condition : Return Values
printf(“\nCondition : Return Values\n” ); 5>3 && 5<10 : 1
printf(“\n5>3 && 5<10 : %5d”,5>3 && 5<10); 8>5 || 8<2 : 1
printf(“\n 8>5 || 8<2 : %5d”,8>5 || 8<2); !(8==8) : 0
printf(“\n !(8==8) : %5d”,!(8==8));
}
#include <stdio.h>
int main()
{ Output
int a = 5, b = 5, c = 10, result; (a == b) && (c > b) equals to 1
result = (a == b) && (c > b);
printf("(a == b) && (c > b) equals to %d \n", result); (a == b) && (c < b) equals to 0
result = (a == b) && (c < b); (a == b) || (c < b) equals to 1
printf("(a == b) && (c < b) equals to %d \n", result);
result = (a == b) || (c < b); (a != b) || (c < b) equals to 0
printf("(a == b) || (c < b) equals to %d \n", result);
!(a != b) equals to 1
result = (a != b) || (c < b);
printf("(a != b) || (c < b) equals to %d \n", result); !(a == b) equals to 0
result = !(a != b);
printf("!(a == b) equals to %d \n", result);
result = !(a == b);
printf("!(a == b) equals to %d \n", result);
return 0;
}
4. Bitwise operators
Bitwise operators operate on the individual bits of the operands and are used for bit
manipulation.
These operators do not consider the operand as one entity.

Program to shift inputted data by two bits right.


void main()
{
int x,y;
clrscr();
printf(“Read The Integer from keyboard (x) :-”);
scanf(“%d”, &x);
x>>=2;
y=x; OUTPUT:
Read The Integer from keyboard (x) :-
printf(“The Right shifted data is = %d”,y);
8
} The Right shifted data is = 2
The number entered through the keyboard is 8 and its corresponding binary number is 1 0 0 0.

128 64 32 16 8 4 2 1
0 0 0 0 1 0 0 0
After execution of the program: the inputted data x is to be shifted by 2 bits right side.

128 64 32 16 8 4 2 1
0 0 0 0 0 0 1 0

Shifting two bits right means the inputted number is to be divided by 2𝑠 where s is the number
of shifts. Simply, y=n/2𝑠 , where n = number and s = the number of position to be shift.

As per the program cited above, Y=8/22 = 2.

Program to shift inputted data by three bits left

void main() OUTPUT:


Read the Integer from keyboard (x):- 2
{
int x,y; The Left shifted data is = 16
clrscr();
printf(“Read the Integer from keyboard (x) :-”);
scanf(“%d”, &x);
x<<=3;
y=x;
printf(“The Right shifted data is = %d”,y);
}

Shifting three bits left means the number is multiplied by 8; in short y=n*2𝑠
Where n = number and s = the number of position to be shifted.
As per the program given above, Y=2*23 = 16.
Bitwise AND operator: &
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25 00001100 &
00011001
________
00001000 = 8 (In decimal)
void main()
{
int a,b,c;
clrscr();
printf(“Read The Integers from keyboard (a & b) :-”);
scanf(“%d %d”, &a,&b);
c=a & b;
printf(“The Answer after ANDing is (C)= %d”,c);
}

OUTPUT:
Read The Integers from keyboard (a & b) : 12 25
The Answer after ANDing is (C) = 8

Bitwise OR operator: |
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise OR Operation of 12 and 25 00001100 |
00011001
________
00011101 = 29 (In decimal)
void main()
{
int a,b,c;
clrscr();
printf(“Read The Integer from keyboard (a & b) :-”);
scanf(“%d %d”, &a,&b);
c=a | b;
printf(“The Oring operation bewteen a & b in c = %d”,c);
getche();
}

OUTPUT:
Read The Integer from keyboard (a & b):- 12 25
The Oring operation between a & b in c = 29
Exclusive OR Bitwise Operator: ^

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)
Bitwise XOR Operation of 12 and 25 00001100
^ 00011001
________
00010101 = 21 (In decimal)
void main()
{
int a,b,c;
clrscr();
printf(“Read The Integers from keyboard (a & b) :-”);
scanf(“%d %d”, &a,&b);
c=a^b;
printf(“The data after Exclusive OR operation is in c= %d”,c);
getche();
}
OUTPUT:
Read The Integers from keyboard (a & b) : 12 25
The data after Exclusive OR operation is in c =21

Bitwise complement operator ~

The operator ~ is used for inverting the bits with this operator 0 becomes 1 & 1 becomes 0.

35 = 00100011 (In Binary)


Bitwise complement Operation of 35 ~00100011
________
11011100 = 220 (In decimal)

void main()
{
unsigned int v=35;
clrscr(); OUTPUT:
printf(“\n %u”, ~v); 220
}
5. Assignment operators
A variable can be assigned a value by using an assignment operator.
Operator Name of operator Example Equivalent Statement
Initial value c = 9
= Simple assignment c=5; or c= a+b; Value 5 and a+b assigned to c.
*= Assign product c*=10 c=c*10, c=90
/= Assign quotient c/=5 c=c/5, c=1
%= Assign modulus c%=5 c=c%5 , c=4
+= Assign sum c += 7 c = c + 7, c=16
-= Assign difference c -=8 c=c-8 , c=1
&= Assign bitwise c&=2 c=c&2
AND
|= Assign bitwise OR c|=2 c=c|2
^= Assign bitwise c^=2 c=c^2
XOR
<<= Assign left shift c<<=2 c=c<<2
>>= Assign right shift c>>=2 c=c>>2

void main()
{
int a=10,b=20,c=50,x=5;
printf(“\nInitial value of a =10,b=20,c=50,x=5”);
a+=x;
b-=x;
c*=x; Initial value of a =10,b=20,c=50,x=5
printf(“\n a+=x is equal to %d”,a); a+=x is equal to 15
printf(“\n a-=x is equal to %d”,b); a-=x is equal to 15
printf(“\n a*=x is equal to %d”,c); a*=x is equal to 250
}

void main()
{
int x,y;
printf(“Read the integer from keyboard(x):- ”);
scanf(“%d”,&x);
x>>2;
Read the integer from keyboard(x):-8
y=x;
printf(“The right shifted data is=%d”,y); The right shifted data is=2
}
6. Miscellaneous Operators

Other operators available in C are:


1. Function call operator (i.e. ())
2. Array subscript operator (i.e. [])
3. Member select operator
4. Direct member access operator (i.e. (dot operator or period))
5. Indirect member access operator (i.e. -> (arrow operator))
6. Indirection operator (i.e. *)
7. Conditional operator
8. Comma operator
9. sizeof operator
10. Address-of operator (i.e. &)

Conditional operator:
Conditional operator is the only ternary operator available in C. The conditional operator
contains condition followed by two statements or values. If the condition is true, the first
statement is executed, otherwise the second statement is executed.
Syntax: Condition? Expression 1: Expression 2
If the condition is true expression 1 gets evaluated, otherwise expression 2 gets evaluated.

#include <stdio.h>

#include <conio.h>
Output:
void main()
Greatest of two numbers is 7
{

int a=6,b=7;

printf(“Greatest of two numbers is %d”,((a>b)?a:b));

getch();

Comma operator

The comma operator is used to separate two or more expressions.


The comma operator can be used to link related expressions together.
The comma separating arguments in a function call
The comma operator guarantees left-to-right evaluation
The comma operator has least preference
Example: a=2,b=4,c=a+b; OUTPUT:
(a=2,b=4,c=a+b;) Addition = 5
Subtraction = 1
void main()
{
clrscr();
printf(“Addition = %d\nSubtraction = %d”,2+3,5-4);
}
The size of Operator:

• The operator size of gives the size of the data type or variable in terms of bytes
occupied in the memory.
• Syntax: sizeof(expression) sizeof(3+4) or sizeof(type_name) sizeof(int)

• The operand may be a variable, a constant or a data type qualifier.
Example
int sum;
m = sizeof (sum);
m will return 2 bytes

include <stdio.h>

int main() Output


{
Size of int = 2 bytes
int a, e[10]; float b; double c; char d; Size of float = 4 bytes
Size of double = 8 bytes
printf("Size of int=%lu bytes\n",sizeof(a));
Size of char = 1 byte
printf("Size of float=%lu bytes\n",sizeof(b)); Size of integer type array
having 10 elements = 40 bytes
printf("Size of double=%lu bytes\n",sizeof(c));

printf("Size of char=%lu byte\n",sizeof(d));

printf("Size of integer type array having 10 elements = %lu bytes\n", sizeof(e));

return 0;

Address-of Operator

The address of operand is used to find the address of a data object.


The address of operand must appear towards the left side of its operand.
The operand of the address of operator should be a variable or a function designator.
Syntax: &operand

void main()
{
int a;
int b=10; Output:
int addr=&b; Enter value of a 12
scanf(“%d”,&a);
printf(“enter value of %d”,a); Value -1052642724
printf(“value %d”,addr);
printf(“value %d”,&addr);
}
INPUT OUTPUT OPERATIONS

Formatted Input/output:
 C uses two functions for formatted input and output.
 Formatted input: reads formatted data from the keyboard. Flow from input device to
main memory.
 Formatted output: writes formatted data to the monitor. Bytes flow from main
memory to output devices.
 In formatted functions read and write of all the types of data values require format
string to produce formatted results.
Formatted output :(printf)
 The formatted output as per requirement is displayed on the screen with printf()
 The values of variables are printed according to the sequence.
 The printf () function prints all types of data values to the console.
 It requires format conversion symbol or format string and variable names to print the
data and it should be same in number and type.
 The syntax : printf(“Control string”, variable1, variable2,…, variable n);
 A control string specifies the field format such as %d, %s, %f, %c.

void main()
{
int x=2; Output: -
float y=2.5; 2 2.5000 C
Char z= ‘C’;
printf(“%d %f %c”, x , y , z );
}
int main()
Output:
{
A 65
int y = 65;
clrscr();
printf(“%c %d”, y , y)
return 0;
}
Flags, width and precision with format string:

 Used between the character % and the conversion character


 Flags: A minus sign - Denoting left adjustment of the data.
 Used for output justification, numeric signs, decimal points, trailing zeros. Flag(-) and
flag(+).
 Width specifier: It sets a minimum field width for an output value.
 Specifies width through decimal point or asterisk ‘ * ’.
 A digit: Specifying the minimum width in which the data is to be output. If the digit is
prefixed with a zero, the padding is done with zeros instead of blanks.
 A digit following the period: specifying the precision (number of decimal places for
numeric data) or the maximum number of characters to be output.
 Letter l: To indicate that the data item is a long integer and not an int.

Examples- Width Specifer


void main ()
{
Output
clrscr()
ab
printf(“\n%.2s”, ”abcdef”);
abc
printf(“\n%.3s”, ”abcdef”);
abcd
printf(“\n%.4s”, ”abcdef”);
}

Void main()
{ Output
Int x = 55, y = 33;
clrscr(); 22
printf(“\n%3d”, x-y); 22
printf(“\n%6d”, x-y); 22
printf(“\n%*d”, 15 , x-y); 22
printf(“\n%*d”, 5 , x-y);
}
Examples for the use of precision specifier

void main()
{ Output
float = 123.456789; 123.5
clrscr(); 123.46
printf(“\n% .1f”, g); 123.457
printf(“\n% .2f”, g);
printf(“\n% .3f”, g);
}
 %wd – format for integer output
w is width in integer
d is conversion specification of integer.
 %w.cf - format for float numbers
w- Width in integer
c- Specifies the number of digits point
f- Specifies the conversion specification
 %w.cs –format for string output
w – Width for total number characters
c - displaying leading blanks
s- Conversion specification of string.
void main()
{
clrscr(); OUTPUT:
printf(“\n%5d”,12); 12
printf(“\n%5d”,123); 123
printf(“\n%5d”,1234); 1234
printf(“\n %4.5f”,6.12); 6.12000
16.120000
printf(“\n %4.6f”,16.12);
167.1200000
printf(“\n %4.7f”,167.12); 1678.12000000
printf(“\n %4.8f”,1678.12); Amitkumar
printf(“\n %8s”,“Amitkumar”); Am
printf(“\n %8.2s”,“Amitkumar”);
getche();
}

Formatted Input (scanf)


 It reads all data types value it used to run time assignment of variables
 The standard formatted input function in C is scanf (scan formatted).
 scanf consists of : a format string . An address list that identifies where data are to be
placed in memory.
 scanf ( “format string”, address of variable1, address of variable2,…variablen);
Example :- scanf(“%d”, &rollno); & - Indicates the memory location of variable

#include <stdio.h>
int main()
{
int a;
float b;
printf("Enter integer and then a float: ");
Output:
// Taking multiple inputs
scanf("%d%f", &a, &b); Enter integer and then a float: -3
printf("You entered %d and %f", a, b); 3.4
return 0; You entered -3 and 3.400000
}
Character Test Function

 It is used to test the character taken from the input.


 isalpha(ch)
 isdigit(ch)
 islower(ch)
 isupper(ch)
 tolower(ch)
 toupper(ch) etc,.
Void main()
{
char ch;
clrscr(); Output:- Enter any character/digit: f
printf(“Enter any character/digit:”);
It is a alphabet
ch=getchar();
if(isalpha(ch)>0)
printf(“It is alphabet”);
else if(isdigit(ch)>0);
printf(“It is digit”);
else
print(“It is alphanumberic”);
getch();
}

#include <math.h>
OUTPUT:
void main()
2.000000 raised to 3.000000 is 8.000000
{
double x = 2.0, y = 3.0;
clrscr();
printf(“%lf raised to %lf is %lf\n”, x, y, pow(x, y));
}
Unformatted I/O:
 Works only with character data type.
 In case values of other data types passed to these functions they are treated as character
data.
 Character I/O
 String I/O
 File I/O

Character I/O
getchar() & putchar(): Available in stdio.h header file.
getchar() -It reads one character at a time from standard input.
putchar() - It prints one character on the screen at a time.
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
Output:
void main()
{ enter the character : A
char x; a
printf("enter the character:");
x=getchar();
if(islower(x))
putchar(toupper(x));
else
putchar(tolower(x));
getch();
}
getc () and putc():Available in stdio.h header file.
getc()-Gets one character from the keyboard and putc() displays one character to display
#include<stdio.h>
#include<conio.h>
#include<ctype.h> Output:
void main() enter the character: a
{ A
char x;
printf("enter the character:");
x=getc(stdin);
if(islower(x))
putc(toupper(x),stdout);
else
putc(tolower(x),stdout);
getch();
}
getch() ,putch() and getche()
These functions read the alphanumeric characters from the standard input device. The
character entered is not displayed by getch() function.
putch() This function prints any alphanumeric character taken by the standard input device.

void main()
OUTPUT:
{
Enter any two alphabets A
clrscr();
printf(“Enter any two alphabets”); In the above program, even though the two characters
getche(); are entered, the user can see only one character on
getch(); the screen. The second character is accepted but not
} displayed on the console. The getche() accepts and
displays the character, whereas getch() accepts but
does not display the character.
void main() OUTPUT:
{ Press any key to continue You Pressed: 9
char ch,ch1; 7
clrscr();
The function getch() reads a key stroke and
printf(“Press any key to continue”);
ch=getch(); assigns to the variable ch. putch() displays
printf(“\n You Pressed :”); the character pressed. getche() read 7 and
putch(ch); displayed.
getche(ch1);
}

String I/O
gets() & puts()
gets() This function is used for accepting any string through stdin (keyboard) until enter key is
pressed.
puts() This function prints the string or character array.
gets() accept a string from the user at the run time is by using the gets library function.
puts() displays the strings to the console.
Unlike the scanf function, the gets function reads the entire line of text until a new line
character is encountered and does not stop upon encountering any other whitespace character.
gets() function is suited for reading multi-word strings

#include <stdio.h>
#include<conio.h>

void main()
{
char c[80];
clrscr(); Output:
printf("Input a string:"); Input a string:qwerty
gets(c);
printf("The string is:"); The string is:qwerty
puts(c);
getch();
}

cgets() and cputs()


cgets() This function reads string from the console.
cputs() This function displays string on the console.
void main()
Output:-
{
Enter the text here: How a re you?
Static char *t;
You entered text: How are you?
printf(“\n Enter the text here:”);
In this example character pointer‘t’ is
cgets(t);
declared. The cgets() function reads
t+=2;
string through the keyboard and the
printf(“\n You entered text:”);
cputs() function displays the string on
cputs(t);
the console.
}

Commonly Used Library Functions


 clrscr() - It is used to clear the screen. It clears previos ouptut from the screen and the
output of the current program from the first line of the screen. It is defined in conio.h
header file.
 exit() - This function terminates the program. It is defined in process.h header file.
Example: exit()
 sleep() - This function pauses the execution of the program for a given number of
seconds. The number of seconds is to be enclosed between parentheses. It is defined in
dos.h header file. Example: sleep(5);
 system() - This function is helpful in executing different DOS commands. It returns 0
on success and –1 on failure. Example: system(“dir”);
The command should be enclosed within double quotation marks. After we run this command
using C, directory will be displayed. Programmer can verify this command.

Strong Points for Understandability


The following are a few steps which can be followed to produce the neatness output:
 Give space between numbers.
 Provide suitable and problem-related variable names and headings.
 Provide user prompt so that the user can understand what to do.
 Provide a gap between two lines so that the text should be readable.
 Alert the user about what to do and what not to do.
 Use formatted inputs and outputs for precisely inputting the data and outputting results.
 It is recommended to use escape sequence characters such as \t, \b, \n.

The input functions are categorized into buffered input functions and un buffered input
functions.
1. In buffered input, the input given is kept in a temporary memory area known as the buffer
and is transmitted to the program when the Enter key is pressed. The pressed Enter key is
also transmitted to the program in the form of a new line character, which the program
must handle.
2. In un buffered input, the given input is immediately transferred to the program without
waiting for the Enter key to be pressed.
3. The examples of buffered input functions are scanf, getchar and gets function.
4. The examples of un buffered input functions are getch and getche function.
DECISION STATEMENT AND LOOP CONTROL STATEMENTS:
Program Control Structure
A program is nothing but the execution of one or more instructions sequentially in the order in
which they come into sight.
Program statements that affect the order in which statements are executed or that affect
whether statements are executed are called control structures.
• 3 control structures are:
• Sequential control structures
• Selection (decision /branched) control structures
• Iteration /looping control structures
Sequential control structures
The statements in the program are executed one after another in a sequential manner. This is
called the sequential execution.
Selection (decision /branched) control structures
Based upon the outcome of a particular condition, selection statements transfer control from
one point to another. Selection statements select a statement to be executed among a set of
various statements.
Iteration /looping control structures
Where the logic (sequence of steps) is repeated in a loop until the desired output is obtained
Transfer of control: The C statements such as if, goto, break, continue, switch allow a
program to transfer the control at different places in the program. This is accomplished by
skipping one or more statements appearing in a sequential flow. This jumping of control is
called the transfer of control.

Flow Control Statements

Flow control statements are of two types:


1. Branching statements
a. Selection statements
b. Jump statements
2. Iteration statements

Branching Statements

Branching statements are used to transfer the program control from one point to another.

Conditional branching:
In conditional branching, also known as selection, program control is transferred from one
point to another based upon the outcome of a certain condition. The following selection
statements are available in C: if statement, if-else statement and switch stamen.
Unconditional branching:
In unconditional branching, also known as jumping, program control is transferred from
one point to another without checking any condition. The following jump statements are
available in C: goto statement breaks statement, continue statement and return statement.

DECISION STATEMENT
 A statement is the smallest logical entity that can independently exist in a C program.
 Decision-making statements in a programming language help the programmer to
transfer the control from one part to other parts of the program.
 Thus, these decision-making statements facilitate the programmer in determining the
flow of control.
 This involves a decision-making condition to see whether a particular condition is
satisfied or not.
On the basis of real time applications it is essential:
(i) To alter the flow of a program.
(ii) To test the logical conditions.
(iii) To control the flow of execution as per the selection.

Selection statements /Decision statements–

 If
 if else
 else if ladder
 Nested if
 Nested if else and
 switch statements
if Statement
if(expression) //if header
Statement //if body

Syntax: if statement :-
if (condition or expression) /* no semi-colon */
{
Statements; //code block for true expression
}

Explanation:
If the expression is true then the statement or block of statements gets
executed otherwise these statements are skipped.
The important points about an if statement is as follows:

 An if statement consists of an if header and an if body.


 The conditional statements should not be terminated with semi-colons (;).
 The statements following the if statement are normally enclosed within curly braces.
The curly braces indicate the scope of the if statement.
 If the if controlling expression evaluates to true, the statement constituting if body is
executed.
 If the if controlling expression evaluates to false, if body is skipped and the execution
continues from the statement following the if statement.

#include<stdio.h>
#include<conio.h>
void main(){ Enter the number: 56
int n; The number is positive number.
clrscr();
printf(“Enter the number:”);
scanf(“%d”,&n);
if(n>0)
{
printf(“The number is positive number”);
getch();
}
}
If-else statement:
The if–else statement takes care of the true and false conditions. It has two blocks. One block
is for if and it is executed when the condition is true. The other block is of else and it is
executed when the condition is false.
The else statement cannot be used without if. No multiple else statements are allowed with
one if.
if(expression) //if-else header
statement1 //if body
else //else clause
statement2 //else body

Syntax: if else statement :-

if (condition or expression) /* no semi-colon */


{
True Statements; //code block for true expression
}
else
{
False Statements; //code block for false expression

}
#include<stdio.h>
#include<conio.h>
void main(){ Enter the number: -3
int n; The number is negative number.
clrscr();
printf(“Enter the number:”);
scanf(“%d”,&n);
if(n>0)
{
printf(“The number is positive number”);
else
printf(“The number is negative number”);
getch();
}
}

Nested if/ if ladder

If the body of the if statement is another if statement or contains another if statement, then we
say that if’s are nested and the statement is known as a nested if statement.

if(expression) //nested if statement


{
statements
------------- Syntax
if statement
if( Condition 1 or expression1 )
-------------
statement {
} Statement A
if(Condition 2 or expression2)
{
Statement C
}
else
{
Statement B
} Explanation:
if the expression is true then the true statement or block of statements gets
executed and executes another if else inside it.
if the expression is false then the false statement or block of statements
gets executed and if - true body is skipped.
#include<stdio.h>
int main()
{
/*local variable definition*/
int a=100; Output:
int b=200;
Value of a is 100 and b is 200
/*Check the Boolean condition*/
if(a==100);{
/*If condition is true then check following conditions*/
if(b==200)
{/*if the condition is true then print the following*/
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;
}

Nested if-else /If..else..if ladder Statement

In a nested if-else statement, the if body or else body of an if-else statement is, or contains,
another if statement or if-else statement.
In if else if statement the else statements contains another if statements.
The careless use of a nested if-else statement introduces a source of potential ambiguity
referred to as the dangling else ambiguity. When a statement contains more number of if
clauses than else clauses, then there exists a potential ambiguity regarding with which if
clause does the else clause properly matches up. This ambiguity is known as dangling else
problem.
Syntax of nested if-else statement Syntax of if –else if statement

if(condition) if(condition)
{ {
/*Inside first if block*/ statement 1; /*if block*/
if(condition) statement 2;
{ }
statement 1; /*if block*/ else if(condition)
statement 2; {
} statement 3; /*second if block*/
else statement 4;
{ }
statement 3; /*else block*/ else if(condition)
statement 4; {
} statement 5; /*third if block*/
} statement 6;
else }
{ else
/*Inside else block*/ {
if(condition) statement 7; /*else block*/
{ statement 8;
statement 5; /*if block*/ }
statement 6;
}
else
{
statement 7; /*else block*/
statement 8;
}
}
Figure : if -else -if flow diagram
Program example for nested if else:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf(“Enter three numbers\n”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b) Enter three numbers
{
if(a>c) 3 6 7
printf(“The biggest number is =%d”,a); The biggest number is 7
}
else
{
printf(“The biggest number is=%d”,c);
}
else
if(b>c)
{
printf(“The biggest number is=%d”,b);
}
else
{
printf(“The biggest number is=%d”,c);
}
}
}
getch();
}

Program example for if else-if ladder:

void main()
{
int initial,final,consumed;
float total;
clrscr();
printf(“\n Initial & Final Readings :”);
scanf(“%d %d”, &initial, &final);
consumed = final-initial; OUTPUT:
if(consumed>=200 && consumed<=500) Initial & Final Readings : 800 850
total=consumed * 3.50; Total bill for 50 unit is 75.000000
else if(consumed>=100 && consumed<=199)
total= consumed * 2.50;
else if(consumed<100)
total=consumed*1.50;
printf(“Total bill for %d unit is %f”,consumed,total);
getche();
}

Figure: Dangling problem


Switch Statement:

Switch-The switch statement is a multi way branching statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.

A switch statement is used to control complex branching operations. When there are many
conditions, it becomes too difficult and complicated to use if and if-else constructs. In such
cases, the switch statement provides an easy and organized way to select among multiple
options, depending upon the outcome of a particular condition.
The important points about a switch statement are as follows:
1. A switch statement consists of a switch header and a switch body.
2. A switch header consists of the keyword switch followed by a switch selection expression
enclosed within parentheses.
3. The switch selection expression must be of integral type (i.e. integer type or character
type).
4. The switch body consists of a statement. The statement constituting a switch body can be a
null statement, an expression statement, a labeled statement, a flow control statement,
a compound statement, etc.
5. Generally, a switch body consists of a compound statement, whose constituent statements
are case-labeled statements, expression statements, flow control statements and
an optional default-labeled statement.
6. Case labels of case-labeled statements constituting the body of a switch statement should
be unique, i.e. no two case labels should have or evaluate to the same value.
7. There can be at most one default labeled statement within the switch body.

A switch statement is executed as follows:

1. The switch selection expression is evaluated.


2. The result of evaluation of switch selection expression is compared with the case labels of
the case-labeled statements until there is a match or until all the case-labeled statements
have been examined.
 If the result of evaluation of switch selection expression is matched with the case label
of a case-labeled statement, the execution starts from the matched case-labeled
statement, and all the statements after the matched case-labeled statement within the
switch body gets executed.
 If no case label of case-labeled statements within the switch body matches the result of
evaluation of switch selection expression, the execution starts with the default-labeled
statement, if it is present, and all the statements after the default labeled statement
within the switch body gets executed.
 If none of the case labels match the result of evaluation of switch selection expression
and there is no default-labeled statement present within the switch body, no statement
within the switch body will be executed and the execution continues from the statement
following the switch statement.
Programming example:

#include<stdio.h>
int main()
/*local variable definition*/
char grade=’B’;
switch(grade){
case ‘A’:
printf(“Excellent!\n”); Output:
case ‘B’:
Good!
printf(“Good!\n”);
case ‘C’:
printf(“You passed!\n”);
case ‘D’:
printf(“Better try again!\n”);
default:
printf(Invalid grade!\n”);
}
Printf(“Your grade is %c\n”,grade);
return 0;
}
Nested switch case
The inner switch can be a part of an outer switch.

void main()
{
int x,y;
clrscr();
printf(“\n Enter a Number :”);
OUTPUT:
scanf(“%d”,&x);
Enter a Number: 5
switch(x)
Number is Odd.
{
case 0 :
printf(“\n Number is Even.”);
break;
case 1 :
printf(“\n Number is Odd .”);
break;
default :
y=x%2;
switch(y)
{
case 0:
printf(“\n Number is Even.”);
break;
default :
printf(“\n Number is Odd.”);
}
}
getche();
}

Jump Statements

A jump statement transfers the control from one point to another without checking any
condition, i.e. unconditionally. The following jump statements are present in C language:
1. goto statement
2. break statement
3. continue statement
4. return statement

1) goto Statement

The goto statement is used to branch unconditionally from one point to another within a
function.
It provides a highly unstructured way of transferring the program control from one point to
another within a function. This statement does not require any condition.
User has to define the goto statement as follows:
goto label;

program to detect the entered number as to whether it is even or odd. Use the goto
statement.

# include <stdlib.h>
void main()
{
int x;
clrscr();
printf(“Enter a Number :”);
Enter a Number: 5
scanf(“%d”,&x);
5 is Odd Number.
if(x%2==0)
goto even; In the above program, a number is entered.
else The number is checked for even or odd with
goto odd; modules division operator. When the number
even : is even, the goto statement transfers the
printf(“\n %d is Even Number.”,x); control to the label even. Similarly, when the
return; number is odd the goto statement transfers
odd: the control to the label odd and respective
printf(“\n %d is Odd Number.”,x); message will be displayed.
}

Reasons to avoid goto statement

 Code that is hard to follow


 Allows you to do bad stuff such as jump out of scope
 It provides a highly unstructured way of transferring the program control from one point
to another within a function.
 It often makes the program control difficult to understand and modify.

The important points about a goto statement are as follows:

 The goto statement is always used in conjunction with an identifier-labeled statement.


 The goto statement on execution transfers the program control to an identifier-labeled
statement having a label name same as the label name used in the goto statement.
 The goto statement can be used to make a forward jump as well as a backward jump. If
the goto statement is present before its corresponding identifier-labeled statement, the
jump made will be known as a forward jump. If the goto statement is present after its
corresponding identifier-labeled statement, the jump made will be known as a
backward jump.
2) Break statement
The keyword break allows the programmers to terminate the loop. The break skips from the
loop or block in which it is defined. The control then automatically goes to the first statement
after the loop or block. The break can be associated with all conditional statements.
1. It is used to come out of the loop instantly. When a break statement is encountered
inside a loop, the control directly comes out of loop and the loop gets terminated. It is
used with if statement, whenever used inside loop.
2. This can also be used in switch case control structure. Whenever it is encountered in
switch-case block, the control comes out of the switch-case
The syntactic form of a break statement is: break;
The important points about a break statement are as follows:
 A break statement can appear only inside, or as a body of, a switch statement or a loop.
 A break statement terminates the execution of the nearest enclosing switch or the
nearest enclosing loop.

//break statement
Example – Use of break in a while loop
#include <stdio.h>
int main() {
int num =0;
Output:
while(num<=100)
value of variable num is: 0
{
value of variable num is: 1
printf("value of variable num is: %d\n", num);
value of variable num is: 2
if (num==2)
Out of while-loop
{
break;
}
num++; }
printf("Out of while-loop"); return 0;
}

3) The continue Statement

The continue statement is used inside loops. When a continue statement is encountered inside
a loop, control jumps to the beginning of the loop for next iteration, skipping the execution of
statements inside the body of loop for the current iteration.
Syntax: continue;

The important points about a continue statements are as follows:


 A continue statement can appear only inside, or as the body of, a loop.
 A continue statement terminates the current iteration of the nearest enclosing loop.

Programming example for continue:


#include <stdio.h> Output:
int main() { 01235678
for (int j=0; j<=8; j++) {
if (j==4)
{ /* The continue statement is encountered when * the value of j is equal to 4. */
continue;
}
/* This print statement would not execute for the * loop iteration where j ==4 because in that
case * this statement would be skipped. */
printf("%d ", j); }
return 0;
}

4) return statement

• The return statement is used to terminate the execution of a function and transfer
program control back to the calling function.
• A function may or may not return a value. A return statement returns a value to the
calling function and assigns to the variable in the left side of the calling function.
Syntax

return; or //Form 1

return expression; //Form 2

The important points about a return statement are as follows:


A return statement without an expression (i.e. Form 1) can appear only in a function whose
return type is void.
2. A return statement with an expression (i.e. Form 2) should not appear in a function whose
return type is void.
3. A return statement terminates the execution of a function and returns the control to the
calling function.

#include<stdio.h>
Void_eligible_or_not (int x);
int main()
{ int n;
printf("Enter age: ");
scanf("%d", &n); Expected Output:
eligible_or_not(n); 1st run:
// signal to operating system everything works fine Enter age: 16
return 0; You are not yet ready
} 2nd run:
void_eligible_or_not(int age) Enter age: 17
{ Try next year
if(age >= 18)
{
printf("You are eligible to vote");
return;
}
else if(age == 17 )
{
printf("Try next year");
return;
}
else
{printf("You are not yet ready"); return}
}
LOOP CONTROL AND ITERATION CONTROL
Iteration is a process of repeating the same set of statements again and again until the
Specified condition holds true. A loop is defined as a block of statements which are repeatedly
executed for certain number of times.

The C language provides the following three iteration statements:

1. for statement
2. while statement
3. do-while statementutline

In general, loops are classified as:


1. Counter-controlled loops.
2. Sentinel-controlled loops.
Counter-Controlled Loops
Counter-controlled looping is a form of looping in which the number of iterations to be
performed is known in advance.
The counter controlled loop starts with the initial value of the loop counter and terminates
when the final value of the loop counter is reached they are also known as definite repetition
loops.
Sentinel-Controlled Loops
In sentinel-controlled looping, the number of times the iteration is to be performed is not
known beforehand, this type of loop is also known as indefinite repetition loop.
Various terms in loop are:
Loop variable: It is a variable used in the loop.
Initialization: It is the first step in which starting and final values are assigned to the loop
variable. Each time the updated value is checked by the loop itself.
Increment/decrement: It is the numerical value added or subtracted to the variable in each
round of the loop. The updated value is compared with the conditions.
1. for loop
The for loop allows to execute a set of instructions until a certain condition is satisfied.
Condition may be predefined or open-ended.
 Initialization section: The initialize counter sets to an initial value. This statement is
executed only once. It is used to initialize (i.e. assign a starting value to) the loop
counter.
 Condition section: The test condition is a relational expression that determines the
number of iterations desired or determines when to exit from the loop. The ‘for’ loop
continues to execute as long as conditional test is satisfied. When the condition
becomes false the control of the program exits from the body of the ‘for’ loop and
executes next statement after the body of the loop.
 Manipulation section: The value of variable either incremented or decremented
The for statement is executed as follows:
a. Initialization section is executed only once at the start of the loop.
b. The expression present in the condition section is evaluated.
i. If it evaluates to true, the body of the loop is executed.
ii. If it evaluates to false, the loop terminates and the program control is
transferred to the statement present next to the for statement.
c. After the execution of the body of the loop, the manipulation expression is evaluated.
d. These three steps represent the first iteration of the for loop. For the next iterations,
Steps b and c are repeated until the expression in Step b evaluates to false.

Print the first five numbers starting from 1 together with their squares.

void main()
{ OUTPUT:
int i; Number: 1 it’s Square: 1
clrscr(); Number: 2 it’s Square: 4
Number: 3 it’s Square: 9
for(i=1;i<=5;i++)
Number: 4 it’s Square: 16
printf(“\n Number: %5d it’s Square: %5d”,i,i*i); Number: 5 it’s Square: 25
}

Display numbers from 1 to 15 using for loop. Use i = i +1.

void main()
{
int i;
clrscr(); OUTPUT:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
for(i=1;i<=15;i=i+1)
printf(“%5d”,i);
}
Nested for Loops
In nested for loops one or more for statements are included in the body of the loop.
The numbers of iterations in this type of structure will be equal to the number of iteration in
the outer loop multiplied by the number of iterations in the inner loop.
Syntax:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}

Program to perform subtraction of two loop variables. Use nested for loops.
void main()
{
int a,b,sub; OUTPUT:
a=3 b=1 a-b = 2
clrscr();
a=3 b=2 a-b = 1
for(a=3;a>=1;a–-) a=2 b=1 a-b = 1
{ a=2 b=2 a-b = 0
for(b=1;b<=2;b++) a=1 b=1 a-b = 0
{ a=1 b=2 a-b =-1
sub=a-b;
printf(“a=%d\t b=%d\t a-b=%d\n”,a,b,sub);
}
}
}

2. while loop
The while loop is frequently used in programs for the repeated execution of statement/s in
a loop. Until a certain condition is satisfied the loop statements are executed.
The while statement is executed as follows:
The while controlling expression is evaluated.
i. If it evaluates to true, the body of the loop is executed.
ii. If it evaluates to false, the program control is transferred to the statement present next to the
while statement.
b. After executing the while body, the program control returns back to the while header.
c. Steps a and b are repeated until the while controlling expression in Step a evaluates to false.
7. While making the use of while statement, always remember to initialize the loop counter
before the while controlling expression is evaluated and to manipulate the loop counter
inside the body of while statement, i.e. before the while controlling expression is evaluated
again. (that is increment or decrement manipulation).

Program to add 10 consecutive numbers starting from 1. Use the while loop.

void main()
{
int a=1,sum=0;
clrscr();
while(a<=10) OUTPUT:
{ 1 2 3 4 5 6 7 8 9 10
printf(“%3d”,a); Sum of 10 numbers : 55
sum=sum+a;
a++;
}
printf(“\n Sum of 10 numbers :%d”,sum);
}

Program to calculate factorial of a given number. Use while loop.


void main()
{
int a,fact=1;
clrscr();
printf(“\n Enter The Number :”);
scanf(“%d”, &a);
while(a>=1) OUTPUT:
{ Enter The Number: 5
printf(“ %d *”,a); 5* 4 * 3 * 2 * 1 * = 120
fact=fact*a; Factorial of Given number is 120
a --;
}
printf(“ = %d”,fact);
printf(“\n Factorial of Given number is %d”,fact);
}

3. do while loop

do //do-while header
statement //do-while body
while(expression); //while clause

 The do-while statement is executed as follows:


a. The statement, i.e. body of do-while statement, is executed.
b. After the execution of a do-while body, the do-while controlling expression is evaluated.
i. If it evaluates to true, the statement, i.e. do-while body is executed again and Step
b is repeated.
ii. If it evaluates to false, the program control is transferred to the statement present next
to the do-while statement.
 While making the use of a do-while statement, always remember to initialize the loop
counter before the do-while statement and to manipulate it inside the body of the do-while
statement so that the do-while controlling expression eventually becomes false.
 The statement, i.e. body of the do-while loop is executed once, even when the do-while
controlling expression is initially false.
Use the do–while loop and display a message ‘this is a program of do–while loop’ five times.
OUTPUT:
void main()
This is a program of do while loop.
{
This is a program of do while loop.
int i=1;
This is a program of do while loop.
clrscr();
This is a program of do while loop.
do
This is a program of do while loop.
{
printf(“\n This is a program of do while loop.”);
i++;
}
while(i<=5);
}

Write a program to check whether the given number is prime or not?


void main()
{
int n,x=2;
clrscr();
printf(“Enter The number for testing (prime or not) :”);
scanf(“%d”,&n);
do
{
if(n%x==0)
{
printf(“\n The number %d is not prime.”,n);
getch();
exit(0); OUTPUT:
} Enter The number for testing (prime or not) : 5
x++; The number 5 is prime.
}
while(x<n);
printf(“\n The number %d is prime.”,n);
getche();
}

BOHM AND JACOPINI’S THEORY


The structured programming provides simplicity. Bohm and Jacopini showed the following
three forms of controls:
(i) sequence
(ii) selection
(iii) repetition
ARRAYS
ARRAY, FUNCTIONS AND STRINGS

Arrays: Characteristics One-dimensional and Two-dimensional arrays Functions:


Declaration & Definition of function Built in function User defined function Types
of functions Call by value &reference Strings: Formatting strings String handling
functions.

An array:-

An array is a very popular and useful data structure used to store data elements in
successive memory locations. More than one element is stored in a sequence, so it is
also called a composite data structure.
An array is a linear and homogeneous data structure. It means that similar types of
elements are stored contiguously in the memory and that too under one variable name.

An array is a data structure_ that is used for the storage of homogeneous data i.e., an
array is a collection of elements of the same data type. The data type of an element is
called element type.
Characteristics of an Array
1) An array holds elements that have the same data type.
2) Array elements are stored in subsequent/contiguous memory locations.
3) The individual elements of an array are not named. All the elements of an array share a
common name, i.e. the array name.
4) Elements of an array are accessed using an index value. ...index starting from 0.
5) Two-dimensional array elements are represented as matrix. A matrix can be
represented as a table of rows and columns.
6) Array size should be mentioned in the declaration. Only constants and literal values (an
integer value like 5, 10, 12,...) can be assigned the number of elements in an array
7) Array name represents the address of the starting element

The important points about arrays are as follows:


The individual elements of an array are distinguished and are referred to or accessed
according to their positions in an array. The position of an element in an array is
specified with an integer value known as index or subscript.
The array index in C starts with 0, i.e. index of the first element of an array is 0.
The memory space required by an array can be computed as (size of data type) ×
(Number of elements in an array).
Arrays are always stored in contiguous (i.e. continuous) memory locations. if the first
element is stored at memory locations 2000-2001, the next elements will be stored at
the memory locations 2002-2003, 2004-2005, and so on.
Example:
b= a [2];
a [2]=a[3];
(a) In the statement b=a[2] b b
is an integer.
(b) In the statement a[2]=a[3] or vice versa, the value of a[2] is assigned to a[3], where
both the elements are of the same array.
Array Terminology
Size: Number of elements or capacity to store elements in an array is called its size. It is
always mentioned in brackets ([]).
Type: Types refer to data type. It decides which type of element is stored in the array. It also
instructs the compiler to reserve memory according to data type.
Base: The address of the first element (0th) is a base address. The array name itself stores
address of the first element.
Index: The array name is used to refer to the array element. For example, num[x], num is
array name and x is index. The value of x begins from 0 to onwards depending on the size of
the array. The index value is always an integer value.
Range: Index of an array i.e. value of x varies from lower bound to upper bound while
writing or reading elements from an array. For example, in num [100], the range of index is 0
to 99.
Word: It indicates the space required for an element. In each memory location, computer can
store a data piece. The space occupation varies from machine to machine. If the size of
element is more than word (one byte) then it occupies two successive memory locations. The
variables of data type int, float, long need more than one byte in memory.
In general, arrays are classified as:
1) One dimensional array
2) Multi dimensional array-
(Two dimensional array
One dimensional array
Array elements are stored contiguously in sequence one after the other. A single-
dimensional or one-dimensional array consists of a fixed number of elements of the same
data type organized as a simple linear sequence.
Array declaration:
Declaration of a one-dimensional array - data type followed by the variable name and lastly
the array size is enclosed in square brackets.
Array size should be integer constant and it must be greater than zero and data type should
be valid C data type.

Syntax: Data_type arrayname [array_size_int];


Example: int a[5]; char ch[4]; float real[20]; long num[3];
Array Initialization:

Syntax: Data_type variable name [array_size_int]


int num[5] = {1,2,4,2,5}; char c[4]={a,b,c,d}; float real[5]={1.1,1.2,1.3,1.4,1.5}
num[0] refers to the 1, num[1] refers to the 2 , num[2] refers to the 4

num[3] refers to the 2 , num[4] refers to the 5

Example program for one dimensional array in C:


#include<stdio.h>
int main(){
int i;
int arr[5] = {10,20,30,40,50};// declaring and Initializing array in C
//To initialize all array elements to 0, use int arr[5]={0};
/* Above array can be initialized as like below also
arr[0] = 10;
Output:
arr[1] = 20;
Value of arr[0] is 10
arr[2] = 30;
Value of arr[1] is 20
arr[3] = 40;
Value of arr[2] is 30
arr[4] = 50; */
Value of arr[3] is 40
for (i=0;i<5;i++)
Value of arr[4] is 50
{// Accessing each variable
\
}}

Write a program to display array elements with their addresses.


int main()
{
int num[5]={1,2,3,2,5};
clrscr(); Output:
\ num[0] = 1 Address : 65516
\ num[1] = 2 Address : 65518
\ num[2] = 3 Address : 65520
num[3] = 2 Address : 65522
\
num[4] = 5 Address : 65524
\n num[4] = %d Address
return 0;

Write a program to display names of days of a week using single-dimensional array


having length of 7.
void main()
{
int day[7],i;
clrscr();
\nEnter numbers between 1 to 7:\
for(i=0;i<=6;i++)
day[i]);
for(i=0;i<=6;i++)
switch(day[i])
{
case 1:
\
break; OUTPUT:
case 2: Enter numbers between 1 to 7:
\ 1324578
break; 1st day of week is Sunday
case 3: 3rd day of week is Tuesday
\ 2nd day of week is Monday
break; 4th day of week is Wednesday
case 4: 5th day of week is Thursday
\n%dth day of week is We 7th day of week is Saturday
break; 8th is invalid day
case 5:
\
break;
case 6:
\
break;
case 7:
\
break;
default :
\n %dth is Invalid
}
}
One-Dimensional Array and Operations

1. C Program to Read& Print Array Elements


#include<stdio.h>
int main() {
int i, arr[50], num;
printf("\nEnter no of elements :");
Output:
scanf("%d", &num);
Enter no of elements : 5
//Reading values into Array
arr[0]= 70
printf("\nEnter the values :");
arr[1]=50
for (i = 0; i < num; i++) {
arr[2]=40
scanf("%d", &arr[i]);
arr[3]=90
}
arr[4]=100
//Printing of all elements of array
for (i = 0; i < num; i++)
{
printf("\narr[%d] = %d", i, arr[i]);
}
return (0);
}

2. C Program to delete an element from the specified location from Array

#include<stdio.h>
int main() {
int arr[30], num, i, loc;
printf("\nEnter no of elements :");
scanf("%d", &num);

//Read elements in an array


printf("\nEnter %d elements :", num);
for (i = 0; i < num; i++)
{
scanf("%d", &arr[i]);
}
//Read the location
printf("\n location of the element to be deleted :");
scanf("%d", &loc);

/* loop for the deletion */


while (loc < num-1) Output:
{ Enter no of elements: 3
arr[loc] = arr[loc+1];
loc++; Enter 3 elements 10 20 30
} Location of the elements to be deleted: 1
num--; // No of elements reduced by 1
//Print Array 10 30
for (i = 0; i < num; i++)
printf("\n %d", arr[i]);
return (0);
}
3. C Program to Insert an element in an Array
#include<stdio.h>
int main() {
int arr[30], element, num, i, location;
printf("\nEnter no of elements :");
scanf("%d", &num);
//Read elements in an array
for (i = 0; i < num; i++)
{
scanf("%d", &arr[i]);
}
printf("\nEnter the element to be inserted :");
scanf("%d", &element);
printf("\nEnter the location");
scanf("%d", &location);
//Create space at the specified location
for (i = num; i > location; i--)
{
arr[i] = arr[i - 1]; Output of the Program:
}
Enter no of elements: 5
num++;
arr[location] = element; 12345

Enter the element to be inserted: 6


//Print out the result of insertion
for (i = 0; i < num; i++) Enter the location: 2
printf("n %d", arr[i]);
162345
return (0);
}
4. C Program to Copy all elements of an array into another array
#include<stdio.h>
int main() {
int arr1[30], arr2[30], i, num;

printf("\nEnter no of elements :");


scanf("%d", &num);

//Accepting values into Array


printf("\nEnter the values :");
for (i = 0; i < num; i++) {
scanf("%d", &arr1[i]); Output:
}
Enter no of elements: 5
/* Copying data from array 'a' to array 'b */
for (i = 0; i < num; i++) { Enter the values: 11 22 33 44 55
arr2[i] = arr1[i];
The copied array is: 11 22 33 44 55
}
//Printing of all elements of array
printf("The copied array is :");
for (i = 0; i < num; i++)
printf("\narr2[%d] = %d", i, arr2[i]);
return (0);
}
5. C Program to Search an element in Array
#include<stdio.h>
int main()
{
int a[100],n,element, i;
-

for(i=0;i<n;i++); Output:

Enter array size [1-100]: 5

Enter array elements: 10 20 30 40 50


for(i=0;i<n;i++); Enter element to search: 30
{
if(a[i]==element) Element found
{
\
}
else{
\
}
}
6. C Program to Reversing an array element
#include<stdio.h>
int main() {
int arr[30], i, j, num, temp;
printf("\nEnter no of elements : ");
scanf("%d", &num);
//Read elements in an array
for (i = 0; i < num; i++) {
scanf("%d", &arr[i]);
}
j = num - 1; // j will Point to last Element
i = 0; // i will be pointing to first element

while (i < j) {
temp = arr[i]; Output
arr[i] = arr[j];
Enter no of elements: 5
arr[j] = temp;
i++; // increment i 11 22 33 44 55
j--; // decrement j
Result after reversal: 55 44 33 22
}
11
//Print out the Result of Insertion
printf("\nResult after reversal : ");
for (i = 0; i < num; i++) {
printf("%d \t", arr[i]); }
return (0);
}
7. C Program to Find Largest Element in Array
#include<stdio.h>
int main() {
int a[30], i, num, largest;
printf("\nEnter no of elements :");
scanf("%d", &num);
//Read n elements in an array
for (i = 0; i < num; i++)
scanf("%d", &a[i]);
Output:
//Consider first element as largest
largest = a[0]; Enter no of elements: 5
for (i = 0; i < num; i++) {
11 55 33 77 22
if (a[i] > largest) {
largest = a[i]; Largest Element: 77
}
}
// Print out the Result
printf("\nLargest Element : %d", largest);
return (0);
}
8. C Program to Find Smallest Element in Array
#include<stdio.h>
int main() { Output:
int a[30], i, num, smallest;
printf("\nEnter no of elements :"); Enter no of elements: 5
scanf("%d", &num); 11 44 22 55 99
//Read n elements in an array Smallest Element: 11
for (i = 0; i < num; i++)
scanf("%d", &a[i]);

//Consider first element as smallest


smallest = a[0];
for (i = 0; i < num; i++) {
if (a[i] < smallest) {
smallest = a[i];
}
}

// Print out the Result


printf("\nSmallest Element : %d", smallest);
return (0);
}
9. Sum of elements in an array
#include<stdio.h>
int main() {
int i, arr[50], sum, num;
printf("\nEnter no of elements :");
scanf("%d", &num);

//Reading values into Array


printf("\nEnter the values :"); Output: Enter no of elements: 3
for (i = 0; i < num; i++) Enter the values: 11 22 33
scanf("%d", &arr[i]);
a[0]=11
//Computation of total
sum = 0; a[1]=22
for (i = 0; i < num; i++)
a[2]=33
sum = sum + arr[i];
Sum=66
//Printing of all elements of array
for (i = 0; i < num; i++)
printf("\na[%d]=%d", i, arr[i]);

//Printing of total
printf("\nSum=%d", sum);

return (0);
}
10.Sort the elements in an array in ascending order
#include<stdio.h>
#define MAX_SIZE 100 //maximum array size
int main()
{
int arr[max_size];
int size;
int i,j,temp;
/*input size of array*/

/*input elements in array*/

for(i=0;i<size;i++)

for(i=0;i<size;i++)
{
/* place current selected element array[i] to its correct place.*/
for(j=i+1;j<size;j++);
{
/*swap if currently selected array element is not as its correct position*/
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
/*print the sorted array*/
\
for(i=0;i<size;i++);
Output:
{
\ enter size of array: 5
}
enter elements in array: 10 9 5 11 2
return 0;
} elements of array in ascending order:

2 5 9 10 11
Two dimensional arrays
Two dimensional arrays is nothing but array of array. A two-dimensional array
has its elements arranged in a rectangular grid of rows and columns. The elements of a two-
dimensional array can be accessed by using a row subscript (i.e. row number) and a column
subscript (i.e. column number).
A two-dimensional array is popularly known as a matrix.
Array declaration:

Syntax: Data_type variable name [No_of_rows_int][No_of _coloumns_int];


Example:int x[3][2];
Array Initialization

Syntax: data_type array_name[row_size] [col_size]={variables};


Example:int arr[2][2] = {1,2, 3, 4};
arr [0] [0] = 1;
arr [0] ]1] = 2;
arr [1][0] = 3;
arr [1] [1] = 4;

Example program for two dimensional array in C: Sum of two matrix


#include<stdio.h> Enter the number of rows and columns of matrix: 2 2
int main()
Enter the elements of first matrix
{
int i,j; 2
int arr[2][2] ; 2
for (i=0;i<2;i++)
2
{ for (j=0;j<2;j++)
{ 2

Enter the elements of second matrix


} 3
}
3
for (i=0;i<2;i++)
{ for (j=0;j<2;j++) 3
{ 3

Sum of entered matrices:-


5 5
5 5
}

}
}
Matrix multiplication using two dimensional arrays
#include<stdio.h>
#include<stdlib.h>

int main(){

int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
printf("enter the number of row=");
scanf("%d",&r);

printf("enter the number of column=");

scanf("%d",&c);

printf("enter the first matrix element=\n");


for(i=0;i<r;i++)

for(j=0;j<c;j++)

{
scanf("%d",&a[i][j]);

} }

printf("enter the second matrix element=\n");


for(i=0;i<r;i++)

{
for(j=0;j<c;j++)

scanf("%d",&b[i][j]);
} }

printf("multiply of the matrix=\n");


for(i=0;i<r;i++)

for(j=0;j<c;j++)
{

mul[i][j]=0; enter the number of row=3

for(k=0;k<c;k++) enter the number of column=3

enter the first matrix element=


{
111
mul[i][j]+=a[i][k]*b[k][j];
222
} } }
333
//for printing result
enter the second matrix element=
for(i=0;i<r;i++)
111
{
222
for(j=0;j<c;j++) 333
{ multiply of the matrix=

printf("%d\t",mul[i][j]); 666

} 12 12 12

printf("\n"); 18 18 18

return 0;
}
Draw backs of Linear Arrays
1. The number of elements, which are to be stored in an array, is to be known first.
2. When an array is declared, memory is allocated to it. If array is not filled completely, the
vacant place occupies memory.
3. Once the array is declared, its dimension can be changed.

You might also like