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

H. Ateeq Ahmed,: B. Tech Iyearisem

The document summarizes the classification of computers based on size and functionality. It discusses the different types of computers like supercomputers, mainframes, mini computers, and microcomputers classified based on their size. Supercomputers are the highest performing systems used for intensive tasks. Mainframes are used by large organizations for bulk data processing. Mini computers were cheaper than mainframes and used for control and interaction. Microcomputers are small and inexpensive computers that formed the basis for modern devices. Computers are also classified based on functionality into servers, workstations, and information appliances designed for specific tasks.

Uploaded by

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

H. Ateeq Ahmed,: B. Tech Iyearisem

The document summarizes the classification of computers based on size and functionality. It discusses the different types of computers like supercomputers, mainframes, mini computers, and microcomputers classified based on their size. Supercomputers are the highest performing systems used for intensive tasks. Mainframes are used by large organizations for bulk data processing. Mini computers were cheaper than mainframes and used for control and interaction. Microcomputers are small and inexpensive computers that formed the basis for modern devices. Computers are also classified based on functionality into servers, workstations, and information appliances designed for specific tasks.

Uploaded by

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

Specially Prepared for Engineering Students

As per R19
B. Tech
I Year I Sem
Syllabus

By
H. Ateeq Ahmed, M.Tech.,
Asst. Professor of CSE,
Kurnool.

As per JNTUA B.Tech I Year I Sem-R19 Syllabus NOT FOR


SALE
ABOUT AUTHOR

H. ATEEQ AHMED has completed B.Tech from Safa College


of Engineering & Technology, JNTUA, Anantapur, M.Tech from
Samskruti College of Engineering & Technology, JNTUH, Hyderabad.
Currently he is working as an Asst. Professor in the Department of CSE at
Dr. KVSR Institute of Technology, Kurnool, A.P. He has more than
10 years of teaching experience. He has vast subject knowledge in the field
of Computer networks & organization, Network security, Software design
& testing, Operating Systems, Programming in C & Java and Data mining.

His dynamic and illustrative approach towards the subjects helps


the students to enrich their skills in their academics which can help them to
achieve success in job career.

He always believes in real time approach to solve various problems


and expect the same with his students which can help them to understand
their subject in an easy and efficient manner.

He has prepared many materials of different subjects for engineering


students which can help them to prepare for exams in an easy method.

Finally, we expect our students to acquire as much knowledge as


possible and convert his dynamic teaching into their individual success.
ACKNOWLEDGEMENT

First I thank Almighty God for giving me the knowledge to learn and teach
various students.

It’s my privilege to thanks my parents as without their right guidance and


support, this book will be a dream for me.

Finally, I thank my colleagues and friends for helping me during tough


period of time.

“Interest & Focus are two KEYWORDS of a perfect programmer”

“The goal of this book is to find the next Programmer in YOU in a

magical way…”

H. Ateeq Ahmed, M.Tech.,

Mobile no: 994 8 37 8 994,

E-mail ID: [email protected].

Website: engineeringdrive.blogspot.in

My YouTube Channel: ENGINEERING DRIVE


Syllabus & Contents

Topics Page No.


UNIT-I
Computer Fundamentals:
What is a Computer,
Evolution of Computers,
Generations of Computers,
Classification of Computers,
Anatomy of a Computer,
Memory revisited,
Introduction to Operating systems,
Operational overview of a CPU.

Introduction to Programming, Algorithms and Flowcharts:


Programs and Programming,
Programming languages,
Compiler, 1 - 26
Interpreter,
Loader,
Linker,
Program execution,
Fourth generation languages,
Fifth generation languages,
Classification of Programming languages,
Structured programming concept,
Algorithms,
Pseudo-code,
Flowcharts,
Strategy for designing algorithms,
Tracing an algorithm to depict logic,
Specification for converting algorithms into programs.
UNIT-II
Introduction to computer problem solving:
Introduction,
the problem-solving aspect,
Top down design,
implementation of algorithms,
the efficiency of algorithms,
the analysis of algorithms.
27 - 45
Fundamental algorithms:
Exchanging the values of two variables,
counting,
summation of a set of numbers,
factorial computation,
sine function computation,
generation of the Fibonacci sequence,
reversing the digits of an integer.
UNIT-III
Types, Operators, and Expressions:
Variable names, data types and sizes, constants,
declarations, arithmetic operators,
relational and logical operators,
type conversions, increment
and decrement operators,
bitwise operators, assignment operators and expressions,
conditional expressions precedence and order of evaluation.
Input and output:
standard input and output, formatted output-Printf,
formatted input-Scanf.
Control Flow:
Statements and blocks, if-else, else-if, switch,
Loops-while and for, 46 – 78
Loops-Dowhile,
break and continue,
Goto and labels.
Functions and Program Structure:
Basics of functions,
functions returning non-integers,
external variables,
scope variables, header variables,
register variables,
block structure,
initialization,
recursion,
the C processor.
UNIT-IV
Factoring methods:
Finding the square root of a number, the smallest divisor of a number,
The greatest common divisor of two integers, generating prime numbers.
Pointers and arrays:
Pointers and addresses, pointers and function arguments,
pointers and arrays, address arithmetic, character pointers and functions, 79 – 105
pointer array; pointers to pointers, Multi-dimensional arrays,
initialization of arrays, pointer vs. multi-dimensional arrays,
command line arguments, pointers to functions, complicated declarations.
Array Techniques:
Array order reversal, finding the maximum number in a set,
removal of duplicates from an order array, finding the kth smallest element
UNIT-V
Sorting and Searching:
Sorting by selection, sorting by exchange, sorting by insertion,
Sorting by partitioning, binary search.
Structures:
Basics of structures, structures and functions, arrays of structures, pointers
to structures, self-referential structures, table lookup, typedef, unions, bit- 106 – 130
fields.
Some other Features:
Variable-length argument lists, formatted input-Scanf, file access, Error
handling-stderr and exit, Line Input and Output, Miscellaneous Functions.
Department of CSE 1

UNIT-I
COMPUTER FUNDAMENTALS

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 2

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 3

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 4

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 5

Classification of Computers
The computer systems can be classified on the following basis:
1. On the basis of size.
2. On the basis of functionality.
3. On the basis of data handling.
Classification on the basis of size
1. Super computers :
The super computers are the most high performing system. A supercomputer is a
computer with a high level of performance compared to a general-purpose computer.
Supercomputers actually play an important role in the field of computation, and are used
for intensive computation tasks in various fields, including quantum mechanics, weather
forecasting, climate research, oil and gas exploration, molecular modeling, and physical
simulations.
eg: PARAM, jaguar, roadrunner.

2. Mainframe computers :
These are commonly called as big iron, they are usually used by big organisations for
bulk data processing such as statics, census data processing, transaction processing and
are widely used as the severs as these systems has a higher processing capability as
compared to the other classes of computers, most of these mainframe architectures were
established in 1960s.
Eg: IBM z Series, System z9 and System z10 servers.

3. Mini computers :
These computers came into the market in mid 1960s and were sold at a much cheaper
price than the main frames, they were actually designed for control, instrumentation,
human interaction, and communication switching as distinct from calculation and record
keeping, later they became very popular for personal uses with evolution.
They usually took up one or a few inch rack cabinets, compared with the large
mainframes that could fill a room, there was a new term “MINICOMPUTERS” coined
Eg: Personal Laptop, PC etc.

4. Micro computers :
A microcomputer is a small, relatively inexpensive computer with a microprocessor as
its CPU. It includes a microprocessor, memory, and minimal I/O circuitry mounted on a
single printed circuit board.The previous to these computers, mainframes and
minicomputers, were comparatively much larger, hard to maintain and more expensive.
They actually formed the foundation for present day microcomputers and smart gadgets
that we use in day to day life.
Eg: Tablets, Smartwatches.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 6

Classification on the basis of functionality


1. Servers :
Servers are nothing but dedicated computers which are set-up to offer some services to
the clients. They are named depending on the type of service they offered. Eg: security
server, database server.

2. Workstation :
Those are the computers designed to primarily to be used by single user at a time. They
run multi-user operating systems. They are the ones which we use for our day to day
personal / commercial work.

3. Information Appliances :
They are the portable devices which are designed to perform a limited set of tasks like
basic calculations, playing multimedia, browsing internet etc. They are generally
referred as the mobile devices. They have very limited memory and flexibility and
generally run on “as-is” basis.

4. Embedded computers : They are the computing devices which are used in other
machines to serve limited set of requirements. They follow instructions from the non-
volatile memory and they are not required to execute reboot or reset.

Classification on the basis of data handling

1. Analog : An analog computer is a form of computer that uses the continuously-


changeable aspects of physical fact such as electrical, mechanical, or hydraulic
quantities to model the problem being solved.

2. Digital : A computer that performs calculations and logical operations with quantities
represented as digits, usually in the binary number system of “0” and “1”.

3. Hybrid : A computer that processes both analog and digital data, Hybrid computer is a
digital computer that accepts analog signals, converts them to digital and processes them
in digital form.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 7

Anatomy of a Computer

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 8

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 9

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 10

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 11

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 12

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 13

Introduction to Operating Systems


An operating system is a software which acts as an
interface between the end user and computer hardware. Every computer must have at least
one OS to run other programs. An application like Chrome, MS Word, Games, etc needs
some environment in which it will run and perform its task.
The OS helps you to communicate with the computer without knowing how to speak
the computer's language. It is not possible for the user to use any computer or mobile device
without having an operating system

Types of Operating Systems

1. Single user Operating systems


A single-user operating system is a system in which only one user can access the
computer system at a time.
A single user operating system provides the facilities to be used on one computer by
only one user. In other words, it supports one user at a time. However, it may support more
than one profiles. Single keyboard and single monitor are used for the purpose of interaction.
The most common example of a single user operating system is a system that is found in a
typical home computer.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 14

2. Multiuser Operating systems


A multi-user operating system allows more than one user to access a computer system
at one time.
A multi-user operating system has been designed for more than one user to access the
computer at one time. Generally, a network is laid down, so that a computer can be remotely
used. Mainframes and minicomputers work on multi-user operating systems. These operating
systems are complex in comparison to single user operating systems.

3. Distributed Operating systems


A distributed operating system is a software over a collection of independent,
networked, communicating, and physically separate computational nodes. They handle jobs
which are serviced by multiple CPUs.

Operational Overview of a CPU


The central processing unit (CPU) is the unit which performs most of the processing inside a
computer. To control instructions and data flow to and from other parts of the computer, the
CPU relies heavily on a chipset, which is a group of microchips located on the motherboard.
The CPU has three components:
 Control Unit: extracts instructions from memory and decodes and executes them
 Arithmetic Logic Unit (ALU): handles arithmetic and logical operations
 Registers- The CPU contains internal memory units, which are called registers. These
registers contain data, instructions, counters and addresses used in the ALU's
information processing

The CPU is the heart and brain of a computer. It receives data input, executes instructions,
and processes information. It communicates with input/output (I/O) devices, which send and
receive data to and from the CPU.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 15

INTRODUCTION TO PROGRAMMING, ALGORITHMS AND FLOWCHARTS

Programs and Programming


A Program is a set of instructions compiled together in a file to perform some specific
task by the CPU (Central Processing Unit). It is a series of binary numbers (0s and 1s)
arranged in a sequence, which when given to the computer performs some task.
Computer is a dumb machine with expeditious computational speed. It can give quick
results to many of the complex scientific calculations but it can‟t perform a task on its own. A
computer needs set of instructions to do some task. This set of instructions is contained in a
computer program. Computer program is basically in binary language i.e. series of 0s and 1s.
A large bunch of programs makes the computer functional without which the computer
would be like a paralyzed machine.
Programming is the process of writing an algorithm into a sequence of computer
instructions. Or you can simply say it is the process of writing programs. We generally
transform the solution of a specific problem into computer language. It is the only way
through which we can create our own programs and can execute them on a computer.
Programming requires skill, logical thinking and lots of experience.
Programmers are the person who writes programs in a specific computer
programming language. They are highly skilled, hard working, problem solvers. The world‟s
first programmer was Ada Lovelace. She was widely known for her work on Charles
Babbage‟s Analytical Engine (general-purpose mechanical computer).

Programming Languages
A computer programming language is a language used to write computer programs,
which involves a computer performing some kind of computation or algorithm and possibly
control external devices such as printers, disk drives, robots, and so on. For
example, PostScript programs are frequently created by another program to control a
computer printer or display.
More generally, a programming language may describe computation on some,
possibly abstract, machine. It is generally accepted that a complete specification for a
programming language includes a description, possibly idealized, of a machine or processor
for that language.
In most practical contexts, a programming language involves a computer;
consequently, programming languages are usually defined and studied this way.
Programming languages differ from natural languages in that natural languages are
only used for interaction between people, while programming languages also allow humans
to communicate instructions to machines.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 16

Classification of Programming Languages

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 17

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 18

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 19

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 20

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 21

Fourth Generation Languages(4GL)


A fourth generation language is a grouping of
programming languages that attempt to get closer than 3GLs to human language, form of
thinking and conceptualization.
4GLs are designed to reduce the overall time, effort and cost of software development. The
main domains and families of 4GLs are: database queries, report generators, data
manipulation, analysis and reporting, screen painters and generators, GUI creators,
mathematical optimization, web development and general purpose languages.
4GLs are more programmer-friendly and enhance
programming efficiency with usage of English-like words and phrases, and when appropriate,
the use of icons, graphical interfaces and symbolical representations. The key to the
realization of efficiency with 4GLs lies in an appropriate match between the tool and the
application domain. Additionally, 4GLs have widened the population of professionals able to
engage in software development.
Many 4GLs are associated with databases and data
processing, allowing the efficient development of business-oriented systems with languages
that closely match the way domain experts formulate business rules and processing
sequences. Many of such data-oriented 4GLs are based on the Structured Query Language
(SQL), invented by IBM and subsequently adopted by ANSI and ISO as the standard
language for managing structured data.

Fifth Generation Languages(5GL)


A fifth generation (programming) language (5GL) is a
grouping of programming languages build on the premise that a problem can be solved, and
an application built to solve it, by providing constraints to the program (constraint-based
programming), rather than specifying algorithmically how the problem is to be solved
(imperative programming).
In essence, the programming language is used to denote
the properties, or logic, of a solution, rather than how it is reached. Most constraint-based and
logic programming languages are 5GLs.
Considerable research has been invested in the 1980s and
1990s, into the development of 5GLs. As larger programs were built, it became apparent that
the approach of finding an algorithm given a problem description, logical instructions and a
set of constraint is a very hard problem in itself.
During the 1990s, the wave of hype that preceded the
popularization of 5GLs and predictions that they will replace most other programming
languages, gave way to a more sober realization.

Structured Programming Concept


Structured programming (sometimes known as modular programming) is a subset of
procedural programming that enforces a logical structure on the program being written to
make it more efficient and easier to understand and modify. Certain languages such
as Ada, Pascal, and dBASE are designed with features that encourage or enforce a logical
program structure.
Structured programming frequently employs a top-down design model, in which
developers map out the overall program structure into separate subsections. A defined
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 22

function or set of similar functions is coded in a separate module or submodule, which means
that code can be loaded into memory more efficiently and that modules can be reused in other
programs. After a module has been tested individually, it is then integrated with other
modules into the overall program structure.
Almost any language can use structured programming techniques to avoid common
pitfalls of unstructured languages. Unstructured programming must rely upon the discipline
of the developer to avoid structural problems, and as a consequence may result in poorly
organized programs. Most modern procedural languages include features that encourage
structured programming. Object-oriented programming (OOP) can be thought of as a type of
structured programming, uses structured programming techniques for program flow, and adds
more structure for data to the model.

Compiler
A compiler is a computer program that transforms code written in a high-level
programming language into the machine code. It is a program which translates the human-
readable code to a language a computer processor understands (binary 1 and 0 bits). The
computer processes the machine code to perform the corresponding tasks.
A compiler should comply with the syntax rule of that programming language in
which it is written. However, the compiler is only a program and cannot fix errors found in
that program. So, if you make a mistake, you need to make changes in the syntax of your
program. Otherwise, it will not compile.

Interpreter
An interpreter is a computer program, which coverts each high-level program
statement into the machine code. This includes source code, pre-compiled code, and scripts.
Both compiler and interpreters do the same job which is converting higher level
programming language to machine code.
However, a compiler will convert the code into machine code (create an exe) before
program run. Interpreters convert code into machine code when the program is run.

Conclusion of Compiler vs Interpreter


 A compiler is a computer program which transforms code written in a high-level
programming language into the machine code
 An interpreter is a computer program, which coverts each high-level program
statement into the machine code.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 23

 Compliers generates intermediate machine code that is saved to the computer as an


exe.
 Interpreter never generates any intermediate machine code.
 The interpreter converts the source code line-by-line during RUN Time.
 The compiler needs a lot of time analyzing and processing the program.
 Interpreter spends less time on analyzing and processing a program.

Linker and Loader


Linker and Loader are the utility programs that plays a major role in the execution of
a program. The Source code of a program passes through compiler, assembler, linker, loader
in the respective order, before execution. On the one hand, where the linker intakes the
object codes generated by the assembler and combine them to generate the executable
module. On the other hands, the loader loads this executable module to the main memory for
execution.

Let us discuss the difference between Linker and loader with the help of a comparison chart.

BASIS FOR COMPARISON LINKER LOADER

Basic It generates the executable It loads the executable module


module of a source program. to the main memory.

Input It takes as input, the object It takes executable module


code generated by an generated by a linker.
assembler.
Function It combines all the object It allocates the addresses to an
modules of a source code to executable module in main
generate an executable memory for execution.
module.

Program Execution
Whenever a C program file is compiled and executed, the compiler generates some
files with the same name as that of the C program file but with different extensions. So, what
are these files and how are they created?
Below image shows the compilation process with the files created at each step of the
compilation process:

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 24

Every file that contains a C program must be saved with „.c‟ extension. This is
necessary for the compiler to understand that this is a C program file. Suppose a program file
is named, first.c. The file first.c is called the source file which keeps the code of the program.
Now, when we compile the file, the C compiler looks for errors. If the C compiler reports no
error, then it stores the file as a .obj file of the same name, called the object file. So, here it
will create the first.obj. This .obj file is not executable. The process is continued by the
Linker which finally gives a .exe file which is executable.

Pseudocode
“Pseudocode is an informal way of programming description that does not require any strict
programming language syntax or underlying technology considerations.“
 It is used for creating an outline or a rough draft of a program.
 Pseudocode summarizes a program‟s flow, but excludes underlying details.
 System designers write pseudocode to ensure that programmers understand a software
project's requirements and align code accordingly.
 Pseudocode is not an actual programming language.
 So it cannot be compiled into an executable program.
 It uses short terms or simple English language syntaxes to write code for programs
before it is actually converted into a specific programming language.
 This is done to identify top level flow errors, and understand the programming data
flows that the final program is going to use.
 This definitely helps save time during actual programming as conceptual errors have
been already corrected.
 Firstly, program description and functionality is gathered and then pseudocode is used
to create statements to achieve the required results for a program.
 Detailed pseudocode is inspected and verified by the designer‟s team or programmers
to match design specifications.
 Catching errors or wrong program flow at the pseudocode stage is beneficial for
development as it is less costly than catching them later.
 Once the pseudocode is accepted by the team, it is rewritten using the vocabulary and
syntax of a programming language.

Example
C code: if (i < 10) { i++; }
pseudocode: if i is less than 10, increment i by 1.

Strategy for designing algorithms


The following are the various strategies used for designing algorithms.
 Divide and conquer
 Greedy Method
 Dynamic Programming
 Backtracking
 Branch & Bound
 Linear Programming

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 25

Tracing an algorithm to depict logic


“An algorithm trace is a method for hand simulating the execution of your code in order to
manually verify that it works correctly before you compile it.”
It is also known as a "desk check."

Example
Consider the algorithm to convert and display the distance from miles to kms.

Step-1: Get the distance in miles.


Stept-2: Convert the distance to kms.
Step-2.1: The distance in kms is 1.609 times the distance in miles.
Step-3: Display the distance in kms.

Let us trace the above algorithm,


If step-1 will get the distance of 10 miles, step-2.1 would convert it to 1.609*10 or 16.09
kms.
This correct result would be displayed by step-3.

Specification for converting algorithms into programs


“An algorithm is a set of steps designed to solve a problem or accomplish a task.“
Algorithms are usually written in pseudocode, or a combination of your speaking language
and one or more programming languages, in advance of writing a program.

1. Determine the outcome of your code. What is the specific problem you want to solve or
the task you want it to accomplish? Once you have a solid idea of what you're aiming to
accomplish, you can determine the steps it will take to get there.

2. Decide on a starting point. Finding your starting and ending point are crucial to listing the
steps of the process. To determine a starting point, determine the answers to these questions:

 What data/inputs are available?


 Where is that data located?
 What formulas are applicable to the issue at hand?
 What are the rules to working with the available data?
 How do the data values relate to each other?

3. Find the ending point of the algorithm. As with the starting point, you can find the end
point of your algorithm by focusing on these questions:
 What facts will we learn from the process?
 What changes from the start to the end?
 What will be added or no longer exist?

4. List the steps from start to finish. Start with broad steps. To use a real-world example,
let's say your goal is to have lasagna for dinner. You've determined that the starting point is to
find a recipe, and that the end result is that you'll have a lasagna fully cooked and ready to eat
by 7 PM.

5. Determine how you will accomplish each step. Now that you have a step-by-step outline,
it's time to think about how you might code each step. Which language will you use? What
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 26

resources are available? What's the most efficient way to accomplish each step in that
language? Incorporate some of that code into your algorithm. Expand each step until you've
detailed the entire process.

6. Review the algorithm. Now that you've written your algorithm, it's time to evaluate the
process. Your algorithm is designed to accomplish something specific, and you'll need it to
start writing your program.

*******

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 27

UNIT-II
INTRODUCTION TO COMPUTER PROBLEM SOLVING

Introduction

Programs and Algorithms

Requirements for Solving Problems by Computer

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 28

The Problem Solving Aspect

1. Problem definition phase

the problem definition phase.

2. Similarities among problems

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 29

General Problem Solving Strategies

Top-down Design

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 30

Breaking a problem into sub problems

Construction of Loops

The following are the three steps in the construction of loops.

(1) Establishing the initial conditions


(2) Finding the iterative construct
(3) Termination of loops.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 31

Implementation of Algorithms

Use of procedures to emphasize modularity

Choice of variable names

Documentation of programs

Debugging Programs

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 32

The Efficiency of Algorithms

The following points must be considered

 Redundant computations
 Referencing array elements
 Inefficiency due to late termination
 Early detection of desired output conditions

The Analysis of Algorithms

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 33

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 34

FUNDAMENTAL ALGORITHMS
Exchanging the values of two variables

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 35

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 36

Counting

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 37

Thus

Finally

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 38

Summation of a set of Numbers

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 39

Factorial Computation

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 40

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 41

Sine Function Computation

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 42

Generation of the Fibonacci sequence

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 43

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 44

Reversing the digits of an Integer

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 45

*******

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 46

UNIT-III
TYPES, OPERATORS AND EXPRESSIONS
Introduction to the C Language
 C is a structured programming language.
 It was developed by M. Dennis Ritchie in 1972 at Bell Laboratories.
 It is considered a high-level language because it allows the programmer to concentrate
on the problem at hand and not worry about the machine that the program will be
using.
 While many languages claim to be machine independent, C is one of the closest to
achieving that goal.
 That is another reason why it is used by software developers whose applications have
to run on many different hardware platforms.

Variable Names
“A Variable is the name given to memory location to store data value in it.”
Unlike constant, the value of a variable can be changed.
A variable name must be chosen in such a way that it improves the readability of a program.
Syntax
Data_type var_name=var_value;

Example
int x=10;
The above variable „x‟ contains value 10 and it is of integer data type.

Identifiers
 One feature present in all computer languages is the identifier.
 Identifiers allow us to name data and other objects in the program.
 Each identified object in the computer is stored at a unique address.
 If we didn‟t have identifiers that we could use to symbolically represent data
locations, we would have to know and use object‟s addresses.
 Instead, we simply give data identifiers and let the compiler keep track of where they
are physically located.
Example
int x;

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 47

x is known as identifier.
Rules for Identifiers
 An identifier must start with a letter or underscore: it may not have a space or a
hyphen.
 An identifier must not be a keyword.
 It can consist of letters, digits or underscore.
 Identifier names are case sensitive.
 The maximum length of identifier must be less than or equal to 31 characters.

Data types and sizes


A data type is used to indicate the type of value stored in a variable.
A data type indicates the following
 Type of value stored in a variable
 Memory allocated for data value
 Type of operations that can be performed on the variable.
Data types are classified in to the following categories.
1. Integer data types
2. Floating point data types
3. Characters

1. Integer data types


It is used to store whole numbers.
The size of the integer depends on the word length of a machine i.e. it can be either 16 or 32
bits.

Signed Integers:
Signed integers are those integers which uses 15 bits for storing the magnitude of a number
and I bit for storing its sign.
The left most bit i.e. 16th bit is used for storing the sign.
1-> Negative number
0-> Positive number

Example:
signed int x=10;
0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
Magnitude
Sign
0-> Positive number
Unsigned Integers
Unsigned integers uses all 16 bits to store the magnitude.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 48

Data type Size (bytes) Format Specifier Range


int 2 or 4 %d -32768 to 32767 or
-21474836648 to 21474836648
unsigned int 2 %u 0 to 65535
signed int 2 %d -32768 to 32767
short int 2 %hd -32768 to 32767
unsigned short 2 %hu 0 to 65535
int
signed short int 2 %hd -32768 to 32767
long int 4 %ld -21474836648 to 21474836648
unsigned long 4 %lu 0 to 4294967295
int
signed long int 4 %ld -21474836648 to 21474836648

Example Program
Write a C program to display the value of an integer variable.
#include<stdio.h>
#include<conio.h>

void main()
{
int a=10;
clrscr();
printf("Value of a=%d",a);
getch();
}

Expected Output
Value of a=10

2. Floating point data types:


These are used to store real numbers i.e. decimal point numbers or numbers with fractional
values.
Data type Size (bytes) Format Specifier Range
float 4 %f -3.4e-38 to 3.4e+38
double 8 %lf 1.7e-308 to 1.7e+308
long double 10 %Lf 3.4e-4932 to 1.1e+4932

Example Program
Write a C program to display the value of a floating variable.
#include<stdio.h>
#include<conio.h>

void main()
{
float a=2.5;

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 49

clrscr();
printf("Value of a=%f",a);
getch();
}

Expected Output
Value of a=2.500000

3. Character data type:


This data type is used to store characters.
Each character has an equivalent ASCII value.
The format specifier used with character data type is %c.

Data type Size (bytes) Format Specifier Range


char or signed 1 %c -128 to 127
char
unsigned char 1 %c 0 to 255

Example Program
Write a C program to display a single character.
#include<stdio.h>
#include<conio.h>

void main()
{
char ch=‟A‟;
clrscr();
printf("Character=%c",ch);
getch();
}

Expected Output
Character=A

Constants
Constants are data values that cannot be changed during the execution of a program.
Like variables, constants have a type.
In this section, we discuss Boolean, character, integer, real, complex, and string constants.

Character constants
A character constant is enclosed in single quotes.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 50

Integer constants

Real constants

Complex constants
The two components of a complex constant must be of the same precision, that is, if the real
part is type double, then the imaginary part must also be type double.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 51

Declarations
 We are required to declare our variables to the C compiler before you use them.
 You do this by providing a list of variables near the beginning of the program.
 That way, the compiler knows what the variables are called and what type of variables
they are (what values they can contain).
 Officially, this process is known as declaring your variables.
Example

int count;
char key;
char lastname[30];

 Three variables are declared here: an integer variable, count; a character variable,
key; and a character variable, lastname, which is a string that can be as many as 30
characters long.
 Doing this at the beginning of the program tells the compiler several things. First, it
says, "These things are variables!" That way, when the compiler sees lastname in a
program, it knows that it's a string variable.
 Second, the declarations tell the compiler which type of variable is being used. The
compiler knows that integer values fit into the count variable, for example.
 Third, the compiler knows how much storage space to set aside for the variables.

OPERATORS
Operators are C tokens which can join together individual constants, variables, array elements
etc.
C operators are classified into the following categories.
 Arithmetic operators
 Relational operators
 Logical operators
 Assignment operators
 Increment and Decrement operators
 Conditional operators
 Bitwise operators
 Special operators

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 52

Arithmetic Operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division

Relational operators
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to

Logical operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Assignment operators
It is used to assign the result of an expression to a variable.
It is denoted as „=‟.

Increment and Decrement operators


Operator Meaning
a++ Post increment
++a Pre increment
a-- Post decrement
--a Pre decrement

Example Program
Write a C program to show the use of increment & decrement operators.
#include<stdio.h>
#include<conio.h>

void main()
{
int x,y;
x=5;
y=5;
clrscr();

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 53

x++;
printf("x=%d",x);

y--;
printf("\ny=%d",y);

getch();
}

Expected Output
x=6
y=4

Conditional operator
It is also known as ternary operator.
Syntax
exp1?exp2:exp3;
The value of exp1 is evaluated first, If it is true, value of exp2 is evaluated otherwise exp3 is
evaluated.

Example Program
Write a C program to find the biggest of two numbers using Conditional operator.
#include<stdio.h>
#include<conio.h>

void main()
{
int a,b,big;
clrscr();
a=20;
b=10;
big=(a>b)?a:b;
printf("Big number is %d",big);
getch();
}
Expected Output
Big number is 20

Bitwise operators
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR(XOR)
~ One‟s Complement
<< Shift left
>> Shift right
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 54

Special operators
(i) Comma operator(,)
It is used to separate the variables
Eg:
int a,b,c;

(ii) sizeof operator


It return the no. of bytes the operand occupies.
Eg: sizeof(operand)

Precedence and Order of Evaluation


 Precedence is used to determine the order in which different operators in a complex
expression are evaluated.
 Associativity is used to determine the order in which operators with the same
precedence are evaluated in a complex expression.
 Each operator in „C‟ has a precedence associated with it.
 This precedence is used to determine how each expression containing more than one
operator is evaluated.
 The operator at the higher level of precedence is evaluated first and the operators of
the same precedence are evaluated either from left to right or from right to left
depending up on the level.
The following are the two distinct levels of Arithmetic operators.
(i) High priority arithmetic operators are *,/,% and
(ii) Low priority arithmetic operators are +, -

Example-1
x=a-b/3+c*2-1
Now let a=9, b=12, c=3 then
x=9-12/3+3*2-1
The above expression is evaluated as follows.
x=9-4+3*2-1
x=9-4+6-1
x=15-4-1
x=15-5
x=10

If parenthesis are used then expression within the parenthesis is evaluated first.
Example-2
x=9-12/6*(2-1)
x=9-12/6*1
x=9-2*1
x=9-2
x=7

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 55

 When an expression contains two operators of equal priority then the tie between
them is settled using the associativity of operators.
 Associativity are of two types
Left to Right
Right to Left
 Left to Right associativity means that the left operand must not be involved in any
other sub expression.
 Similarly, Right to Left associativity means that the right operand should not involved
in any sub expressions.

Evaluating Expressions
When an expression consists of different types of variables, compiler follows rules of type
conversions.

RULE:
If the operands are of different types, the lower type is automatically converted to higher type
and the result will be of higher type.
The result of expression is then converted to the type of variable present at the left hand side
of the assignment operator.

Example
int i;
float f;
double d;

int j=i*d+f/i;
int j=double type+float type
int j=double type.

Finally, the result is converted to integer type as j is an integer variable.

INPUT AND OUTPUT


Formatted Console I/O
 The functions printf( ) and scanf( ) perform formatted output and input— that is, they
can read and write data in various formats that are under your control.
 The printf( ) function writes data to the console.
 The scanf( ) function, its complement, reads data from the keyboard.
 Both functions can operate on any of the built-in data types, plus null-terminated
character strings.
The following are the two types of formatted I/O functions
(a) printf()
(b) scanf()
(a) printf()
This function is used to print result on the monitor.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 56

Syntax
printf(“control string”,arg1,arg2,….,argn);
Examples
printf(“%d”,a);
printf(“%d%c”,num,ch);

Printing Characters
 To print an individual character, use %c.
 To print a string, use %s.

Printing Numbers
 You can use either %d or %i to display a signed integer in decimal format.
 These format specifiers are equivalent; both are supported for historical reasons, of
which one is the desire to maintain an equivalence relationship with the scanf( )
format specifiers.
 To output an unsigned integer, use %u.
 The %f format specifier displays numbers in floating point.
 The matching argument must be of type double.

Displaying an Address
 If you want to display an address, use %p.
 This format specifier causes printf( ) to display a machine address in a format
compatible with the type of addressing used by the computer.
( b) scanf()
This function is used to read values for variables from keyboard.

Syntax
scanf(“control string”,address_list);
where control string specifies the type of values that have to read from the keyboard.
Examples
scanf(“%d”,&a);
scanf(“%d%f”,&a,&b);
scanf(“%d%f%c”,&a,&b,&c);
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 57

CONTROL FLOW
Expression Statements
 The previous unit covers expressions thoroughly.
 However, a few special points are mentioned here.
 Remember, an expression statement is simply a valid expression followed by a
semicolon, as in
func(); /* a function call */
a = b+c; /* an assignment statement */
b+f(); /* a valid, but strange statement */
; /* an empty statement */
 The first expression statement executes a function call.
 The second is an assignment. T
 The third expression, though strange, is still evaluated by the compiler because the
function f( ) may perform some necessary task.
 The final example shows that a statement can be empty (sometimes called a null
statement).

Block Statements
 Block statements are simply groups of related statements that are treated as a unit.
 The statements that make up a block are logically bound together.
 Block statements are also called compound statements.
 A block is begun with a { and terminated by its matching }.
 Programmers use block statements most commonly to create a multi statement target
for some other statement, such as if.
 However, you may place a block statement anywhere you would put any other
statement.
 For example, this is perfectly valid (although unusual) C code:
#include <stdio.h>
void main()
{
int i;
{ /* a free-standing block statement */
i = 120;
printf(''%d", i);
}
}

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 58

CONTROL STATEMENTS
Control statements are the statements that allow the programmer to specify the next statement
that must be executed depending on some conditions.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 59

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 60

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 61

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 62

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 63

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 64

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 65

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 66

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 67

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 68

Example Programs for Selection statements

(i) Simple if
#include<stdio.h>
#include<conio.h>

void main()
{
int age;
age=20;
clrscr();
if(age>=18)
{
printf("Eligible for voting.");
}
getch();
}

Expected Output
Eligible for voting.

(ii) if else
#include<stdio.h>
#include<conio.h>

void main()
{
int age;
age=15;
clrscr();
if(age>=18)
{
printf("Eligible for voting.");
}
else
{
printf("\nNot eligible for voting.");
}
getch();
}

Expected Output
Not eligible for voting.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 69

(iii) else if ladder


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

void main()
{
float per;
per=76;
clrscr();
if(per>=70 && per<=100)
{
printf("Distinction");
}
else if(per>=60 && per<70)
{
printf("\nFirst Class");
}
else if(per>=50 && per<60)
{
printf("\nSecond Class");
}
else
{
printf("\nFailed");
}
getch();
}

Expected Output
Distinction

(iv) switch
#include<stdio.h>
#include<conio.h>
void main()
{
int day;
day=5;
clrscr();
switch(day)
{
case 0:
printf("SUNDAY");
break;

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 70

case 1:
printf("\nMONDAY");
break;

case 2:
printf("\nTUESDAY");
break;

case 3:
printf("\nWEDNESDAY");
break;

case 4:
printf("\nTHURSDAY");
break;

case 5:
printf("\nFRIDAY");
break;

case 6:
printf("\nSATURDAY");
break;

default:
printf("\nInvalid Day number");
}

getch();
}

Expected Output
FRIDAY

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 71

FUNCTIONS AND PROGRAM STRUCTURE

Basics of functions
A function is a self-contained block of statements that perform some specific task for the
program.
Functions are used to provide modularity to the software. By using functions, you can divide
complex tasks into small manageable tasks. The use of functions can also help avoid
duplication of work. For example, if you have written the function for calculating the square
root, you can use that function in multiple programs

Functions are classified into two categories.


(1) Built in functions or Standard library functions
(2) User defined functions.

Library Functions:
 As the name suggests, library functions are nothing but commonly required functions
grouped together and stored in a Library.
 This library of functions is present on the disk and is written for us by people who
write compilers for us.
 Almost always a compiler comes with a library of standard functions.
Examples:
printf(), scanf() etc.

User defined functions:


User defined functions are those functions that are used by the user according to the
requirement of the program.

Syntax:
return-type function-name(parameter-list)
{
local variables;
statements;
}

Advantages of functions:
 A function provides modularity and readability to the software.
 To define the function, you have to define the function name, the return data type and
the formal parameters.
 It is recommended to declare a function prototype before using a function.
 If the function does not return any value, then you have to set the return data type as
void.
 A call to a function should be compatible with the function definition.

Example Program
//Using userdefined function

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

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 72

void message(); // function prototype

void main()
{
clrscr();
printf("\nHow r u?");
message();
getch();
}

void message() // function definition


{
printf("\nI am fine!");
}

Expected Output
How r u?
I am fine!

Explanation
 Here, main( ) itself is a function and through it we are calling the function
message( ). What do we mean when we say that main( ) „calls‟ the function message(
)? We mean that the control passes to the function message( ).
 The activity of main( ) is temporarily suspended; it falls asleep while the message( )
function wakes up and goes to work.
 When the message( ) function completes the execution of statements, the control
returns to main( ), which comes to life again and begins executing its code at the
exact point where it left off.
 Thus, main( ) becomes the „calling‟ function, whereas message( ) becomes the
„called‟ function.

Understanding the scope of Functions


 The scope rules of a language are the rules that govern whether a piece of code knows
about or has access to another piece of code or data.
 Each function is a discrete block of code.
 Thus, a function defines a block scope.
 This means that a function's code is private to that function and cannot be accessed by
any statement in any other function except through a call to that function.
 The code and data defined within one function cannot interact with the code or data
defined in another function because the two functions have different scopes.
 Variables that are defined within a function are local variables.
 A local variable comes into existence when the function is entered and is destroyed
upon exit. Thus, a local variable cannot hold its value between function calls.
 The only exception to this rule is when the variable is declared with the static storage
class specifier.
 This causes the compiler to treat the variable as if it were a global variable for storage
purposes, but limit its scope to the function.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 73

“Scope is defined as the area of the program in which the variable is visible or accessible.”
Consider the following function which contains the local variable „i‟ as follows.
void fun()
{
int i=10; // „i‟ is a local variable
printf(“i=%d”,i);
}
Hence the scope of variable „i‟ is within the function fun().

Storage Class Specifiers


To fully define a variable one needs to mention not only its „type‟ but also its „storage
class‟. In other words, not only do all variables have a data type, they also have a „storage
class‟. A variable name identifies some physical location within the computer where the
string of bits representing the variable‟s value is stored. There are basically two kinds of
locations in a computer where such a value may be kept— Memory and CPU registers. It is
the variable‟s storage class that determines in which of these two locations the value is stored.
A variable‟s storage class tells us:
 Where the variable would be stored.
 What will be the initial value of the variable, if initial value is not specifically
assigned.(i.e. the default initial value).
 What is the scope of the variable; i.e. in which functions the value of the variable
would be available.
 What is the life of the variable; i.e. how long would the variable exist.

There are four storage classes in C:


(a) Automatic storage class
(b) Register storage class
(c) Static storage class
(d) External storage class

Let us examine these storage classes one by one.


(a) Automatic storage class
The features of a variable defined to have an automatic storage class are as under:
Storage − Memory.

Default initial value − An unpredictable value, which is often called a garbage value.

Scope − Local to the block in which the variable is defined.

Life − Till the control remains within the block in which the variable is
defined.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 74

Example Program
void main( )
{
auto int i, j ;
printf ( "\n%d %d", i, j ) ;
getch();
}
The above program shows how an automatic storage class variable is
declared, and the fact that if the variable is not initialized it contains a garbage value.

(b) Register storage class


The features of a variable defined to be of register storage class are as under:
Storage - CPU registers.

Default initial value - Garbage value.

Scope - Local to the block in which the variable is defined.

Life - Till the control remains within the block in which the variable is
defined.

A value stored in a CPU register can always be accessed faster than the one that is
stored in memory. Therefore, if a variable is used at many places in a program it is better to
declare its storage class as register. A good example of frequently used variables is loop
counters. We can name their storage class as register.

Example Program
void main( )
{
register int i ;
for ( i = 1 ; i <= 10 ; i++ )
printf ( "\n%d", i ) ;
getch();
}
Here, even though we have declared the storage class of i as register, we cannot say for
sure that the value of i would be stored in a CPU register. Why? Because the number of CPU
registers are limited, and they may be busy doing some other task. What happens in such an
event, the variable works as if its storage class is auto.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 75

(c) Static storage class


The features of a variable defined to have a static storage class are as under:
Storage − Memory.

Default initial value − Zero.

Scope − Local to the block in which the variable is defined.

Life − Value of the variable persists between different function calls.

Let us now compare the two programs and their output given below to understand the
difference between the automatic and static storage classes

The above programs consist of two functions main( ) and increment( ). The function
increment( ) gets called from main( ) thrice. Each time it increments the value of i and prints
it. The only difference in the two programs is that one uses an auto storage class for variable
i, whereas the other uses static storage class.
Like auto variables, static variables are also local to the block in which they are
declared. The difference between them is that static variables don‟t disappear when the
function is no longer active. Their values persist. If the control comes back to the same
function again the static variables have the same values they had last time around.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 76

(d) External storage class


The features of a variable whose storage class has been defined as external are as follows:
Storage − Memory.

Default initial value − Zero.

Scope − Global.

Life − As long as the program‟s execution doesn‟t come to an end.

External variables differ from those we have already discussed in that their scope is global,
not local. External variables are declared outside all functions, yet are available to all
functions that care to use them.

Example Program
int x = 21 ;
void main( )
{
extern int y ;
printf ( "\n%d %d", x, y ) ;
getch();
}
int y = 31 ;
Here, x and y both are global variables. Since both of them have been defined outside
all the functions both enjoy external storage class. Note the difference between the following:
extern int y ;
int y = 31 ;
Here the first statement is a declaration, whereas the second is the definition. When
we declare a variable no space is reserved for it, whereas, when we define it space gets
reserved for it in memory. We had to declare y since it is being used in printf( ) before it‟s
definition is encountered. There was no need to declare x since its definition is done before
its usage. Also remember that a variable can be declared several times but can be defined
only once.

Recursion
In C, it is possible for the functions to call themselves.
A function is called „recursive‟ if a statement within the body of a function calls the same
function.
Thus recursion is the process of defining something in terms of itself.

Example Program
Let us now see a simple example of recursion. Suppose we want to calculate the factorial
value of an integer. As we know, the factorial of a number is the product of all the integers
between 1 and that number. For example, 4 factorial is 4 * 3 * 2 * 1. This can also be

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 77

expressed as 4! = 4 * 3! where „!‟ stands for factorial. Thus factorial of a number can be
expressed in the form of itself. Hence this can be programmed using recursion as follows.

//Recursion Example
#include<stdio.h>
#include<conio.h>

int fact(int n); // function prototype

int fact(int n)
{
int f;
if(n==0 || n==1)
return(1);

f=fact(n-1)*n; //fact() is recursive function


return(f);
}

void main()
{
int n,res;
clrscr();
printf("\nEnter the number:");
scanf("%d",&n);
res=fact(n);
printf("\nFactorial=%d",res);
getch();
}

Expected Output
Enter the number:5
Factorial=120

The C Preprocessor Directives #define and #include


You can include various instructions to the compiler in the source code of a C
program. These are called preprocessor directives, and they expand the scope of the
programming environment.

(i) #define
The #define directive defines an identifier and a character sequence (a set of characters) that
will be substituted for the identifier each time it is encountered in the source file. The
identifier is referred to as a macro name and the replacement process as macro replacement.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 78

The general form of the directive is


#define macro-name char-sequence
Notice that there is no semicolon in this statement. There may be any number of spaces
between the identifier and the character sequence, but once the character sequence begins, it
is terminated only by a newline.

Example
#define UPPER 25
This statement is called „macro definition‟ or more commonly, just a „macro‟. What purpose
does it serve? During preprocessing, the preprocessor replaces every occurrence of UPPER in
the program with 25.
Example Program
#define UPPER 25
main( )
{
int i ;
for ( i = 1 ; i <= UPPER ; i++ )
printf ( "\n%d", i ) ;
}
In this program instead of writing 25 in the for loop we are writing it in the form of
UPPER, which has already been defined before main( ) through the statement.

(ii) #include
The second preprocessor directive is file inclusion. This directive causes one file to be
included in another.
The preprocessor command for file inclusion looks like this:
#include "filename"
and it simply causes the entire contents of filename to be inserted into the source code at that
point in the program.

It is common for the files that are to be included to have a .h extension. This
extension stands for „header file‟, possibly because it contains statements which when
included go to the head of your program. The prototypes of all the library functions are
grouped into different categories and then stored in different header files. For example
prototypes of all mathematics related functions are stored in the header file „math.h‟,
prototypes of console input/output functions are stored in the header file „conio.h‟, and so on.

Actually there exist two ways to write #include statement. These are:
#include "filename"
#include <filename>
The meaning of each of these forms is given below:
This command would look for the file goto.c in the current directory
#include "goto.c" as well as the specified list of directories as mentioned in the include
search path that might have been set up.
This command would look for the file goto.c in the specified list of
#include <goto.c>
directories only.
*******
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 79

UNIT-IV
FACTORING METHODS

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 80

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 81

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 82

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 83

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 84

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 85

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 86

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 87

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 88

POINTERS AND ARRAYS

Pointers and addresses


Pointer Variables
As we know that, each variable has two attributes: address and value.
A variable can take any value specified by its data type.
For example, if the variable i is of the integer type, it can take any value permitted in the
range specified by the integer data type.
A pointer to an integer is a variable that can store the address of that integer.

Consider the declaration,

int i = 3 ;

This declaration tells the C compiler to:


(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.
(c) Store the value 3 at this location.
We may represent i‟s location in memory by the following memory map.

We can print this address number through the following program:


void main( )
{
int i = 3 ;
printf ( "\nAddress of i = %u", &i ) ; // “address of” operator
printf ( "\nValue of i = %d", i ) ;
printf(“\nValue of i=%d”,*(&i)); // “value at address” operator
}

Expected Output
Address of i = 65524
Value of i = 3
Value of i=3

Pointer Operators
Look at the first printf( ) statement carefully. ‘&’ used in this statement is C‟s
‘address of’ operator. The expression &i returns the address of the variable i, which in this
case happens to be 65524. Since 65524 represents an address, there is no question of a sign
being associated with it. Hence it is printed out using %u, which is a format specifier for
printing an unsigned integer. We have been using the „&‟ operator all the time in the scanf( )
statement.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 89

The other pointer operator available in C is ‘*’, called ‘value at address’ operator. It gives
the value stored at a particular address. The „value at address‟ operator is also called
‘indirection’ operator.

Pointer
“A Pointer is a variable that can store the address of another variable”.
Syntax
Data-type *variable;

Example
int *i;
In the above declaration, „*‟ indicates that „i‟ is a pointer variable.

Example Program
//Program to show the use of pointer
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,*ptr;
clrscr();
ptr=&a; // address of a is stored in ptr
printf("\nAddress of a is %u",ptr); // displaying the address of a
printf("\nValue of a is %d",*ptr); // displaying the value of a
getch();
}

Memory Representation
a ptr

10 65524

Address 65524 65522

The expression &a gives the address of the variable a. This address can be collected in a
variable, by saying,
ptr = &a ;
But remember that ptr is not an ordinary variable like any other integer variable. It is a
variable that contains the address of other variable (a in this case). Since ptr is a variable the
compiler must provide it space in the memory.

Expected Output
Address of a is 65524
Value of a is 10

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 90

Pointers to Functions
 A particularly confusing yet powerful feature of C is the function pointer.
 A function has a physical location in memory that can be assigned to a pointer.
 This address is the entry point of the function and it is the address used when the
function is called.
 Once a pointer points to a function, the function can be called through that pointer.
 Function pointers also allow functions to be passed as arguments to other functions.
 “A pointer to function is a variable that can store the address of functions in c
language”.
 Along with storing the address of a variable, a pointer has the ability to store the
address of functions that are used in the program.

Example Programs
(1)
//Pointer to built in function
#include<stdio.h>
#include<conio.h>
void main()
{
int (*ptr)(); // declaration of a pointer to function variable
ptr=&clrscr;
(*ptr)();
printf("\nAddress of clrscr()=%u",ptr);
getch();
}
Expected Output
Address of clrscr()=2813

Pointer Arithmetic
Like normal variables, pointers can also be used to perform various arithmetic operations like
addition, subtraction etc.
//Program to show the use Arithmetic operations on pointers

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,*res,*ptr1,*ptr2;
clrscr();

printf("\nEnter any two numbers:");


scanf("%d%d",&a,&b);
ptr1=&a;
ptr2=&b;

*res=*ptr1+*ptr2; // addition

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 91

printf("\nSum=%d",*res);

*res=*ptr1-*ptr2; // subtraction
printf("\nDifference=%d",*res);

*res=*ptr1**ptr2; // multiplication
printf("\nProduct=%d",*res);

*res=*ptr1/(*ptr2); // division
printf("\nDivision=%d",*res);

*res=*ptr1%*ptr2; // mod
printf("\nRemainder=%d",*res);
getch();
}
Expected Output
Enter any two numbers:
20
10

Sum=30
Difference=10
Product=200
Division=2
Remainder=0

Pointers and Arrays


There is a close relationship between pointers and arrays.
Consider this program fragment:
char str[80], *p1;
p1 = str;
Here, p1 has been set to the address of the first array element in str. To access the fifth
element in str, you could write
str[4]
or
*(p1+4)

Both statements will return the fifth element. Remember, arrays start at 0. To access the fifth
element, you must use 4 to index str. You also add 4 to the pointer p1 to access the fifth
element because p1 currently points to the first element of str. (Recall that an array name
without an index returns the starting address of the array, which is the address of the first
element.)

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 92

Example Program

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 93

Pointer to Pointer
You can have a pointer point to another pointer that points to the target value. This situation
is called multiple indirection, or pointers to pointers. Pointers to pointers can be confusing.
Figure 5-3 helps clarify the concept of multiple indirection. As you can see, the value of a
normal pointer is the address of the object that contains the desired value. In the case of a
pointer to a pointer, the first pointer contains the address of the second pointer, which points
to the object that contains the desired value.

Figure 5-3
Single and multiple indirection

“A pointer to pointer is a variable that can store the address of another pointer
variable.”
Example Program
//pointer to pointer
void main()
{
int a=10,*ptr1,*ptr2;
clrscr();
ptr1=&a;
printf("\nAddress of a is %u",ptr1);
printf("\nValue of a is %d",*ptr1);
ptr2=&ptr1; // a ponter ptr2 storing the address of another pointer ptr1
printf("\nAddress of ptr1 is %u",ptr2);
printf("\nValue of ptr1 is %u",*ptr2);
getch();
}

Memory Representation
a ptr1 ptr2

10 65524 65522

Address 65524 65522 65520


Expected Output
Address of a is 65524
Value of a is 10
Address of ptr1 is 65522
Value of ptr1 is 65524

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 94

Arrays
“An array is collection of similar elements that are stored in sequential memory locations.”
 An ordinary variable can hold only one value at a time where as an array can store
multiple values of same type.
 An array is a collection of variables of the same type that are referred to through a
common name.
 A specific element in an array is accessed by an index. In C, all arrays consist of
contiguous memory locations.
 The lowest address corresponds to the first element and the highest address to the last
element.
 Arrays can have from one to several dimensions.
 The most common array is the string, which is simply an array of characters
terminated by a null.
Array Initialization methods

Single Dimensional Arrays


The general form for declaring a single-dimension array is
type var_name[size];

Like other variables, arrays must be explicitly declared so that the compiler can
allocate space for them in memory. Here, type declares the base type of the array, which is
the type of each element in the array, and size defines how many elements the array will hold.
For example, to declare a 100- element array called balance of type float, use this statement:

float balance[100];

Example
int a[5];
a

a[0] a[1] a[2] a[3] a[4]

65516 65518 65520 65522 65524

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 95

 Here, int specifies the type of the variable, just as it does with ordinary variables and
„a‟ specifies the name of the variable.
 The [5] however is new. The number 5 tells how many elements of the type int will
be in our array. This number is often called the „dimension‟ of the array.
 The bracket ( [ ] ) tells the compiler that we are dealing with an array.
 a[0] refers to the first element in the array whereas the whole number 65516 is its
address in memory.

Array Initialization
 So far we have used arrays that did not have any values in them to begin with.
 We managed to store values in them during program execution.
 Let us now see how to initialize an array while declaring it.
Example

int a[5] ={ 2, 4, 6,10, 12 };


or
int a[]={ 2, 4, 6,10, 12 };
a
a[0] a[1] a[2] a[3] a[4]
2 4 6 8 10
65516 65518 65520 65522 65524

Array elements are referred to using subscript; the lowest subscript is always 0 and
the highest subscript is (size –1). If you refer to an array element by using an out-of-range
subscript, you will get an error. You can refer to any element as a[0], a[1], a[2], etc

Thus, an array is a collection of similar elements. These similar elements could be all
ints, or all floats, or all chars, etc. Usually, the array of characters is called a „string‟,
whereas an array of ints or floats is called simply an array. Remember that all elements of
any given array must be of the same type. i.e. we cannot have an array of 10 numbers, of
which 5 are ints and 5 are floats.

Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={2,4,6,8,10};
clrscr();
printf("\nFirst element=%d",a[0]);
printf("\nFifth element=%d",a[4]);
getch();
}

Expected Output
First element=2
Fifth element=10
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 96

Multi Dimensional Arrays


Two dimensional arrays
Two dimensional arrays are often expressed and analyzed as
matrix of rows and columns.

Declaration & Initialization:


Syntax:
Data-type array-name[row-size][column-size]={ {row1 elements},{row2 elements},…};

Number of elements in array= (row-size * column size)


Example
int a[3][2]={{2,4}, {6,8}, {10,12}};
Column Index

Row Index

 First element of the array is referred as a[0][0]


 Sixth element is referred as a[2][1].
 Total number of elements in the above array is 6 i.e. (3*2=6).
 The array arrangement shown in matrix form is only conceptually true.
 This is because memory doesn‟t contain rows and columns.
 In memory whether it is a one-dimensional or a two-dimensional array the array
elements are stored in one continuous chain.

The arrangement of array elements of a two-dimensional array in memory is shown below:

Memory Representation:
a[0][0] a[0][1] a[1][0] a[1][1] a[2][0] a[0][1]
2 4 6 8 10 12
65516 65518 65520 65522 65524 65526
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][2]={{2,4},{6,8},{10,12}},i,j;
clrscr();
printf("The array elements are");
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 97

for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf("\n%d",a[i][j]);
}
}
getch();
}
Expected Output
The array elements are
2
4
6
8
10
12

Command line arguments


 Sometimes it is useful to pass information into a program when you run it.
 Generally, you pass information into the main( ) function via command line
arguments.
 A command line argument is the information that follows the program's name on the
command line of the operating system.
 When main is called, it is called with two arguments.
 The first (conventionally called argc, for argument count) is the number of command-
line arguments the program was invoked with.
 The second (argv, for argument vector) is a pointer to an array of character strings that
contain the arguments, one per string.
For example, when you compile a program, you might type something like the following
after the command prompt,
C:\TC>sum 10 20

Example Program
void main(int argc,char *arg[])
{
int a,b,c;
clrscr();
a=atoi(arg[1]); // atoi() converts string to number
b=atoi(arg[2]);
c=a+b;
printf("\nSum=%d",c);
getch();
}
Expected Output
C:\TC>sum 10 20
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 98

Sum=30
Number of arguments=3

Explanation
In the above output, the three arguments are sum, 10 and 20.
By default, the argument “sum” is stored in arg[0] whereas 10 and 20 are stored in arg[1],
arg[2] respectively.
The argument in the main i.e argc counts the number of arguments.

Complicated Declarations
Most of the times declarations are simple to read, but it is hard to read some declarations
which involve pointer to functions. For example, consider the following declaration from
“signal.h”.

void (*bsd_signal(int, void (*)(int)))(int);

Let us see the steps to read complicated declarations.


1) Convert C declaration to postfix format and read from right to left.

2) To convert expression to postfix, start from innermost parenthesis, If innermost parenthesis


is not present then start from declarations name and go right first. When first ending
parenthesis encounters then go left. Once whole parenthesis is parsed then come out from
parenthesis.

3) Continue until complete declaration has been parsed.

Example
int (*fp) ();

Let us convert above expression to postfix format.


 For the above example, there is no innermost parenthesis, that‟s why, we will print
declaration name i.e. “fp”.
 Next step is, go to right side of expression, but there is nothing on right side of “fp” to
parse, that‟s why go to left side.
 On left side we found “*”, now print “*” and come out of parenthesis. We will get
postfix expression as below.

fp * () int

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 99

ARRAY TECHNIQUES

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 100

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 101

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 102

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 103

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 104

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 105

*******

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 106

UNIT-V
SORTING AND SEARCHING
 Sorting refers to ordering data in an increasing or decreasing fashion according to
some linear relationship among the data items.
 Searching is a process of locating a particular element present in a given set of
elements. The element may be a record, a table, or a file.
 Searching Algorithms are designed to check for an element or retrieve an element
from any data structure where it is stored.
Based on the type of search operation, these algorithms are generally classified into two
categories:
1. Linear Search
Linear search is a very simple search algorithm. In this type of search, a sequential search
is made over all items one by one. Every item is checked and if a match is found then that
particular item is returned, otherwise the search continues till the end of the data
collection.

2. Binary Search
Binary search is a fast search algorithm. This search algorithm works on the principle of
divide and conquer. For this algorithm to work properly, the data collection should be in
the sorted form.

Sorting by selection
 Selection sort is a simple sorting algorithm.
 This sorting algorithm is an in-place comparison-based algorithm in which the list is
divided into two parts, the sorted part at the left end and the unsorted part at the right
end.
 Initially, the sorted part is empty and the unsorted part is the entire list.
 The smallest element is selected from the unsorted array and swapped with the
leftmost element, and that element becomes a part of the sorted array.
 This process continues moving unsorted array boundary by one element to the right.
 This algorithm is not suitable for large data sets.

How Selection Sort Works?


Consider the following depicted array as an example.

For the first position in the sorted list, the whole list is scanned sequentially. The first
position where 14 is stored presently, we search the whole list and find that 10 is the lowest
value.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 107

So we replace 14 with 10. After one iteration 10, which happens to be the minimum value in
the list, appears in the first position of the sorted list.

For the second position, where 33 is residing, we start scanning the rest of the list in a linear
manner.

We find that 14 is the second lowest value in the list and it should appear at the second
place. We swap these values.

After two iterations, two least values are positioned at the beginning in a sorted manner.

The same process is applied to the rest of the items in the array.
Following is a pictorial depiction of the entire sorting process −

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 108

Bubble sort or Exchange sort


 Bubble sort is a simple sorting algorithm.
 This sorting algorithm is comparison-based algorithm in which each pair of adjacent
elements is compared and the elements are swapped if they are not in order.
 This algorithm is not suitable for large data sets

How Bubble Sort Works?


We take an unsorted array for our example. Bubble sort takes Ο(n2) time so we're keeping it
short and precise.

Bubble sort starts with very first two elements, comparing them to check which one is
greater.

In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we
compare 33 with 27.

We find that 27 is smaller than 33 and these two values must be swapped.

The new array should look like this −

Next we compare 33 and 35. We find that both are in already sorted positions.

Then we move to the next two values, 35 and 10.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 109

We know then that 10 is smaller 35. Hence they are not sorted.

We swap these values. We find that we have reached the end of the array. After one
iteration, the array should look like this −

To be precise, we are now showing how an array should look like after each iteration. After
the second iteration, it should look like this −

Notice that after each iteration, at least one value moves at the end.

And when there's no swap required, bubble sorts learns that an array is completely sorted.

Insertion Sort
 This is an in-place comparison-based sorting algorithm.
 Here, a sub-list is maintained which is always sorted.
 For example, the lower part of an array is maintained to be sorted.
 An element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate
place and then it has to be inserted there.
 Hence the name, insertion sort.
 The array is searched sequentially and unsorted items are moved and inserted into the
sorted sub-list (in the same array).
 This algorithm is not suitable for large data sets.

How Insertion Sort Works?

We take an unsorted array for our example.

Insertion sort compares the first two elements.


Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 110

It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list.

Insertion sort moves ahead and compares 33 with 27.

And finds that 33 is not in the correct position.

It swaps 33 with 27. It also checks with all the elements of sorted sub-list. Here we see that
the sorted sub-list has only one element 14, and 27 is greater than 14. Hence, the sorted sub-
list remains sorted after swapping.

By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10.

These values are not in a sorted order.

So we swap them.

However, swapping makes 27 and 10 unsorted.

Hence, we swap them too.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 111

Again we find 14 and 10 in an unsorted order.

We swap them again. By the end of third iteration, we have a sorted sub-list of 4 items.

This process goes on until all the unsorted values are covered in a sorted sub-list.

Sorting by Partitioning
 Quick sort is a highly efficient sorting algorithm and is based on partitioning of array
of data into smaller arrays.
 A large array is partitioned into two arrays one of which holds values smaller than the
specified value, say pivot, based on which the partition is made and another array
holds values greater than the pivot value.
 Quick sort partitions an array and then calls itself recursively twice to sort the two
resulting subarrays.
 This algorithm is quite efficient for large-sized data sets.

Partition in Quick Sort


Following animated representation explains how to find the pivot value in an array.

The pivot value divides the list into two parts. And recursively, we find the pivot for each
sub-lists until all lists contains only one element.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 112

Binary Search
 Binary search looks for a particular item by comparing the middle most item of the
collection.
 If a match occurs, then the index of item is returned.
 If the middle item is greater than the item, then the item is searched in the sub-array to
the left of the middle item.
 Otherwise, the item is searched for in the sub-array to the right of the middle item.
 This process continues on the sub-array as well until the size of the subarray reduces
to zero.

How Binary Search Works?


For a binary search to work, it is mandatory for the target array to be sorted. We shall learn
the process of binary search with a pictorial example. The following is our sorted array and
let us assume that we need to search the location of value 31 using binary search.

First, we shall determine half of the array by using this formula −


mid = low + (high - low) / 2
Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.

Now we compare the value stored at location 4, with the value being searched, i.e. 31. We
find that the value at location 4 is 27, which is not a match. As the value is greater than 27
and we have a sorted array, so we also know that the target value must be in the upper
portion of the array.

We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 113

The value stored at location 7 is not a match, rather it is more than what we are looking for.
So, the value must be in the lower part from this location.

Hence, we calculate the mid again. This time it is 5.

We compare the value stored at location 5 with our target value. We find that it is a match.

We conclude that the target value 31 is stored at location 5.


Binary search halves the searchable items and thus reduces the count of comparisons to be
made to very less numbers.

STRUCTURES
We have seen earlier how ordinary variables can hold one piece of information and
how arrays can hold a number of pieces of information of the same data type. These two data
types can handle a great variety of situations. But quite often we deal with entities that are
collection of dissimilar data types.

For example, suppose you want to store data about a book.


You might want to store its name (a string), its price (a float) and number of pages in it (an
int). If data about say 3 such books is to be stored, then we can follow two approaches:

(a) Construct individual arrays, one for storing names, another for storing prices and still
another for storing number of pages.
(b) Use a structure variable.

In the first approach, the program becomes more difficult to handle as the number of
items relating to the book go on increasing. For example, we would be required to use a
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 114

number of arrays, if we also decide to store name of the publisher, date of purchase of book,
etc. To solve this problem, C provides a special data type—the structure.

Structure Definition
 A structure contains a number of data types grouped together.
 These data types may or may not be of the same type.
 Unlike arrays which can store elements of same data type, a structure can hold data of
different data types.

Declaring a Structure
The general form of a structure declaration statement is given below:

Syntax
struct <structure name>
{
structure element 1 ;
structure element 2 ;
structure element 3 ;
......
......
};

Example
struct book
{
char name ;
float price ;
int pages ;
};

The above statement defines a new data type called struct book. Each variable of this
data type will consist of a character variable called name, a float variable called price and an
integer variable called pages.
Once the new structure data type has been defined one or more variables can be
declared to be of that type. For example the variables b1, b2, b3 can be declared to be of the
type struct book, as,

struct book b1, b2, b3 ;

This statement sets aside space in memory. It makes available space to hold all the
elements in the structure—in this case, 7 bytes—one for name, four for price and two for
pages. These bytes are always in adjacent memory locations.
If we so desire, we can combine the declaration of the structure type and the structure
variables in one statement.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 115

For example,
struct book
{
char name ;
float price ;
int pages ;
};
struct book b1, b2, b3 ;

(or)

struct book
{
char name ;
float price ;
int pages ;
} b1, b2, b3 ;
Important points about structure declaration
 The closing brace in the structure type declaration must be followed by a semicolon.
 It is important to understand that a structure type declaration does not tell the compiler
to reserve any space in memory. All a structure declaration does is, it defines the
„form‟ of the structure.
 Usually structure type declaration appears at the top of the source code file, before
any variables or functions are defined. In very large programs they are usually put in a
separate header file, and the file is included (using the preprocessor directive
#include) in whichever program we want to use this structure type.

Initialization of structures
Like primary variables and arrays, structure variables can also be initialized where they are
declared. The format used is quite similar to that used to initiate arrays.

struct book
{
char name[10] ;
float price ;
int pages ;
};
struct book b1 = { "Basic", 130.00, 550 } ;
struct book b2 = { "Physics", 150.80, 800 } ;

Accessing Structure Elements


 Having declared the structure type and the structure variables, let us see how the
elements of the structure can be accessed.
 In arrays we can access individual elements of an array using a subscript.
 Structures use a different scheme. They use a dot (.) operator.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 116

 So to refer to pages of the structure defined in our sample program we have to use,
b1.pages
Similarly, to refer to price we would use,
b1.price

Note that before the dot there must always be a structure variable and after the dot there must
always be a structure element.

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

void main()
{
struct book
{
char name[20];
float price;
int pages;
};
struct book b1={"C Language",275.50,450}; // Initialization of structure variable
clrscr();
printf("\nBook Name=%s",b1.name);
printf("\nPrice=%.2f",b1.price);
printf("\nPages=%d",b1.pages);
getch();
}
Expected Output
Book Name=C Language
Price=275.50
Pages=450

How Structure Elements are Stored


Whatever be the elements of a structure, they are always stored in contiguous memory locations.
The following program would illustrate this:
main()
{
struct book
{
char name ;
float price ;
int pages ;
};
struct book b1 = { 'B', 130.00, 550 } ;
printf ( "\nAddress of name = %u", &b1.name ) ;
printf ( "\nAddress of price = %u", &b1.price ) ;
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 117

printf ( "\nAddress of pages = %u", &b1.pages ) ;


getch();
}
Memory Representation
Actually the structure elements are stored in memory as shown below

Expected Output
Address of name = 65518
Address of price = 65519
Address of pages = 65523
Example Program
void main()
{
struct book
{
char name[20];
float price;
int page;
}b1;
clrscr();

printf("\nEnter the name, price, pages of book\n");


scanf("%s%f%d",&b1.name,&b1.price,&b1.page);

printf("\nBook Name=%s",b1.name);
printf("\nPrice=%.2f",b1.price);
printf("\nPages=%d",b1.page);

getch();
}
Expected Output
Enter the name, price, pages of book
CP
275.50
370

Book Name=CP
Price=275.50
Pages=370

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 118

Arrays of Structures
 If we want to store data of 100 books we would be required to use 100 different
structure variables from b1 to b100, which is definitely not very convenient.
 A better approach would be to use an array of structures.
 The syntax we use to reference each element of the array b is similar to the syntax
used for arrays of ints and chars.
 For example, we refer to zeroth book‟s price as b[0].price. Similarly, we refer first
book‟s pages as b[1].pages.

Example Program
//Array of structures
struct student
{
int rno;
char name[20];
};

void main()
{
struct student s[2]={{25,"Ritchie"},{20,"Babbage"}}; // structure array initialization
int i;
clrscr();

printf("\n***Students Details***");
for(i=0;i<2;i++)
{
printf("\nRoll no=%d \nName=%s",s[i].rno,s[i].name);
printf("\n-----------------\n");
getch();
}

Expected Output
***Students Details***
Roll no=25
Name=Ritchie
-----------------

Roll no=20
Name=Babbage
-----------------

Passing Structures to Functions


Like an ordinary variable, a structure variable can also be passed to a function.
The following are the three different ways of passing structure arguments to functions.

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 119

(a)Passing individual structure elements to a function


Example Program
//to pass an individual structure element
void display(char *n,char *a,int p); // function prototype

void main()
{
struct book
{
char name[20];
char author[20];
int price;
};
struct book b={"Computer","Ateeq",250};
clrscr();
display(b.name,b.author,b.price); // passing individual structure elements to display()
getch();
}
void display(char *n,char *a,int p)
{
printf("\nBook Name:%s \nAuthor:%s \nPrice:%d",n,a,p);
}
Expected Output
Book Name:Computer
Author:Ateeq
Price:250

In the above program, we are passing the base addresses of the arrays name and
author, and the value stored in price.
Thus, this is a mixed call—a call by reference as well as a call by value.

(b) Passing entire structure to a function


It can be immediately realized that to pass individual elements would become more
tedious as the number of structure elements go on increasing.
A better way would be to pass the entire structure variable at a time.

Example Program
//to pass an entire structure
void display(); // function prototype

struct book // structure named “book”


{
char name[20];
char author[20];
int price;
};
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 120

void main()
{
struct book b={"Computer","Ateeq",200};
clrscr();
display(b); // passing entire structure variable „b‟
getch();
}
void display(struct book b1)
{
printf("\nName=%s \nAuthor=%s \nPrice=%d",b1.name,b1.author,b1.price);
}
Expected Output
Book Name:Computer
Author:Ateeq
Price:250

(c) Passing address of structure to a function


//to pass the address of structure
Like variables, the address of structure variable can be passed to a function.

Example Program
void display(); // function prototype
struct book // structure definition outside the main()
{
char name[20];
char author[20];
int price;
};

void main()
{
struct book b={"Computer","Ateeq",200};
clrscr();
display(&b); // passing address of structure variable „b‟ to display()
getch();
}
void display(struct book *b1)
{
printf("\nName=%s \nAuthor=%s \nPrice=%d",b1->name,b1->author,b1->price);
}
Expected Output
Book Name:Computer
Author:Ateeq
Price:250

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 121

Pointers to structures
The way we can have a pointer pointing to an int, or a pointer pointing to a char, similarly
we can have a pointer pointing to a struct.
Such pointers are known as „structure pointers‟.
//Pointer to structure
void main()
{
struct student
{
char name[20];
int rno;
float per;
};
struct student s={"Taufeeq",25,71.00};
struct student *ptr;
ptr=&s; // pointer “ptr” pointing to structure variable „s‟

printf("\nName:%s \nRollno:%d \nPercentage:%.2f",ptr->name,ptr->rno,ptr->per);


getch();
}
Expected Output
Name:Taufeeq
Rollno:25
Percentage:71.00

 We can‟t use ptr.name or ptr.rno because ptr is not a structure variable but a pointer
to a structure, and the dot operator requires a structure variable on its left.
 In such cases C provides an operator ->, called an arrow operator to refer to the
structure elements.
 Remember that on the left hand side of the ‘.’ structure operator, there must always be
a structure variable, whereas on the left hand side of the „->’ operator there must
always be a pointer to a structure.

Memory Representation
b1.name b1.rno b1.per

Taufeeq 25 71.00

Address-65472 65492 65494


ptr

65472

65498

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 122

Self Referential structures


Self Referential structures are those structures that have one or more pointers which point to
the same type of structure, as their member.

Example
struct node {
int data1;
char data2;
struct node* link;
};

int main()
{
struct node ob;
return 0;
}
In the above example „link‟ is a pointer to a structure of type „node‟.
Hence, the structure „node‟ is a self-referential structure with „link‟ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before
accessing, as by default it contains garbage value.

Table Lookup
 A lookup table, also known as LUT, is an array used in computer programming that
holds values which would otherwise need to be calculated.
 The table may be manually populated when the program is written, or the program
may populate the table with values as it calculates them.
 When the values are needed later, the program can look them up,
saving CPU resources.

Typedef
“typedef provides the facility of providing alternative names for the basic data types in C
such as int, pointers and structures”.
A program that carries out so many tasks would be very big in size. In such a program if we
start using the normal integer data type to represent variables that hold different entities we
would soon lose track of what that integer value actually represents. This can be overcome by
using typdef.

Example Programs
(1)
//using typdef with simple data types
void main()
{
typedef int integer; // using integer instead of int
integer a;

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 123

a=10;
clrscr();
printf("\na=%d",a);
getch();
}

Expected Output
a=10

(2)
//Using typedef with pointers
void main()
{
int a=10;
typedef int* integer;
integer ptr; // ptr is a pointer to int
clrscr();
ptr=&a;
printf("\nAddress of a is %u",ptr);
printf("\nValue of a is %d",*ptr);
getch();
}

Expected Output
Address of a is 65524
Value of a is 10

(3)
//using typedef with structure
struct student
{
int rno;
char name[15];
};
void main()
{
typedef struct student profile;
profile s={25,"Ahmed"};
clrscr();
printf("\nRollno=%d \nName=%s",s.rno,s.name);
getch();
}

Expected Output
Rollno=25
Name=Ahmed
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 124

Bit Fields
 Bit field provides exact amount of bits required for storage of values.
 If the variable value is 1 or 0, we need a single bit to store it.
 Similarly, if the variable value is between 0 and 3, the two bits are sufficient for
storing these values.
 In the same what, if the variable value is between 0 and 7 the three bits are enough to
hold the values.
 To hold the information we use variables.
 The variables occupy a minimum of one byte for char and two bytes for integer.
 Instead of using complete integer if bits are used, space of memory can be saved.

Syntax
struct numbers
{
unsigned int first:2;
unsigned int second:3;
};
The colon(:) in the above declaration tells the compiler that bit
fields are used in the structure and the number after it indicates how many bits are required to
allot to the field.

Example Program
struct numbers
{
unsigned int first:2;
unsigned int second:3;
};
void main()
{
struct numbers n;
clrscr();
n.first=3;
n.second=7;
printf("\nFirst Number:%d",n.first);
printf("\nSecond Number:%d",n.second);
getch();
}
Expected Output
First Number:3
Second Number:7

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 125

Unions
 Like structure, a union can hold data belonging to different data types but it hold only
one object at a time.
 In the structure each member has its own memory locations whereas, members of
unions have same memory locations.
 The union requires bytes that are equal to the number of bytes required for the largest
member.
 For example, if the union contains char, integer and float then the number of bytes
reserved in the memory is 4 bytes (i.e. the size of float).
 Unlike structure members which can be initialized all at the same time, only one
union member should be initialized at a time.

Syntax
The syntax of union is similar to the structure which is shown below

union <union_ name>


{
union element 1 ;
union element 2 ;
union element 3 ;
......
......
};
Let us now observe the difference between union and structure by using the
following program.

Example Program
//To show the difference between structure & union
struct student1 // structure
{
int rno;
char grade;
};
union student2 //union
{
int rno;
char grade;
};

void main()
{
struct student1 s={25,'A'}; // initialization of structure members at a time
union student2 u;
clrscr();

printf("\nRollno=%d",s.rno);
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 126

printf("\nGrade=%c",s.grade);

u.rno=30; // initialization of union member 1


printf("\nRollno=%d",u.rno);
u.grade='B'; // initialization of union member 2
printf("\nGrade=%c",u.grade);

printf("\nSize of Structure=%d bytes",sizeof(s)); // displaying size of structure


printf("\nSize of Union=%d bytes",sizeof(u)); // displaying size of union
getch();
}

Example Program
Rollno=25
Grade=A
Rollno=50
Grade=B
Size of Structure=3 Bytes
Size of Union=2 Bytes
In the above, the size of structure is sum of the sizes of all its
members i.e. int & char which is (2+1)=3 bytes whereas the size of union is the size of the
member which belongs to largest data type i.e. int which is of 2 bytes.

SOME OTHER FEATURES


Variable-length argument lists
You can specify a function that has a variable number of parameters. The most
common example is printf( ). To tell the compiler that an unknown number of arguments
will be passed to a function, you must end the declaration of its parameters using three
periods.
For example, this prototype specifies that func( ) will have at least two integer
parameters and an unknown number (including 0) of parameters after that:
int func(int a, int b, . . .);
This form of declaration is also used by a function's definition.
Any function that uses a variable number of parameters must have at least one actual
parameter.
For example, this is incorrect:
int func(. . .); /* illegal */

Formatted input-Scanf
[Refer UNIT-III, Page No.]

File access
In C, a file may be anything from a disk file to a terminal or printer. You associate a
stream with a specific file by performing an open operation. Once a file is open, information
can be exchanged between it and your program. Not all files have the same capabilities. For

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 127

example, a disk file can support random access, while some printers cannot. This brings up an
important point about the C I/O system: All streams are the same, but all files are not.

The File Pointer


 The file pointer is the common thread that unites the C I/O system.
 A file pointer is a pointer to a structure of type FILE. It points to information that
defines various things about the file, including its name, status, and the current
position of the file.
 In essence, the file pointer identifies a specific file and is used by the associated
stream to direct the operation of the I/O functions.
 In order to read or write files, your program needs to use file pointers.
To obtain a file pointer variable, use a statement like this:
FILE *fp;

Opening a File
 The fopen( ) function opens a stream for use and links a file with that stream.
 Then it returns the file pointer associated with that file.
 Most often (and for the rest of this discussion), the file is a disk file.

The fopen( ) function has this prototype,


FILE *fopen(const char *filename, const char *mode);

 where filename is a pointer to a string of characters that make up a valid filename and
may include a path specification.
 The string pointed to by mode determines how the file will be opened.
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 128

 Table 9-2 shows the legal values for mode.


 Strings like ''r+b" may also be represented as "rb+".
 As stated, the fopen( ) function returns a file pointer.
 Your program should never alter the value of this pointer.
 If an error occurs when it is trying to open the file, fopen( ) returns a null pointer.

The following code uses fopen( ) to open a file named TEST for output.
FILE *fp;
fp = fopen("test", "w");

Although the preceding code is technically correct, you will usually see it written like this:
FILE *fp;
if ((fp = fopen("test","w"))==NULL) {
printf(''Cannot open file.\n");
exit(1);
}
This method will detect any error in opening a file, such as a write-protected or a full
disk, before your program attempts to write to it. In general, you will always want to confirm
that fopen( ) succeeded before attempting any other operations on the file.

Closing a File
The fclose( ) function closes a stream that was opened by a call to fopen( ). It writes
any data still remaining in the disk buffer to the file and does a formal operating-system-level
close on the file. Failure to close a stream invites all kinds of trouble, including lost data,
destroyed files, and possible intermittent errors in your program. fclose( ) also frees the file
control block associated with the stream, making it available for reuse. Since there is a limit
to the number of files you can have open at any one time, you may have to close one file
before opening another.
Problem Solving and Programming By: H. Ateeq Ahmed
Department of CSE 129

The fclose( ) function has this prototype,


int fclose(FILE *fp);
where fp is the file pointer returned by the call to fopen( ). A return value of zero
signifies a successful close operation. The function returns EOF if an error occurs. You can
use the standard function ferror( ) (discussed shortly) to determine the precise cause of the
problem. Generally, fclose( ) will fail only when a disk has been prematurely removed from
the drive or there is no more space on the disk.

Line Input and Output


To read and write data types that are longer than 1 byte, the C file system provides
two functions: fread( ) and fwrite( ). These functions allow the reading and writing of blocks
of any type of data.
Their prototypes are
size_t fread(void *buffer, size_t num_bytes, size_t count, FILE *fp);
size_t fwrite(const void *buffer, size_t num_bytes, size_t count, FILE *fp);

Example Program
/* Write some non-character data to a disk file and read it back. */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
double d = 12.23;
int i = 101;
long 1 = 123023L;
if((fp=fopen("test", "wb+"))==NULL) {
printf(''Cannot open file.\n");
exit(1);
}
fwrite(&d, sizeof(double), 1, fp);
fwrite(&i, sizeof(int), 1, fp);
fwrite(&l, sizeof(long), 1, fp);
rewind(fp);
fread(&d, sizeof
(double), 1, fp);
fread(&i, sizeof(int), 1, fp);
fread(&l, sizeof(long), 1, fp);
printf("%f %d %ld", d, i, 1);
fclose(fp);
return 0;
}

Problem Solving and Programming By: H. Ateeq Ahmed


Department of CSE 130

Miscellaneous Functions
 Miscellaneous functions use the address letter M followed by two digits.
 They perform a group of instructions such as coolant on/off, spindle on/off, tool
change, program stop, or program end.
 They are often referred to as machine functions or M-functions.

Miscellaneous functions Description


This function gets the current value of the
getenv() environment variable
This function sets the value for
setenv() environment variable
This function modifies the value for
putenv() environment variable
Displays most recent error that happened
perror() during library function call
Returns random integer number range from
rand() 0 to at least 32767
Suspends the execution of the program for
delay() particular time

*******

Problem Solving and Programming By: H. Ateeq Ahmed

You might also like