0% found this document useful (0 votes)
3 views

Programming in C -Converted

The document provides an overview of computer fundamentals, including the classification of computers into supercomputers, mainframes, minicomputers, and microcomputers, along with their characteristics. It discusses the components of a computer system, such as hardware and software, input and output devices, and memory types, including RAM and ROM. Additionally, it covers the role of operating systems and the booting process in managing computer operations.

Uploaded by

Gk Pradeep
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Programming in C -Converted

The document provides an overview of computer fundamentals, including the classification of computers into supercomputers, mainframes, minicomputers, and microcomputers, along with their characteristics. It discusses the components of a computer system, such as hardware and software, input and output devices, and memory types, including RAM and ROM. Additionally, it covers the role of operating systems and the booting process in managing computer operations.

Uploaded by

Gk Pradeep
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

* Programming in C

ABVG Degree College,Jangaon 1

.
* Programming in C
Mainframe computers:
Programming in C A mainframe computer supports a vast number of
users. It can process large amounts of data at very
high speeds. These computers are very large in size,
UNIT-1 and expensive.
Computer Fundamentals The main difference between a supercomputer and
a mainframe is that:
Introduction of Computers: A supercomputer can execute a single program
The term computer is derived from the Latin word faster than a mainframe. A Mainframe uses its
compute, which means to calculate. power to execute many programs concurrently.
Example: The IBM 370 and IBM 3090.
A Computer is an electronic device that processes
data and converts it into information that is useful Minicomputers
to people. A minicomputer can be used by multiple users
(between10 to 100). It is smaller in size. They are
A computer is a data processor. It can accept input less expensive. Minicomputers are used for
[data + instructions]. The computer stores the input in scientific and engineering tasks. They are also used
memory cells. It then processes the stored input. It as small servers.
gives out the result as output information. Example: The IBM AS/400.
Microcomputers:
The computer accepts input and outputs data in an The microcomputer can be used by a single user at
alphanumeric form. Internally it converts the input a time. It contains a microprocessor chip, a memory
data [English] to meaningful binary digits [Machine system, interface units and I/O units, etc.
Language], performs the given operations and There are many types of microcomputers:
transforms the data from binary format to English. Desktop computer: It is a microcomputer that can
fit on a desk.
Classification of Computers Laptop computer: It is a microcomputer that can fit
Based on their configuration, Computers can be on your lap.
classified into 4 types: Palmtop computer/PDAs: It is a hand-sized
1. Super Computers microcomputer. Its screen serves both as an input
2. Mainframe Computers and output device.
3. Mini Computers ****
4. Micro Computers Anatomy of a Computer

Super-computers: A computer system can be divided into two


Super-computers are very fast and powerful components:
machines. They are very large in size. They can I. Hardware
perform quadrillions of calculations per second. They II. Software
are very Expensive. Super Computers can be used in Hardware: The physical components of a computer
weather forecasting, nuclear energy research, etc. is known as the Hardware. It includes:
Example: • Input and output devices
1. CRAY super computer [ USA] • Central processing unit (CPU)
2 .Sunway TaihuLight [China] • Memory unit and storage devices
3. Aaditya • Interface unit
4. Param Yuva-II [ INDIA]

ABVG Degree College,Jangaon 2

.
* Programming in C
Input Devices Printer The printer is a device that prints any data,
The devices, which are used to enter the data and report, document, etc. Printers can produce hard
instructions into the computer are known as the input copies of the data. They are of 2 types: An impact
devices. The most common input devices are: printer: It is a printer in which the print head will
be in physical contact with the paper. Example: Dot
Keyboard: A Keyboard is like a type-writer. matrix printer.
Normally it contains of 104 keys. Keyboard follows A non–impact printer: It is a printer in which the
QWERTY layout. It includes Character keys, print head does not have any physical contact with
Function keys, Control keys, Navigation keys, the paper. Example: Laser printer.
Toggle keys, miscellaneous keys, etc.

Central processing unit (CPU)


Mouse A mouse is the pointing device. It is used to Central Processing Unit (CPU) acts as the brain of
move the cursor around the screen and to point to an the computer. It contains the following functional
object. It has two or three buttons for clicking. It units:
tracks the motion of the mouse pointer. It senses the
clicks and sends them to the computer. So that it can Registers These are high-speed storage devices.
respond appropriately. The Instruction Register (IR) holds the current
instructions. The Program Counter (PC) holds the
address of the next instruction. It also contains a set
of general-purpose registers for temporary storage
of data values.
Arithmetic logic unit (ALU): It can perform
Scanner A scanner is a device that scans pictures or arithmetic operations, such as addition and
documents. So that we can store them, seen, modify subtraction and the logical operations, such as
and print on a printer. comparing two numbers.
Control unit (CU) The control unit coordinates all
the devices. It controls the transfer of data and
instructions between main memory and the
registers in the CPU.
Output devices Memory Unit
An electronic storage area of a computer is known
The devices, which can show or display the output/ as Memory. It is mainly of two types:
result information are known as the output devices. It primary memory and the secondary memory.
includes Primary memory Primary memory stores the
Monitor: Computer display devices are known as a currently executing data and. Primary memory is
monitor or Visual Display Unit (VDU). Monitor of also known as main memory. This memory is
different sizes and technology. CRT (Cathode-ray accessed directly by the processor. It includes
tube) and LCD (liquid crystal display) monitors are RAM, Cache memory.
the two common types of Monitors. Secondary Memory Secondary memory provides
large storage. It is permanent memory and
inexpensive. It is slower than primary memory. It is
also known as auxiliary memory. It includes
Storage devices such as hard disks, floppy disks,
CDROMs, and magnetic tapes.

ABVG Degree College,Jangaon 3

.
* Programming in C

Unit of memory The following figure shows an interface unit:


The unit of memory is a byte. The memory’s capacity
is expressed in number of bytes. The following are
some units used to express the memory capacity:
• Kilobyte (KB) = 1024 bytes
• Megabyte (MB) = 1024 Kilobytes
• Gigabyte (GB) = 1024 Megabytes
• Terabyte (TB) = 1024 Gigabytes
• Petabyte (PB) = 1024 Terabytes
• Exabyte (EB) = 1024 Petabytes
• Zettabyte (ZB) = 1024 Exabytes
• Yottabyte (YB) = 1024 Zettabytes
Motherboard
Memory hierarchy It is an electronic circuit board. It holds all the
A computer system uses various types of memory. components in the computer system. The
These memory differ in speed, cost, size, and motherboard provides physical connections among
volatility. They can be organized in a hierarchy, as them. It consists of the following:
shown below:
▪ CPU Socket: It holds the central processor.
▪ Memory Sockets: These sockets hold the
RAM.
▪ Interface module: It is for the hard disk,
floppy disk, and CD-ROM drives.
▪ ROM integrated chip: It contains the
BIOS programs.
▪ Ports and expansion slots: It is used to
connect a device with the bus.
▪ PCI slots: It connects the I/O devices.
▪ Advanced graphics port (AGP): It holds
the Video card.
It shows that from top to bottom, the speed decreases ▪ Parallel port: It is used as the printer port,
but the capacity increases and the prices become or LPT1.
much lower. The registers, Cache, RAM are volatile ▪ Serial ports: These are used as
but the secondary memory are non-volatile. communication ports or COM ports.
Interface unit ▪ USB (universal serial bus): This is a serial
A set of parallel lines that interconnects the CPU with port. USB can connect the devices, such as
memory and I/O devices are known as the interface mouse, keyboards, hard disk drives, pen-
unit. drives, cameras, modems and printers.
It can be classified into three types: ▪ CMOS: The CMOS stands for
Data bus: It can carry the actual data. Complementary Metal Oxide
Address bus memory or Input/output device: It can semiconductor memory. It is a type of RAM
transport the Addresses. that stores information about the size of the
Control bus: It can carry the control information hard disk, the amount of RAM, etc.
between the CPU and other devices.

ABVG Degree College,Jangaon 4

.
* Programming in C

System unit Application software


The System Unit holds all the system components in Application software is designed to perform
it. It is sometimes called cabinet. It holds the main specific tasks of the users. Microsoft Word,
components like motherboard, hard disk, SMPS, etc. Microsoft Excel, Microsoft Power Point, Microsoft
Cabinets are of two types. Access, etc. are some of the examples of
i) AT cabinets (or mini-tower) application software.
ii) ATX cabinets
• AT cabinets are smaller and cheaper. They are Application software is of 2 types: custom software
popularly called mini-tower cabinets. They and pre-written software packages.
are used for older processors and smaller Custom Software:
motherboards. Software that is developed for a specific user is
• ATX cabinets are larger in size than AT known as custom software.
cabinets. They are more expensive and
have more features. A pre-written software package is a software that is
developed for general needs of all the users.
Software The most important software are :
Software provides the instructions that tell the ▪ Database management software, e.g.
hardware what to do. A set of instructions is known Oracle, DB2, Microsoft SQL server, etc.
as a Program. A set of related programs are known as ▪ Spreadsheet software, e.g. Microsoft Excel.
a software. It can provide desired functions and ▪ Word processing, e.g. Microsoft Word,
performance. Corel Wordperfect
Comparison between computer program and software ▪ Desktop publishing (DTP), e.g. Pagemaker.
Computer program Software ▪ Graphics software, e.g. Corel Draw.
Program Software ▪ Statistical, e.g. SPSS,Tora.
A single developer is A large number of
involved. developers are involved. Memory
RAM:
Small in size Extremely large in size RAM stands for Random Access Memory. Any
Have Have enormous location in a RAM can be accessed directly. RAM
limited functionality functionality. is volatile in nature. Its contents can be erased when
the power is off. So that it is also known as
The user interface may User interface must be Temporary Memory. They are limited in size.
not be very important. carefully designed for
the users TYPES OF RAM:
There are two types of RAM. Dynamic RAM and
Static RAM.
Software is generally 2 types: System software, Dynamic RAM (DRAM): It refreshes its data after
Application software. every few milliseconds. It has higher storage
System software capacity and is cheaper than Static RAM.
System software is designed to run the computer. The Static RAM (SRAM): It need not be refreshed. It
software such as language translator, operating remains stable as long as power is supplied to it.
system, loader, linker, etc are the system software. SRAM is costlier but has higher speed than DRAM.

ABVG Degree College,Jangaon 5

.
* Programming in C
Static RAM Dynamic RAM Secondary Memory
It does not require It requires‘‘refresheing’’ There are four main types of secondary storage
refreshing. devices:
It is more expensive It is less expensive • Disk drives
It is lower in bit It holds more bits of • CD drives (CD-R, CD-RW, and DVD)
density storage • Tape drives
It is faster than It is slower than SRAM. • USB flash drives
dynamic RAM.
Floppy Disk:
Cache Memory The floppy disk is a thin, round piece of plastic
It is a high-speed memory. It stores the data currently material, coated with a magnetic medium.
in use by the processor. It acts as a high speed buffer The floppy disk is enclosed by a plastic shell. Its
between CPU and main memory. It increases the size is 3½ inches and can store 1.44 MB of data.
processing speed. The cache memory is very
expensive and is limited in capacity. Hard Disk:
There are two levels of cache: A hard disk is a permanent memory device found
Level 1 (Primary) cache This type of cache memory inside the system unit. A hard disk consists of metal
is placed on the processor itself. This cache is very platters. Each platter is divided into tracks and
fast and its size varies generally from 8 KB to 64 KB. sectors. Read/write heads are used to read/write the
Level 2 (Secondary) cache It is slower than L1 cache. data. The storage capacity of a hard disk is very
It is usually 64 KB to 2 MB in size. Level 2 cache is large and expressed in terms of gigabytes (GB). It
also called external cache. stores the data permanently.

ROM CD’s
ROM stand for Read Only Memory. ROM is used in A CD is a portable secondary storage medium.
personal computers for storing start-up instructions. It Various types of CDs are available: CD-R and
is used for BIOS test or POST. ROMs can be written CD-RW. Once created Data stored on CD-R
only at the time of manufacture. (CDRecordable) disc can’t be changed. A
PROM: CDRewritable (CD-RW) disc can be erased and
A Programmable ROM (PROM), is also non-volatile reused. . CD-RW drives are used to create and read
and can be programmed only once. both CD-R and CD-RW discs.
EPROM: Erasable Programmable Read Only
Memories can be written electrically. Its data can be Tape drive
erased by using ultraviolet light. A tape drive is a data storage device that reads and
EEPROM: Electrically Erasable Programmable writes data on a magnetic tape. Magnetic tapes are
Read Only Memory (EEPROM can be written onto generally used for backup. Magnetic tapes are
by electrical signals. Its data can be erased by cheap but has a long stability.
electrical signals.
USB Flash drive:
It is a small, portable flash memory card. It can be
plugged into a computers USB port. It is easy to
carry and more durable. Because it cannot contain
any internal moving parts. It is also are called pen
drive.

ABVG Degree College,Jangaon 6

.
* Programming in C
Operating System
An operating system is a system software that acts as
an intermediary between the user and the Hardware.
Mac, MS Windows, Linux, Solaris, Android etc are
some of the operating systems.

The common functions of an operating system:

▪ Process(or) management
A process is a program in execution. The operating
system decides which process to run. It also assigns
priority to the processes.

▪ Memory management Operating system is


responsible to allocate and de-allocate • First, the instruction is fetched from main
memory. memory and loaded into Instruction
Register (IR), Its address is specified by PC
▪ Device management The operating system register.
controls accesses to the I/O devices among the • Then it increments the PC to the next
processes. instruction in the program.
• In IR, the instruction is decoded to
▪ File management: The file system in an determine the actions needed for its
operating system allows users to create, execution.
delete, modify, open, close, and apply other • The control unit enables execution of the
operations to various types of files. instruction.
• The result of the instruction is stored
Booting (written) to either a register or a memory
Booting is the initial set of operations that the location.
computer performs when it is switched on. • The next instruction of a program will
When a computer is switched on, it performs follow the same steps.
BIOS/POST and loads the Operating system files into • This will continue until there is no more
memory. instruction in the program or the computer
Booting is of 2 types: is turned off.
Cold booting: The process of starting the computer
and loading its operating system by turning the power Generation and Classification of Programming
on. Languages:
Warm booting: The process of restarting the A programming language is an artificial
computer and loading its operating system again is formalism in which algorithms can be expressed. It
known as warm booting. is the communication bridge between a
programmer and computer. It is useful to create
Operational overview of a CPU programs that the computer can understand.
The processing required for a single instruction is
called an instruction cycle. The CPU performs four
steps for each instruction: fetch, decode, execute, and
store.

ABVG Degree College,Jangaon 7

.
* Programming in C

as a High Level Language. It is known as the Third


The programming languages are broadly classified
Generation Language (3GL).
into 5 generations:
Example:
First Generation Language:
Computer is an electronic machine. It knows only
machine (electronic) codes.
ON and OFF are known as the Machine codes.
ON can be indicated with 1 and OFF can be indicated
with 0.
A language which contains only 1’s and 0’s in it is
known as Machine Language. It is also known as the There are many high level languages like
First Generation Language(1GL). FORTRAN, ALGOL, COBOL, C, C++, JAVA,
C#, etc.
A Machine language is directly understood by the
computer. It has the following format: High level languages uses different types of
translators to convert the instructions into machine
understandable form.

For example: C language uses a Compiler.

Fourth Generation Language:


Fourth Generation Languages are more English like
Example:
languages. They are especially useful for accessing
the databases. 4GL’S can reduce programming
effort and time to coding.

SQL, SAS, COGNOS, PHP, etc. are some


Second Generation Language: examples of 4GL’s.
The Language that use mnemonics for computer
operations and memory locations is known as Fifth Generation Language:
Assembly language. It was created in early 1950’s. It The software that automatically generate 3GL code
is known as the Second Generation Language (2GL). based on the arrangement of the graphical symbols
Assembly language uses an Assembler. An or icons [by the programmer] is known as a Fifth
Assembler is a translator. It translates the assembly Generation Language. These are the natural
language instructions into machine understandable languages.
form. CASE tools are the examples of Fifth generation
Example: languages.

***

Third Generation Language:


The language that contains English like statements
and mathematical symbols is known

ABVG Degree College,Jangaon 8

.
* Programming in C

Classification of Programming Languages: • Scripting languages:


Programming languages can be classified into low- A scripting language is a language that is
level or high-level languages. Both assembly designed for integrating and
language and machine language are considered as communicating with other languages.
low-level languages. Low-level languages are the UNIX shell is one of the earliest scripting
native language of the computer. languages. Some of the most widely used
Based on the programming paradigm, the High level scripting languages are JavaScript,
languages are of three types: VBScript, PHP, Perl, Python, Ruby, ASP.
1. Procedural languages These languages are the interpreted
2. Non-procedural languages languages.
3. Problem oriented languages.
2. Non-procedural languages:
These are the functional languages. A
functional language program consists of
built-in functions with arguments. LISP,
ML, Scheme, etc. are examples of
functional languages.

3. Problem-oriented languages:
These languages provide pre-programmed
functions. The user need to write those
functions. MATLAB is an example of this
1. Procedural programming languages: category. MATLAB is very popular
In procedural programming, each program can be language among scientists and engineers.
divided into small procedures (subroutines or
functions). This style is easier for programmers. ***
There are mainly three types: Translator, Loader, Linker
• Algorithmic languages: In this style, the
programmer must specify the steps, which the • A Translator is a program that translates
computer has to follow. It uses top-down the source program into machine
approach. Languages like C, COBOL, understandable form.
PASCAL and FORTRAN fall into this • A Linker is a program that combines the
category. machine language program with other
[Top-down approach: It is a technique of programs in the library.
programming that first defines the overall outlines of • A Loader is a program that loads the
the program and then fills in the details.] executable program’s from secondary
memory into primary memory and prepares
• Object Oriented languages: Object-oriented them for execution and starts the execution.
programming depends on software objects.
Data and associated operations are combined ***
into objects. This approach provides reuse of
code and design. C++, JAVA, SMALLTALK,
etc. are some examples of object-oriented
languages

ABVG Degree College,Jangaon 9

.
* Programming in C
Compilers – Interpreters 1. Lexical analysis:
In this phase, the source program is scanned
There are two ways to translate a program from high for lexical units (identifiers, operators, etc.).
level language into the machine language. They are: It creates a table called symbol table. The
COMPILING and INTERPRETING. Symbol Table is used to record information
about the user-defined names in the program.
Compiling: When you compile a program, the entire
program is translated into machine language before 2. Syntax analysis: In this phase, tokens are
it is executed. combined into expressions or statements.
• A COMPILER is a translator program that This process is known as parsing. This
performs Compilation. parsing process can produce a Parse Tree.
Syntax rules can be described by using a
• C and C++ languages uses Compilers for their technique called as BNF (Backus Naur
translation. Form) grammar.

Interpreting: When you interpret a program, the


program is translated line by line, as it is executed.
• An Interpreter is a translator program that
performs interpretation.
• JavaScript language uses Interpreter for its
translation.
• JAVA language uses Compilers as well as
Interpreters.

Differences:
1. A Compiler takes the entire program as its
input. 3. Semantic analysis: The semantic analysis
2. An Interpreter takes Instruction by instruction phase further analyses the parsed
as its input. statements.
3. A Compiler generates Object Code
4. An Interpreter does not generate any object 4. Intermediate code generation and
code. optimization: Many compilers produce an
5. A Compiler requires more memory intermediate form of code for optimization.
6. An Interpreter requires less memory. The intermediate code may be is in
assembly language.
***
Compiling, Linking and Loading a Program 5. Code generation: This is the final phase
that converts the intermediate code into
A Compiler translates a program written in a source target machine code. It also performs
language into target language. The compilation linking and loading step to generate an
process can be divided into the following phases: executable program.
1. Lexical Analysis
2. Syntax Analysis ***
3. Semantic Analysis
4. Intermediate code generation
5. Code Generation

ABVG Degree College,Jangaon 10

.
* Programming in C
Software Development
Developing a Program
Software development is more than programming.
There are seven important steps in developing a
It involves a large number of people. Programming
program:
is one of the activities in software development. A
1. Definition
software is built according to client’s requirements.
2. Design
It is driven by cost, schedule and quality. That is,
3. Coding
software should be developed at reasonable cost,
4. Testing
handed over in reasonable time.
5. Documentation
6. Implementation
Software development involves the following
7. Maintenance.
steps:
1. Definition: This is the first step in developing
1. Feasibility study:
a program. The definition must include the
Feasibility study is an assessment of the proposed
needed output, the available input, and etc.
project. It verifies the feasibility of the software
2. Design: This is the second step in developing development. Feasibility study is of three types:
a program. It should design the problem • Economic feasibility
solution (algorithm). • Technical feasibility
• Operational feasibility
3. Coding: This is the third step in developing a
program. It writes the program instructions in Economic feasibility: It verifies whether the
a programing language. The instructions must development of new software will be financially
follow the syntax. beneficial or not.
4. Testing: This is the fourth step in developing Technical feasibility: It verifies various factors
a problem. It tests the program for the errors. such as the performance of the technologies, their
Errors in a program are called bugs. The interoperability with other technologies, etc.
process of finding the bugs and correcting
them is called Debugging. Operational feasibility: It verifies the (a) Type of
5. Documentation: This is the fifth step in tools needed (b) Skills required (c) Documentation
developing a program. It completes the d) other support required for operating the software.
documentation of the program.
Documentation is extremely important. 2. Requirement analysis:
Documentation should contain user In this phase, the requirements related to the
instructions, an explanation of the logic of the software are understood. This is an important step
program, and expected I/O. in developing software. If the requirements of the
user are not properly understood, then the
6. Implementation: This is the sixth step in developing software becomes a failure.
developing a program. After completing the
program, it needs to be installed on a 3. Design:
computer. The Design phase creates the architecture and
7. Maintenance: A completed program requires design of the new software. It has two stages:
attention. It needs to be maintained and • System design
evaluated for possible changes. • Detailed software design.

***

ABVG Degree College,Jangaon 11

.
* Programming in C
• System design: It designs the overall system
architecture. It prepares an abstract
representation of that system.

• Detailed design: It designs the software


system functions. It prepares the specification
of the software to be written.
4. Implementation:
In this phase, the code of the new software is
developed. The programmers in the software
development team use development tools for this
purpose.

5. Testing:
The Testing phase detects errors in the new software
and rectify those errors. The testing phase performs
verification and validation.
• Verification is the process of checking the
software based on some specifications.
• Validation involves testing the product to
verify whether it meets the user requirements.

6. Deployment:
The newly developed software need to be installed in
its target environment. It hand overs the software
documentation to the users. It also gives training to
the users.

7. Maintenance:
In this phase, developed software becomes
operational. It requires a continuous support.

***

ABVG Degree College,Jangaon 12

.
* Programming in C
Algorithms Pseudo-code
To solve any problem a plan is needed. An algorithm • It is a written form representation of the
is a part of the plan for the computer program. algorithm.
What is an Algorithm? • It is in the human language.
Computer scientist Niklaus Wirth stated that: • It uses a limited vocabulary to define its
Program = Algorithms + Data.
actions.
Example:
An algorithm is ‘an effective procedure for solving a
If student's grade is greater than or equal to 60
problem in a finite number of steps’.
Print "passed"
“Effective” means that an answer is found and it has else
a finite number of steps. A well-designed algorithm Print "failed"
should give an answer and also it must be terminated.
Endif
Definition:
An Algorithm is a finite set of instructions for Flowchart and Nassi-Schneiderman
solving a problem. • These are a graphical representation of the
algorithm.
Different Ways of Stating Algorithms: • They use symbols and language to
Algorithms can be represented in four ways: represent sequence, decision, and
1. Step-form repetition actions.
2. Pseudo-code Example:
3. Flowchart Draw a flowchart to find largest of three
4. Nassi-Schneiderman numbers?
Step-form representation: Solution:
• The step-form uses normal language.
• It states the algorithm with written
statements.
• Every statement is logically related to the
preceding statement.
• Each statement solves a part of the problem
and all the statements together complete the
solution.

Example:
Write an algorithm for finding the sum of any two
numbers.
Step 1. START
Step 2. PRINT “ENTER TWO NUMBERS”
Step 3. INPUT A, B ***
Step 4. C A + B
Step 5. PRINT C
Step 6. STOP

ABVG Degree College,Jangaon 13

.
* Programming in C
Strategy for Designing Algorithms Spaghetti code
The strategy for designing algorithms involves 3 A Non-modular code is known as Spaghetti code.
steps: It produces a disorganized computer program. It
1. Investigation step may also contain many GOTO statements in it.
2. Top-Down development step That makes the program more complex.
3. Step-wise refinement ***
Structured programming
Investigation step:
The investigation phase determines the requirements Structured programming is a style of programming
for the problem solution. Here you need to: that includes the following characteristics:
I. Identify the outputs. 1. Block structure:
II. Identify the input variables. The statements in the program must be organized
III. Identify the decisions and conditions. into functional groups.
IV. Identify the processes. 2. Avoidance of jumps:
V. Identify the environment. A lot of GOTO statements makes the programs
more error-prone. Structured programming uses
Top–down development: less number of goto statements. Therefore it is also
It plans the solution by breaking it into smaller known as ‘GOTO less programming’.
modules. 3. Modularity: Structuring the program makes it
• Devise the overall problem solution: Divide easier to understand.
the problem solution into small modules.
• Verify the feasibility of solution: Check that Advantages of structured programming:
the modules together form the whole solution
to the Problem. • Structured programming can develop well-
organized codes.
Stepwise refinement:
• Many developers can work simultaneously
It further decomposes the modules, defines the
on the same program.
procedures and also verifies their correctness.
• It reduces complexity.
• Work out all the details for each module.
• It also saves time
• Decompose any module into further
• It encourages stepwise refinement.
meaningful smaller pieces.
• Group common processes together Disadvantages of structured programming:
• Group common variables together. • Error control may be harder to manage.
• Test each small procedure for its correctness • Managing modifications may also be
difficult.
Example:
• Debugging efforts can be delayed.
Write an algorithm for finding the sum of any two
numbers.
Solution:
***
Let the two numbers be A and B and let their sum be
equal to C. Then, the desired algorithm is given as
follows:
Step 1. START
Step 2. PRINT “ENTER TWO NUMBERS”
Step 3. INPUT A, B
Step 4. C A + B
Step 5. PRINT C
Step 6. STOP ***
ABVG Degree College,Jangaon 14

.
* Programming in C

Overview of C Writing the program:


A C program can be written by using any text
➢ C is a general purpose programming editor (vi / edlin). Turbo C++ provides an
language. Integrated Development Environment for
➢ C was designed by Dennis Ritchie in 1972 at developing a C and C++ programs. An IDE has
AT&T Bell labs of USA on a DEC PDP-11 an environment for writing, modifying, testing, and
that used the UNIX operating system. debugging the programs. After creating the
program (Source Code), it should be saved with file
➢ C is a structured programming language. The extension “.c”.
use of goto is either prohibited or discouraged. Compiling & Linking the program:
Compiling includes pre-processing, compilation,
➢ In C, functions are the building blocks. Thus assembly, and linking. For compiling the C
It allows the programs to be modular. program use the COMPILE command (or
ALT+F9) from the Turbo C++ IDE. If your
➢ C is also known as a middle-level language program has any errors then the COMPILER will
because it combines the best elements of high- list out the compile time errors.
level languages with the features of assembly Executing the program:
language. After successful compilation, use the RUN
command (or Ctrl+F9) from the Turbo C++ IDE to
➢ C code is also portable. It can run on any execute the program. If your program has any
computer errors then it will list out the runtime errors.
Otherwise it will display the result.
➢ C is well suited for system-level
programming.

➢ C has only a few keywords. For example, C89


defines only 32 keywords.

➢ C is suitable to develop almost any type of


software. It can be best suited to develop
system software and also to develop
application software.
***

Developing programs in C
There are mainly three steps in developing a program
in C:
1. Writing the C program
2. Compiling the program
3. Executing the program

***

ABVG Degree College, Jangaon 15


* Programming in C
Errors 2. #include<stdio.h>
Errors in a program are called bugs. The process of This is known as Pre-Processor directive.
finding the bugs and correcting them is called • In C all the lines that begin with #
Debugging. are known as pre-processor
Errors are of Three types: directives. A Pre-Processor is a
▪ Compile errors: These are the errors program that processes the
that are given by the compiler. directives before the compilation
Compile errors prevent the program process.
from running. • #include directive includes the
▪ Linking errors: These are the errors contents of a file during
that are given by the linker and ends compilation. Here, <stdio.h> is a
the program. The linker can also header file that contains
information about I/O functions.
detect and report errors at the time of
linking. 3. int main(void)
▪ Run-time errors: These are the errors A C program may contain one or more
that are given by the operating system. functions. Every C program must contain a
main() function. Every C program starts its
execution at main() statement.
***
4. { }
Parts of a Simple C Program This is a brace. Braces are useful to group a
Let us consider a simple program named first.c: set of statements. Such a group of a program
is called a block.
/* A Simple C Program */ 5. printf(“C is Sea\n”);
#include<stdio.h> printf() is a ‘library function’. It is a
int main(void) formatted output function. Printf() can be
{ used to print the given contents on the
printf(“C is Sea\n”); screen.
return 0; In C, The character combination that
} consists of a backslash ( \) followed by a
letter or digits is known as Escape
Let us see line by line: Sequences. The \n is an escape sequence. It
1. /* A Simple C Program */ is used to print the new line character.
The following are different escape sequence characters:
This is known as a Comment line. We can put Code Meaning
comments in a program. Comments will \a Bell
provide information about the program and its \? Question Mark
instructions. Comment lines starts with /* and \b backspace
ends with */. The C compiler considers them \r Carriage return
as non-executable statements. \t Horizontal tab
A comment line can also begin with //. It \v Vertical tab
extends up to the next line break. So the above \\ Backslash
statement can also be written as follows: \” Double quote
\’ Single quote
//A Simple C Program \n New Line

ABVG Degree College, Jangaon 16


* Programming in C
6. return 0; Structure of a C Program
This statement indicates that the main() function A C program may contain the following structure:
returns a value 0 to the operating system.
The return statement is not mandatory.
7. ; (Semicolon)
In C a semicolon can be used as a statement
terminator.The semicolon is required to
indicate the compiler that the statement is
completed.

8. All program instructions/statements have to be


written in lower-case characters.

Header files
A header file is a file that has C declarations and
macro definitions. It provides the required
information for the pre-processor and compiler to Preprocessor directives:
process the program. In C all the lines that begin with # are known as pre-
The ISO C contains the following header files: processor directives. A Pre-Processor is a program
assert.h signal.h errno.h stddef.h that processes the directives before the compilation
complex.h stdarg.h fenv.h stdint.h process.
ctype.h stdbool.h float.h stdio.h Global declarations:
inttypes.h stdlib.h locale.h time.h The global declaration contain the global variables.
iso646.h string.h math.h wchar.h The variables that are available for all the functions
limits.h tgmath.h setjmp.h wctype.h in the program are known as global variables.

There are two ways of including files in C program: Main program section:
1. #include<filename> All the functions in a c program can be divided
This method tells the preprocessor to look for into two sections:
the file in the default location. This method is ▪ Local definition
used to include standard headers such as ▪ Statements.
stdio.h or stdlib.h. Local definitions:
2. #include “file name” Local definitions are at the beginning of the
This method tells the preprocessor to look for functions. Local definitions are available within
the file in the current directory first, then that function only.
in the predefined locations. This method is Statements:
used to include programmer created files. Statement section consists of the executable
instructions.
***
***

ABVG Degree College, Jangaon 17


* Programming in C
C Tokens Some of the invalid identifiers:
The smallest individual units in a c program are called 1number
tokens or lexical units. C tokens can be classified as struct
follows: student name
C Constants
1. Keywords Constants are the fixed values that do not change
2. Identifiers during the program execution. They are also known
3. Constants as literals. In C, the keyword “const” can be used to
4. Separators declare constants. It has the following syntax:
5. Operators
const datatype identifier = value;
Keywords
keywords are the reserved words. Keywords have a Example: const int i = 30;
fixed meaning. These meanings cannot be changed. const float pi = 3.14;
The keywords cannot be used as variable names.
Constants are of different types
ANSI C defines the following 32 keywords: 1. Integer Constants
2. Real Constants
auto break case char const 3. Character Constants
continue default do double else 4. String Constants
enum extern float for goto
if int long register return 1. Integer Constants
short signed sizeof static struct Integer constants are the whole numbers without
switch typedef union unsigned void any fractional part. There are three types of integer
volatile while constants:
Identifiers
Decimal Integer Constants
Identifiers are the names given to the variables,
The integer constants that contains a set of digits, 0
constants, data types, arrays, functions, structs,
through 9 are known as Decimal integer constants
unions and classes.
Example:
Identifiers has the following rules: 124, -121, 0, 5678
I. An identifier must start with an alphabet (
or underscore). Octal Integer Constants
II. It may contain a sequence of letters and Integer constants that contains a set of digits from
digits the set 0 through 7 are known as Octal integer
III. Identifiers are case sensitive. “count” is constants. An Octal integer starts with 0.
different from “Count”. Example:
IV. Keywords cannot be used as identifiers 010, 0123, 0, 0560
IV. White spaces are not allowed.
V. An identifier may contain any number of Hexadecimal Integer Constants
characters. The integer constants that contain a set of digits 0
Some of the valid identifiers: to 9 and A to F are known as hexadecimal integer
total_marks constatns. A hexaemcal constant starts with 0x or
number1 0X.
_count Example:
Example:
0xB, 0X9d, 0X123F

ABVG Degree College, Jangaon 18


* Programming in C
2. Real Constants Data types
The constants that have fractional parts are called real A data type is a characteristic that defines what type
or floating point constants. These may be represented of data a variable can hold and the set of operations
in fractional form or the exponent form. that can be applied.
Example:
0.08, -0.901, 132.03 In C the data types are broadly classified into the
3. Character Constants following types:
A single character that is enclosed within single
quotes is known as a character constant.
Examples:
‘a’ , ‘S’, ‘4’
4.String constants:
A group of characters enclosed within double quotes
is known as a String constant
Example:
“Dennis Ritchie”
“Ravi”
"C 99"
***
Separators 1.Primary Data types:
There are some special symbols used in C. The standard and basic data types of C are known
[] () {} , ; : as the primary data types. C has five basic data
Braces{}: These opening and ending curly braces types:
marks the start and end of a block.

Parentheses(): These special symbols are used to


indicate function calls and function parameters.

Brackets[]: Opening and closing brackets are used as


array element reference. 1. Char: A char type represents character data type.
*** It occupies 1 byte of memory. It uses the keyword
Operators “char”. Character constants and literals can be
Operators are the symbols that performs some represented within single quotes.
mathematical or logical operations.
Depending on the number of operands, the operators 2. Int: Integers are the numbers without any decimal
can be classified into: point (period/exponent). An int type can be
classified into three types:
• Unary Operators: The operators that require • short: A short type can represent smallest
only single operand are known as unary integers. It occupies 2 bytes of memory.
operators.
• int: An int data type occupies 2 bytes / 4
• Binary Operators: The operators that require
bytes of storage. Its range is -32,768 to
two operands are known as binary operators.
32767 or or -2,147,483,648 to
• Ternary Operators: The operators that 2,147,483,647.
require three operands are known as Ternary • long: A long type can represent long
operators. integers. It occupies 4 bytes of storage.

ABVG Degree College, Jangaon 19


* Programming in C
3. Float: The numbers with decimal point Real/Floating Point Variables: The identifiers
(exponent) are known as floating point that are used to store floating point data are known
numbers or real numbers. They can use the as real variables. The keywords “float”, “double”,
keyword “float”. Float types are classified “long double” can be used to declare real group of
into three types: variables. It has the following syntax:
• float: A float type can represent 6 digits of float id1, id2 ;
precision. It occupies 4 bytes of storage. Its Example: float x=5.3, y=2.4;
range is -3.4e38 to +3.4e38.
Character variables: The identifiers that are used
• double: A double type can represent double
to store a single character is known as character
precision floating point numbers. It occupies
variables. It uses the keyword “char”. It has the
8 bytes of storage. Its range is -1.7e308 to following syntax:
+1.7e308. char id1, id2 ;
• long double: A double type can represent Example: char a= ‘S’, b=’M’;
large range of values. It occupies 10 bytes of
storage. Boolean variables: The variables, which are used
4. Void type: A void type can represent to store either TRUE of FALSE are known as
“valueless”. It specifies an empty set of Boolean variables. It uses the keyword “bool”.
Example: bool counter=TRUE;
values.
Program Statements
Variables: A statement is a syntactic construction that
Variables are the names given to the memory performs an action. In C, Program statements can
locations. Variables can store data. A variable can be classified into the following types:
change its value during the program execution.
Variables will follow the rules of identifiers.
Variables can be declared by using the following
syntax:
data type identifier= value;
example: int x = 10;
float f =2.3;
C variables are of four types:
Declaration statements:
Variable integer variables Declaration statements declares the variables.

real variables They have the following general form:


data type variable_name_1,
character variables variable_name_2, ..., variable_name_n;
Example: int a, b, c;
boolean variables Variables can be declared at three basic places:
• Variables that are declared inside a
Integer Variables: The identifiers that are used to function are called local variables.
store integer data are known as integer variables. It
• The variables that are declared in the
uses the keyword “int”. It has the following syntax:
definition of function parameters are called
int id1, id2 ; formal parameters.
• The variables that are declared outside all
Example: int a=10, b=20; functions are called global variables.

ABVG Degree College, Jangaon 20


* Programming in C
Expression statements: Arithmetic Operators
Expression statement is a sequence of operators and Arithmetic operators can perform the arithmetic
operands. It performs computation of a value. For operations. There are five main arithmetic
example: operators in ‘C’. They are:
x = 4; is a statement. ‘+’ for additions, ‘-' for subtraction, ‘*’ for
sum =a+b; is a statement multiplication, ‘/’ for division and ‘%’ for
remainder division.
Compound statements:
The following table shows the arithmetic operators
Compound statement is a sequence of statements that
in c:
may be treated as a single statement.
Labeled statements:
A labelled statement can be used to mark any
statement. So that control may be transferred to that
statement by switch statement.
Control statements:
A control statement is a statement that determine the
‘flow of execution’ in a program. These are of 3 types:
• Selection statements:
Selection statements allow a program to select a
particular statements for execution.
Example: if..else statement The operators *, / and % have higher precedence
• Iteration statements: than + and -. Multiplication, division and remainder
Iteration statements are used to execute the operations will be carried out before addition and
statements repeatedly. subtraction.
Example: while, for, and do..while statements Relational Operators:
• Jump statements: Relational operators are symbols that are used to
Jump statements can cause an unconditional test the relationship between two operands. If the
jump to some other place in the program. relation is true, it returns 1; if the relation is false, it
Example: goto statement returns value 0.
C’ has six relational operators as follows:
***
Operators
An operator is a symbol that performs the
mathematical, or logical operations. C has the
following types of operators:

ABVG Degree College, Jangaon 21


* Programming in C
Logical Operators These operators have lower precedence than the
There are three logical operators in C language, they arithmetic operators.
are logical &&(and) , logical !!(or), logical !(not). Increment and Decrement operators
The result of a logical and operation will be true only
The unary ‘++’ and ‘--’ operators are known as
if both operands are true, whereas the result of a
increment and decrement operators. These
logical or operation will be true if either operand is
operators can increment or decrement the value of
true or if both operands are true.
a variable by 1.
These operators can be used in ‘prefix’ and
‘postfix’ formats:
• var++; post increment
• var-- ; // Post decrement
• ++var; // Pre increment
• --var; // Post decrement.
Difference between prefix and postfix formats:
In a prefix format, First the operand is
incremented/decremented. Second its value will be
assigned to the variable on its left.
Bitwise Operators
Bitwise operators perform manipulations of data In a postfix format, First the operand’s value will
at bit level. Bitwise operators are not applied be assigned to the variable on its left. Second the
to float or double. operand is incremented/decremented.
Operator Meaning Conditional Operator
& Bitwise AND The conditional operator has three expressions. It
| Bitwise OR takes the following form:
^ Bitwise Exclusive OR expression1 ? expression2 : expression3;
<< Left Shift First, expression1 is evaluated. If it is true(1), then
>> Right Shift expression2 will be taken as the final result.
The following is the truth table of Bitwise operators: Otherwise, expression3 is will be taken as the final
a b a&b a|b a^b result.
For example:
0 0 0 0 0
int m = 1, n = 2, min;
0 1 0 1 1
min = (m < n ? m : n); /* min is assigned a value 1
1 0 0 1 1
*/
1 1 1 1 0
For example:
The bitwise shift operators shifts the bit value. These min = (m < n ? m++ : n++);
operators shifts the bits by the specified number of
m is incremented because m++ is evaluated. But n
positions. is not incremented because n++ is not evaluated.
Example: Comma Operator
a = 0001000 The comma operator allows the evaluation of
a << 2 = 0100000 multiple expressions, separated by the comma. It
evaluates from left to right in order. It takes the
a >> 2 = 0000010 value of the rightmost expression as the final result.
It takes the following form:
expressionM = (expression1, expression2, …,
expressionN);
int i = 0;
int j;
ABVG Degree College, Jangaon 22
* Programming in C
Sizeof operator j = (i += 1, i += 2, i + 3);
Sizeof is a special operato. It calculates the size of any Here, j will be assigned the value 6.
data item. It takes a single operand that may be a type Associativity determines the order in which
name (e.g., int) and returns its size. operators of equal priority are evaluated. It defines
Example: the direction, L to R or right-to-left.
int n;
n=sizeof(char); Rules of Operator Precedence:
C applies the following rules to its operators when
Assignment Operators evaluating the arithmetic expressions:
Assignment Operator is Used to assign value to an 1. The expressions contained within pairs of
variable. In C assignment Operator is denoted by parentheses are evaluated first. Parentheses are said
equal to sign(=). Assignment Operator is binary to be at the “highest level of precedence.”
operator. It operates on two operands. 2. Multiplication, division and remainder
It has the following format: operations are applied next.
v=exp; 3. Addition and subtraction operations are
Example: evaluated next.
count = 9; 4. If an expression contains several same level of
sum = a+b; operators then evaluation proceeds from left to
C Provides a short hand notation of assignment. It has right.
the following format: 5. The assignment operator (=) is evaluated last.
v op=exp;
Example: The following table shows the precedence of
operators:
Operator Name Example Equillent
expression
+= Addition x += 4; x = x + 4;
assignment
-= Subtraction x-=4 x=x-4
Assignement
*= Multiplication x*=4 x=x*4
Assignment
/= Divison x/=4 x=x/4
assignment
%= Reminder x%=4 x=x%4
assignment
***
Expression Evaluation–precedence and
associativity
C operators have two properties: Priority and
Associativity.
Priority determines the order in which different
operators are evaluated. Operators of higher
precedence are applied before the operators of lower
precedence.

ABVG Degree College, Jangaon 23


* Programming in C
Examples of expressions: The following rules have to be followed while
1. x = 5 * 4 + 6 * 5 converting the expression from one type to another
= 20 + 6 * 5 to avoid the loss of information:
= 20+30
• All integer types to be converted to float.
=50
• All float types to be converted to double.
2. x= 3 * ( 5 +4 ) * 6 • All character types to be converted to
=3*9*6 integer.
= 27 * 6
= 162 ***
***
Type Conversion
The process of converting one predefined type into
another type is called type conversion.

Type conversion is two types:


Implicit Type Conversion:
A type conversion that is automatically performed by
the compiler is known as implicit type conversion or
type promotion.

It has the following rules:


• All short and char are automatically converted
to int.
• If either of the operand is of type long double,
then others will be converted to long double
and result will be long double.
• If either of the operand is double, then others
are converted to double.
• If either of the operand is float, then others
are converted to float.

Explicit Type Conversion:


A type conversion that is performed by the
programmer is known as explicit type conversion.
The explicit type conversion is also known as type
casting.
It takes the following form:
(data_type)expression;
where, data_type is any valid c data type, and
expression may be constant, variable or expression.
For example,
x=(int)a+b*d;

ABVG Degree College, Jangaon 24


* Programming in C

Unit – II getchar(): -
The getchar() is a non-formatted Input function. It
Input-Output can read a single character at a time. It has the
following format:
Input-Output: char_variable = getchar();
Generally, The keyboard and the screen are the Example:
standard input and output devices in programming. int ch;
All input and output is performed with streams. A ch = getchar();
Stream is a sequences of bytes. In input operations, The getchar()function reads a character and places
the bytes flow from keyboard to main memory. In it in the memory location “ch”
output operations, bytes flow from main memory to
screen. putchar():-
The putchar() is a non-formatted output function. It
In C, the input and output are managed through can displays a single character at a time on the
standard streams. Those standard streams are: monitor screen. It has the following format:
1. stdin : Standard Input Stream putchar(char_variable);
2. stdout : Standard Output Stream Example:
int ch = ‘x’;
3. stderr : Standard Error Stream
puchar(ch)’
When a program execution begins, these three
The putchar() function displays the character stored
streams are connected to the program automatically.
in the memory location “ch”.
Normally, the standard input stream is connected to
the keyboard and the standard output stream is
1. Write a C program to display a keyed in
connected to the screen. A third stream, the standard
character.
error stream, is connected to the screen.
Solution
#include<stdio.h>
I/O Functions in C
main()
C has a number of standard functions to perform input
{
and output operations.
int ch;
In C, The input/output (I/O) functions are of two
ch=getchar();
types:
putchar(ch);
1. Non-formatted input/output functions
return 0;
2. Formatted input/output functions. }
Non-formatted input/output functions : I/O
The I/O statements that does not use format codes Input A
are known as Non-Formatted I/O functions. Output A
These functions can handle one character at a
time. There are two important non-formatted I/O
functions in C:
1. getchar()
2. putchar()

ABVG Degree College, Jangaon 25


* Programming in C
2. Write a C Program to convert alphabets from printf() uses the following format codes:
lower-case letters to Upper-case letters.
Solution Format Code Meaning
#include<stdio.h>
main() %c Character
{ %d Decimal Integer
int ch,n;
%i Integer
ch=getchar();
n=(ch>=‘a’)&&(ch<=‘z’)? putchar(ch-32): %f Float
putchar(ch);
%o Octal integer
putchar(n); %p Pointer
return 0;
} %s String
I/O %u Unsigned decimal
(i) Input m Integer
Output MM
scanf():
(ii) Input b scanf() is a formatted input statement. It can read
Output BB the given input from the keyboard. It has the
following format:
(iii) Input $ scanf(“control_string”,variable1_address,
Output $$ variable2_ address,...);
Formatted input/output functions Here, The control string is also known as “Format
The I/O statements that use specific format codes for String”.
their I/O are known as Formatted I/O functions. scanf() uses the following format codes:
These functions can handle different data types.
There are two important formatted I/O functions in C: Format Code Meaning
1. scanf()
2. printf() %c Character
printf(): %d Decimal Integer
printf() is a formatted output statement. It can print
the specified contents on the screen. It has the %i Integer
following format: %f Float
printf(“control_string”, variable1, variable2,
variable3,...); %o Octal integer
Here, The control string is also known as “Format %p Pointer
String”. The format string may contain three types
of objects: %s String
1. Ordinary characters : These are copied to %u Unsigned decimal
output. Integer
2. Format specifier field: It is denoted by %
and the code.
3. Control code: It includes control characters
such as \n, \b, and \t.

ABVG Degree College, Jangaon 26


* Programming in C
Example:
Write a C Program to add two integer numbers and Control Statements
find their Sum Depending on the requirements of a problem, it
Solution might be required to alter the normal sequence of
#include <stdio.h> execution in a program. The order in which
main() statements are executed is called the flow of
{ control. Controlling the flow of a program is a very
int a,b,c; important aspect of programming.
printf(“\nEnter the first number: ”);
scanf(“%d”,&a); C provides different types of control statements to
printf(“\nEnter the second number: ”); control the flow of execution. They are:
scanf(“%d”,&b); • Selection or Branching Statements
c=a+b; • Iteration or Looping Statements
printf(“Sum = %d \n”,c); • Jumping Statements
return 0;
}
Output
Enter the first number : 5
Enter the second number: 10
Sum= 15

Escape sequences
Escape sequences are the control codes that can be
used to control the output as required. C has the
following escape sequence characters:

Code Meaning
Code Meaning
\a Ring bell (a is for alert) Selection Statements
\? Question mark Selection statements are of three types:
\b Backspace • One-way Selection Statements→ These
\r Carriage return statements can do a particular thing or they
\f Form feed do not do anything. In C a simple if
\t Horizontal tab \ statement can do this.
\v Vertical tab • Two-way Selection Statements→ These
\0 ASCII null character statements can do one thing or another
\\ Backslash thing. In C an if..else statement can do this.
\” Double quote • Multi-way Selection Statements→ These
\’ Single quote
statements can do one of many different
\n New line
things. In C an else..if ladder/nested if
\o Octal constant
statements can do this.
\x Hexadecimal constant

ABVG Degree College, Jangaon 27


* Programming in C
if statement if-else statement
One-way decisions can be handled with a simple if Two-way decisions can be handled with if-else
statement. It has the following format: statement. It has the following format:
if(TestExpr) if(TestExpr)
{ {
Statement-T; statement-T;
} }
Statement-X; else
{
TestExpr is the test expression. StmtT can be a single statement-F;
statement or a block of statements enclosed by curly }
braces { }. Statement-X;
The if...else statement works as follows:
The simple if statement works as follows: First, it verifies the ‘test expression’. If the test
First, it verifies the ‘test expression’. If the test expression is TRUE (1), statement-T will be
expression is TRUE (1), then it executes statement-T. executed. If the test expression is FALSE (0) then
if the test expression is FALSE (0) then it skips the statement-F will be executed.
statement-T and directly goes to statement-X.
The following flowchart illustrates if..else
The following flowchart illustrates if statement: statement:

Write a program to find the largest among three Write a C program to check whether a number
numbers. given by the user is odd or even.
#include <stdio.h> #include <stdio.h>
main() int main()
{ {
int a, b, c, max; int n,r;
printf(“\nEnter 3 numbers”); printf(“\nEnter the number”);
scanf(“%d %d %d”, &a, &b, &c); scanf(“%d”, &n);
max=a; r=n%2;
if(b>max) if(r==0)
max=b; printf(“EVEN”);
if(c>max) else
max=c; printf(“ODD”);
printf(“Largest No is %d”, max); return 0;
getche(); }
return 0;
}

ABVG Degree College, Jangaon 28


* Programming in C
Write a C program to check whether the given
if..else..if statement (else..if ladder) number is zero, positive, or negative.
Multi-way decisions can be handled with if-else-if #include <stdio.h>
statement. It has the following format: main()
if(TestExpr1) {
statement-T1; int n;
else if(TestExpr2) printf(“\n ENTER A NUMBER:”);
statement-T2; scanf(“%d”, &n);
else if(TestExpr3) if(n > 0)
statement-T3; printf(“%d is positive \n”,n);
. else if(n == 0)
. printf(“%d is zero \n”,n);
. else
else if(TestExprN) printf(“%d is negative \n”,n);
statement-TN; return 0;
else }
statement-F;
Nested if
if..else..if statement works as follows: Placing a if statement within another if statement is
If TestExpr1 is TRUE (1) then statement-T1 is called a nested if. It has the following format:
executed. If TestExpr2 is TRUE (1) then statement- if(TestExpr1)
T2 is executed, and so on. If all the test expressions {
are FALSE (0), then the statement statement-F is if(TestExpr2)
executed. {
statement-2T;
The following flowchart illustrates if..else…if }
statement: else
{
statement-2F;
}
}
else
{
if(TestExpr3)
{
statement-3T;
}
else
{
statement-3F;
}
}

ABVG Degree College, Jangaon 29


* Programming in C
The following figure illustrates nested if statement. switch Statement
Switch statement is a multi-way selection
statement. It has the following format:
switch(expr)
{
case constant1: stmtList-1;
break;
case constant2: stmtList-2;
break;
case constant3: stmtList-3;
break;
………………………….
………………………….
default: stmtList-n;
}
Here, the case constants must be integer or
character constants.

The switch statement works as follows:


Write a C program to find the largest of three
The switch statement verifies the expression
numbers.
against a list of case values. When a match is found
#include <stdio.h>
then the statements in the corresponding statement
main()
list are executed. Whenever there is no match then
{
the default statements are executed.
int a, b, c;
printf(“\nEnter three numbers”); The following figure illustrates Switch statement:
scanf(“%d %d %d”, &a, &b, &c);
if(a > b)
if(a > c)
printf(“%d”, a);
else
printf(“%d”, c);
else
if(b > c)
printf(“%d”, b);
else
printf(“%d”, c);
return 0;
}

Figure: Switch Statement

ABVG Degree College, Jangaon 30


* Programming in C
Example:
Write a program to perform arithmetic operations
addition, subtraction, multiplication, and division
between two variables. Use the switch construct to
choose the operations.
Solution:
#include<stdio.h>
#include<conio.h>
main()
{
int a, b;
char operator;
clrscr();
printf(“Enter your expression: \n”);
scanf(“%d %c %d ”,&a, &operator, &b);
switch(operator)
{
case ‘+’:
printf(“%d \n”, a + b);
break;
case ‘-’:
printf(“%d \n”, a - b);
break;
case ‘*’:
printf(“%d \n”, a * b);
break;
case ‘/’:
if(b == 0)
printf(“division by zero. \n”);
else
printf(“%d \n”, a / b);
break;
default:
printf(“Unknown Operator \n”);

}
getche();
return 0;
}

***

ABVG Degree College, Jangaon 31


* Programming in C
Iterative Statements
(Looping Control Statements) ➢ C has three loop constructs: while,
A loop allows to execute the statements repeatedly. for, and do-while.
There are mainly two types of loops: ▪ while and for are pre-test loops and do-
1. Bounded loop while is a post-test loop.
2. Unbounded loop.

→Bounded loops can be used when you know how While loop
many times you need to loop. C provides one while statement is a pre-test loop. First, it verifies
bounded loop: for loop. the test expression before every iteration of the
loop.
→Unbounded loops can be used when you does not It has the following syntax:
know how many times to loop. C provides two types
of unbounded loops: while loop and do...while loop. Initialization;
while (TestExpr)
A loop can be either a {
• pre-test loop or stmT
• post-test loop. ...
→In a pre-test loop, first, the condition is checked. If ...
the test condition is true, then only it executes the Updating
statements of that loop. }
This process is repeated till the test expression
becomes false. In a pre-test loop, the statements may stmT will be executed repeatedly till the value of
not be executed even once. TestExpr becomes 0 (FALSE).
The following figure shows the execution of
→In the post-test loop, first the code is always “while” loop:
executed once. The test condition is tested at the end
of the loop. If the test condition is true, the loop
repeats. if it is false the loop terminates.

Figure: While Loop

ABVG Degree College, Jangaon 32


* Programming in C
Example: 3. Write a C program that asks the user to
1. Write a C Program to illustrate ‘while’ loop. enter some numbers and then find their
#include <stdio.h> average
main() #include <stdio.h>
{ int main()
int c; {
c=5; // Initialization int n, a, c=1,s=0;
while(c>0) // Test Expression float avg;
{ printf(“\n HOW MANY NUMBERS?”);
printf(“ \n %d”,c); //statement-T scanf(“%d”, &n);
c=c-1; // Updating while(c<=n)
} {
return 0; printf(“\n Enter the number: ”);
} scanf(“%d”, &a);
I/O: s+=a;
5 c++;
4 }
3 avg=(float)s/n;
2 printf(“ \n AVERAGE IS %f ”, avg);
1 return 0;
}
2. Write a C program that accepts input from the
keyboard and counts the positive integers until a
I/O:
negative number is entered.
HOW MANY NUMBERS? 5
#include <stdio.h>
Enter the number: 10
main( )
Enter the number: 20
{
Enter the number: 30
int x = 1;
Enter the number: 40
int count = 0;
Enter the number: 50
printf(“\n Enter the Number:”);
AVERAGE IS =30.0
scanf(“%d”,&x);
while(x >= 0)
4. Write a C Program to find the sum of the
{
digits of the number
count += 1;
#include <stdio.h>
scanf(“%d”,&x);
int main()
}
{
printf(“ \n\nThe number of positive integers are: %d”,
int n, s=0, r;
count);
printf(“Enter the Number”);
return 0;
scanf(“%d”, &n);
}
while(n>0)
I/O:
{
Enter the Number: 10
r=n%10;
20
s=s+r;
30
n=n/10;
40
}
50
printf(“\nSum of digits %d”, s);
-60
return 0;
The number of positive integers are:5
}
ABVG Degree College, Jangaon 33
* Programming in C
I/O: do-while loop
Enter the Number: 1234 do while loop is a post-test loop. It has the
Sum of digits 10 following format:
do
4. Write a C program for counting the number {
of words, lines, special characters in a given stmT; /* statements block*/
text. }while(TestExpr);

#include<stdio.h> First, it executes the statements block once. Then it


#include<conio.h> verifies the test expression. If it is TRUE (1) then it
main( ) again executes the statements block. Thus the
{ statements block will be executed repeatedly till the
char ch; value of Test expression becomes 0 (FALSE).
int lines=0, words=0, chars=0;
clrscr( ); For a do while loop, it is guaranteed that the body
of the loop will execute at least once.
printf("Enter the required no. of lines:\n");
while((ch=getchar( ))!=EOF) The following figure shows a do while loop:
{
if(ch==10)
lines++;

if(isspace(ch))
words++;
chars++;
}
printf("\nNumber of Lines : %d", lines+1);
printf("\nNumber of Words: %d", words+1);
printf("\nTotal Number of Characters: %d", chars);
getch( );
return 0; Statements
} Block

I/O
Enter the required no. of lines:
This is a Test
This is a Test
This is a Test ^Z

Number of Lines : 3
Number of Words : 12
Number of Characters: 44

ABVG Degree College, Jangaon 34


* Programming in C
Example: I/O
1. Write a c program to find the sum of the positive Enter a Number: 5
numbers entered by the user. Terminate the loop if 5x1=5
the user enters a negative number. 5 x 2 = 10
#include <stdio.h> 5 x 3 = 15
#include<conio.h> 5 x 4 =20
main() 5 x 5 = 25
{ 5 x 6 = 30
int x = 1; 5 x 7 = 35
int sum = 0; 5 x 8 = 40
do { 5 x 9 = 45
printf("Enter a Number:"); 5 x 10 = 50
scanf(“%d”, &x);
if(x >= 0) for loop
sum +=x; for loop is called as a bounded or definite loop. It
} while(x >= 0); has the following format:
printf("\n Sum = %d", sum);
getche(); for(initialization; TestExpr; updating)
return 0; {
} stmsT; // Body of the loop
I/O }
Enter a Number: 10
Enter a Number: 20 1. Initialization: for loop first initializes the looping
Enter a Number: 30 control variable. Initialization can be done only
Enter a Number: 40 once.
Enter a Number:50 2. TestExpr: It represents a test expression. If it is
Enter a Number: -60 TRUE (1) then only it executes the body of the
Sum = 150 loop.
3. Updating: It updates the looping control variable.
2.Write a C Program to generate the multiplication
table of the given number. The for loop follows the following sequence:
#include <stdio.h>
#include<conio.h> 1. Do the initialization.
main() 2. If the value of the test expression is FALSE(0),
{
int n, i = 1; then terminate the loop and go to step 6;
printf("Enter a Number:"); otherwise if the test expression is TRUE(1), then
scanf(“%d”, &n);
do { go to step 3.
printf(“\n %d x %d = %d”, n, i, n*i); 3. Execute the body of the loop.
i++;
} while(i<=10); 4. Update the expression.
getche(); 5. Go to step 2.
return 0;
} 6. Execute the next statement.

ABVG Degree College, Jangaon 35


* Programming in C
The following figure illustrates the for loop: 2.Write a C program to print the sum of the series
1+2+3+4+... up to n terms.
#include <stdio.h>
#include<conio.h>
main()
{
int i, n, sum=0;
clrscr();
printf(“\n Enter the No. of terms”);
scanf(“%d”, &n);
for(i=1; i<=n; i++)
sum+=i;
printf(“\n Sum is %d”, sum);
getche();
return 0;
}

I/O:
Enter the number of terms: 5
Sum is 15

Example:
Write a C program to print the numbers from 1 to 3.Write a C program to calculate the factorial of
10. the given number.
#include<stdio.h>
#include<stdio.h> #include<conio.h>
#include<conio.h> main()
main() {
{ int n, i, f=1;
int i; printf(“\n Enter the number: ”);
clrscr(); scanf(“%d”,&n);
for(i = 1; i <= 10; i++) for(i=1;i<=n;++i)
printf(“%d”,i); f*=i;
return 0’ printf(“\n Factorial is %ld”,f);
} getche();
return 0;
I/O }
1
2 I/O:
3 Enter the number: 5
4 Factorial is 120
5
6
7
8
9
10

ABVG Degree College, Jangaon 36


* Programming in C
4.Write a C program to find whether the given
number is Prime Number or not? for(i=2;i<n;i++)
{
#include <stdio.h> fib=n1+n2;
#include<conio.h> printf(" %d ",fib);
main() n1=n2;
{ n2=fib;
int n, i, flag = 0; }
printf("Enter a Number: "); getche();
scanf("%d",&n); return 0;
for(i=2;i<=n/2;i++) }
{ I/O:
if(n%i==0) Enter the range for Fibonacci Series: 10
{ The Fibonacci Sries is:
flag=1; 1 1 2 3 5 8 13 21 34 55
break;
} 6.Write a C program to find whether the given
} number is Strong Number?
if (flag==0) #include<stdio.h>
printf("%d is a prime number.",n); #include<conio.h>
else main()
printf("%d is not a prime number.",n); {
getche(); int n,x,r,i,f,sum=0;
return 0; clrscr();
} printf("Enter a Number:");
scanf("%d",&n);
I/O: for(x=n; n ;n=n/10)
(1.) {
Enter a Number: 4 i=f=1;
4 is not a prime number r=n%10;
(2.) while(i<=r)
Enter a Number: 7 {
7 is a Prime Number f=f*i;
i++;
5.Write a C program to calculate the Fibonacci }
series of a given number. sum=sum+f;
#include<stdio.h> }
#include<conio.h> if(sum==x)
main() printf("\n%d is a Strong Number",x);
{ else
int i,n, fib, n1=1,n2=1; printf("\n %d is not a Strong Number",x);
clrscr();
printf("Enter the range for Fibonacci Series:"); getche();
scanf("%d",&n); return 0;
printf("\n The Fibonacci Series is: \n"); }
printf("%d %d ",n1,n2);

ABVG Degree College, Jangaon 37


* Programming in C
I/O: 8.Write a C program whether the given number is
(1) Armstrong number or not?
Enter a Number: 128 #include<stdio.h>
128 is not a Strong Number #include<conio.h>
(2) main()
Enter a Number: 145 {
145 is a Strong Number int n,x,r,sum=0;
clrscr();
7. Program to find whether the given number is a printf("Enter a number:");
Palindrome? scanf("%d",&n);

#include<stdio.h> for(x=n; n!=0;n=n/10)


#include<conio.h> {
main() r=n%10;
{ sum=sum+r*r*r;
int n,r,rev=0,x; }
clrscr(); if(x=sum)
printf("Enter any number:"); {
scanf("%d",&n); printf("\%d is a Armstrong number",n);
x=n; }
while(n!=0) else
{ {
r=n%10; printf("\%d is not a Armstrong number",n);
rev=r+(rev*10); }
n=n/10; getche();
} return 0;
if( rev == x) }
printf("%d is a palindrom number ",x);
else I/O:
printf("%d is Not a palindrom number ",x); (1)
getche(); Enter a Number: 12
return 0; 12 is not a Armstrong number
} (2)
Enter a Number: 153
I/O: 153 is a Armstrong number
(1)
Enter a Number: 12
12 is not a Palindrome number
(2)
Enter a Number: 121
121 is a Palindrome number

ABVG Degree College, Jangaon 38


* Programming in C
Special Control Statements 3. break statement:
C has some control statements to terminate a loop or The break statement is used in loops and switch
a function. Those control statements are: return, statement to terminate execution of the loop or
break, and continue. switch
statement. It has the following form:
1. goto Statement break;
The goto statement is an unconditional control The break statement causes the control to go out of
statement. It transfers the control the label specified the loop/block.
in the goto statement. The following C program illustrate break/return
It has the following format: statements:
goto label_name; #include <stdio.h>
main( )
A statement label must be followed by a colon (:) {
int c;
Example: for(;;)
#include <stdio.h> {
main() if(c==5)
{ break;
int n, i,f=1; printf(“ \t %d”, c);
printf(“\n Enter the number:”); c++;
scanf(“%d”,&n); }
if(n<0) getche();
goto end; return 0;
i=1; }
loop:
f=f*i; 4. continue statement:
i++; The continue statement does not terminate the loop.
if(i<=n) But it can continue with the next iteration.
goto loop; It takes the following form:
printf(“\n FACTORIAL IS %d”, f);
end: continue;
return 0;
} Example:

2. return statement:
The return type is used in a function definition to set
its returne value.
The return statement has two forms.
(1) return;
This format can be used for the functions
which return a blank control without value.
(2) return expression;
This format can be used for the functions which
return a particular value.

ABVG Degree College, Jangaon 39


* Programming in C
Example:
The following program illustrates for loop:
#include <stdio.h>
main()
{
int i;
clrscr();
for(i=1;i<=5;i++)
{
if(i==3)
continue;
printf(“\t %d”, i);
}
getche();
return 0;
}
I/O:
1245
Difference between break and continue
break statement continue statement
It helps for an early It helps to skip the
exit from the block remaining statements
where it appears under it. It continues
with next iteration
It can be used in all It can be used only in
control statements loops,
and switch
statement
5. exit:
exit statement terminates the program. Before
termination, exit does the following:
• closes all files
• writes buffered output (waiting to be output)
• calls other "exit functions"
Example:
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>
int main(void)
{
int status;
printf("Enter either 1 or 2\n");
status = getch();
exit(status - '0'); // exits here
return 0; // this line never executes
}

ABVG Degree College, Jangaon 40


* Programming in C
Arrays Example:
Introduction: int ar[10];
This can declare a one dimensional array with 10
Generally, A variable can store only one value at a elements of integer type.
time.
For example: Initializing Integer Arrays
char ch;
int n; Arrays can be initialized by using the following
float price; format:
These are of different data types. Each variable can datatype array_name[size] = {Elements};
store only one value. These types of variables are Example: int arr[5] = { 1,2,3,4,5}
called scalar variables. This can create and initialize a one dimensional
array, as shown below:
A scalar variable is a single variable whose stored
value is an atomic data type. Therefore, variables are 1 2 3 4 5
not suitable to store a collection of values. C provides arr[0] arr[1] arr[2] arr[3] arr[4]
a derived data type called an Array. An array can
store a collection of values. Accessing array elements:

What is an array? An array element can be referenced as:


Definition: < array name>[<index>]
An array is a collection of data elements that are Here, <index> is an integer constant or variable
ordered, fixed in size, and homogeneous. ranging from 0 to <size>– 1.
→An array is a derived data type. It can store huge
quantities of data. Example:
arr [0] = 98;
In C, arrays are of two types: arr [1] = 75;
• one-dimensional arrays arr[2] = 80;
arr [3] = 95;
• Multidimensional arrays
arr[4] = 98;
total = arr[0] + arr[1] + arr[2] + arr[3] + arr[4];
One-dimensional Array:
An array that can have single subscript (index) is Example:
known as a one-dimensional array. Its index starts at Write a c program to illustrate one dimensional
0 and ends at size-1. arrays?
#include <stdio.h>
Declaration of a One-dimensional Array main()
An array declaration has 3 attributes: {
• The type of data i.e., int, char, double, float, int i, a[10];
etc. for(i = 0; i< 10; i++)
• The number of values i.e., the maximum {
number of elements a[i] = i;
• A name printf(“a[%d] = %d\n”, i, a[i]);
A one-dimensional array can be declared by using the }
following syntax: printf(“\n”);
data_type array_name [SIZE]; return 0;
}

ABVG Degree College, Jangaon 41


* Programming in C
/* printf(“\n Enter the array elements \n”);
I/O for(i=0 ; i<n; i++)
a[0] = 0 scanf(“%d”, &a[i]);
a[1] = 1 printf(“\n Enter the key to be searched \n”);
a[2] = 2 scanf(“%d”,&key);
a[3] = 3 for(i=0 ; i<n; i++)
a[4] = 4 if(a[i] == key)
a[5] = 5 {
a[6] = 6 printf(“\n Found at %d”,i);
a[7] = 7 FOUND=1;
a[8] = 8 }
a[9] = 9 if(FOUND = = 0)
/* printf(“\n NOT FOUND...”);
2. Write a C program to calculate Fibonacci series getche();
by using arrays concept. return 0;
/* }
Fibonacci series is a series in which any element is I/O: How many numbers:5
the sum of the previous two elements. Enter array elements: 3 6 9 12 16
*/ Enter the key to be searched: 9
#include <stdio.h> Found at 2
main() Sorting an array
{ Bubble sort:
int fib[15],i; A bubble sort compares adjacent array elements
fib[0] = 0; and exchanges their values if they are out of order.
fib[1] = 1; In this way, the smaller values ‘bubble’ to the top
for(i = 2; i < 15; i++) of the array (towards element 0) and the larger
fib[i] = fib[i-1] + fib[i-2]; values sink to the bottom of the array.
for(i = 0; i < 15; i++)
printf(“ %3d ”, fib[i]); The following example shows the bubble sort:
getche();
return 0;
}
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144

Write a C program to search for an element in the Write a C program to sort the array elements
array. using bubble sort.
#include <stdio.h>
#include <stdio.h> #include<conio.h>
#include<conio.h> #include <stdlib.h>
#include <stdlib.h> main()
main() {
{ int a[30],n,i,j,temp;
int a[30],n,i,key, FOUND=0; clrscr();
clrscr(); printf(“\n How many numbers”);
printf(“\n How many numbers”); scanf(“%d”,&n);
scanf(“%d”, &n); if(n>30)

ABVG Degree College, Jangaon 42


* Programming in C
{
printf(“\n Too many Numbers”);
exit(0);
}
printf(“\n Enter the array elements \n”);
for(i=0 ; i< n; i++)
scanf(“%d”, &a[i]);
for(i = 0; i < n-1; i++)
{
for(j = 0; j < (n - i) -1; j++) Accessing array elements:
if(a[j] > a[j+1]) An 2D-array elements can be referenced as:
{ <array name>[<RowIndex>][<Column Index>]
temp = a[j]; Here, <index> is an integer constant or variable
a[j] = a[j+1]; ranging from 0 to <size>– 1.
a[j+1] = temp; <

} Example:
} arr [0][0] = 1;
printf(“\n The numbers in sorted order \n”); arr [0][1] = 2;
for(i=0 ; i<n; ++i) arr [0][2] = 3;
printf(“\n %d”, a[i]); arr [1][0] =4;
getche(); arr [1][1] = 5;
return 0; arr[1][2] = 6;
} arr [2][0] = 7;
arr [2][1] = 8;
Multidimensional Arrays arr[2][2] = 9;

total = arr[0][0] + arr[0][1] + arr[0][2] + arr[1][0] +


Arrays with more than one dimension are called arr[1][1] + arr[1][2] + arr[2][0] + arr[2][1] +
multidimensional arrays. arr[2][2] ;
Declaring a Two-dimensional Array:
An array of two dimensions can be declared as
Working with Two-dimensional Arrays:
follows: The most important application of the two-
data_type array_name[size1][size2]; dimensional array is with a matrix. A matrix is
Here, data_type is any valid data type. Size1 is the
defined as an ordered rectangular array of
number of rows and Size2 are the number of columns.
numbers.
Transpose of a matrix:
Initialization of a Multidimensional Array: The transpose of a matrix is found by exchanging
Arrays can be initialized by using the following rows for columns, i.e., for Matrix A = (aij) the
format: T
transpose of A is A =(aji). (i is the row num ber and
datatype array_name[size1] [size2] = {Elements}; j i s the column number). For examp le, the
Example: int arr[3][3] = { {1,2,3},{4,5,6}, following is the transpose of a matrix A:
{7,8,9}}

This can create and initialize a two dimensional array, 12 3 1 47


as shown below: A= 4 5 6 AT = 2 5 8
78 9 3 6 9

ABVG Degree College, Jangaon 43


* Programming in C
Example: Matrix addition and subtraction
//Write a C program to find the transpose of a matrix. Two matrices A and B can be added or subtracted
#include <stdio.h> if and only if they have same number of rows and
#inclde<conio.h> columns. For example:
int main()
{
1 2 3 2 1 2
int i, j;
A= 1 0 2 B= 1 0 3
int a[3][3], t[3][3];
clrscr();
printf("Enter elements in to the Array:");
for(i = 0 ; i < 3; i++) Addition If A and B above are matrices of the same
for(j = 0 ; j < 3; j++) type, then their sum is found by adding the
{ corresponding elements
printf("\nEnter an Element:"); aij + bij.
scanf("%d", &a[i][j]); Example:
}
printf("\n Matrix A:\n");
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++) Subtraction If A and B are matrices of the same
printf(" %d ", a[i][j]); type, then their difference is found by subtracting
printf("\n"); the corresponding
} elements aij – bij.
for(i = 0; i< 3; i++) Example:
{
for(j = 0; j < 3; j++)
{
t[i][j]= a[j][i];
}
} Example: Write a C Program to perform Matrix
Addition.
printf("\n Transpose of the matrix A is:\n"); #include<stdio.h>
for(i = 0; i < 3; i++) #include<conio.h>
{ main()
for(j = 0; j < 3; j++) {
{ int r,c,i,j, a[10][10],b[10][10],c[10][10];
printf(" %d ", t[i][j]); clrscr();
} printf("Enter the Order of matrix:");
printf("\n"); scanf("%d %d",&r,&c);
}
getche(); printf("\nEnter the first matrix:");
return 0; for(i=0;i<r;i++)
} for(j=0;j<c;j++)
scanf("%d",&a[i][j]);

ABVG Degree College, Jangaon 44


* Programming in C
printf("\nEnter the second matrix:"); For example: For a n × n matrix case, where A has
for(i=0;i<r;i++) dimensions m × n and B has dimensions n × p. The
for(j=0;j<c;j++) product of A and B is the matrix C, which has
scanf("%d",&b[i][j]); dimensions m × p.

c[i][j]=0; Example: Write a C Program for matrix


for(i=0;i<r;i++) multiplication
for(j=0;j<c;j++)
c[i][j]=a[i][j]+b[i][j]; #include<stdio.h>
#include<conio.h>
printf("\nThe result matrix is:\n");
for(i=0;i<r;i++) int main()
{ {
for(j=0;j<c;j++) int row1, col1;
{ int row2, col2;
printf(" %d ",c[i][j]); int i,j,k;
} int a[10][10];
printf("\n"); int b[10][10];
} int m[10][10];
getche(); clrscr();
return 0; printf("\n Enter the size of matrix->1:");
} scanf("%d %d", &row1, &col1);
printf("\n Enter Elements for matrix-> 1 \n");
/* for(i = 0 ; i< row1; i++)
output: {
Enter the Order of matrix: 2 2 for(j = 0 ; j<col1; j++)
{
Enter the first matrix: printf("Enter an Elemennt:");
12 scanf("%d", &a[i][j]);
34 }
Enter the second matrix: }
43 printf("\n Enter the size of matrix->2:");
21 scanf("%d %d", &row2, &col2);
The result matrix is: printf("\n Enter Elements for matrix-> 2\n");
55 for(i = 0 ; i< row2; i++)
55 {
*/ for(j = 0 ; j<col2; j++)
{
Matrix multiplication
printf("Enter an Elemennt:");
When the number of columns of the first matrix is
scanf("%d", &b[i][j]);
equal to the number of rows in the second matrix, then
}
matrix multiplication can be performed.
}
Example:

ABVG Degree College, Jangaon 45


* Programming in C

Strings
printf("\n Matrix a is:\n");
One-dimensional Character Arrays
for(i = 0; i < row1; i++)
→A String is an arrays of characters.
{
In C, a String can be terminated by a null
for(j = 0; j < col1; j++)
character(\0).
printf("%3d", a[i][j]);
printf("\n");
Declaraing a String
}
Strings can be declared like one-dimensional
arrays. For example:
printf("\n Matrix b is: \n");
char name[30];
for(i = 0; i < row2; i++)
char address[80];
{
for(j = 0; j < col2; j++)
String Initialization
printf("%3d", b[i][j]);
Strings allow a shorthand initialization, for
printf("\n");
example,
}
char str[9] = “I like C”;
char msg[] = “Hello”;
if(col1 == row2)
{ Printing Strings
printf("\n Multiplication is possible and the Result is The format code ‘%s’ can be used to print strings
as follows \n"); by using printf(). For For example,
for(i=0; i<row1; i++) printf(“%s”,name);
for(j=0; j<col2; j++)
{ Reading a String
m[i][j] = 0; The format code %s can be used to read a string
for(k = 0; k < col1; k++) with scanf().
m[i][j] += a[i][k] * b[k][j]; For example:
} scanf("%s', &name);
Write a C Program to illustrate Strings:
for(i = 0; i < row1; i++) #include<stdio.h>
{ main()
for(j = 0; j < col2; j++) {
printf("%3d", m[i][j]); char str[50];
printf("\n"); printf(“Enter a string”);
} scanf(“%s”,str);
} printf(“The string was :%s\n”,str);
return 0;
else }
printf("\n Multiplication is not possible");
getche(); I/O:
return 0; (a) Enter a string: Ritchie
} The string was :Ritchie

ABVG Degree College, Jangaon 46


* Programming in C
Character Manipulation in the String strchr(s1,ch) Returns pointer to first
In C, all the character-handling functions are occurrence ch in s1.
available with <ctype.h> header file. All the fuctions
strstr(s1,s2) Returns pointer to first
(except toupper() and tolower() ) return true or false.
occurrence s2 in s1.
<ctype.h> provides the following functions: Counting number of characters in a string
1. ialnum(c) : It returns true if c is alphabetic or strlen() function can be used to find the length of
numeric. a string.
2. isalpha(c): It returns trueif c is alphabetic. It has the following format:
3. scntrl(c): It returns true if c is a control character. strlen(str);
4. isdigit(c): It returns true if c is a digit. Example:
5. isxdigit(c): It returns true, if c is a hexa-decimal int l;
digit. char s1[9]="Mahathma";
5. isprint(c): It returns true, if c is printable. l=strlen(s1);
6. isspace(c): It returns true, if c is a space or escape it reurns 9 to the variable l.
sequence character \n, \t, \v.
7. islower(c): It returns true, if c is in lower case.
Example Program to find the length of a string:
8. isupper(c):It returns true, if c is in upper case.#include <stdio.h>
9. tolower(c): It returns the lower case version of c.
#include <string.h>
10. toupper(c): It returns the upper case version of c.
main()
{
String Manipulation char s[100];
C provides many functions to manipulate strings. All int len;
the string functions are available with <string.h>. printf(“Enter a string”);
Some of the functions in <string.h> are: gets(s);
Table: string manipulation functions available in len = strlen(s);
string.h printf("\n Length of %s is = %d",s,len);
Function Description getche();
return 0;
strcpy(s1,s2) Copies s2 into s1 }
strcat(s1,s2) Concatenates s2 to s1. Copying a string into another
That is, it appends the In C, strcpy() function can be used to copy one
string s2 to the end of the string to another. It has the following format:
string s1 strcpy(s1,s2);
strncat(s1,s2,n) Appends the string pointed For example:
to by s2 to the end of the #include <string.h>
string pointed to by s1 up main()
to n characters long. {
strlen(s1) char s1[] =“Hello, world!”;
Returns the length of s1.
char s2[20];
That is, it returns the
strcpy(s2, s1);
number of characters in
printf("\n String 1 = %s",s1);
the string
printf("\n String 2 = %s",s2);
strcmp(s1,s2) Returns 0 if s1 and s2 are return 0;
the same. Returns less than }
0 if s1s2.

ABVG Degree College, Jangaon 47


* Programming in C
Comparing strings Write a C program to illustrate String functions
strcmp() function can be used to compare two strings.
in C.
It returns the value zero if the strings are equal. It
#include <stdio.h>
returns a positive value if the first string is greater
#include <string.h>
than the second string. It returns a negative value if
int main()
the first string is lesser than the second string.
{
char s1[20] = "Sri";
Example: Write a C program to compare 2 strings. char s2[20] = " Sneha";
#include <stdio.h> char s3[40];
#include <string.h> printf("Initially Length of string1 is : %d",
int main() strlen(s1);
{ printf("Length of string2 is : %d", strlen(s2);
char x[15],y[15]=“C Programming ”; if (strcmp(s1, s2) ==0)
strcpy(x, y); {
if(strcmp(x, y == 0) printf("string 1 and string 2 are equal");
printf(“Equal \n”); }else
else {
printf(“Unequal \n”); printf("string 1 and 2 are different");
getche(); }
return 0; strcat(s1,s2);
} strcpy(s3,s1);
printf("Modified String s1 is: %s", s1);
It produces the following output: printf("String s2 is: %s", s2);
Equal printf("String s3 is: %s", s3);
getche();
Putting strings together retrn 0;
strcat() function can concatenate two strings }
together. I/O:
It has the following format: Initially Length of string1 is: 3
strcat(s1,s2) Length of string1 is: 5
For example. String1 nd String2 are different
Write a C program to concatenate two strings. Modified String1 is : Sri Sneha
#include <stdio.h> String2 is : Sri
#include <string.h> String3 is : Sri Sneha
int main()
{ ****
char s[30] =“Hello,”;
char str[] =“world!”;
printf(“%s\n”, s);
strcat(s, str);
printf(“%s\n”, s);
getche();
return 0;
}

***

ABVG Degree College, Jangaon 48


* Programming in C

UNIT-III Programmer-defined functions:


The Programmer can write his own functions to
Functions define specific tasks. These are known as
C is a Modular Programming Language. In a Modular programmer-defined functions.
programming language, a large program can be Example: main()
divided into a set of functional modules or blocks.
Why are functions needed?
C provide a way of breaking up a program into Functions provides the following benefits:
segments or modules. These segments are called ➢ It makes programs easier to understand and
functions. maintain.
➢ The main program can consist of a series of
A function is a self-contained block of program function calls. They can be executed as
statements that performs a particular task. It is a many times as needed.
section of a program that performs a specific job. ➢ Functions may be reused in multiple
programs. This enables code sharing.
We should write the programs with a large number of
small compact functions. But not with a small number ➢ Functions can be used to protect data. The
of large functions. data defined with in a function is called the
local data. It is available only within that
Example: function.
➢ By using functions many programmers can
work on a project by dividing it into
different functions.

USING FUNCTIONS
You can use a function by calling it. A function
which calls another function is known as a Calling
Function. A function which responds to a function
call is known as a Called function.

When a function is called, the code contained in the


• Functions makes a program more manageable Called function is executed. After finishing
and easy to understand. execution the control returns to the Calling
• A function may be called as many times as function.
needed.
• Functions are reusable and can be used in In C, a user defined function should be declared
multiple programs. before using it in the program. A declaration that
contains the function’s return type, function name
A C program is a combination of functions. In C the and a list of parameters is known as the Function
functions are of 2 types: Prototype. The compiler uses function prototypes
Library Functions: to validate function calls. A function prototype has
The standard C library provides many functions for the following format:
performing common mathematical calculations,
string manipulations, character manipulations, return_data_type function_name (datatyp list);
input/output, and many other useful operations.
Example:: sqrt(), pow(), strlen(),strcmp(), tolower(),
toupper(), scanf(), printf(), clrscr(), etc.
ABVG Degree College, Jangaon 49
* Programming in C
A function prototype has three basic parts: Function calling
function_name: This is the name given to the A function must be called (invoked) in order to
function. execute it. A function call statement has the
return_data_type: This specifies the type of data following form:
given back to the calling function. function_name(List of formal parameters);
data_type_list : This list specifies the data type of the or
variables. These are also known as the formal variable_name = function_name(List of formal
parameters. parameters);
Examples::
(a) int sum(int x, floaty); A void function does not return any value. It only
(b) int isPrime(int); returns the control from called function to calling
(c) void printMessage(void); function.
(d) void fibo_series(int); A function call without parameters/arguments has
Function definition the following format:
A list of statements in the program that describes the function_name();
specific task done by the function is called a function or
definition. It consists of the function header and the variable_name = function_name();
function body.
The function definition has the following form: Write a C program that uses a function to convert
return_data_type functionname(data_type_list) temperature from Fahrenheit scale to Celsius
{ scale.
/* Function Body */ #include <stdio.h>
} float ftoc(float); // Function prototype declaration
int main(void)
Example: {
int sum(int x, int y) float tf;
{ float tc;
int s; printf(“\n Enter the Temperature in Fahrenheit: ”);
s = x+y; scanf(“%f”, &tf);
return(s); tc = ftoc(tf); Function calling
}
printf(“%f Fahrenheit equals %f Celsius \n”, tf,tc);
Example: return 0;
void multiply(int a, int b) }
{ /* FUNCTION DEFINITION */
int p; float ftoc(float f) Function header
p = a*b; {
printf(“\n Product = %d”,p); float factor = 5.0/9.0;
} float freezing = 32.0;
float celsius;
return statement celsius = factor ∗(f - freezing);
The return statement has the following form: return celsius;
return expression; }
or
return(expression);
The return statement returns the value of result to the
calling function.

ABVG Degree College, Jangaon 50


* Programming in C
CALL BY VALUE mechanism Example:
Data can be passed to a function by using two #include <stdio.h>
techniques: void doubleThem(int [], int); /* declaration of
1. Pass by value or Call by value function */
2. Pass by reference or Call by reference. int main(void)
{
call by value: int a[10] = {1,2,3,4,5,6,7,8,9,10};
Calling a function by passing values as arguments int size=10;
is known as call by value. printf(“\n\n The given numbers are :”);
In call by value, a copy of the data is sent to the for (i = 0; i < size; i++)
formal parameters of the called function. So that the printf(“%d,”,a[i]);
function cannot directly modify the values of the doubleThem(a,size); /* function call */
arguments. printf(“\n\n The double numbers are : ”);
for (i = 0; i < size; i++)
Example: printf(“%d,”,a [i]);
#include <stdio.h> return 0;
int mul(int num); /* function prototype */ }
main(void)
{ void doubleThem(int arr[], int size)
int result,num = 3; {
printf(“\n Before function call: num = %d ”, num); int i;
result = mul(num); for(i = 0; i < size; i++)
printf(“\n After return from function: result = %d”, {
result); arr[i] = 2 * arr[i];
printf(“\n After return from function: num = %d”, }
num); }
return 0;
} I/O
/* function definition */ The given numbers are :1, 2, 3, 4, 5, 6, 7, 8, 9,10,
int mul(int num) The double numbers are : 2, 4, 6, 8, 10, 12, 14,16,
{ 18, 20,
num *= 10;
return num; Example 2:
} Write a program that uses a function to find the
maximum value in an array.
I/O: #include <stdio.h>
Before function call.: num = 3, int maximum(int [],int); /* function prototype */
After return from function: result = 30 int main(void)
After return from function: num = 3 {
int a[5], i, max;
PASSING ARRAYS TO FUNCTIONS printf(“Enter 5 numbers\n”);
When an array is passed to a function, the address of for(i = 0; i < 5; ++i)
the array is passed. It will send the address of the first scanf(“%d”, &a[i]);
element in the array to the called function. max = maximum(a,5); /* function call */
printf(“\nMaximum value is %d\n”, max);
So that the called function can modify the contents of return 0;
that array. Consider the following example. }

ABVG Degree College, Jangaon 51


* Programming in C
int maximum(int arr[], int n) void function1()
{ {
int max, i; int x=0; // Local variable
max = arr[0]; x++; // referring local variable
for(i = 1; i < n; ++i) printf(“\n x = %d”, x);
if(arr[i] > max) }
max = arr[i]; I/O:
return max; x=1
} x=1
x=1
I/O: x=1
Enter 5 numbers 11 15 8 21 7 x=1
Maximum value is 21
// Global Variables
SCOPE of Variables #include<stdio.h>
The region of the program over which a variable is #include<conio.h>
visible is called the scope of the variable. The scope void function1();
relates to the accessibility, visibility, longevity. int x=0; // Global Variable
main()
Global and Local Variables {
Variables declared within the function body are called int i; // Local Variable
local variables. Local variables are usable inside the clrscr():
function body. They are recreated each time a for(i=0;i<5;i++)
function is called. function1();
Variables declared outside of all the functions of a getche();
program and accessible by any function are called return 0;
global variables. These variables are known to all }
functions in the program. void function1()
{
Consider the following example: x++; // refreing global varibale
// Local Variables. printf(“\n x = %d”, x);
#include<stdio.h> }
#include<conio.h> I/O:
void function1(); x=1
main() x=2
{ x=3
int i; // local Variable x=4
clrscr(): x=5
for(i=0;i<5;i++) Storage Class
function1(); A Storage class is an attribute that specifies:
getche(); • Where the variables would be stored,
return 0; • How long they would exist,
} • What is their scope
• What would be the default values?

ABVG Degree College, Jangaon 52


* Programming in C
C provides four storage class specifiers that are • Register type cannot be used for large
automatic, external, register, and static. sized variables.
The storage class specifies take the following form: • Register type cannot be used for global
storage_class_specifier data_type variable_name ; variables.
• You cannot obtain the address of a
The storage class – auto
register variable by using ‘&’ operator.
The variables that are declared within the body of a
function are known as automatic variables (Local The storage class – static
variables or Internal Variables). The keyword auto The variables that are declared as static can
can be used to declare automatic variables. maintain their values between function calls. The
For example: default value of a static variable is zero.
auto char gender;
It specifies that the variable gender is an automatic Static variables are of two types: static local
variable. These variables can be accessed with in that variables and static global variables.
function only. A static local variable is allotted a permanent
storage location in the primary memory. It can
Write a C program to illustrate the use of the maintain its value during the function calls.
automatic storage class variable. The static global variables can be accessible by all
#include <stdio.h> functions in the program.
#include<conio.h>
main() Write a C program that illustrates the use of local
{ static variables and functions.
auto int a =5; // automatic variable #include <stdio.h>
clrscr(); void show(void);
printf(“\n a = %d”,a); main()
{ {
int a = 10; // automatic by default int i;
printf(“\n a = %d”,a); clrscr();
} for(i=0;i<3;i++)
printf(“\n a = %d”,a); {
return 0; show();
} }
I/O getche();
a=5 return 0;
a = 10 }
a=5 void show(void)
{
The storage class – register static int i;
printf(“\n i=%d”,i);
Values stored in CPU registers can be accessed faster. i++;
The keyword register can be used to store a value in }
CPU registers. The register type can be used for the Output
most frequently used variables such as counters. i=0
i=1
i=2

ABVG Degree College, Jangaon 53


* Programming in C
main()
The storage class – extern {
The variables that are both alive and active ………
throughout the entire program are known as external ……....
variables. They are also known as global variables. recursive();
External variables will use the keyword "extern". …………
Example: ………….
#include<stdio.h> }
void increment();
int i=10; int recursive()
main() {
{ ………..
i++; recursive()
printf("\n %d",i); ………..
increment(); }
return 0;
} Example: Write a C Program to generate
void increment() Fibonacci Series by using Recursion.
{ #include <stdio.h>
i++; #include <stdlib.h>
printf("\n%d",i); int fib(int); /* function prototype */
} int main()
{
int i,j;
The inline function printf(“\n Enter the number of terms: ”);
C99 provides inline functions. An Inline function can scanf(“%d”,&i);
reduce function call overhead. It means that instead printf(“\n Fibonacci sequence for %d terms is:”,i);
of calling, the function’s code will be expanded in for( j=1; j<=i; j++)
line. This is useful for small functions. printf(“ %d”,fib(j));
getche();
An Inline function can be declared by placing the return 0;
keyword inline in the function definition. }
Example: int fib(int val) // Recursive Function
inline int sum(int x, int y) {
{ if(val <= 2)
return x+y; return 1;
} else
return(fib(val - 1) + fib(val - 2)); // Recursive call
}
Recursion
Calling a function by itself is known as Recursion. Output
A function that calls itself is known as a Recursive (a) Enter the number of terms: 6
function. Fibonacci sequence for 6 terms is: 1 1 2 3 5 8
(b) Enter the number of terms: 4
The recursion continues until some condition is met Fibonacci sequence for 4 terms is: 1 1 2 3
to stop it. if...else statement can be used to stop a
recursive call.

ABVG Degree College, Jangaon 54


* Programming in C
Write a C Program to find the factorial of the Address of operator:
given number by using recursion In C &(ampersand)is known as an address of
#include<stdio.h> operator. It can be useful to know the location of a
#include<conio.h> variable.
For example:
int factorial(int n); int i = 3;

main() The address of i can be printed by using the


{ following statement:
int n,f; printf(“\n Address of i = %u”, &i);
clrscr();
printf("Enter a Number:"); Indirection Operator and Dereferencing
scanf("%d",&n); In C the pointer operator ‘*’ is called the ‘value at
f=factorial(n); address’ operator. It returns the value stored at a
printf("\n Factorial of %d is = %d ",n,f); particular address. The value at address operator is
getche(); also called indirection operator or dereference
return 0; operator.
}
Pointers can be used to:
int factorial(int n) • call a function by address ( Call by
{ Reference)
int fact; • return more than one value from a
if(n = =1) function indirectly
return(1);
• manipulate arrays more easily
else
fact=n*factorial(n-1); • create complex data structures, such as
return(fact); linked lists and binary trees.
} • compile faster, more efficient code.

/* Declaring a Pointer:
output The syntax for declaring a pointer variable is
=========== datatype * pointer_variable;
Enter a Number : 4
Factorial of 4 is = 24 Example:
*/ char *ptr;
Initializing and Assigning Values to Pointers
Pointers A pointer may be initialized to an address or NULL,
A pointer is a special type of variable that can hold or 0.
the memory address of another variable.

Pointer does not hold a value but it holds the address


of another variable. A Pointer can access a variable
indirectly by using the address of the variable.

ABVG Degree College, Jangaon 55


* Programming in C
Example: void swap(int *a, int *b)
#include <stdio.h> {
#include<conio.h> int temp;
int main() temp = *a;
{ *a = *b;
int a=5, b=10; *b = temp;
int *p; }
p = &a; Output
printf(“\n a=%d b=%d *p=%d”, a, b,*p); 5 10
p=&b; 10 5
printf(“\n a=%d b=%d *p=%d”, a, b,*p);
getche(); Array of Pointers
return 0; An array of pointers can be declared very easily. It
} is has the following format:
Output data type arr_pointer[size];
a=5 b=10 *p=5 Example:
a=5 b=10 *p=10 int *p[10];
This declares an array of 10 pointers. The first
pointer is called p[0], the second is p[1], and so on
up to p[9].
For Example:
Call by Reference int *p[10];
Call by reference is possible with the help of pointers. int a = 10, b = 20, c = 30;
Calling a function by passing addresses as p[0] = &a;
arguments is known as Call by Reference. By using p[1] = &b;
call by reference, you can change the values at calling p[2] = &c;
function. For example, It can be as shown below:
swap(&x, &y);

Example:
#include <stdio.h>
int swap(int*, int*);
int main()
{
int x=5,y=10; For example:
void swap(int *,int *); #include<stdio.h>
printf(“%d %d\n”,x,y); main()
swap(&x, &y); {
printf(“%d %d\n”,x,y); int a[]={1,2,3,4,5};
return 0; int b[]={10,20,30,40,50};
} int c[]={100,200,300,400,500};
int *p[3];
int i,j;
p[0]=a;
p[1]=b;
p[2]=c;

ABVG Degree College, Jangaon 56


* Programming in C
Dynamic memory allocation
for(i=0;i<3;++i) Dynamic memory allocation is the ability for a
{ program to obtain or release memory at run time.
printf("%d",p[i]);
} ➢ Dynamic memory allocation uses the
getche(); functions such as malloc() or calloc().
return 0;
} malloc(): This function allocates a block of
memory from the heap. It ha the following syntax:
Pointer to Array void* malloc(size)
In C, we can use a pointer to point to an Array. Then malloc() takes one argument
we can use that pointer to access the array elements. Example:
C treats arrays almost like pointers. So that we can x = (int*) malloc(50 * sizeof(int));
directly set a pointer to an array
for example: calloc(): This function can be used to allocate a
main() block of memory. calloc() takes two arguments. It
{ has the following syntax:
int i; void *calloc(nitems, size)
int a[5] = {1, 2, 3, 4, 5}; Example:
int *p = a; // same as int*p = &a[0] x = (int*)calloc(50, sizeof(int));
clrscr();
for (i=0; i<5; i++) →The difference in malloc and calloc is that malloc
{ does not set the memory to zero where as calloc
printf("%3d", *p); sets allocated memory to zero.
p++;
}
realloc(): This function can change the memory
getche();
size that is already allocated to a variable.
return 0;
Example:
}
x=(int*)malloc(50 * sizeof(int));
x=(int*)realloc(x,100);
here, the instruction p = a makes the pointer point to
the address of the array. The number at this address is
free(): This function de-allocates memory. It
the first element of the array.
returns the memory to the system. It has the
following syntax:
void free(void *ptr)
Example:
free(x);

Advantages of dynamic memory allocation:


• We can create dynamic arrays.
• We can create dynamic data structures such
as stacks, queues, linked lists, trees, etc.

ABVG Degree College, Jangaon 57


* Programming in C

Write a C program to illustrate dynamic memoey


allocation
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, *a, i, s=0;
clrscr();
printf(“\n enter no. of elements of the array:”);
scanf(“%d”,&n);
a=(int *)malloc(n*sizeof(int));
if(a==NULL)
{
printf(“\n memory allocation unsuccessful...”);
exit(0);
}
printf(“\n enter the array elements one by one”);
for(i=0; i<n;++i)
{
scanf(“%d”,&a[i]));
s+=a[i];
}
printf(“\n sum is %d ”,s);
getche();
return 0;
}

***

ABVG Degree College, Jangaon 58


* Programming in C
Example:
Unit – IV S1.sno=101;
S1.sname=”Ritchie”;
User-defined Data Types S1.marks=625;

Structures S2.sno=201;
A structure is a collection of variables under a single S2.sname=”Bobbage”;
name. These variables can be of different types S2.marks=654;

A structure is declared by using the keyword struct. Initialization of Structures


The general format to declare a structure is: By default a structure can also be initialized by the
struct <structure_tag_name > system. By default the integer and float data type
{ members are initilaized with zero. Char and string
<data_type member_name1>; type members can be initialized with ‘\0’.
<data_type member_name2>;
. . . …. ….. ….; A structure can be intialized by using the following
}<structure_variable1>,<structure_variable2> format:
,...; struct <structure_tag_name>
Example: {
struct student <data_type member_name1>;
{ <data_type member_name2>;
int sno; }<structure_variable1> = {constant1,constant2, .
char sname[10]; .};
float marks; OR
} s1,s2; struct <structure_tag_name> <structure_variable>
= {constant1,constant2,..};
This will declare a structure with three members and
with 2 structure variables, as shown below: For example: The following program illustrates the
structures:
#include<stdio.h>
sno snam #include<conio.h>

marks struct student


{
S1 int sno, s1, s2, s3, total;
char sname[15];
float avg;
};
sno snam
main()
marks {
S2 struct student student1;
Accessing the Members of a Structure clrscr();
The members of a structure can be accessed by using printf("Enter Student Number:");
the ‘.’ the ‘dot operator’. It has the following form: scanf("%d",&student1.sno);
< structure_variable >.< member_name > ; printf("Enter Student Name:");
scanf("%s",&student1.sname);

ABVG Degree College, Jangaon 59


* Programming in C
printf("Enter Marks in Subject1:"); This will declare an array of structures as shown
scanf("%d", &student1.s1); below:
printf("Enter Marks in Subject2:");
scanf("%d", &student1.s2);
printf("Enter Marks in Subject3:");
scanf("%d", &student1.s3);
student1.total=student1.s1+student1.s2+ student1.s3;
student1.avg = student1.total/3;

printf("\n\n Student Number = %d", student1.sno);


printf("\n Student Name = %s", student1.sname);
printf("\n Marks in Subject1 =%d", student1.s1);
printf("\n Marks in Subject2 =%d", student1.s2);
printf("\n Marks in Subject3 =%d", student1.s3); Write a C program to illustrate an array
printf("\n Total Marks = %d", student1.total); structures
printf("\n Average Marks = %f", student1.avg); #include <stdio.h>
struct student
getche(); {
return 0; int sno, s1, s2, s3, total;
} char sname[15];
float avg;
Arrays of Structures }student1[3];
Declaring a structure variable as an array of objects is
known as Array of Structures. Each element in an int main()
array of structures contains the members of the {
structure. int i;
An array of structures can be created by using the clrscr();
following format: printf("Enter 10 Students information:\n");
struct <structure_tag_name > for(i=0;i<10;i++)
{ {
<data_type member_name1>; printf("Enter Student Number: ");
<data_type member_name2>; scanf("%d", &student1[i].sno);
... printf("Enter Student Name: ");
}<structure_variable>[index]; scanf("%s", student1[i].sname);
or
printf("Enter Marks in Subjct1: ");
struct <structure_tag_name>
scanf("%d", &student1[i].s1);
<structure_variable>[index];
printf("Enter Marks in Subjct2: ");
Example: scanf("%d", &student1[i].s2);
printf("Enter Marks in Subjct3: ");
struct student scanf("%d", &student1[i].s3);
{
int sno, s1, s2, s3, total; student1[i].total = student1[i].s1+ student1[i].s2+
char sname[15]; student1[i].s3;
float avg; student1[i].avg = student1[i].total/3;
}student1[3]; }

ABVG Degree College, Jangaon 60


* Programming in C
Accessing and Initializing the Members of
printf("Student Information:\n"); a Union

printf("\n sno \t name \t s1 \t s2 \t s3 \t total \t avg The members of a union can be accessed by using
:\n"); the ‘.’ the ‘dot operator’. It has the following form:
for(i=0;i<10;i++) < union_variable >.< member_name > ;
{
printf("\n%d \t %s \t %d \t %d \t %d \t %d \t%f Example:
\n", student1[i].sno, student1[i].sname, student1[i]. e1.eno=101;
s1, student1[i].s2, student1[i].s3, student1[i].total, e1.ename=”Ritchie”;
student1[i].avg); e1.salary=25000;

} Write a program that illustrates the unions.


union emp
getche(); {
return 0; ine eno;
} char ename[10];
float salary;
Union }e1;
A union is a a collection of variables under a single
name. The members of a union can share the same main()
storage. The amount of storage allocated to a union is {
sufficient to hold its largest member. clrcsr();
A Union can maintain only one member at a time in printf("Enter Employee Number:");
that storage. scanf("%d",&e1.eno);

A union can be declared by using the keyword printf("\n\t Employee Number = %d", e1.eno);
"union". printf("Enter Employee Name:");
scanf("%s",e1.ename);
Declaring a Union and its Members: printf("\n\t Employee Name = %s", e1.ename);
The general format for declaring a union is :
union tag_name printf("Enter Employee Salary:");
{ scanf("%f",e1.salary);
data type member1;
data typemember2; printf("\n\t Employee Salary = %f", e1.salary);
.
. getche();
data type memberN; return 0;
}variable1,variable2,variable3,…,variableX; }

Example:
union emp
{
int eno;
char ename[10];
float salary;
} e1;

ABVG Degree College, Jangaon 61


* Programming in C
Difference between Structure and union struct S
{
Structure versus Union int i;
char ch;
Memory allocation: The amount of memory float d;
required for a structure is equal to the sum of the size };
of all the members. For a union, the amount of the union U
memory required is same as that of the largest {
member. int i;
For example: char ch;
#include <stdio.h> float d;
#include <stdlib.h> };
#include <string.h>
struct S int main()
{ {
int i; struct S a={10,‘A’,3.1415};
char ch; union U b={10};
float d; printf(“\n a.i=%d a.ch=%c a.d=%lf”, a.i,a.ch,a.d);
}; printf(“\n b.i=%d b.ch=%c b.d=%lf”, b.i,b.ch,b.d);
b.ch=‘B’;
union U printf(“\n b.i=%d b.ch=%c b.d=%lf”, b.i,b.ch,b.d);
{ b.d=5.12345;
int i; printf(“\n b.i=%d b.ch=%c b.d=%lf”, b.i,b.ch,b.d);
char ch; return 0;
double d; }
};
Output
int main() a.i=10 a.ch=A a.d=3.141500
{ b.i=10 b.ch= b.d=0.000000
printf(“\n Size of the structure is %d”, sizeof(struct b.i=66 b.ch=B b.d=0.000000
S)); b.i=-1388133430 b.ch= b.d=5.123450
printf(“\n Size of the union is %d”, sizeof(union U));
return 0; Enumeration Types
}
Output Enumeration data types are the user defined data
Size of the structure is 7 type. The members of a enum can represent a set of
Size of the union is 4 integer constants. The keyword enum can be used
to declare an enumeration type.
Member access: A structure member can be accessed
at any point of time. But in Unions, we can access Syntax to declare a Enum:
only one member enum tag_name
at any given time. Because at any moment of time, {
only one union member will have a meaningful value. member1,
The other members have garbage values. member2,
Example: …,
#include <stdio.h> memberN
#include <stdlib.h> }variable1,...,variableX;
#include <string.h>
ABVG Degree College, Jangaon 62
* Programming in C

ABVG Degree College, Jangaon 63


* Programming in C

ABVG Degree College, Jangaon 64

You might also like