Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PPS Notes Unit-I (1) - Merged

Download as pdf or txt
Download as pdf or txt
You are on page 1of 151

UNIT – I

COMPUTER SYSTEM:
 A Computer is an electronic device which performs operations such as accepts the data, stores the data,
manipulates or process the data according to a pre-stored instructions and produces the desired result. All
these tasks are performed at high-speed and accuracy.
 A Computer computes the data (input) supplied to it and generates information (output).
 A Computer is an electronic device which takes the input, processes it, and gives the output according to the
user needs.
 A computer is a system made of two major components: Hardware and software.
Hardware: Hardware of a computer system are the physical components which we can touch and feel.
 Example: Keyboard and Mouse.
 The hardware of a computer system can be classified as:
1. Input Devices (I/P)
2. Processing Devices (CPU)
3. Output Devices (O/P)

1. Input Devices: Input devices are used to enter the data into the computer system.
Example: Keyboard, Mouse, Scanner, Microphone, Camera…etc.
2. Output Devices: Output devices are used to take the information (output) from a computer system.
Example: Monitor (Display or Standard Output), Printer, Speakers…etc.
(If the output is shown on the monitor we call it as softcopy. If it is printed on a paper using the printer, we
call it as hardcopy)
3. Processing Unit (or) Central Processing Unit:
 The CPU is responsible for executing instructions such as arithmetic calculations, comparison between
data, and movement of data inside the system.
 The modern day computers can have one or more CPUs in it.
 The CPU, internal to it will have three different parts: ALU, CU and MU.
o ALU (Arithmetic and Logic Unit): ALU will performs the Arithmetic and Logical Operations
such as +,-,*,/ (Arithmetic Operations) &&, || ( Logical Operations) inside a computer system.
o CU (Control Unit): Every Operation such as storing, computing and retrieving the data should
be governed by the control unit.
o MU (Memory Unit): The Memory unit is used for storing the data. The Memory unit is
classified into two types. They are:
a) Primary Memory
b) Secondary Memory
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
a) Primary Memory (Main Memory): The primary memory also known as main memory is a
place where the programs and data are stored temporarily during processing. The data in primary
memory are erased when the computer is turned off. The following are the two memory types, which
are treated as primary memory.
ROM (Read Only Memory): It represents Read Only Memory that stores data and
instructions even when the computer is turned off. The contents in the ROM can‘t be
modified once if they are written. It is used to store the BIOS information which is helpful in
loading the operating system into the RAM from HDD.
RAM (Random Access Memory): It represents Random Access Memory that stores data
and instructions when the computer is turned on. The contents in the RAM can be modified
any number of times by instructions. It is used to store the programs under execution. The
content in the RAM are volatile, that is when the computer turned off the content of RAM
will be lost.
b) Secondary Memory (Auxiliary Memory): The following are the different kinds of secondary
memories. They can also be called as auxiliary memory. The content of these devices will remain
permanent even when the computer is turned off. The programs and data remain in the secondary
storage, ready for the next time use.
Magnetic Storage: The Magnetic Storage devices store information that can be read, erased
and rewritten a number of times. Example: Floppy Disks, Hard Disks, Magnetic Tapes.
Optical Storage: The optical storage devices that use laser beams to read and write stored
data. Example: CD (Compact Disk), DVD (Digital Versatile Disk).
There are other forms of memory devices like: Cache Memory and CPU Registers.
Cache Memory: These are superfast memory locations and are directly accessible by the CPU. The
content are volatile again. They are maintained in very small amounts as they are very costly.
CPU Registers: There are internal memory location of the CPU. The data inside the CPU is stored
in these registers for processing.

Software: Software is a virtual component of the computer.


 It is the collection of programs (instructions) that tells the hardware, how to do its job.
 The following figure shows the breakdown of computer software.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
System Software:
 It manages the computer resources and provides interface between the hardware and user.
 System software does not serve the user needs directly.
 It is divided into three classes: (a) operating system, (b) system support and (c) system development.

(a) Operating System:


o It provides services like user interface, file and database access.
o Provides interface to communication systems like internet protocols.
o It keeps the system operating in an efficient manner.

(b) System Support Software:


o It provides system utilities and other operating services.
o System utilities include sorting programs and disk format programs.
o Other operating system services are performance statistics and security monitoring to
protect the system and data.

(c) System development Software:


o Includes the language translators to convert programs into machine language for
execution.
o Debugging tools to make sure the programs are error free.
o Computer assisted software engineering (CASE).

Application Software:

 It is directly responsible for solving the user problems.


 It is divided into two classes: (a) general-purpose software and (b) application specific software.

(a) General Purpose software:


o They can be used for more than one application.
o They are called as general purpose because they can be used to solve a variety of user
computing problems.
o Examples: Word processors, database management systems and computer aided design
systems.

(b) Application Specific Software:


o They can be used only for the task for which they are designed.
o They cannot be used for other general tasks.
o Examples: A general ledger system used by accountants and material management
system used by manufacturing organization.
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
Relationship between system and application software

 The following figure shows the relationship between the system software and application software.
 In this figure, each circle represents an interface point.
 The inner core is the computer hardware. The outer most layer represents the user.
 The user uses application software to work with the system. This application software interacts with
operating system, which is a part of system software layer.
 The system software have the direct interaction with the hardware.
 The opening at the bottom of the figure is the path followed by the user to interact directly with
operating system when necessary.

COMPUTER LANGUAGES
 To write a program for a computer the computer language is used.
 The computer languages have changed over the years from machine language to natural language.
 The following summary shows, how computer languages have evolved from machine language to
natural language.
 1940‘s -- Machine Languages
 1950‘s -- Symbolic Languages
 1960‘s -- High Level Languages

Machine Languages:
 In the early days of computers, the only available programming language was machine language.
 The problem with machine language is that, each computer will have its own machine language, which
made up of only 0’s and 1’s.
 The following program will give an idea of how instructions can be written in machine language.
 All instructions in machine language must be streams of 0’s and 1’s, because internal circuits of the
computer system are made of switches, transistors and other electronic devices.
 These devices can be in any one of the two possible states: on or off.
 The off state is represented by 0; the on state is represented by 1.
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
Symbolic Languages
 In 1950s, Admiral Grace Hopper, a mathematician developed the concept of a special program that
convert programs into machine language.
 During these days, programming languages simply mirrored machine languages using symbols, or
mnemonics, to represent the machine language instructions.
 As these languages used special symbols, they were known as symbolic languages.
 The computer does not understand any other languages except its own machine language. Hence there is
a need to translate symbolic languages into machine language.
 A special program called an assembler is used, which translates symbolic languages into machine
languages.
 As symbolic languages are assembled using an assembler into machine languages, they also called as
assembly languages.

High-Level Languages
 Symbolic languages required the programmers to concentrate on the hardware of the computer that they
were using, as these languages are still dependent on the machine.
 Writing program in symbolic languages is very difficult because each instruction has to be coded separately.
 Because of these issues programmers thought that there is a requirement of sophisticated and efficient
programming technique.
 This led to the development of high-level programming languages.
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
 High-Level languages are machine independent (portable). They allow the programmers to concentrate
more on application rather than the computer hardware.
 The programmers also free from remembering the symbols and mnemonics specific to the computer system.
 However like symbolic languages, these languages also be converted to machine language before giving it
to the computer.
 The process of converting high-level languages into machine languages is known as compilation.
 The most widely used high-level language was FORTRAN created by John Backus and IBM team in 1957,
it is still in use in scientific and engineering applications.
 COBOL was also another high-level language used, developed by Admiral Grace Hopper.
 C is also a high-level language used for the development of System software and other application
programs. It was developed by Dennis Ritchie in 1972.

CREATING AND RUNNING PROGRAMS


 Computer hardware will understand program instruction only if they are coded in machine language.
 Programs written in high-level languages like C needs to be converted into machine level language with the
help of a special program known as a compiler.
 The process of compiling and executing a C program is having different steps, as shown in the following
figure.
 Note that these steps are repeated many time during the development to correct errors and make
improvements in the program.
 It is the programmer’s job to write and edit the programs.
 Basically in this process there are four steps:
1. Writing and editing the program.
2. Compiling the programs.
3. Linking the program with required library modules.
4. Executing the program.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
1. Writing and Editing Programs:
 Programmers use text-editors to write programs.
 A text editor helps to enter, change and store characters into programs. A text editor is a general
purpose application which can be used to write letters, create reports or to write programs.
 A more specific text editor can be used to write programs, which included with a compiler. Some of
other features of a text editor are search commands to locate and replace statements, copy and paste
commands to copy or move statements, and formatting commands like tabs to align statement.
 After writing the program the file will be saved to the disk. This will be known as source file and
this will be the input to the compiler.
2. Compiling programs:
o The source file code stored on the disk must be translated into machine language before giving it to
the computer (executing). This is the job of a compiler.
o The C compiler will have two separate programs: (a) the pre-processor and (b) the translator.
(a) Pre-processor:
 It reads the source code line by line and prepares it for translator.
 In the program it scans for special instructions known as pre-processor commands.
 These commands tells the pre-processor to look for special code libraries, make
substitutions in the code.
 The result of the pre-processing is called the translation unit.
(b) Translator:
 The translator actually converts the high-level language code into machine language.
 It reads the translation unit prepared by the pre-processor line by line and write the
resulting object module (machine language instructions) to a separate file.
 These object module is then combined with other precompiled units (hardware related
information) to form the final module in machine language.
 Here even as the final module program is in machine language, it is not ready for
execution. It has to go through two more steps.
3. Linking Programs:
 A C program is made of many functions. Some of them are written by the programmer (known as
user-defined functions) and they are part of the program.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 But some functions known as pre-defined functions (such as input/output functions and
mathematical library functions) the code will exists in library files and must be attached to the
program before execution.
 This is exactly the job of a linker program. The linker assembles all of these functions both pre-
defined and user-defined into the final executable program.

4. Executing programs:
 Once the program has been linked it is ready for execution.
 To execute a program the program has to be loaded into primary memory. The operating system
command ‘run’ can be used to achieve this job.
 Getting the program into the main memory is the function of an operating system program known as
loader. It locates the executable program in secondary memory and loads it to main memory.
 After loading everything into the memory, the program takes the control and starts the execution.
 In today’s integrated development environments (IDEs) these steps are combined under simple
mouse clicks or pull-down menu bars or simple shortcut key combinations.
 In typical program execution, the program takes input either from the user or from a file. After
processing the data, it prepares the output either to the user’s monitor or to a file.
 Once the execution process finishes the operating system removes the program from main memory.

COMPUTING ENVIRONMENTS
 In the early days of computing the only environment available was the mainframe computing environment,
where the mainframe computer is used to satisfy all operations given to it. No sharing of resources from
other computers.
 Later with the advancement of minicomputers and personal computers, many computing environment came
into existence. These computing environments are:
1. Personal Computing Environment
2. Time-Sharing Environment
3. Client-Server Environment
4. Distributed Computing Environment
Personal Computing Environment:
 In 1971, Marcian E. Hoff of Intel has combined all basic elements of the central processing unit onto a
single chip known as microprocessor.
 This was the first computer on a single chip named Intel 4004. It was the grandfather to many of today’s
modern computing processors.
 In personal computing environments, a personal computer (PC) will be used where all of the computer
hardware components are connected together inside a single computer.
 This environment will have the whole computer of its own. The user can perform whichever operation he
want.
 Atypical personal computer is shown in the following.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Time-Sharing Environment:
 In time-sharing environment many users are connected to one or more minicomputers or central
mainframes.
 They use terminals which are non-programmable computers. Terminals are dumb devices.
 In the time-sharing environment, the output devices (such as printers) and auxiliary storage devices (such as
disks) are shared by all of the users.
 Computer labs in colleges and universities are best examples of time sharing environment.
 In time-sharing environment the central computer is responsible for the following duties:
o It must control the shared resources.
o It must manage the shared data and printing.
o It must do the computing.
 Generally in time sharing environments if the terminal count increases, sometimes the central computer will
become so busy, that the users will get frustrated because of the slow response of the computer.
 The following figure shows a general time sharing environment.

Client / Server Environment:


 In this environment the computing splits between a central computer and users’ computer.
 The users basically use personal computers or workstations so that some of the computing responsibility can
be moved to the personal computers.
 In the client / server environment, the users’ micro computers are known as clients. The central computer is
known as a server.
 The server may be a powerful microcomputer, minicomputer or a central mainframe.
 Because the work is now shared the response time is faster, and the users will be more productive.
 A typical client/server environment is shown in the following figure:

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Distributed Computing:
 The distributed computing environment provides a seamless integration of computing functions between
different servers and clients.
 The Internet is responsible for providing this integration.
 For example: Google server uses several computers as servers to provide its services.
 This environment provides a reliable, scalable and highly available network.
 The following figure shows a distributed computing system.

ALGORITHM:
 An algorithm is a step by step process to solve any given computational problem.
 That is an Algorithm refers to a set of rules/instructions that step-by-step define how a work is to be done to
get the expected results.
 The Algorithm is language-independent, i.e. the plain instructions in an algorithm can be written in any
language to get the expected output.
Characteristics / Specifications of Algorithms:
Not all written instructions can be considered as an algorithm. In order to consider the written statements as an
algorithm it must have the following characteristics.

 Input: An algorithm has zero or more inputs, taken from a specified set of objects.
 Output: An algorithm has one or more outputs, which have a specified relation to the inputs.
 Definiteness: Each step must be precisely defined; each instruction is clear and unambiguous.
 Finiteness: The algorithm must always terminate after a finite number of steps.
 Effectiveness: An algorithm must be basic and simple. And it has to give the expected solution to the
problem in a finite number of steps.
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
Example: To cook a new recipe, one reads the instructions/steps and execute them one by one, in the given
sequence. The result can be obtained as a new dish cooked perfectly. Similarly, algorithms help to do a task in
programming to get the expected output.

How to write an algorithm:


 While writing algorithm any intelligible statements can be used, as long as it is understandable by the
concerned parties.
 No need to follow any programming language syntax or notations specifically in the algorithms. There is no
fixed syntax for writing the algorithms.
 Any language can be used to write the algorithms with optional mathematical notations. Ex: English with
mathematical notations.
 An algorithm can be designed to get a solution of a given problem.
 A problem can be solved in more than one ways. Hence, many solution algorithms can be derived for a
single problem.
 Any person with domain knowledge can write the algorithm. As there is need to describe the steps in natural
language.
Example-1:
Problem − Design an algorithm to add, subtract, multiply, divide and to find the reminder of two
numbers and display the result.
Step 1: Start
Step 2: Declare num1, num2 & sum.
Step 3: input num1 and num2.
Step 4: sum=num1+num2
Step 5: print sum
Step 6: Stop

Example 2:
Problem − Design an algorithm to Calculate the Interest of a Bank Deposit.
Step 1: Start
Step 2: declare amount, year, rate and interest.
Step 3: input amount, year, and rate.
Step 4: interest=Amount*Years*Rate/100.
Step 5: print interest.
Step 6: Stop.

Example-3:
Problem − Design an algorithm to determine whether the Temperature is below or above the
freezing Point (32◦F).
Step 1: Start
Step 2: declare temperature.
Step 3: input temperature.
Step 4: if temperature < 32
print “below freezing point”
else
print “above freezing point”
Step 5: Stop

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Example-4:
Problem − Design an algorithm to find the biggest in two numbers.
Step 1: Start
Step 2: Declare num1 and num2.
Step 3: Read num1 and num2.
Step 4:if num1 < num2
print “num1 is big”
else
print “num2 is big”
Step 5: Stop

Example-5:
Problem − Design an algorithm to determine whether a student passed in the exam or not.
Step 1: Start
Step 2: Declare m1, m2, m3, m4, m5, m6 and avg.
Step 3: Read m1, m2, m5, m4, m5 and m6.
Step 4: avg=(m1+m2+m3+m4+m5+m6)/6"
Step 4: if avg < 60
print “FAIL”
else
print “PASS”
Step 5: Stop

Example-6:
Problem − Design an algorithm to find the given number is even or odd.
Step 1: Start
Step 2: Declare num, rem.
Step 3: Read num.
Step 5: if num%2==0
print “num is EVEN”
else
print “num is ODD”
Step 6: Stop
PSEUDO CODE:
 Pseudocode is an informal way of programming description that does not require any strict programming
language syntax.
 Pseudocode is a methodology that allows the programmer to represent the implementation of an algorithm.
 Pseudo codes are used to represent algorithms so that they can be interpreted by programmers irrespective to
their programming background or knowledge.
 Pseudo code (as the name suggest, is a false code) is also programming language independent.
 Pseudo code has no syntax like any of the programming language, it can’t be compiled or interpreted by the
computer.
Advantages of pseudocode –
• Pseudocode can be understandable by the programmers of all programming languages.
• Pseudocode acts as a bridge between the program and the algorithm or flowchart.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
• Pseudocode works as a rough documentation, so the program of one developer can be understood easily
when a pseudo code is written out. In industries, the approach of documentation is essential. And that’s
where a pseudo-code plays a vital role.
• The main goal of a pseudo code is to explain what exactly each line of a program should do, hence making
the code construction phase easier for the programmer.

Example:
C code: Pseudocode:
If(i<10) if i is less than 10
{ increment i value by 1
i++;
}

Example-1:
Problem − Design a pseudocode to add, subtract, multiply, divide and to find the reminder of two
numbers and display the result.
This program will allow the user to add two numbers.
Declare variables num1, num2 and sum.
Read values for num1 and num2.
Add num1 and num2 and assign the result to sum.
sum←num1+num2
print the value of sum on the output screen

Example 2:
Problem − Design a pseudocode to Calculate the Interest of a Bank Deposit.
This program will allow the user the user to calculate the interest for a bank deposit.
Declare variables amount, year, rate and interest.
Read values for amount, year, and rate.
Calculate the interest with formula "interest=Amount*Years*Rate/100.
print the value of interest on the output screen.

Example-3:
Problem − Design a pseudocode to determine whether the Temperature is below or above the freezing
Point (32◦F).
This program will allow the user to determine whether the temperature is below or above the freezing
point.
Declare variable temperature.
Read value for temperature.
if temperature value is lesser than 32, print a message “temperature is below freezing point”.
Otherwise print a message “temperature is above freezing point”.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Example-4:
Problem − Design a pseudocode to find the biggest in two numbers.
This program will allow the user to find the biggest in two numbers.
Declare variables num1 and num2.
Read values for num1 and num2.
if num1 value is greater than num2 value, print a message num1 is big.
else print a message num2 is big.

Example-5:
Problem − Design a pseudocode to determine whether a student passed in the exam or not.
This program will allow the user to determine whether a student passed in the exam or not by considering
6 – different course marks.
Declare variables for courses M1, M2, M5, M4, M5, M6 and grade.
Read values for M1, M2, M5, M4, M5 and M6.
Calculate the average grade with formula "Grade=(M1+M2+M3+M4+M5+M6)/6"
if grade value is greater than 60, print a message PASS.
else print a message FAIL.

Example-6:
Problem − Design a pseudocode to find the given number is even or odd.
This program will allow the user to find the given number is even or odd.
Declare variable num, reminder.
Read value for num.
Calculate the reminder by using a formula reminder=num%2.
if reminder is equal to zero, print a message num is EVEN.
else print a message num is ODD

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
FLOWCHARTING:
 Flowchart is a program design tool in which standard graphical symbols are used to represent the logical
flow of data through a function.
 A flowchart is used to show the logic flow of a program. It is a pictorial representation of an algorithm.
 The primary purpose of a flowchart is to show the design of an algorithm. Graphical symbols are used to
show the design.
 Flowchart can be used to design either the complete program or the part of the program, such parts can be
called as functions in c language.
 When using flowcharts programmers are free from programming language syntax, so they can focus more
on problem to be solved.
 To design a flowchart the following symbols can be used:
1. Auxiliary Symbols
2. Primary Symbols

1. Auxiliary Symbols:
 These symbols enhance the readability or functionality of the flowchart. They do not show any
instructions or commands.
 These symbols are shown in the following figure: (a) Terminal (b) Flow Lines and (c) Connectors

(a) Terminal:
 The Oval symbol is used as a terminal.
 It is used to show the beginning and ending of an algorithm.
 To show the beginning the START is used inside the oval, and to show the ending the
word STOP or RETURN is used inside the oval.
 The basic rule of structured programming is every algorithm should have only one
entry point (START terminal) and one exit point (STOP/RETURN terminal).
(b) Flow Lines:
 Flow lines are used to connect different symbols of a flowchart. They also shows the
order or sequence of the symbols.
 Every symbol in a flowchart will have some entering and some exiting lines.
 For example the START oval will have only one exiting line and the STOP oval will
have only one entering line.
(c) Connectors: A connector symbol, a circle with a number in it is used in two situations.
i. When the end of the page is reached but the flowchart is finished: Here a
connector is used at the bottom of the page to show that the flow continues at the
top of the next page. Refer the following figure (a).

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
ii. If the logic details do not fit into the main flowchart: Two sets of connectors are
used to handle this situation. The first set connects the entry point of the separated
flowchart, and the second set connects the end point. Refer the following figure
(b).

2. Primary Symbol:
 The primary symbols are used to show the instructions or actions needed to solve the problem.
 These category of symbols used to show: (a) Sequence (b) Decision / Condition (Selection
Statements) and (c) Repetition (Looping Statement).
(a) Sequence
 Sequence symbols are used to represent actions that must be performed in a linear order.
 To this symbols the flow must enter at the top of the symbol, and flow exit at the bottom of the
symbol.
 They do not allow any flow change.
 There are four different types of sequence symbols:
i. Null statement
ii. Assignment statement
iii. Input / Output statement
iv. Module call statement
v. Compound statement
I. Null statement:
o A null statement is a sequence statement, as it cannot change the flow direction.
o There is no symbol defined to represent a null statement. It is simply a flow line.

II. Assignment statement:


o A rectangle symbol is used for assignment statements.
o This symbol is used whenever there is an assignment operation needs to be shown inside the
flowchart.
o Assignment operator is shown using a left-pointing arrow. Right side to the arrow expression and
left side the variable will be shown.

III. Input / Output Statement:


o A parallelogram symbol is used for input / output statements.
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
o Reading input from the keyboard and writing output on the output screen (console) can be
represented using input / output statements.

IV. Module-Call Statement:


o A rectangle with two vertical bars inside is used for module call.
o Every time when there is a module call in the flowchart, there must be another flowchart with
same module name.
o In separated flowchart the start oval contains the name of the module, and the last oval contains
the RETURN. It indicates that the separated flowchart is not the end of the program.

V. Compound Statement:
o A broken-line rectangle is used for compound statement.
o All statements that makes the compound statement are encapsulated inside a broken-line
rectangle.
o In C-Programming a compound statement represents a block of code, which is enclosed in curly
brackets.

(b) Selection Statements:


o Unlike the sequence statements, conditional statements can cause the flow of the program to change.
o They allow the execution of selected statements and skipping of other statements.
o There are two types of selection statements:
i. Two-way selection statements.
ii. Multi-way selection statements.
I. Two-way selection statements:
o The diamond symbol is used as a two-way selection symbol.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
o Generally this symbol is used to represent if-else statement in any programming language. The
true condition logic is shown right side of the diamond, and false condition logic is shown left
side. If any of the logic doesn’t exist, then a null statement can be used.
o The separated logic will join at a single point with the help of a connector.
o In each branch only one statement is allowed, if there are more than one statement a compound
statement will be used.

Example: The following algorithm reads an integer. If the integer’s value is greater than 10, subtract
10 and writes the result. It the value is lesser than 10, it does nothing.

II. Multiway Selection Statement:


o In C programming the multiway selection statement is a Switch statement.
o If a language does not support switch statement the same can be implemented using if-else
statement or else-if ladder.
o A multiway statement can have as many braches as needed. In each branch one and only one
statement is allowed. If multiple statements are there a compound statement can be used.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Example: Design a flowchart for a program that reads one character representing a letter grade and
prints the corresponding grade point average (GPA).

(c) Looping Statements:


C has three looping statement:
i. for loop
ii. while loop
iii. do – while loop
I. for loop:
o for loop is a counter controlled loop.
o It has a complex statement which has 3-parts. Any of which can be null.
(1) Loop initialization - which normally sets the counter for the loop.
(2) Test condition – which is used to test the condition
(3) Update – which increments or decrements the counter value.
o As for loop is a pre-test loop, the test condition will be checked before the body of the for
loop gets executed.
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
o The body of the for loop must contain one and only one statement, if more statements are to
be represented, use a compound statement.

o Although there are three statements in a for loop, but only two actions are performed in each
iteration.
o In the first iteration only initialization and condition are used. In rest of all iterations only
update and condition will be used.

Example: Design a flowchart to read 20 numbers and print the sum. Since the number of times is
known in advance, for loop is an excellent choice.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
II. while loop:
o While loop is a conditional loop and not a counter controlled loop.
o It is also a pretest loop. If the condition becomes false in first iteration the body of the loop
may never be executed.

Example: Design a flowchart that reads numbers from the keyboard and print their total. As the
number of times is not known in advance a conditional loop is the best choice. To break the loop, or
to limit the number of times a negative input -1 can be read from the keyboard.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
III. do – while loop statement:
o The third type of looping statement is do – while loop.
o There are two major differences between while loop and do – while loop
1. A while loop is a pre-test loop, but a do – while loop is a posttest loop.
2. If the test condition fails in the first iteration, the body of a while loop may never
be executed, but the body of a do – while loop is executed at least once.
o The following figure shows the use of the do – while statement, it can be observed that
the condition is tested at the end of the loop.

Example-1:
Problem – Draw a flowchart to add, subtract, multiply, divide and to find the reminder of two numbers
and display the result.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Example 2:
Problem − Draw a flowchart to Calculate the Interest of a Bank Deposit.

Example-3:
Problem − Draw a flowchart to determine whether the Temperature is below or above the freezing Point
(32◦F).

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Example-4:
Problem − Draw a flowchart to find the biggest in two numbers.

Example-5:
Problem – Draw a flowchart to determine whether a student passed in the exam or not.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Example-6:
Problem − Design a pseudocode to find the given number is even or odd.

INTRODUCTION TO THE C-LANGUAGE (OR) HISTORY OF C-LANGUAGE


o C – Language is a structured, high-level programming language.
o It is considered as high-level language because it allows the programmer to concentrate on the problem in
hand and not to worry about machine hardware.
o C – Language is a machine independent language. This is the reason why many software developers use c-
language whose applications needs to run on many different computers.
o C – Language is derived from ALGOL (the first language to use block structure).
o ALGOL was introduced in the early 1960s make the way to the development of structured programming
concepts.
o Two computer scientist Corrado Bohm and Guiseppe Jacopini published a paper in 1966, which defines the
concept of structured programming.
o Another computer scientist, Edsger Dijkstra wrote a letter to the editors of the communications of the ACM
(Association of Computing Machinery) popularized the concepts of structured programming and brought
the attention of computer science community.
o In 1967, Martin Richards developed a language called Basic Combined Programming language or BCPL.
o Later Ken Thompson in the year 1970 developed a similar language named it as B. B was used to develop
the first version of UNIX (one of the popular network operating system in use today).
o Finally, in 1972, Dennis Ritchie developed C, by combining many concepts from ALGOL, BCPL and B and
added the concept of data types. This version of C is known as traditional C, as popularized by a book by
Brain W. Kernighan and Dennis Ritchie in the year 1978.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
o In 1983, the American National Standards Institute (ANSI) has given a standard definition for C, it got
approved in December 1989. In 1990 the International Standards Organization (ISO) adopted the ANSI
standard. This version of C is known as C89.
o In 1995 minor changes were made to the standard. This version is known as C95.
o In 1999 a significant changes were made to the standard. This version is referred as C99. The following
changes were made to it.
1. Extension to character type to support non English characters.
2. A Boolean type.
3. Extension to the integer type.
4. Inclusion of type definition in the for statement.
5. Addition of imaginary and complex types.
6. Inclusion of line comment (//).
STRUCTURE OF A C PROGRAM:
Every C program is made of (a) one or more pre-processor commands, (b) a global declaration section and (c) one
or more functions.
(a) Pre-processor commands:
o The pre-processor commands come at the beginning of the program. It tell the processor how to
prepare the program for compilation.
o All pre-processor commands start with a pound sign (#); this is just the rule of C known as syntax.
o The pre-processor command tells the compiler to include the library files into the programs. Library
files like stdio.h (Standard input / output header files) and conio.h (console input / output header
files).
o Generally library files contains definitions for pre-defined functions like printf();. Printing is one of
the input / output processes identified in stdio.h library file.
o The syntax for including a pre-processor command into the program is: #include<stdio.h>.
o There should not be any space between the pound symbol (#) and the include keyword.
o The keyword include tells the compiler to include the header file specified in angular bracket (<>)
into the program.

(b) Global Declaration Section:


o The global declaration section comes after the pre-processor commands.
o It is the place where global variable are declared.
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
o The basic idea about global declarations (global variables) is that they are visible to all parts of the
program.

(c) Main function section:


o The work in a program will be carried out by functions.
o Functions are block of code separated to accomplish a specific task.
o One and only one function must be a main function. The main function is the starting point of the
program. The program execution will begin from main function.
o Every function in a C-Program is divided into two parts:
i. Declaration section: It declares the data that will be used inside the function. Declarations
inside a function are known as local declarations, they are visible only to the function where
they are declared.
ii. Statement section: It contains the actual logic or instructions to the computer that makes it to
do something. In C these instructions are known as statements, hence the name statement
section.
o Syntax to use main function is: int main(void)
o Here int says that the function main will return integer value to the operating system. And void
indicates that it has no parameters.

COMMENTS
 Comments are helpful in documenting the code.
 Comments improves the readability and understanding of the code.
 Comments are placed within the program, with actual programming code.
 The compiler ignores these comments when it translates the program into executable code.
 In C there are two different types of comments:
a. Block Comments
b. Line Comments
(a). Block Comments:
 A block comment is used when he comment will span several lines.
 A block comment uses an opening token ‘/*’ and a closing token ‘*/’, between opening and closing token
the comment which span more than one line is used.
 No space is allowed between the token symbols, that is ‘/’ and ‘*’ should come together like ‘/*’ for
opening comment and ‘*/’ for closing comment.
Example:
/* This is a block comment
Which spans
More than one line */

(b) Line Comment:


 The line comment uses two slashes (//) to identify the start of the comment.
 Line comment does not require an end-of-comment token. The end of the line automatically ends this
comment.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 Only one line of comment is accepted inside a line comment. When the comment size is very short line
comments will be used.
Example:
// This is a single line comment
int a=10; //This is a partial line comment

Nesting of comment: Comments can be nested, one within another. Doing so does not give any specific meaning
but one has to know what happens if we nest the comments. In nesting of comments we have the following
possibilities.
(i) Nesting line comment within a line comment
(ii) Nesting line comment within a block comment
(iii) Nesting block comment within a line comment
(iv) Nesting block comment within a block comment

(i) Nesting line comment within a line comment: Nesting a line comment within a line comment does not raise
any error. The start token of the nested line comment will be ignored by the compiler. Hence will not generate
any error condition.

(ii) Nesting Line comment within a block comment: Nesting a line comment within a block comment will also
not generate any error. The start token of the nested line comment will be ignored by the compiler as part of
the comment. Hence will not generate any error condition.

(iii)Nesting of block comment within a line comment: Nesting of a block comment within a line comment will
generate error, only if the block comment will span more than one line.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
(iv) Nesting of block comment within a block comment: Nesting of a block comment within a block comment
will always generate error. Because the start token of the nested block comment will be ignored as part of the
comment. And closing token of nested block comment will become the closing token of outer block comment.
Rest of the comment will generate error.

IDENTIFIERS:
 Identifiers are used to name data and other objects in the program. It is similar to nouns in natural
languages.
 When objects are declared in computer program they will be stored at unique memory locations, these
memory locations will have unique addresses to represent them. If we don’t have symbolic names to these
memory locations, then there is need to know and use these addresses to access the memory locations.
 Instead of doing the above, we simply give symbolic names (identifiers) to these memory locations, and the
compiler will keep track of where they are stored.
 There are some rules while framing the identifier:
1. First character must be an alphabetic character or underscore.
2. Must consisits only of alphabetic characters, digits, or underscores.
3. First 63 characters of an identifier are significant.
4. Cannot be a keyword.

 The forst character of the identifier cannot be underscore, because many objects in library files use
underscore as the first letter in their identifiers. If we do the same we may get duplicate names, which
becomes very confusing for the compiler.
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
 C-language is a case sensitive language, that is uppercase and lowercase letters are differently treatted by
the compiler.
 No space is allowed withing the identifier. Underscore and Capitalization can be used to separate the words.

KEYWORDS:
 Keywords are also known as reserved words. They are syntactical tokens which have special meaning when
used in programming.
 Keywords cannot be used as identifiers for variables, functions or named constants in programming.
 In C-language there are 37 – keywords, they are listed in the following table:
auto extern short _Bool float signed
break for sizeof case goto static
char if struct _Complex _Imaginary switch
const inline typedef continue int union
default long unsigned do register void
double restrict volatile else return while
enum

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
DATATYPES (OR) TYPES:
 A type is defined as a set of values and a set of operations that can be applied on those values.
 A type not only defines the type of data to be stored but also the size of the storage location.
 Example: A light switch – it has two values on and off, and only two possible operations turn on and turn
off.
 In C-language the types are divided into four major catogories: void, integral, floating-point and derived.

 The first three types are known as primitive types (or basic types) which are independently defined.
 The last type is derived type which are derived from basic types.

1. Void Type:
o The keyword void is used to indicate void type.
o The void type has no values and no operations.
o The void type is used to specify that a function has either no parameters or no return values.
o Example: int main(void); - in this statement the function has no parameters.
o The void type is also used to define a pointer to generic type.
o Example: void* ptr; - in this statement ptr becomes a pointer to the generic type of data.

2. Integral type:
o In C-language there are three integral types namely: Boolean, character and integer.
o Integral types doesn’t hold fractional part they are whole numers.

(a) Boolean:
 In C-language Boolean type is included in C99. It is named after the French mathamaticain and
phylosopher George Boole.
 A boolean will have only two values: true and false.
 Before C99 integers were used to represent the boolean values; a nonzero number (positive or
negetive) is used to represent true, and a zero is used to represent false.
 The keyword bool is used refer boolean type.
 A boolean type is stored in memory as 0 (false) or 1 (true).

(b) Character:
 In computers a character is any value that can be represented in computer’s alphabet (character set).
 In C-standard there are two character types: char and wchar_t.
 Many computers will use 1-byte to store the char data types. A byte is 8-bits. With 8 bits, there are
256 different possible char values.
 In English the letter a is different from x in its visual formation of the graphical associated with the
letter. But in computers the letter a is binary 0110 0001 and letter x is binary 0111 1000. The
decimal values of these two letters 97 for a and 120 for x.
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
 In C99 standard To support non-English languages or languges that don’t use the Roman alphabet
wide charater type (wchar_t) is used.

char

wchar_t

(c) Integer:
 An integer type is a number without a fraction part.
 C supports four different sizes of integer data types: short int, int, long int and long long int.
 A short int also referred as short, long int as long and long long int as long long.
 These data types are organized from the smallest to the largest as shown in the following figure.
 To know the size of any data type, C provides the sizeof operator, that gives the exact size in bytes.
sizeof(short) < sizeof(int) < sizeof(long) < sizeof(long long)

short int

int

long

long long

Signed and Unsigned integers:


 Integers can be signed or unsigned. If an integer is signed then one bit must be used for a sign (0 is plus, 1 is
minus).
 If an inteer is unsigned it can store a positive number that is twice as large as the signed integer.
 The follwing table list typical range of values for different types of integers.
Type Byte Size Minimum Value Maximum Value
short int 2 -32,768 32,767
int 4 -2,147,483,648 2,147,483,647
long int 4 -2,147,483,648 2,147,483,647
long long int 8 -9,223,372,036,854,775,807 9,223,372,036,854,775,806

3. Floating-Point Types:
 In C, there are three floating-point types: real, imaginary and complex.
 Floating point types are always signed and there is no possibility for unsigned.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
(a) Real:
 Real type holds values that consists of an integral and a fractional part. Ex: 49.32
 There are three different sizes of real types namely: float, double and long double.
 Real types are also organized from smaller size to larger size, the relationship is shown in the
following figure.

float

double

long double

sizeof(float) < sizeof(double) < sizeof(long double)

(b) Imaginary Type:


 An imaginary number is a real number multiplied by the sqare root of -1 (√-1).
 C defines an imaginary type to support imaginary numbers in programming.
 There are three different types of imaginary types: float imaginary, double imaginary, long double
imaginary.
 Many C implementations do not support imaginary types yet, and the functions to support imaginary
types are not part of this standard either.

(c) Complex Type:


 A complex number is a combination of a real number and an imaginary number.
 C defines complex type to support complex numbers in programming.
 There are three diffent types of complex types: float complex, double complex and long double
complex.

Type summary: The following type summmerizes the standard data type.

Category Type C Implemeentation


Void Void void
Integral Boolean bool
Character char, wchar_t
Integer short int, int, long int, long long int
Floating-point Real float, double, long double
Imaginary float imaginary, double imaginary, long double imaginary
Complex float complex, double complex, long double complex

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
VARIABLES
 Variables are named memory locations that have a type, such as integer or character.
 The type here determines the values that a variable may hold, and operations that can be applied on the
variable.
 Like every other object in C, a variable must be declared, defined and initialized before it can be used any
where in the programming.
 Declaration: In C, declaration means giving name to an object. Naming an object will be done with the help
of identifier.
 Definition: Definitions are used to create the object. The definition will allocate the memory to the object.
 Initialization: Initialization assigns a specific value to the defined object. Without initialization the variable
will hold the garbage value.
 In C, variable declaration and definition will be done at the same time. And initialization can be done
according to the requirement.

Variable declaration and definition:


 In C, variable declaration and definition will be done at the same time.
 Variable declarations are used to name the variables, naming the variable is nothing but giving an identifier
to it.
 Variable definitions are used to allocate the memory to the variable, memory allocation is nothing but
specifying the datatype to the variable.
 In simple terms, the declaration give variables a symbolic name, and definition reserves memory.
 Where the variables are located inside memory is not a programmer’s concern, it is a concern of the
compiler. The programmer uses the symbolic name (identifier) associated with variable to access the
content from it.

 A variable’s type can be any datatype, such as character, integral or real, but cannot be a void type.
 To create a variable, first specify the type (datatype) and then the name (identifier).

Variable Creation:
Syntax:
float price;

 C-allows multiple variables of same type to be defined at the same time in a single statement. It is
considered as poor programming style
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
Multiple Variable Creation in Single Statement:
Syntax:
float balance, price;

Variable Initialization:
 The variables can be initialized at the same time when they are defined. That is in a single statement it is
possible to do variable declaration, definition and initialization.
 To initialize a variable when it is defined, the identifier has to be followed by an assignment operator (=),
and the initilizer value.
Variable declaration, definition and initialization in single
statement:
Syntax:
float price = 3.759;

 In multiple variable definitions when initializer is used with only one variable, the initialization will be
applied to that variable only, but not to all.
Multiple variable declaration, definition and initialization in
single statement:
Syntax:
float balance, price = 3.759;

 To avoid the above confusion the variables has to be defined in separate lines.

Multiple variable declaration, definition and initialization in


seperate statement:
Syntax:
float balance = 100.324;
float price = 3.759;
 If not initialized properly or if initialization is not done at all, the variables will hold the garbage value
(Meaningless values left over from a previous use).

CONSTANTS:
 Constants are data values that cannot be changed during program execution.
 Like variables, constatns will also have type.
 In C there are different types of constants like: Boolean, character, integer, real, complex and string.
Constant Representation:
Boolean Constatnts:
 A boolean data type can take only two values. The values are 1(true) and 0(false).
 That is, there are only two possible symbols to represent a boolean data type: 1(true) and 0(false).
 To use boolean type, requires the inclusion of standard boolean library file into the program stdbool.h.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Character Constants:
 Character constants are enclosed between two single quotes (apostrophes).
 There are characters which do not have any graphical symbol associated with them. They cannot be printed
directly on the output screen, or they don’t have any direct character on the keyboard.
 To represent such characters a backslash(\) is used before the character. This backslash is called as escape
characters.
 For example: A new line character don’t have any symbol associated with it on the keyboard. So character
‘\n’ is used to represent a new line character.
ASCII Character Symbolic Representation
Null character ‘\0’
Alert (bell) ‘\a’
Backspace ‘\b’
Horizontal tab ‘\t’
Vertical tab ‘\v’
New line ‘\n’
Single quotes ‘\’’
Double quotes ‘\”’
Backslash ‘\\’

Integer Constants:
 Integer constants are simply coded as they are in real time. The value 15 is simply coded as 15.
 By default all integer constants are signed inegers.
 To override this default, that is to make the integer constant of different size: for Unsigned (u or U), for long
(l or L), for long long (ll or LL) can be used after the number.
 These codes can be combined to get the required meaning.
 There is no way to specify a short integer.
 If no code is suffixed by default the type will be int.
Examples of Integer Constants
Representation Value Type
+123 123 int
-378 -378 int
-32,228L -32,228 long int
76542LU 76,542 unsigned long int
12789845LL 12,789,845 long long int

Real Constants:
 Real constants will have integer part and fractional part seperated by a dot (.). Ex: 37.273
 By default all real constants will be in double.
 To override this default size: for float (f ot F) and for long double (l or L) can be used as suffix with the
value.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Examples of Real Constants
Representation Value Type
0. 0 double
.0 0 double
2.0 2.0 double
3.1416 3.1416 double
-2.0f -2.0 float
3,1415926536L 3,1415926536 long double

Complex Constants:
 Complex constants are widely used in engineering and mathamatical applications.
 Complex constants are coded as two parts, the real part and the imaginary part, seperated by a plus sign.
 The real part is coded using the real part rules. The imaginary part is coded as real number multipled(*) with
imaginary constant i(√-1).
 As with real constant, by default complex constant is double.
 To override this for float (f or F) and for long double (l or L) can be used.
Examples of Complex Constants
Representation Value Type
12.3+14.4*i 12.3+14.4*(√-1) double complex
14F+16F*i 14F+16F*(√-1) float complex
1.4736L+4.56756L*i 1.4736L+4.56756L*(√-1) long double complex

String Constants:
 A string constant is a sequence of zero or more characters enclosed in double quotes.
“” //An empty String
“h”
“Hello world\n”
“How are your”
“Good Morning!”

 The difference between null character and an empty string is that:


i. The null character represents no value, but as a character it is 8 zero bits (when stored consumes
8-bits in computer memory.
ii. The Empty string on the other hand is a string containing nothing. Neither it stores any character
not it consumes any memory in computer.
‘\0’ Null character

“” Empty String

Coding Constants:

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
In C, there are three different ways in which the constants can be coded in a program: (a) literal constants,
(b) defined constants and (c) memory constants.

(a) Literal constants:


 A literal is an unnamed constant used to specify data.
 If the is known in advance and cannot be changed during the execution, then a leteral for that data can
be used instead using a variable.
 Literals are coded using the format rules for constants.
 For example:
The literal 5 is used in the following statement:
a = b + 5;

(b) Defined Constants:


 Another way to define a constant is to use the preprocessor command define.
 Like all preprocessor commands, define should be prefixed with a pound symbol (#).
 The define command is placed in the beginning of the program.
 For example:
#define INTEREST_RATE 0.5
#define PI 3.141592

(c) Memory Constants:


 The third way to use a constant is memory constant.
 Memory constants use a C-type qulifier, const, to indicate that the data in the identifier cannot be
changed.

General Syntax:
const type identifier = value;
 Defining memory constants is similar to defining variable, prefixing const will make the content to be
fixed in the memory location, and cannot be changed.
 The memory constants must be initialized where they are defined, otherwise they permanently hold a
garbage value.
 For example:
const float PI = 3.141592;
const INTEREST_RATE 0.5

SYNTAX AND LOGICAL ERRORS:


(a) Syntax
 All languages have a set of rules for how words and sentences should be structured.
 These rules are collectively known as the language syntax.
 In computer programming, syntax serves the same purpose, defining how declarations, functions,
commands, and other statements should be arranged.

(b) Syntax errors

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 A syntax error is an error in the source code of a program. Since computer programs must follow strict
syntax to compile correctly, any aspects of the code that do not conform to the syntax of the programming
language will produce a syntax error.
 Syntax errors are small grammatical mistakes, sometimes limited to a single character.
 For example:
i. Missing out quotes.
ii. Missing out brackets.
iii. Using upper case characters in key words e.g. IF instead of if.
iv. Missing out a semicolon at end of a statement.
v. Using tokens in the wrong order.

(c) Logic errors


 A logic error (or logical error) is a mistake in a program’s source code that results in incorrect or unexpected
behaviour.
 It is a type of runtime error that may simply produce the wrong output or may cause a program to crash
while running.
 Many different types of programming mistakes can cause logic errors.
 For example:
i. Assigning a value to the wrong variable may cause a series of unexpected program errors.
ii. Multiplying two numbers instead of adding them together may also produce unwanted results.
iii. Calculating average = test1 + test 2 + test3 / 3, it Should be (test1 + test2 + test3)/3

Difference between Syntax Error and Logical Error


Syntax Error vs Logical Error
A syntax error is an error in the syntax of a sequence of A logical error is an error in a program that
characters or tokens that is intended to be written in a causes it to operate incorrectly or terminate
particular programming language. abnormally.
Occurrence
A logical error occurs due to a fault in the
A syntax error occurs due to fault in the program syntax.
algorithm.
Detection
In compiled languages, the compiler indicates the syntax The programmer has to detect the error by
error with the location and what the error is. himself.
Simplicity
It is easier to identify a syntax error. It is difficult to identify a logical error.

OBJECT CODE AND EXECUTABLE CODE


The Programming Process:
 Computers do not understand human languages. They only understand sequences of numbers that
represented in machine language.
 On the other hand, it is be very difficult for humans to write programs in machine language.
 Therefore, programming languages were invented to make it easier for humans to write computer programs.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 The program (source code) must be translated into machine language so that the computer can execute the
program (as the computer only understands machine language).
 The way that this translation occurs depends on the translator programs.
 In case of high level programming languages a special program called compiler is used to translate the
program into machine language.
 C is also known as a compiled programming language because it uses a compiler to translate the instructions
into machine language.
 A compiler takes the program code (source code) and converts it into a machine language module (called an
object file).
 Another specialized program, called a linker, combines this object file with other previously compiled
object files (in particular run-time modules also known as library modules) to create an executable file.
 The object code, eventhough it is in machine language, it is not ready for execution because it doesn’t have
the integration of library files. This integration has to be done with the help of linker program.
 The executable code is in machine language and it is ready for execution, it can be executed in any
computer to get the desired output.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Unit-II:
ATHEMATIC EXPRESSIONS
Expressions: An expression is a sequence of operands and operators that reduces to a single value.
Operator: An operator is a syntactical token that requires an action to be taken.
Operand: An operand is an object on which the operation is performed. Simply operand is an object
which receives operation from operator.
Expressions can be of two types: simple expressions and complex expressions.
Simple Expression: A simple expression contains only one operator. Ex: 2+7
Complex Expression: A compound expression contains more than one operator. Ex: 2+7*6

OPERATORS IN C-LANGUAGE:
 Operators are the foundation for any programming language. The functionality of C programming
language is incomplete without the use of operators.
 The operator can be defined as symbols that performs a specific mathematical or logical computations on
operands. In other words operator operates on the operands.
 In C, Operators are broadly categorized into 3 – types: i) Unary Operators ii) Binary Operator and
iii)Ternary Operator
 This broad categorization is done based on the number of operands the operator will use in exhibiting its
functionality.
i) Unary Operators: Operators of this type, operates or works with a single operand. Hence the
name unary operators. For example: (++, --).
ii) Binary Operators: Operators of this type, operates or works with a two operands. Hence the name
binary operators. For example: (+, -, *./).
iii) Ternary Operators: Operators of this type, operates or works with a three operands. Hence the
name ternary operators. For example: (?:).
 Based on the above criterion in mind, Operators are categorized into the following categories:
a) Arithmetic Operators:
b) Relational Operators:
c) Logical Operators
d) Bitwise Operators
e) Assignment Operators
f) Increment and Decrement Operators
g) Conditional Operator
h) Other Operators
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
a) Arithmetic Operators:
Arithmetic operators are used to perform arithmetic/mathematical operations on operands.

Arithmetic Operator Operator function Binary Form


+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a / b (b≠0)
% Modulus a % b (b≠0)
Note:
1. While performing division the second operand must be not equal to zero.
2. While performing modulo division both the operands must be integers, and second operand
must be non-zero.

b) Relational Operators:
Relational operators are used for comparison of two operand values. All of the relational operators are
binary operators. They need two operands to perform their functionality. They are as follows:

‘==’ (equal operator):


o It checks whether the two given operands are equal or not.
o If so, it returns true. Otherwise it returns false.
o For example: 5==5 will return true.

‘!=’ (not equal operator):


o It checks whether the two given operands are equal or not.
o If not, it returns true. Otherwise it returns false.
o It is the exact boolean complement of the ‘==’ (equal operator).
o For example: 5!=5 will return false.

‘>’ (Greater than operator):


o It checks whether the first operand is greater than the second operand or not.
o If so, it returns true. Otherwise it returns false.
o For example: 6>5 will return true.

‘<‘ (Less than operator):


o It checks whether the first operand is lesser than the second operand or not.
o If so, it returns true. Otherwise it returns false.
o For example: 6<5 will return false.

‘>=’ (Less than or equal operator):


o It checks whether the first operand is greater than or equal to the second operand or not.
o If so, it returns true. Otherwise it returns false.
o For example: 5>=5 will return true.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
‘<=’ (Greater than or equal operator):
o It checks whether the first operand is lesser than or equal to the second operand or not.
o If so, it returns true. Otherwise it returns false.
o For example: 5<=5 will also return true.
Relational Operator Operator function Binary Form
== Equal a == b
!= Not Equal a != b
> Greater than a>b
< Less than a<b
>= Greater than or equal a >= b
<= Less than or equal a <= b
Note: The following set of operators are complement to each other.
< is complement to >=
> is complement to <=
== is complement to !=

C program to demonstrate working of relational operators


// C program to demonstrate working of relational operators
#include <stdio.h>

int main()
{
int a=10, b=4;

if (a > b)
printf("a is greater than b\n");
else printf("a is less than or equal to b\n");

if (a >= b)
printf("a is greater than or equal to b\n");
else printf("a is lesser than b\n");

if (a < b)
printf("a is less than b\n");
else printf("a is greater than or equal to b\n");

if (a <= b)
printf("a is lesser than or equal to b\n");
else printf("a is greater than b\n");

if (a == b)
printf("a is equal to b\n");
else printf("a and b are not equal\n");
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
if (a != b)
printf("a is not equal to b\n");
else printf("a is equal b\n");

return 0;
}
Output:
a is greater than b
a is greater than or equal to b
a is greater than or equal to b
a is greater than b
a and b are not equal
a is not equal to b

c) Logical Operators:
Logical operators are used to perform logical operations such as Logical AND, Logical OR and Logical
NOT. They are used to combine two or more conditions/constraints or to complement the evaluation of
the original condition in consideration. They are as follows:

Logical AND (&& Operator):


o The ‘&&’ operator returns true when both the conditions in consideration are satisfied.
Otherwise it returns false. It is a binary operator.
o For example: a && b returns true when both a and b are true (i.e. non-zero).

Logical OR (|| Operator):


o The ‘||’ operator returns true when one (or both) of the conditions in consideration is
satisfied. Otherwise it returns false. It is a binary operator.
o For example: a || b returns true if one of a or b is true (i.e. non-zero). Of course, it returns
true when both a and b are true.

Logical NOT (! Operator):


o The ‘!’ operator returns true the condition in consideration is not satisfied. Otherwise it
returns false. It is a unary operator.
o For example: !a returns true if a is false, i.e. when a=0.

Logical Operator Operator function Binary Form


&& Logical AND a && b
|| Logical OR a || b
Logical Operator Operator function Unary Form
! Logical NOT !a

C program to demonstrate working of logical operators


// C program to demonstrate working of logical operators
#include <stdio.h>

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
int main()
{
int a=10, b=4, c = 10, d = 20;

if (a>b && c==d)


printf("a is greater than b AND c is equal to d\n");
else printf("AND condition not satisfied\n");

if (a>b || c==d)
printf("a is greater than b OR c is equal to d\n");
else printf("Neither a is greater than b nor c is equal to d\n");

if (!a)
printf("a is zero\n");
else printf("a is not zero");

return 0;
}
Output:
AND condition not satisfied
a is greater than b OR c is equal to d
a is not zero

d) Bitwise Operator:
Bitwise operators work at bit level of the given operands. There are 6-different types of bitwise operators:
& (bitwise AND operator):
o This operator takes two numbers as operands and does AND on every bit of two numbers.
o The result of AND is 1 only if both bits are 1.

| (bitwise OR operator):
o This operator takes two numbers as operands and does OR on every bit of two numbers.
o The result of OR is 1 if any of the two bits is 1.

^ (bitwise XOR operator):


o This operator takes two numbers as operands and does XOR on every bit of two numbers.
o The result of XOR is 1 if the two bits are different.
o This operator is used to check whether the given number is even or odd.

<< (bitwise left shift operator):


o This operator takes two numbers, left shifts the bits of the first operand, and the second
operand decides the number of places to shift.

>> (bitwise right shift operator):


o This operator takes two numbers, right shifts the bits of the first operand, and the second
operand decides the number of places to shift.

~ (bitwise NOT operator):


MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
o This operator takes one number and inverts all bits of it. (0’s become 1’s and 1’s become
0’s)
o This operator is used to find the one’s complement of a given number.

Bitwise Operator Operator function Binary Form


& Bitwise AND a&b
| Bitwise OR a|b
^ Bitwise XOR a^b
<< Bitwise Left Shift a << 2
>> Bitwise Right Shift a >> 2
Logical Operator Operator function Unary Form
~ Bitwise Not ~a

Examples:
a b a&b a|b a^b ~a
0 0 0 0 1 1
0 1 0 1 0 1
1 0 0 1 0 0
1 1 1 1 1 0
a = 5(00000101), b = 9(00001001)
a&b = 00000001
a|b = 00001101
a^b = 00001100
~a = 11111010
b<<1 = 00010010
b>>1 = 00000100

C Program to demonstrate use of bitwise operators


/* C Program to demonstrate use of bitwise operators */
#include<stdio.h>
int main()
{
char a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
printf("a = %d, b = %d\n", a, b);
printf("a&b = %d\n", a&b); // The result is 00000001
printf("a|b = %d\n", a|b); // The result is 00001101
printf("a^b = %d\n", a^b); // The result is 00001100
printf("~a = %d\n", a = ~a); // The result is 11111010
printf("b<<1 = %d\n", b<<1); // The result is 00010010
printf("b>>1 = %d\n", b>>1); // The result is 00000100
return 0;
}
Output:
a = 5, b = 9
a&b = 1
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
a|b = 13
a^b = 12
~a = -6
b<<1 = 18
b>>1 = 4

Instructions when using bitwise operators:


1. The left shift and right shift operators should not be used for negative numbers:
i. If any of the operands is a negative number, the result is undefined behavior.
For example: results of both -1 << 1 and 1 << -1 is undefined.
ii. If the number is shifted more than the size of integer, the behavior is undefined.
For example: 1 << 33 is undefined.

2. The left-shift and right-shift operators are equivalent to multiplication and division by 2 respectively.
For example: if x=18 then x<<1 = 36, x>>1 = 9
#include<stdio.h>
int main()
{
int x = 18;
printf ("x << 1 = %d\n", x << 1);
printf ("x >> 1 = %d\n", x >> 1);
return 0;
}
Output:
36 9

3. The & operator can be used to quickly check if a number is odd or even.
For example: The value of expression (x & 1) would be non-zero only if x is odd, otherwise the value
would be zero.
#include<stdio.h>
int main()
{
int x = 19;
(x & 1)? printf("Odd"): printf("Even");
return 0;
}

Output:
Odd

e) Assignment Operators:
 The assignment operator (=) evaluates the operand on the right side of the operator (=) and places the
value in the variable on the left.
 The value on the right side must be of the same data-type of variable on the left side otherwise the
compiler will raise an error.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 The right-side value cannot be a constant, doing so is an error.
Syntax:
variable = expression (or) constant;

Types of Assignment:
There are three different types of assignments possible using the same operator (=).
1. Simple assignment: This type of statement will have only one assignment operator in it. The right
side value or the result will be assigned to the left-side variable.
Example: a=10; //Here variable a will hold 10 after assignment.

2. Multiple assignment: This type of statement will have multiple assignment statements in it.
Example: a=b=c=10; // Here value 10 will be assigned to a, b, c variables

3. Compound assignment: It is a shorthand notation for a simple assignment. It requires the left
operator to be repeated as a part of the right expression. There are five compound assignment
operators listed in the following table.
Operator Example Equivalent Statement
+= c += 7 c=c+7
-= c -= 8 c=c–8
*= c *= 10 c = c * 10
/= c /= 5 c=c/5
%= c %= 5 c=c%5

f) Increment and decrement Operators:


 These category of operators are unary operators.
 They are used to add 1, increment (++) or subtract one (--) from the given variable.
 As they are unary operators they can be used in two different ways: Postfix and Prefix.
 Postfix: In this form, the operator is place before the variable, and the variable’s value will be
incremented by 1 after the expression evaluation. Hence the name postfix.
Syntax: a=b++; /*here first the ‘a’ value will be initialized with ‘b’ value and the b gets
incremented*/
#include<stdio.h>
int main(void)
{
int a,b=7;
clrscr();
a=b++; //postfix increment
printf("\n%d %d", a, b);
a=b--; //postfix decrement
printf("\n%d %d", a, b);
getch();
return 0;
}
Output:
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
78
87

 Prefix: In this form, the operator is place before the variable, and the variable’s value will be
incremented by 1 before the expression evaluation. Hence the name prefix.
Syntax: a=++b; /*here first the ‘a’ value will be incremented by 1 and then will be
initialized to ‘b’ */
#include<stdio.h>
int main(void)
{
int a,b=7;
system("cls");
a=++b; //postfix increment
printf("\n%d %d", a, b);
a=--b; //postfix decrement
printf("\n%d %d", a, b);
return 0;
}
Output:
88
77

Operator Example Meaning Equivalent Statements


++ i++ postfix i=i+1; i+=1;
++ ++i prefix i=i+1; i+=1;
-- i-- postfix i=i-1; i -=1;
-- --i prefix i=i-1; i-=1;

g) Conditional Operator:
 Conditional operator also known as ternary operator.
 It is the only operator in C, which takes three operands in its operation.
 The (?:) token is used to form this operator.

Syntax: conditional_expression? Expression1 : Expression2;


The result of the above operation is based on the conditional_expression, if this expression is true
(nonzero) then expression1 gets evaluated, if the conditional_expression is false (zero) then expression2
will be evaluated.

 The conditional operator is equivalent to the if-else statement.


Conditional Operator if-else statement
#include<stdio.h> #include<stdio.h>
int main(void) int main(void)
{ {
int a=6,b=7; int a=6,b=7;
system("cls"); system("cls");
a>b?printf("%d is big", a):printf("%d is big",b); if(a>b)
return 0; printf("%d is big", a);
} else
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
printf("%d is big",b);
return 0;
}
Output Output
7 is big 7 is big

h) Other Operators:
C supports the following set of special operators:
& (Address Operator)  The address operator is used get the address of an operand.
 It is a unary operator, it requires only on operand.
 When used with the operand, it returns the address of that operand’s
memory location.
* (Indirection Operator)  To access the value from the given address, the * operator is used.
 Generally it deal with pointer, where to get the value from a pointer
this operator is used.
 It is also a unary operator, requires only one operand to perform its
functionality.
, (Comma Operator)  This operator does not show any operations on the operands, rather it
is used to separate the expressions which are appearing in the same
line.
 Like regular use, the comma operator is used like a separator.
 Example: int a,b,c;
j=(i=12,i+20);
sizeof() Operator  This operator is used to know the memory size of the operand
supplied.
 As it is a unary operator, it operates on single operand.
 Syntax: sizeof(datatype/variable);
 Example: sizeof(a);
sizeof(int);
. and  (Member access The . (dot) and  operators are used to access the members of a
Operators: structure (directly or indirectly).

PRECEDENCE AND ASSOCIATIVITY:


 Expression evaluation is easy if it is a simple expression to be evaluated, but problem arises when we have
a complex expression to evaluate.
 Without the knowledge of precedence, it is difficult to determine the order in which the operators in a
complex expression are evaluated.
 Precedence: Precedence is used to determine the order in which different operators in a complex
expression are evaluated.
 Associativity: Associativity is used to determine the order in which operators with same precedence are
evaluated in a complex expression.
 Always the precedence is applied before the associativity, knowing that there are more operators with
same precedence level, the associativity is applied.
 If there are no operator with same precedence, no need to apply the associativity.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 Every operator in C is having a precedence, the higher the precedence the earlier the operator gets
evaluated.

Example: 2+3*4 = ?
In precedence table operator * is having higher precedence than operator +, hence the * will be
evaluated first and then +, so the value is 14 (see the following precedence table).

Associativity:
 Associativity can be left-to-right or right-to-left.
 Left-to-right associativity evaluates the expression by starting on the left and moving to the right.
 Right-to-left associativity evaluates the expression by starting on the right and moving to the left.
 Remember, associativity is used only when there are operators with same precedence level in occur in a
complex expression.

Associativity Rule

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
OPERATOR PRECEDENCE TABLE

Example:
1. 3*8/4 is 6
2. 2+3%2*4 is 6
3. 3*8/4%4*5 is 10

CONDITIONAL BRANCHING (DECISION MAKING)


 Decision is nothing but selecting the right choice between multiple alternatives.
 In computers always the decision will be made based on conditions, for a condition there are two
possibilities, either true or false.
 Always for every possibility of the decision, there will be action or set of actions defined. Based on the
condition result the possible path way will be selected.
 If the specified condition becomes true, a set of actions suitable to that will be selected for execution,
failing which the false operations will be selected.
 In C – The following possible conditional branching statements are there:
I. Simple if – statement
II. If – else statement

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
III. Nested if – else statement
IV. Else – if ladder
V. Switch statement

I. Simple if – Statement:
 In C, the simplest form of decision making is the if – statement.
 If statement will have a condition helpful in making the decision.
 If the condition is true then the statement-block will be executed.
 If the condition is false it does not do anything (or the statements block is skipped). Simply the
simple form of if statement will not have anything to do in case of the false condition.
 The condition is given in parentheses and must be evaluated as true (nonzero value) or false
(zero value).
 If a compound statement need to be provided, it must be enclosed in opening and closing
braces.
Syntax: Simple if statement
if (condition)
{
statement-block;
}
Flow Chart: Example:
Example:
main()
{
int a=10,b=20;
if(a>b)
{
printf(“%d”,a);
}
printf(“%d”,b);
}

Output:
10
20
Whenever the specified condition becomes true, statement-block gets executed. If condition
becomes false it has nothing to do.

II. If – else statement (Two – Way selection statement)


 Another form of decision making statement is two – way selection statement.
 In this not only the actions for true condition state, but also the actions for false condition state
are specified.
 The expression or condition which is followed by if statement must be enclosed in
parenthesis. No semicolon is needed for an if…else statement.
 As like simple – if, if the condition is true, the if part statements will be executed. And if
condition is false, the else part statement will be executed.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Syntax: Flowchart:

Whenever expression value is true (non – zero), statement1 will be executed. If the expression
value is false (zero), statement2 will be executed.
Compound statement:

One and only one statement is allowed in each part of if and else, use statement block
(compound statement) if more than one statement need to be specified.
Example: program for finding the biggest number in two.
#include<stdio.h>
int main(void)
{
int a,b;
clrscr();
printf(“Enter the two Numbers:”);
scanf(“%d %d”, &a,&b);
if(a>b)
printf(“%d is big”, a);
else
printf(“%d is big”, b);
getch();
return 0;
}
Output:
Enter the two Numbers:
10 20
20 is big

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
III. Nested if – else:
 Nested if…else means within the if…else you can include another if…else either in if block or in
else block.
 It is a way towards forming multi-way selection statements in C.
 By nesting the if – else within another if – else, the programmers will have the possibility of
including multiple conditions in the programs.
 With multiple conditions, there exist multiple possible paths.
Syntax: Flowchart:

Using Nested if – else, two expressions are included. With two expressions it is possible to include three
statements that is three different paths for execution.
Example: Program to find the biggest number in three numbers.
#include<stdio.h>
int main(void)
{
int a,b,c;
clrscr();
printf("Enter a,b,c values:");
scanf("%d %d %d",&a,&b,&c);
if(a>b)
{
if(a>c)
printf("%d is big",a);
else
printf("%d is big",c);
}
else
{
if(b>c)
printf("%d is big",b);
else
printf("%d is big",c);
}
getch();
return 0;
}
Output:
Enter a,b,c values:2 7 29
29 is big
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
The Dangling else Problem:
 The nested if – else statement has to be used with extra care, otherwise it may lead to dangling else
problem.
 This problem arises when there is no matching else for every if in the statement.
 In C, always an else part is paired with the most recent unpaired if.
 Doing so may result that some of the if statements may left unpaired.

Syntax: Flowchart:

Consider the above example syntax, from the syntax it is clear that the programmer intended the else
statement to be paired with the first if, but the compiler pair it with the second if. This is known as
dangling else problem.

 The solution to the dangling else problem can be obtained by simply taking a compound statement (a set
of curly braces to separate the true part for the first if statement) into consideration.
Syntax: Flowchart:

Consider the above figure; from this it is clear that when compound statement (curly braces) is used the
true part for the first if statement is separated, now the else will be paired with the first if and the
second if remains unpaired.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 The else-if ladder:
 Nested if – else can be used in such a way, so that the programmers can put more number of
conditions into it, to have multiple paths.
 It is way of having multiple paths flows (multiway – selection) in a program known as else – if ladder.
 In else – if ladder, the first if is coded with its associated statements, the else part for this if will have
another if statement with its associated statements, this series will continue until the programmers need
is satisfied. This structure will form a ladder of if – else – if – else – if …. Hence the name else – if
ladder.
Syntax: Flowchart:

The conditions are evaluated from the top to down. As soon as a true condition is found the
statement associated with it is executed and the control is transferred to the statementx by skipping
the rest of the ladder. When all n conditions become false, final else containing default statement
that will be executed
Example:
#include<stdio.h>
int main(void)
{
float m1,m2,m3,m4;
float avg;
system("cls"); //clrscr();
printf("Enter marks for (m1,m2,m3,m4):\n");
scanf("%f %f %f %f",&m1,&m2,&m3,&m4);
avg=(m1+m2+m3+m4)/4;
if(avg>=75)
printf("\nDistinction");
else if(avg<75 && avg>=60)
printf("\nFirst Class");
else if(avg<60 && avg>=50)
printf("\nSecond Class");
else if(avg<50 && avg>=40)
printf("\nThird Class");
else
printf("\nFail");

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
getch();
return 0;
}
Output:
Enter marks for (m1,m2,m3,m4):
65 75 69 78
First Class

 Switch Statement:
 The switch statement is a way to implement a multiway selection statement in C.
 The switch statement is used only when the selection condition reduces to an integral expression.
 If the selection condition is not an integral value, the else – if ladder is used.
 Switch is selection statement in which decision for selection is made between many alternatives.
 A switch statement allows a single variable to be compared with several possible case labels, which
are represented by constant values.
 If the variable matches with one of the constants, then an execution jump is made to that point.
 A case label cannot appear more than once.
 When none of the case labels are matching with the conditional expression then a default case will be
evaluated.

Syntax: Flowchart:

To break every case, so as to avoid multiple case execution when matching case is found,
the break statement is used. Practically speaking every case should have a break
statement as the last statement to avoid the execution of multiple statements.
 Break causes the program to jump out of the switch statement, that is go to the
closing braces (}) and continues the remaining code of the program.

Example:
#include<stdio.h>
int main(void)
{
char ch;
system("cls"); //clrscr();
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
printf("Enter your choice(R,B,G):\n");
scanf("%c",&ch);
switch(ch)
{
case 'R':printf("RED");
break;
case 'B':printf("BLUE");
break;
case 'G':printf("GREEN");
break;
default: printf("Invalid Option...!");
}
getch();
return 0;
}
Output:
Enter your choice(R,B,G):
B
BLUE

LOOPS IN C (REPETITION)
 Loops are nothing but an approach to repeat set of statements for a specific number of times.
 Every repetition is known as an iteration in the programming terminology.
 The real power of computers is in their ability to repeat an operation or a series of operations many times.
 This repetition, called looping, is one of the basic structured programming concepts.
 Each loop must have an expression that determines the termination point for the loop. If there is no
termination point specified the loop will iterate for infinite number of times.
 The basic loop concept is shown in the following figure, as there is no termination condition specified the
loop will iterate infinitely.

 Loops in C are broadly categorized as pretest loops and posttest loops.


 Pretest Loops: In pretest loops, in every iteration the condition (which is used to terminate the loop) will
be tested before the body of the loop gets executed. If the condition is true, the body of the loop gets
executed, and if the condition is false the loop exits.
 Posttest Loops: In posttest loops, in every iteration the condition (which is used to terminate the loop)
will be tested after the body of the loop gets executed. If the condition is true, the body of the loop gets
executed, and if the condition is false the loop exits.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 The major difference between a pretest and a posttest loop is, in a pretest the body of the loop executes
zero or more times, but in a posttest loop the body of the loop executes one or more times.
 That is if the termination condition fails in the first iteration, in a pretest loop the body of the loop never
executes, but in a posttest loop body of the loop executes at least once, after that only the condition will be
checked.
Initialization and Updating:
 The main entity which controls the complete loop functioning is the termination conditions, which
specifies when the loop will terminate, failing which the loop will enter into an infinite number of
iteration.
 Hence there is a need to do some change in the condition, so as to meet the termination point.
 Initialization must be done before the loop body, generally the initialization part initialized the operands
involved in termination condition expression.
 The update process helps in making changes to the termination condition, if there is no change in the
condition the loop will enter into infinite. Update process updates the operands involved in the
termination condition. The update process will be done inside body of the loop, as it has to be updated in
every iteration of the loop.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Comparison between Pre-test and Post-test Loops:

LOOPS IN C (while, do – while and for Loops)


 In C, there are three different types of loops: while loop, do – while loop and for loop.
 While and do – while loops can be used as event controlled loops, and the for loop is used as
counter controlled loop.
 All three loops continue as long as the termination condition becomes true. Once the termination
condition fails they will terminate.
 For every loop the initialization part and update part has to done as per the requirement.

while loop:
 The while loop is a pretest loop.
 It uses an expression (termination condition) to control the loop.
 As it is a pretest loop it tests the expression before every iteration of the loop.
Syntax: Flowchart:

 No semicolon is required at the end of the while statement.


 But to the within the while statements semicolon is needed.
 The body of the loop must contain one and only one statement at any time. To specify more than one
statement group them using a compound statement.
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
Syntax: Flowchart:

Example: To print 1 to 10 natural numbers


#include<stdio.h>
int main(void)
{
int i;
system("cls"); //clrscr();
i=1;
while (i<=10)
{
printf("%d ",i);
i++;
}
getch();
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10

do – while loop:
 The do – while loop is a post-test loop.
 Like while loop, do – while also uses an expression to control the loop.
 It tests the condition after the execution of the body.
 The body of the loop must contain one and only one statement at any time. To specify more than one
statement group them using a compound statement.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Syntax: Flowchart:

Unlike other looping statement a semicolon is required at the end of the do – while statement, and
also to the statements within the body.
Example: To print 1 to 10 natural numbers
#include<stdio.h>
int main()
{
int i;
system("cls"); //clrscr();
i=1;
do
{
printf("%d ",i);
i++;
}while(i<=10);
getch();
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10

 In while loop if the condition becomes false in the first iteration, the body of the loop never gets executed.
But in do – while the body of the loop gets executed at least once, even if the condition fails in the first
iteration.

for loop:

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 The for loop statement is a pretest loop statement. It tests the condition in each iteration before the body
gets executed.
 Generally the for contains three expressions, the first expression is an initialization expression, the second
expression is a limit test expression (termination condition) and the third expression is a updating
expression.
 The body of the loop must contain one and only one statement at any time. To specify more than one
statement group them using a compound statement.
 The expression1 in the syntax will be executed only once when the loop starts, expression2 will be tested
in every iteration before the execution of the body (hence the name pretest) and expression3 after
executing the body of the loop.
Syntax: Flowchart:

Note that the semicolon is not required at the end of the for loop statement, but the statement
within the loop body do require semicolons at the end.
The following figure compares the while loop and for loop

Example: To print 1 to 10 natural numbers


#include<stdio.h>
int main(void)
{
int i;
system("cls"); //clrscr();
for(i=1;i<=10;i++)
{
printf("%d ",i);
}
getch();
return 0;
}
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
Output:
1 2 3 4 5 6 7 8 9 10

Nested for Loop:


 Generally all forms of loops supports nesting concepts, but it can be more comfortable to use nested for
loops whenever necessary.
 Nested for loop is nothing but having a for loop as a part of another loop.
Example: printing number in matrix format
#include<stdio.h>
int main(void)
{
int i,j;
system("cls"); //clrscr();
for(i=1;i<=3;i++)
{
for(j=1;j<=4;j++)
printf("%d ",j);
printf("\n");
}
getch();
return 0;
}
Output:
1234
1234
1234

The different forms of using a for loop:


 The for loop can be used in the following forms
Option 1:
for (k= 1; k< = 10 ;)
{
printf(“%d”, k);
k = k + 1;
}
 Here the increment is done within the body of the for loop and not in the for statement.
Note that the semicolon after the condition is necessary.

Option 2:
int k = 1;
for (; k< = 10; k++);
{
printf(“%d”, k);
}
 Here the initialization is done in the declaration statement itself, but still the semicolon
before the condition is necessary.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Option 3: The infinite loop
 One of the most interesting uses of the for loop is the creation of the infinite loop.
 Since none of the three expressions that form the for loop are required, it is possible to
make an endless loop by leaving the conditional expression empty.
 For example: for (; ;)
printf(“The loop will run forever\n”);

Other looping statements (break and continue)


Break statement:
 If used in a loop, the break statement causes the loop to terminate.
 It is same like as of the termination condition is becoming false.
 In a series of nested loops the break statement terminates only the loop where it got invoked.
 When using a break statement, it needs a semicolon at the end.
 The break statement can be used in any of the loops while, do – while and for, and even in selection
statements.
Syntax:

Example: Demonstrate the use of break


#include<stdio.h>
int main(void)
{
int i;
system("cls"); //clrscr();
i=1;
while(i<=10)
{
if(i==8)
break;
printf("%d ",i);
i++;
}
printf("\nOther statements");
getch();
return 0;
}
Output:
1234567
Other statements

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Continue Statement:
 Unlike the break statement the continue statement does not terminate the loop, but simply transfers the
control to the testing condition in while and do – while, and in for loop it transfers the control to the
update statement.
 The continue statement when encountered in the body of the loop, simply skips the remaining part in the
current iteration and continues with the next iteration.
Syntax:

Example: Demonstrate the use of continue


#include<stdio.h>
int main()
{
int i;
system("cls"); //clrscr();
for(i=1;i<=10;i++)
{
if(i == 3)
continue;
printf("%d ",i);
}
getch();
return 0;
}
Output:
1 2 4 5 6 7 8 9 10

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
ARRAYS IN C:

 If we have to read, process and print 10 integers, then we need 10 integers in memory for the duration of
the program.
 We can declare and define 10 variables with a different name.
 To read these 10 variables from the keyboard we need 10 read statements, and also to print these 10 variables
onto the output screen we need 10 output (printf) statements. This is something redundancy in programming
code.
 The approach may look simpler and acceptable to some extend for 10 variables, but if the variable count
increases rapidly, nowhere the above concept is acceptable.
 To process large amount of data, C uses a powerful data structure called array.
 An array is a collection of elements of the same data type.
 Array elements can be initialized, accessed and manipulated using the indexing.
Example: score[10] Here score will contain 10-elements
 Array index always start at ‘0’ and end at total-number of elements minus one.
 In our example the index for score will start at 0 and end at 9.

Using Arrays in C
C provides two different types of arrays
 One-Dimensional arrays: In One-dimensional arrays the data are organized linearly in only one direction.
 Two-Dimensional arrays: In Two-Dimensional arrays the data are organized in rows and columns, like a
matrix.

ONE-DIMENSIONAL ARRAYS:
Array declaration and definition
 Like every other object in C, an array must be declared, defined and initialized before it can be used in the
program.
 Array declaration tells the compiler the name of the array.
 Array definition specifies the size or number of elements in the array. In a fixed length array, the size of
the array is a constant and must have a value at the compile time.
Example: type arrayname[array_size];
 The declaration and definition format for a variable length is same as like a fixed length array except the
size is a variable. The array size will be determined when the program is executed. Once the size is
determined it cannot be changed.

Accessing elements in arrays:


 To access the individual elements in an array the array index can be used. The index must be an integral
value or can be an expression that evaluates to an integral value.
 To process all the elements in the array a loop can be used. Consider the following code segment:

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
for(i=0;i<10;i++)
printf(“ %d”, scores[i]);
 The arrays name is the symbolic reference for the address to the first byte of the array. The index
represents an offset from the beginning of the array to the element being referenced.

Storing values in Arrays:


 Declaration and definition only reserves space for the elements in the array.
 To store values in the array they must be initialized.
 To initialize values in the array elements they can be read from the keyboard or they can be assigned with
individual values.

Initialization:
 Array elements in a fixed-length array can be initialized when they are declared. For variable-length
arrays they cannot be initialized when they are defined.
 To initialize the array elements with a set of values, they must be enclosed in braces and separated by
commas.
 It is a compile error to specify more values than elements in the array.
 The initialization can be done in the following ways:
(a) Basic initialization: int scores[5]={3,7,12,24,45};
(b) Initialization without size: int scores[]={3,7,12,24,45};
(c) Partial initialization: int scores[5]={3,7,0,0,0};
(d) Initialization to all zeros: int scores[5]={0};

The first example array the score array will have 5-elements and they contain specific set of values.
In the second example, when the array is completely initializing then the size attribute can be omitted.
In the third example, if the array is initialized with partial values rest of the elements will be
initialized to zero.
In the fourth example can be used to initialize all the elements to zeros.

Inputting values:
 An array can be initialized from the keyboard. The values can be read from the keyboard and initialized to
array.
 The most appropriate loop to use with arrays is the for loop.
for(i=0;i<9;i++)
scanf(“%d”,&scores[i]);
Assigning values:
 Array elements can be assigned individually by using a set of values, with the help of assignment operator.
Example: scores[4]=10;
 Assigning one array to another array is not possible even if they match fully in type and size. To do so we
have to copy all the elements individually from one array to another.
for(i=0;i<10;i++)
scores[i]=temp[i];
Printing values:
 To print the contents of the array, a normal for loop can be used.
Example: for(i=0;i<10;i++)
printf(“%d “,scores[i]);

Index Range checking:


 The C-language does not check the boundary of an array.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 As a programmer it is our job to ensure all references to indexed elements are valid and within the range.
 If an array is used with an invalid index, the results will be unpredictable.
Example: for(i=1;i<=10;i++) // indexing going out of range
printf(“%d “,scores[i]);

//Program to calculate sum of all the array elements.


#include <stdio.h>
int main(void)
{
int a[10];
int i, size, sum=0;
printf("Enter the size of the array[<10]:");
scanf("%d", &size);
printf("\nEnter the elements of an array:");
for (i=0;i<size;i++)
scanf("%d",&a[i]);
for (i=0;i<size;i++)
sum+=a[i];
printf("Sum of all array elements: %d",sum);
getch();
return 0;
}
Output:
Enter the size of the array[<10]:4

Enter the elements of an array:1 2 3 4


Sum of all array elements: 10

TWO-DIMENSIONAL ARRAYS
 In One-dimensional arrays the data are organized linearly in only one direction.
 Many applications require data to be stored in more than one dimension.
 Matrices require an array that consists of rows and columns as shown in the following figure, which is
generally called as two-dimensional array.

 In C-language a two dimensional array will be considered as an array of arrays. That is a two dimensional
array is an array of one-dimensional arrays.

Declaration and Definition:


 Two-dimensional arrays like One-dimensional arrays must be declared and defined before being used.
 Declaration tells the compiler the name of the array; definition specifies the type and size of each
dimension.
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
 The size of a two array must be a constant and must have a value at compile time.
Example: int scores[5][4];

Initialization:
 The definition of a Two-Dimensional array only reserves the memory for the elements in the array.
 No values will be stored in the locations. The locations will generally contain unpredictable values or
garbage values without initialization.
 Initialization of array can be done when the array is defined.
 The values for the array must be enclosed in braces.
Example: int scores[3][2]={2,3,5,4,6,9};
 Nested braces must be used to show the exact number of rows and columns.
Example: int scores[3][2]={{2,3,5},{4,6,9}};
 In a Two-Dimensional array, if the array is completely initialized with values, only the first dimension can
be omitted. The second dimension must need to be specified.
Example: int scores[][2]={{2,3,5},{4,6,9}};
 The whole array can be initialized to zeros.
Example: int scores[5][4]={0};

Inputting Values:
 Another way to initialize the values is, we can read them from the keyboard.
 In Two-Dimensional array, it usually requires nested for loops.
 The first loop, the outer loop controls the rows from zero to the maximum number and the inner loop
controls the columns from zero to the maximum number.
Example: for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf(“%d”,&scores[i][j]);
Outputting values:
 The values inside a Two-Dimensional array can be printed using two nested loops.
 The first loop, the outer loop controls the rows from zero to the maximum number and the inner loop
controls the columns from zero to the maximum number.
 To print the matrix in a table format, a newline is printed at the end of each row.
Example: for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf(“ %d”,scores[i][j]);
printf(“\n”);
}
Accessing values:
 Individual elements can be initialized using the assignment operator.
scores[2][0]=23;
scores[2][2]=scores[1][1]+12;

/* Write a C program to perform Addition of two matrices */

#include <stdio.h>
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
int main(void)
{
int a[2][2], b[2][2], c[2][2], i, j;
system("cls"); //clrscr();
printf("\nEnter values for matrix A(2X2):\n");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d", &a[i][j]);

printf("\nEnter values for matrix B(2x2):\n");


for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&b[i][j]);

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


for(j=0; j<2; j++)
c[i][j] = a[i][j]+b[i][j];

printf("\nThe resultant matrix C(2x2):\n");


for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
printf("%d ", c[i][j]);
printf("\n");
}
getch();
return 0;
}
Output:
Enter values for matrix A(2X2):
2468

Enter values for matrix B(2x2):


8642

The resultant matrix C(2x2):


10 10
10 10

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
STRINGS
 A string is a series of characters treated as a single unit.
 String is a variable length piece of data. Strings are divided into two major categories.
o Fixed length strings.
o Variable length strings.

Fixed length strings:


 In implementation of a fixed-length string, the important thing is to make decide the size of the variable. If
we make it too small, it sometimes can’t store all of the data. If we make it too big, we waste the memory.
 Another problem is how to differentiate between data and non-data. A solution is to use special characters
like spaces to indicate non data. In this case the space can’t be used as a character in the string.

Variable-Length strings:
 A much preferred solution is to create a structure that can expand and contract according to the size of the
value we want to store.
 Example: To store a person name with only three characters the structure should contract and provide
three characters and to store a person name with 30-characters the structure should expand and provide
30-characers.
 Here also there is a problem: as we are using a variable length structure in computers memory, there must
be a way to indicate the end of the string.
 Two common techniques are used to indicate the end of the string.
o Length-Controlled Strings
o Delimited Strings

Length-Controlled Strings:
 In this type of strings a count is used as the first character in the string that specifies the number of
characters in the string.
 This count then be used by string manipulation functions to determine the length of the string.

Delimited Strings:
 In this type of strings the end is specified by a special character known as delimiter, hence the name
delimited strings.
 This concept is similar to using a full stop (.) at the end of a sentence in English. Where each sentence is
of variable length and a special symbol full stop is used to indicate the end of the sentence.
 The disadvantage of using a delimiter is that it eliminates one character from being used for data in the
string.
 The most common delimiter is a null character (\0).
 All C strings are of variable length and delimited once.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
C-Strings
 A C string is a variable length array of characters that is delimited by the null character.
 A string is stored in an array of characters and delimited by a null character (\0).

 As a string is stored in an array, the name of the string is a pointer to the beginning of the string.
 There is a big difference between how a character is stored in memory and a one-character string is stored.
The character requires only one memory location, but the one-character string requires two memory
locations one for actual character and one for delimiter.
 To store an empty string in memory also requires one memory location to store the delimiter.

String Constants:
 A string literal or a string constant is a sequence of characters enclosed in double quotes.
 When string constants are used in a program, C automatically creates an array of characters, initializes to a
null delimited string, and stores it.
Example: “C is a programming language”
“Hello World”
 A string literal is stored in memory like any other object. It has an address, and can be referred by using a
pointer. Here the string literal as it is a sequence of characters, itself a pointer constant to the first element.
 The string itself can be used to refer the individual characters by using index.
Example: “hello”[1]  e

Declaring and defining Strings:


 C has no string type. To use strings in C programming they must be declared and defined as character
arrays.
 When defining the array to a store a string, we must provide enough space for both actual data and
delimiter.
Example: char str[9];
 In this example it is possible to store a string of eight characters long as the last character must be a
delimiter.
 A character pointer can also be used to hold strings of variable length in a program, because the name of
the string or the string itself is a reference to the starting memory location.
Example: char* pStr;
Initializing Strings:
 Initialization of strings is much like initialization any other object in C. We use assignment operator to
initialize the string when they are defined.
Example: char str[9]=”Good day”;
 As declaration, definition and initialization all are happening at a same point of time, the size attribute can
be ignored.
Example: char str[]=”Good day”;

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 Strings can be initialized by using a set of characters where the last character is going to be the delimiter.
This method is not used, because it is very tedious to code.
Example: char str[9]={‘G’,’o’,’o’,’d’,’ ‘,’D’,’a’,’y’,’\0’};
 The most common way for defining and initializing a string in programming is using a pointer. This
method first creates a string literal into the memory and assigns its address to the character pointer. Later
that pointer can be used to refer the string.
Example: char* pStr=”Good Day”;
String Input/Output functions
Functions gets() and puts() are two string functions to take string input from the user and display it respectively.

#include<stdio.h>

int main(void)
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}

Strings and the Assignment Operator


 The string is an array and the name of the string is a pointer constant.
 As a pointer constant is should always be used as an rvalue but not as lvalue.
Example: char str1[6]=”Hello”;
char str2[6];
str1=str2; //compile error
String Manipulation Functions:
 The C Library provides a rich set of string handling functions that are placed under the header file
<string.h> and <ctype.h>.

 Some of the string handling functions are (string.h):


o strlen() strcat() strcpy()
o strcmp() strstr() strrev()

 Some of the string conversion functions are (ctype.h):


o toupper() tolower()

 C provides different predefined set of string functions which are helpful in manipulating the strings.

String Length
strlen () function:
 This function counts and returns the number of characters in a string. It takes the form
Syntax: int n=strlen(str);

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 Where n is an integer variable, which receives the value of the length of the string. The counting ends at
the first null character.
 The string length function (strlen) returns the length of a string that is the number of characters in the
string excluding the null character.
 If the string is empty then the string length function returns zero.

Example:
#include<stdio.h>
#include<string.h>
int main(void)
{
int len;
char str[]="hello";
len=strlen(str);
printf("%d",len);
getch();
return 0;
}
Output:
5

String Copy
 The String copy functions strcpy(); copies the contents from one string including the null character to
another string.
 There are two string copy functions:
I. Basic string copy strcpy();
II. String copy length controlled strncpy();

I. Basic string copy strcpy();


 The basic string copy function strcpy(); copies the contents of the from one string fromstr
including the null character to another string tostr.
Syntax: strcpy(tostr,fromstr);
 If fromstr is longer than the tostr then, the data in memory after tostr is destroyed.
 The destination string should be large enough to hold the source string.
 If fromstr is longer than tostr, the data in memory after tostr is destroyed.
 The function returns the address of tostr.

Example:
#include<stdio.h>
#include<string.h>
int main(void)
{
char fromstr[]="hello",tostr[10];
strcpy(tostr,fromstr);
puts(tostr);
puts(fromstr);
getch();
return 0;
}

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Output:
hello
hello

II. String copy length controlled strncpy();


 String copy length controlled strncpy(); function copies the content of one sting to another, but it
sets a maximum number of characters that are to be copied.
 This function contains a parameter that specifies the maximum number of characters that can be
copied at a time.
Syntax: strncpy(tostr,fromstr,size);
 If the actual size of the fromstr is equal or greater than size parameter, then size number of
characters are copied.
 If the fromstr size is smaller than the size parameter, the entire string is copied and then null
characters are inserted into the tostr until the size parameter is satisfied.
 If the fromstr is longer than the size the copy stops after size bytes have been copied. In this case
the destination variable tostr may not be a valid string; that is it may not have a delimiter.

Example:
#include<stdio.h>
#include<string.h>
int main(void)
{
char fromstr[]="hello",tostr[10];
strncpy(tostr,fromstr,2);
puts(tostr);
puts(fromstr);
getch();
return 0;
}
Output:
he
hello

Sring Compare
C has two string compare functions:
I. Basic string compare strcmp();
II. String compare length controlled strncmp();

I. Basic string compare strcmp();


 The strcmp(); function compares the two string until an unequal character is found or until the end of
the string is reached.
 This function returns an integer to indicate the result of the comparison.
Syntax: strcmp(str1,str2);
 If both strings are equal the function returns zero. If length of str1 < str2, it returns < 0 value. If length
of str1 > str2, it returns > 0 value.

II. String comparison length controlled strncmp();

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 The strncmp(); function compares the two strings until unequal character is found in a specified number of
characters have been tested, or until the end of the string is reached.
 This function returns an integer to indicate the result of the comparison.
Syntax: int strncmp(str1, str2, size);
 If both strings are equal the function returns zero. If length of str1 < str2, it returns < 0 value. If length of
str1 > str2, it returns > 0 value.

Example:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str1[ ] = "Hyderabad" ;
char str2[ ] = "Hydarabad" ;
int i, j, k;
i = strncmp ( str1, str2, 3) ;
j = strncmp ( str1, str2, 4) ;
k = strncmp ( str1, str2, 10) ;
printf ( "\n%d %d %d", i, j, k ) ;
}
Output
0 4 4

String Concatenation
 The string concatenation function appends one string to the end of another string.
 The size of the destination string should be large enough to hold the resulting string. If it is not the data at
the end of the destination string will be destroyed.
 C has two string concatenation functions:
I. Basic string concatenation strcat();
II. String concatenation length controlled strncat();

I. Basic string concatenation strcat();


 The function copies str2 to the end of str1, beginning at the delimiter. That is the delimiter is
replaced with the first character of the str2. The delimiter from str2 is copied to the resulting string.
Syntax: strcat(str1, str2);
 The resulting string length is the sum of the length of str1 plus the length of str2.
 The function returns the address pointers to the resulting string.

Example:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str1[ ] = "Hyderabad" ;
char str2[ ] = "ISL" ;
strcat ( str1, str2);
printf ( "%s", str1);
getch();
return 0;
}
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
Output
HyderabadISL

II. String concatenation length controlled strncat();


 The strncat(); function copies only the specified number of characters from source string str1 to
destination string str2. A null character is appended at the end.
Syntax: strncat(str1, str2, size);
 If the length of str2 is less than size, then the function will work in same as basic string copy.
 If the length of str2 is greater than size, then only the number of characters specified by size are
copied, and a null character is appended at the end.
 If the value of size is zero or less than zero, then no characters are copied.

Example:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str1[ ] = "Hyderabad" ;
char str2[ ] = "ISL" ;
strncat ( str1, str2, 2) ;
printf ( "%s", str1 ) ;
getch();
return 0;
}
Output
HyderabadIS

Search for a substring


 Searching for a sub-string in a string can be done only from the beginning of the string.
 The function strstr(); is used to locate a substring in a string from the beginning of the string.
Syntax: strstr(string, sub_string);
 If sub_string exists in string then a pointer pointing to the first character of the sub_string is returned.
 If sub_string does not exist in string then a null pointer is returned.

String reverse
strrev() function:

 The function strrev is used to reverse the contents of the given string.
 The function strrev(); takes the string and reverses it, and places the reversed string in the given string
only.
Syntax: strrev(string);

Example:
#include<stdio.h>
#include<string.h>
int main(void)
{

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
char s[]="hello";
strrev(s);
puts(s);
getch();
return 0;
}
Output:
olleh

Changing the case of characters toupper() and tolower() functions:


toupper() function:

 toupper() function takes the character value as parameter, and converts it into the uppercase character.
 If the converted character is already in upper case, it remains as it is.
Syntax: tolower(char);

Example:
#include<stdio.h>
#include<string.h>
int main(void)
{
char ch = 'i';
printf("%c",toupper(ch));
getch();
return 0;
}
Output:
I

tolower() function:

 tolower() function takes the character value as parameter, and converts it into the lowercase character.
 If the converted character is already in lower case, it remains as it is.
Sybtax: tolower(char);

Example:
#include<stdio.h>
#include<string.h>
int main(void)
{
char ch = 'I';
printf("%c",tolower(ch));
getch();
return 0;
}
Output:
i

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
toascii() function:

 toascii() function takes the character value as parameter, and converts it into the equivalent ASCII value.
Syntax: toascii(char);

Example:
#include<stdio.h>
#include<string.h>
int main(void)
{
char ch = 'A';
printf("%d",toascii(ch));
getch();
return 0;
}
Output:
65

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Unit – III, Basic Algorithms

 Algorithm: In programming, algorithm is a set of well-defined instructions in sequence to solve the


problem.
 Algorithms are universal. The algorithm you use in C programming language is also the same algorithm
you use in every other language.
 Generally, the algorithms are written in natural languages, irrespective to the computer language used to
solve the problem.

Qualities of a good algorithm:


1. Input and output should be defined precisely.
2. Each step in algorithm should be clear and unambiguous.
3. Algorithm should be most effective among many different ways to solve a problem.
4. An algorithm shouldn't have computer code. Instead, the algorithm should be written in such a way
that, it can be used in similar programming languages.
SORTING
 One of the most common applications in computer science is sorting.
 Sorting is the process through which data are arranged according to their values.
 If the data are not arranged in an order, it will take hours trying to find a single piece of information.
 Example: Finding some one’s telephone number in a telephone directory if it is not ordered in name
sequence is a difficult job.
 Sorting is a combination of two different operations: compare and swap. In the comparison operation two
different element values of the array are compared. After comparison based on the requirement the values
are swapped. Swapping is interchanging the values in elements of the array.

Program: Sorting list of elements


#include<stdio.h>
int main(void)
{
int a[5] = {9,1,4,3,5},i,j,temp;
for(i=0;i<5;i++)
for(j=i;j<5;j++)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
printf("Sorted List:\n");
for(i=0;i<5;i++)
printf("%d ",a[i]);
getch();
return 0;
}
Output:
Sorted List:
13459

 There are different sorting mechanisms: Selection sort, Bubble sort, Merge sort, Heap sort … etc.
SEARCHING

 Another common operation in computer science is searching.


 Searching is a process used to find the location of a target among a list of objects.
 In an array searching means that given a value, finding the location (index) of the first element in the array
that contains that value.

 There are two basic searching techniques that can be applied to an array of elements.
 The Linear/Sequential search is used whenever the list is not ordered, small in size and not searched too
often.
 The Binary search is used, if the list is ordered, large in size and searched too often.

SELECTION SORT:

 In the selection sort, the list is divided into two sub-lists, sorted and unsorted, which are divided by an
imaginary wall.
 The smallest element from the unsorted sub-list is found and swapped with the element at the beginning of
the unsorted sub-list.
 After each selection and swapping, the imaginary wall between the two sub-lists moves one element ahead,
increasing the number of sorted elements and decreasing the number of unsorted elements.
 Each time an element is moved from the unsorted sub-list to the sorted sub-list, we call it a sort pass is
completed.
 To sort a list of n-elements, n-1 sort passes are needed.
// C program for implementation of selection sort
#include <stdio.h>
void swap(int*,int*);
void selectionSort(int[],int);
void printArray(int[],int);

// Driver program to test above functions


int main()
{
int list[] = {64, 25, 12, 22, 11};
int last = sizeof(list)/sizeof(list[0]);
selectionSort(list, last-1);
printf("Sorted array: \n");
printArray(list, last);
return 0;
}

void swap(int* xp, int* yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int list[], int last)


{
int cur, walk, smlst;

// One by one move boundary of unsorted subarray


for (cur = 0; cur < last; cur++)
{
// Find the minimum element in unsorted array
smlst = cur;
for (walk = cur+1; walk <= last; walk++)
if (list[walk] < list[smlst])
smlst = walk;

// Swap the found minimum element with the first element


swap(&list[smlst], &list[cur]);
}
}

/* Function to print the list */


void printArray(int list[], int last)
{
int i;
for (i=0; i < last; i++)
printf("%d ", list[i]);
printf("\n");
}

Output:
Sorted array:
11 12 22 25 64

BUBBLE SORT:

 In the bubble sort, the list is divided into two sub-lists, sorted and unsorted.
 The smallest element is bubbled from unsorted sub-list and moved to the sorted sub-list.
 After moving the smallest element to the sorted sub-list, the imaginary wall moves one element ahead,
increasing the number of sorted elements and decreasing the number of unsorted elements.
 Moving one element each time from unsorted sub-list to the sorted sub-list completes one sort pass.
 Given a list of n-elements, the bubble sort takes n-1 sort passes to sort the data.
 Remember the bubble sort concept starts from the end of the list.
// C program for implementation of Bubble sort
#include <stdio.h>
void swap(int*, int*);
void bubbleSort(int[],int);
void printArray(int[],int);

int main()
{
int list[] = {64, 34, 25, 12, 22, 11, 90};
int size = sizeof(list)/sizeof(list[0]);
bubbleSort(list, size);
printf("Sorted array: \n");
printArray(list, size);
return 0;
}

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

// A function to implement bubble sort


void bubbleSort(int list[], int size)
{
int cur, walk;
for (cur = 0; cur < size; cur++)
for (walk = size-1; walk > cur; walk--)
if (list[walk] < list[walk-1])
swap(&list[walk-1], &list[walk]);
}

/* Function to print an array */


void printArray(int list[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", list[i]);
}
Output:
Sorted array:
11 12 22 25 34 64 90

LINEAR/SEQUENTIAL SEARCH

 In sequential search, the searching for the target will start from the beginning of the list, and will continue
until the target is found or until the end of the list is reached (no target found case).

Example:

 The following figure lists the steps to find 62. The process will first compare the value with data at index 0,
then 1, 2, and 3 before finding the element at 5th location (index 4).
 If the target value is not in the list, then the comparison operation will reach the end of the list, making sure
that the target is not in the list. The figure also lists the steps for finding the value 72, which is not there in
the list.
// C-Program for Linear Search.
#include<stdio.h>
int seqSearch(int[],int,int);
int main(void)
{
int list[20], target, index, i, size;
system("cls"); //clrscr();
printf("Enter the size of the list:");
scanf("%d", &size);
printf("Enter any %d elements:\n", size);
for (i = 0; i < size; i++)
scanf("%d", &list[i]);

printf("Enter a target value to search:");


scanf("%d", &target);
index=seqSearch(list,target,size);

if (index==-1)
printf("%d isn't present in the list.\n", target);
else
printf("%d is present at index %d in the list",target, index);
getch();
return 0;
}

int seqSearch(int list[],int target,int size)


{
int index;
for (index = 0; index < size; index++)
if (list[index] == target)
return index;
return -1;
}
Output:
Enter the size of the list:5
Enter any 5 elements:
43679
Enter a target value to search:7
7 is present at index 3 in the list

BINARY SEARCH

 The sequential search algorithm is very slow.


 If we have an array of 1 million elements, we must do 1 million comparisons in the worst case.
 If the array is not sorted, this is the only solution.
 If the array is sorted, we can use a more efficient algorithm called binary search.
 We have to use binary search whenever the list contains more than 50 elements.

How it works:

 The binary search starts by comparing the data in the element in the middle of the list. This determines if
the target is in the first half or second half of the list.
 If the target is in the first half, no need to search the second half and if the target is in the second half, then
no need to search the first half.
 Either way half of the list will be eliminated from consideration.
 The same process will be repeated until the target is found or it’ll be confirmed that the target is not in the
list.
 The two important cases in binary searching process are:
o The target found case.
o The target not found case.

To find the middle of the list, we need three variables, one to identify the beginning of the list (first), one to
identify the middle of the list (mid), and one to identify the end of the list (last).

Target Found:

 The following figure shows finding 22 in a sorted list. In our case first will be 0 and last will be 11 and mid
can be calculated as follows.
mid = (first + last) / 2;
 Since the index mid is an integer, the result of will be an integral value: mid = ( 0 + 11 ) / 2 = 11 / 2 = 5
 At index location 5, the target is greater than the list value ( 22 > 21 ). Therefore the list location from 0
through 5 can be eliminated.
 Now in the step the first will be made as: first = mid + 1 i.e. first = 5 + 1 = 6. And further calculates the mid
by using same formulae: mid = (first + mid)/2 i.e. mid = ( 6 + 11 ) / 2 = 17 / 2 = 8.
 Again the target will be tested with value at mid, this time the target is less than the list value ( 22 < 62 ).
 This eliminates locations 8 through 11.
 This time last will be adjusted as: last = mid – 1 i.e. last = 8 – 1 = 7 and mid = ( first + last ) / 2 = ( 6 + 7 ) /
2 = 6.
 Now at mid location the value matches with the target. This will stop the search.

Target Not Found:

 The target not found in the binary search is something when we searched all the possibilities and didn’t
find the target in the list.
 This is done in the binary search when first becomes greater than last.
 Thus only two conditions terminate the binary search algorithm: Either the target is found or first
becomes larger than last.
//Binary Search algorithm
#include <stdio.h>
int binSearch(int[],int,int);
int main(void)
{
int i, index, size, target, list[20];
system("cls"); //clrscr();
printf("Enter size of the list:");
scanf("%d",&size);
printf("Enter any %d elements:\n", size);
for(i = 0; i < size; i++)
scanf("%d", &list[i]);
printf("Enter target value:\n");
scanf("%d", &target);
index=binSearch(list,target,size);
if(index==-1)
printf("%d isn't found in the list",target);
else
printf("%d is fount at %d in the list",target,index);
getch();
return 0;
}

int binSearch(int list[], int target, int size)


{
int first, mid, last;
first = 0;
last = size - 1;

while (first <= last)


{
mid = (first+last)/2;
if(target == list[mid])
return mid;
else if (target > list[mid])
first = mid+1;
else
last = mid-1;
}
return -1;
}
Output:
Enter size of the list:10
Enter any 10 elements:
2 5 7 9 13 17 21 27 29 31
Enter target value:
21
21 is fount at 6 in the list

FUNCTIONS:

 The programs we have presented so far have been very simple. They solved problems that could be
understood without too much effort.
 As the program size grows and it is common practice to divide the complex program into smaller
elementary parts.
 The planning for large programs is simpler. First we must understand the problem as a whole; then break it
into simpler and smaller understandable parts. We call each of these parts of a program a module and
subdividing a problem into manageable parts top-down design.
 The technique used to pass data to a function is known as parameter passing.

Functions in C:

 In C, the idea of top-down design is done using functions. A C program is made of one or more functions,
but one and only one of which must be named main.
 The execution of the program always starts and ends with main, but it can call other functions to do some
of the job.
 A function in main including main is an independent module that will be called to do a specific task. A
called function receives control from calling function.
 When the called function completes its task, it returns control back to the calling function. It may or may
not return a value to the caller.
 The function main is called by the operating system; main in turn calls other functions. When main is
complete, control return to the operating system.
 In general, the purpose of a function is to receive zero or more pieces of data, operate on them, and return
at most one piece of data.

Advantages of using functions in C:

 Problems can be divided into understandable and manageable steps.


 Functions provide a way to reuse code that can be used in more than one place in the program.
 Functions are used to protect data. The local data described in a function is available only to the function
and only while the function is executing. Local data in a function cannot be seen or changed by a function
outside of its scope.
User-Defined Functions:

 Like every other object in C, functions must be declared, defined and called when needed.
 The function declaration needs to done before the function call, mentions the name of the function, the
return type and type and order of the formal parameters. The declaration uses only the header of the
function and ended with a semicolon.
 The function definition can be coded after the function call contains the code needed to complete the task.
 The function call comes within a function which calls it to get the portion of the job to be done.
 A function name is used three times: for declaration, in a call and for definition.
 Example programs:

// Simple greetings program using functions


#include <stdio.h>
void greetings(void);
void main()
{
greetings();
}

void greetings()
{
printf("Hello World\n");
}
Output:
Hello World

Basic Function Design:

 The classification of the basic function designs is done by their return values and their parameter list.
 Functions either return a value or don’t. Functions that don’t return a value are known as void functions.
 Based on requirement parameter list is also optional. Either they can have parameters or don’t.
 Combining the return values and parameter lists functions can be classified into four basic designs:
1. void functions without parameters
2. void functions with parameters
3. non void functions without parameters
4. non void functions with parameters

1. void functions without parameters:

 A void function can be written without any parameters.


 As the void function does not have a return value, it can be used only as a statement. It cannot be used in an
expression.
result = greeting(); // error. void function

// void functions without parameters


#include <stdio.h>
void add(void);
void main()
{
add();
}

void add(void)
{
int a=10,b=20,sum;
sum=a+b;
printf("Sum of %d,%d is:%d",a,b,sum);
}
Output:
Sum of 10,20 is:30

2. void function with parameters

 A void function can have parameters.


 Parameters are helpful in passing the values from the calling function to the called function. Passing
parameters is a technique of sending the values to the called function.
 As the void function does not have a return value, it can be used only as a statement. It cannot be used in an
expression.

// void functions with parameters


#include <stdio.h>
void add(int,int);
void main(void)
{
int a=10,b=20;
add(a,b);
}

void add(int x, int y)


{
int sum;
sum=x+y;
printf("Sum of %d,%d is:%d",x,y,sum);
}
Output:
Sum of 10,20 is:30

3. Non void functions without parameters

 This type of functions returns a value but don’t have any parameters.
 The most common use of this design reads data from the keyboard or file and returns to the calling
function.
 As this function returns a specific type of value, the function call must be initialized with variable of that
specific type.

// Non - void functions without parameters


#include <stdio.h>
int add(void);
void main(void)
{
int sum;
sum=add();
printf("Sum of a,b is:%d",sum);
}

int add()
{
int a=10,b=20,sum;
sum=a+b;
return sum;
}
Output:
Sum of a,b is:30
//Programs for getValue() function
#include <stdio.h>
int getValue(void);
void main(void)
{
int val1,val2;
val1=getValue();
val2=getValue();
printf("Val1:%d, val2:%d",val1,val2);
}

int getValue(void)
{
int val;
printf("Enter Value:");
scanf("%d",&val);
return val;
}
Output:
Enter Value:24
Enter Value:36
Val1:24, val2:36

4. Non-void functions with parameter

 This type of functions passes parameters and returns a value.


 As this function returns a specific type of value, the function call must be initialized with variable of that
specific type.

//Non-void function with parameters


#include <stdio.h>
int add(int,int);
void main(void)
{
int a=10,b=20,sum;
sum=add(a,b);
printf("Sum of a,b is:%d",sum);
}

int add(int x,int y)


{
int res;
res=x+y;
return res;
}
Output:
Sum of a,b is:30

User Defined Functions:

o Like every other object in C, functions must be declared, defined and initialized (calling of the function).
o The functions defined by the user who is writing the program, but not by the developers of the language are
known as user defined functions.
o To use functions in a C-Program one has to do, the declaration, definition and initialization of the function.
o The function declaration has to be done before function call, which will give the complete picture of the
function.
o And definition will succeed function call, which actually contains the statements (body) of the function.

Function Declaration:

o Function declaration consists of only a function header. It contains no code (body of the function).
o Function declaration consists of three parts: the return type, the function name and the formal parameter
list.
o Function declaration will be terminated by a semicolon.
o The return type is the type of value the function is going to return after performing its job. If there is no
return type the type will be void type.
o In declaration the parameter list will indicate only the valid type and order of the parameters; the variable
identifier can be omitted here in this case.
o Generally the declarations are placed in the global declaration area of the program. That is before the main
function.

Function call:

o The function call is postfix expression.


o The operand in the function call is the function name and the operator is the parenthesis set, which contains
the actual parameters.
o The actual parameters hold the actual values that are to be sent to the called function. They must match
with the function definition’s formal parameter list in both type and order. While specifying actual
parameters variable identifiers are required.
o If the function call is having multiple parameters to be passed, they must be separated by commas.
o Functions can return values. If a functions return type is void it, then it cannot be used as part of an
expression, it has to be called as a stand-alone.
o But if a function is having a return value, then either its call must be initialized with a suitable type variable
or it has to be used in an expression. If the function is called like a stand-alone then the return value will be
discarded.

Function Definition:

o The function definition contains the code for a function.


o It is made up of two parts: the function header and the function body.

function header

 A function header consists of three parts: the return type, the function name, and the formal parameter list.
 A semicolon is not required at the end of the function definition header.
 The return-type should come before the function name; return-type specifies the type of value a function
will return. If the function has nothing to return, the return type will be void.
 The formal parameter list must match with the type and order of the actual parameters. Here while
specifying the formal parameters the variable identifier is must, which will hold the values passed by actual
parameters.

function body

 The function body contains the local declarations and the function statements.
 The body starts with local definitions that specify the variables needed by the function. After local
definition, the function statements, terminating with a return statement.
 If a functions return type is void, it can be written without a return statement.

Formal Parameter List:

 In the definition of a function, the parameters are contained in the formal parameter list.
 This list declares and defines the variables that will contain the data received by the function.
 If the function has no parameters; if it is not receive any data from the calling function, then the parameter
list can be void.

Local Variables:

A local variable is a variable that is defined inside a function body and used without having any role in the
communication between functions.

//Example program for functions


#include<stdio.h>
int add(int,int);
int getValue();
void putValue(int);
void main(void)
{
int a,b,c;
a=getvalue();
b=getvalue();
c=add(a,b);
putvalue(c);
}

int add(int x,int y)


{
int z;
z=x+y;
return z;
}

int getvalue()
{
int temp;
printf("Enter value:");
scanf("%d",&temp);
return temp;
}

void putvalue(int res)


{
printf("Result: %d",res);
}
Output:
Enter value: 24
Enter value: 32
Result: 56
INTER-FUNCTION COMMUNICATION:

 Inter function communication is a concept through which calling function and called function will
communicate with each other, and exchange the data.
 The data flow between the called and calling function can be divided into three strategies:
I. Downward flow
II. Upward flow
III. Bi-directional flow

I. Downward flow:

 In downward communication, the calling function sends data to the called function.
 No data flows in the opposite directions.
 The called function may change the values passed, but the original values in the calling function remains
untouched.
 The pass by value or call by value mechanism is a perfect solution for downward flow.
 A variable is declared and defined in the called function for each value to be received from the calling
function.
 Downward communication is one-way communication. The calling function can send data to the called
function, but the called function cannot send any data to the calling function.

//downward communication
#include<stdio.h>
void downFun(int,int);
void main(void)
{
int a=5;
downFun(a,15);
printf("Value of a is:%d",a);
}

void downFun(int x,int y)


{
x=x+y;
}
Output:
Value of a is: 5
II. Upward Communication:

 Upward communication occurs when the called function sends data back to the calling function without
receiving any data from it.
 C provides only one way for upward flow, the return statement.
 Using return statement only one piece of data item can be returned.
 To send multiple values back to the calling function, we have to use references of variables. References are
memory locations which carries the data from called function to the calling function.

//upward communication
#include<stdio.h>
void upFun(int*,int*);
void main(void)
{
int a,b;
upFun(&a,&b);
printf("Value of a, b are:%d,%d",a,b);
}

void upFun(int* aptr,int* bptr)


{
*aptr = 24;
*bptr = 32;
}
Output:
Value of a, b are: 24,32

III. Bi-direction Communication:

 Bi-directional communication occurs when the calling function sends data down to the called function.
After processing the called function sends data up to the calling.
 The strategy described for upward communication can also be used for bi-direction communication, but
with a little modification.
 The only change is that the indirect reference must be used in both sides of the assignment statement.
 With this change the variable in the called function first is accessed for retrieving data using address
variable in the right hand side.
 The same parameter is used again to store a value in the left-hand side.
 Note: both upward and bidirectional communications are examples for pass by reference or call by
reference mechanisms.

//Bi-directional communication:
#include<stdio.h>
void biFun(int*,int*);
void main(void)
{
int a=2,b=3;
biFun(&a,&b);
printf("Value of a, b are:%d,%d",a,b);
}
void biFun(int* aptr,int* bptr)
{
*aptr = *aptr+24;
*bptr = *bptr+32;
}
Value of a,b are: 26, 35

STANDARD FUNCTIONS (LIBRARY FUNCTIONS):

 C provides a rich collection of standard functions whose definitions have been written and are ready to be
used in our programs.
 To use these functions, we must include their function declarations into our program.
 The function declarations are generally found in header files.
 Instead of adding each declaration separately, a simple statement with header file can be included on top of
the program.

Math functions

 Several library functions are available for mathematical calculations.


 Most of them are in either math header file (math.h) or standard library (stdlib.h).

Absolute value functions:

 These functions will return the absolute value of a number.


 An absolute value is the positive value of the value regardless of its sign.
 There are 3-integer and 3-floating point functions.
 The integer functions are abs, labs, and llabs.
 For abs the parameter must be an int and it returns an int. For labs the parameter must be a long int, and it
returns a long int. For llabs the parameter must be a lond int, and it returns a long long int.
 General Syntax:
 int abs(int);
 long labs(long);
 long long llabs(long long);

 The real functions are fabs, fabsf and fabsl. For fabs the parameter is a double, and it returns a double. For
fabsf the parameter is a float and returns a float. For fabsl the parameter is a long double and returns a long
double.
 General Syntax:
 double fabs(double);
 float fabsf(float);
 long double fabsl(long double);
// Absolute value functions
#include<stdio.h>
#include<math.h>
void main(void)
{
float val=-2.674;
float res;
res = fabsf(val);
printf("Absolute value of %f is %f", val, res);
}
Output:
Absolute value of -2.674000 is 2.674000

Ceiling Functions

 A ceiling is the smallest integral value greater than or equal to a number.


Example: Ceiling of 3.00001 is 4.
 If the complete numbers are considered as continues range from minus infinity to plus infinity, this
function moves the number right towards an integral value.

 The declarations for ceiling function are:


 double ceil (double);
 float ceilf(float);
 long double ceill(long double);

 Example: ceil (-1.9) returns -1.0


ceil (1.1) returns 2.0

// Ceiling Functions
#include<stdio.h>
#include<math.h>
void main(void)
{
float val = 2.674;
float res;
res = ceilf(val);
printf("Ceiling value of %f is %f", val, res);
val = -2.674;
res = ceilf(val);
printf("\nCeiling value of %f is %f", val, res);
}
Output:
Ceiling value of 2.674000 is 3.000000
Ceiling value of -2.674000 is -2.000000
Floor Functions
 A floor is the largest integral value that is equal to or less than a number.
 Example: Floor of 3.99999 is 3.0.
 On number series, this function moves the number left towards an integral value.

 The declarations for floor function are:


 double floor (double);
 float floorf (float);
 long double floorl (long double);

 Example: floor (-1.1) returns -2.0


floor (1.9) returns 1.0
// Floor Functions
#include<stdio.h>
#include<math.h>
void main(void)
{
float val = 2.674;
float res;
res = floorf(val);
printf("Floor value of %f is %f", val, res);
val = -2.674;
res = floorf(val);
printf("\nFloor value of %f is %f", val, res);
}
Output:
Floor value of 2.674000 is 2.000000
Floor value of -2.674000 is -3.000000

Truncate Functions
 The truncate functions return the integral value in the direction of 0.
 They are same as floor functions for positive numbers and same as ceiling function for negative numbers.
 Their function declarations are:
 double trunc (double);
 float truncf (float);
 long double truncl (long double);

 Example: trunc (-1.1) returns -1.0


trunc (1.9) returns 1.0
// Truncate Functions
#include<stdio.h>
#include<math.h>
void main(void)
{
float val = 2.674;
float res;
res = truncf(val);
printf("Truncate value of %f is %f", val, res);
val = -2.674;
res = truncf(val);
printf("\nTruncate value of %f is %f", val, res);
}
Output:
Truncate value of 2.674000 is 2.000000
Truncate value of -2.674000 is -2.000000

Round Functions
 The round functions return the nearest integral value.
 Their function declarations are:
 double round (double);
 float roundf(float);
 long double roundl(long double);

 Example: round (-1.1) returns -1.0


round (1.9) returns 2.0
// Round Functions
#include<stdio.h>
#include<math.h>
void main(void)
{
float val = 2.674;
float res;
res = roundf(val);
printf("Round value of %f is %f", val, res);
val = -2.674;
res = roundf(val);
printf("\nRound value of %f is %f", val, res);
}
Output:
Round value of 2.674000 is 3.000000
Round value of -2.674000 is -3.000000

Power Functions:
 The power (pow) function return the value of the x raised to the power of y.
 An error occurs if the base (x) is negative and the exponent (y) is not an interger, or if the base is zero and
the exponent is not positive.

 The power function declarations are:


 double pow (double, double);
 float powf (float, float);
 long double powlf (long double, long double);

 Example: pow (3.0, 4.0) returns 81.0

Square Root Functions:


 The square root functions return the non-negative square root of a number.
 An error occurs if the number is negative.
 The square root function declarations are:
 double sqrt (double);
 float sqrtf (float);
 long double sqrtlf(long double);

 Example: sqrt (25) returns 5.0

// Power and Square root functions


#include<stdio.h>
#include<math.h>
void main(void)
{
float val1 = 3;
float val2 = 4;
float res1, res2;
res1 = powf(val1,val2);
printf("%f power of %f is %f", val1, val2, res1);
res2 = sqrtf(res1);
printf("\nSquare root of %f is %f", res1, res2);
}
Output:
3.000000 power of 4.000000 is 81.000000
Square root of 81.000000 is 9.000000

PASSING ARRAY TO FUNCTIONS

 Arrays can also be passed as parameters to functions when required.


 There are two possibilities in which arrays can be passed:
a) Passing individual elements
b) Passing the whole array

Passing Individual elements

Individual elements can be either by their values or by their addresses.

Passing data values

 Individual data values of arrays can be passed using their index along with array name.
 As long as the type is matching, the called function is unaware whether the value is coming from an array
or a normal variable.

// Passing data values from an array


#include<stdio.h>
void arrAccess(int);
void main(void)
{
int a[5]={2,4,3,6,9};
arrAccess(a[3]);
printf("Array element after function call: %d",a[3]);
}

void arrAccess(int temp)


{
printf(“Parameter received from calling function: %d”,temp);
temp = 36;
}
Output:
Parameter received from calling function: 6
Array element after function call: 6

Passing Addresses

 The address of the elements of the array can also be passed to the function.
 The individual element addresses can be passed just like any other variable address.
 To pass an array element’s address, the address operator can be prefixed to the element’s indexed
reference.
 Example: The address of 4th element in the array can be passed in following way: &arr[3];

Passing an address of an array element requires two changes in the called function.

 First, it must declare that it is receiving an address.


 Second, it must use the indirection operator (*) to refer to the elements value.
// Passing the address of an array element
#include<stdio.h>
void arrAccess(int*);
void main(void)
{
int a[5]={2,4,3,6,9};
arrAccess(&a[3]);
printf("Array element after function call: %d",a[3]);
}

void arrAccess(int* temp)


{
printf(“Parameter received from calling function: %d”,*temp);
*temp = 36;
}

Output:
Parameter received from calling function: 6
Array element after function call: 36

Passing the whole array

 In C, the name of an array holds the address of the first element in the array.
 Using array name and index values the complete array elements can be accessed.
 Passing the array name instead of a single element, allows the called function to refer to the same array
back in the calling function.
//Passing whole array to called function
#include<stdio.h>
void arrAccess(int[]);
void main(void)
{
int a[5]={2,4,3,6,9},i;
arrAccess(a);
printf("\nAfter function call Elements in Array:");
for(i=0;i<5;i++)
printf("%d ", a[i]);
}

void arrAccess(int arrTemp[])


{
int i;
printf("Elements in Array:");
for(i=0;i<5;i++)
printf("%d ", arrTemp[i]);
for(i=0;i<5;i++)
arrTemp[i] = i;
}
Output:
Elements in Array:2 4 3 6 9
After function call Elements in Array:0 1 2 3 4
Unit - IV

RECURSION

 Programmers use two approaches for writing repetitive algorithms: One approach uses loops and the other
uses recursion.
 Recursion is a repetitive process in which a function calls itself.
 Some older languages do not support recursion. One major language that does not support recursion is
COBOL.
 To study the concept of recursion let us consider the example of finding factorial of a given number.
 In our study we’ll see both iterative definition and recursive definition for finding the factorial.

Iterative Definition

 The factorial of a number is the product of the integral values from 1 to the given number.
 The iterative definition can be shown as:

 An iterative function can be defined which will take only the iteration counter to calculate the factorial but
not the function call.
Example: factorial (4) = 4 * 3 * 2 * 1 = 24

Recursive Definition

 A function is defined recursively whenever the function itself appears within the definition itself.
 The recursive definition of factorial function can be shown as:

 The decomposition of factorial (3), using the above formula is shown in the following formula.
 Observe it carefully; the recursive solution for a problem involves a two-way journey: the decomposition
will be from top to bottom, and then we solve it from bottom to the top.
 Every recursive call must either solve part of the problem or reduce the size of the problem.
 The recursive calculation looks more difficult when using pen and paper, but it is often much easier and
more elegant solution when a computer is used.
 Every recursive solution to the problem will have a base-case and general-case. A base-case will provide
the solution to the problem and all other cases will be known as general-cases.
 In the factorial example the base-case is factorial of (0) and all other cases are general-cases.

Iterative solution to factorial problem

//Iterative solution to factorial problem


#include<stdio.h>
int factorial(int);
void main(void)
{
int n,res;
printf("Enter any number:");
scanf("%d",&n);
res=factorial(n);
printf("Factorial of %d is: %d", n, res);
}

int factorial(int num)


{
int i, fact = 1;
for(i=1;i<=num;i++)
fact=fact*i;
return fact;
}
Output:
Enter any number:5
Factorial of 5 is: 120

Recursive solution to factorial problem

//Recursive solution to factorial problem


#include<stdio.h>
int factorial(int);
void main(void)
{
int n,res;
printf("Enter any number:");
scanf("%d",&n);
res=factorial(n);
printf("Factorial of %d is: %d", n, res);
}

int factorial(int num)


{
if(num == 0)
return 1;
else
return (num * factorial(num-1));
}
Output:
Enter any number:5
Factorial of 5 is: 120

Fibonacci Numbers

 Finding the Fibonacci numbers is another example for recursion.


 Fibonacci numbers are a series in which each number is the sum of the previous two numbers. This number
series is named after an Italian mathematician Leonardo Fibanacci of thirteenth century.
Example: First few numbers in Fibonacci series are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ….
 To start the series always first two numbers will be 0 and 1.
 The generalized statements for Fibonacci series are as follows:
Given: fibonacci0 = 0;
fibonacci1 = 1;
Then: fibonaccin = fibonaccin-1 + fibonaccin-2
 To calculate the fibonacci4 the steps are shown in the following figure:

Iterative solution to factorial problem

//Iterative solution to Fibonacci Series Problem


#include <stdio.h>
void fibonacci(int);
void main(void)
{
int n;

printf("Enter the number of terms: ");


scanf("%d", &n);
fibonacci(n);
}

void fibonacci(int n)
{
int i, term1 = 0, term2 =1, nextTerm;
for (i = 1; i <= n; ++i)
{
printf("%d, ", term1);
nextTerm = term1 + term2;
term1 = term2;
term2 = nextTerm;
}
}
Output:
Enter the number of terms: 6
0, 1, 1, 2, 3, 5,
Recursive solution to factorial problem

//Recursive solution to factorial problem


#include <stdio.h>
int fibonacci(int);
void main(void)
{
int nterms, fib = 0, i;
printf("Enter the nuumber of terms:");
scanf("%d", &nterms);
printf("Fibonacci series terms are:\n");
for (i = 0; i < nterms; i++)
{
printf("%d, ", fibonacci(fib));
fib++;
}
}

int fibonacci(int n)
{
if(n == 0 || n == 1)
return n;
return (fibonacci(n - 1) + fibonacci(n - 2));
}
Output:
Enter the nuumber of terms:6
Fibonacci series terms are:
0, 1, 1, 2, 3, 5,

Finding GCD (Greatest Common Divisor):

 The HCF (Highest Common Factor) or GCD (Greatest Common Divisor) of two integers is the largest
integer that can exactly divide both numbers (without a remainder).

Iterative solution to GCD problem

//Iterative solution to GCD problem


#include <stdio.h>
void main(void)
{
int n1, n2, i, gcd;

printf("Enter two integers: ");


scanf("%d %d", &n1, &n2);

for(i=1; i <= n1 && i <= n2; i++)


{
// Checks if i is factor of both integers
if(n1%i==0 && n2%i==0)
gcd = i;
}
printf("G.C.D of %d and %d is %d", n1, n2, gcd);
}
Output:
Enter two integers: 5 6
G.C.D of 5 and 6 is 1

Recursive solution to GCD problem

// Recursive solution to GCD problem


#include <stdio.h>
int gcd(int, int);
void main(void)
{
int n1, n2;
printf("Enter two integers: ");
scanf("%d %d", &n1, &n2);

printf("G.C.D of %d and %d is %d.", n1, n2, gcd(n1,n2));


return 0;
}

int gcd(int n1, int n2)


{
if (n2 != 0)
return gcd(n2, n1%n2);
else
return n1;
}
Output:
Enter two integers: 6 42
G.C.D of 6 and 42 is 6.
STRUCTURE

 A structure is a collection of heterogeneous data elements.


 A structure in C is a collection of items of different types.
 A structure is a collection of logically related elements, possibly of different types.
Example:

 Each element in a structure is called a field. A field is the smallest element of named data that has meaning.
It has many of the characteristics of the variables. It has a type, an identifier and it also exists in the
memory. It can be initialized a value, and later can be used for manipulations. The only difference between
the variable and a structure field is that, structure field is a part of the structure.
 The difference between an array and a structure is that, all elements in an array must be of same type, but
the elements in a structure can be of same or different types.
 A structure is a convenient way in which data are grouped into one single name. It provides flexibility and
an increased control over accessing the data when it needed. Using structures data can be accessed as a
single grouped object or individual elements can be accessed.

Structure Type Declaration:

 Like every other element in C, a structure must be declared and defined.


 In C we have two ways to declare a structure:
1. Tagged Structures
2. Type-defined structures

1. Tagged Structures:

 The first way to define a structure is using tagged structure.


 A tagged structure can be used to define variables, parameters to functions and return types of functions.
 A tagged structure starts with the keyword struct, followed by the TAG. The TAG is the identifier for the
structure; it is used for accessing the fields of the structure.
 The format is:
Syntax: Example:
Struct TAG Struct STUDENT
{ {
Filed list; char name[20];
}; char ID[10];
int marks;
};
Note: Notice that the structure is concluded with a semicolon, no variables are
defined so no associated storage. It is just a template for the structure.

2. Type-defined structures (using typedef):

It is a more powerful way of declaring a structure. By using the keyword typedef the structure will be declared.

The format is:

Syntax: Example:
typedef struct typedef struct
{ {
Filed list; char name[20];
}TYPE; char ID[10];
int marks;
}STUDENT;

 The type-defined structure differs from the tagged declarations in two ways:
 First, the keyword, type-def, is added in the beginning of the declaration.
 Second, an identifier is required at the end of the block. The identifier will be the structure
type name.

Structure Variable declaration:

 After a structure has been declared, a variable of structure type can created using it.
 The structure type can be declared in the global area of the program, to make it visible to all functions.
 The structure variables are declared in the local declarations.

Tagged Structure Type defined structure


// Global Type declarations // Global Type declarations
struct STUDENT typedef struct
{ {
char name[20]; char name[20];
char ID[20]; char ID[20];
int marks; int marks;
}; }STUDENT;

//Local declarations //Local declarations


struct STUDENT aStudent; STUDENT aStudent;
//Demonstration of Tagged Structure
#include<stdio.h>
struct NODE
{
int data;
char ch;
};
void main(void)
{
struct NODE node;
node.data = 20;
node.ch = 'c';
printf("Data = %d",node.data);
printf("\nCharacter = %c",node.ch);
}
Output:
Data = 20
Character = c

Initialization

 The rules for structure initialization are similar to the rules for array initialization.
 The initializing values are enclosed in braces and separated by commas.
 They must match the corresponding types in the structure definition.
Examples:

Accessing Structures:

 The elements in a structure can be accessed individually or the complete structure can assigned as a whole.

Referencing Individual Fields:

 Structure fields can be accessed and manipulated using operators just like any other normal variables.
 To refer to a field in a structure the structure and the field both has to be referred.
 C uses a hierarchical naming convention that first uses the structure variable identifier and then the field
identifier.
 The structure variable identifier is separated from the field identifier by a dot.
 The dot is known as the direct selection operator.

Example1: Example2:
aStudent.ID SAMPLE sam1={2,5,3.2,’A’};
aStudent.name scanf(“%d %d %f %c”, &sam1.x, &sam1.y,
aStudent.marks &sam1.t, &sam1.u);
prinf(“%d %d %f %c”, sam1.x, sam1.y,
sam1.t, sam1.u);

//Example program on structures


#include<stdio.h>
typedef struct
{
int x;
int y;
float t;
char u;
}SAMPLE;

void main(void)
{
//declaring, defining and initializing the structure variable sam1
SAMPLE sam1 = {5,4,3.2,'A'};
SAMPLE sam2;
printf("sam1 contents:\n");
printf("%d %d %f %c", sam1.x,sam1.y,sam1.t,sam1.u);
printf("\nEnter contents for sam2:\n");
scanf("%d %d %f %c",&sam2.x,&sam2.y,&sam2.t,&sam2.u);
//Modifying sam1
sam1.x=45;
sam1.y=32;
sam1.t=5.4;
sam1.u='d';
printf("\nsam1 contents after modification:");
printf("%d %d %f %c", sam1.x,sam1.y,sam1.t,sam1.u);
printf("\nsam2 contents after modification:");
printf("%d %d %f %c", sam2.x,sam2.y,sam2.t,sam2.u);
}
Output:
sam1 contents:
5 4 3.200000 A
Enter contents for sam2:
3 5 2.45 s

sam1 contents after modification:45 32 5.400000 d


sam2 contents after modification:3 5 2.450000 s
Operations on Structures

 Only one operation is allowed on the structure that is the assignment of a structure to another structure.
 A structure can only be copied to another structure of the same type using the assignment operator.
 When one structure needs to be copied to another structure, instead of assigning the individual members to
another structure’s members, the whole structure can be initialized to another structure.

//Assignment operation between structure variables


#include<stdio.h>
typedef struct
{
int x;
int y;
float t;
char u;
}SAMPLE;

void main(void)
{
//declaring, defining and initializing the structure variable sam1
SAMPLE sam1 = {5,4,3.2,'A'};
SAMPLE sam2;
sam2 = sam1;
printf("sam1 contents:\n");
printf("%d %d %f %c", sam1.x,sam1.y,sam1.t,sam1.u);
printf("\nsam2 contents:\n");
printf("%d %d %f %c", sam2.x,sam2.y,sam2.t,sam2.u);
}
Output:
sam1 contents:
5 4 3.200000 A
sam2 contents:
5 4 3.200000 A

Pointer to structure:

 Structures can also be accessed through pointers.


 Using pointers is one of the most common methods used to reference structures.
 The SAMPLE structure can be used with pointers in the following manner:
SAMPLE* ptr;
Ptr = &sam1;
*ptr // refers to the whole structure
(*ptr).x (*ptr).y (*ptr).t (*ptr).u //Individual field reference

 The parenthesis in the above example are absolutely required, without the parenthesis the compiler will
consider *ptr.x as *(ptr.x). C applies the dot (.) operator first and then the asterisk operator next.
 The reason the parenthesis are needed is that the precedence of the direct selection operator (.) is higher
than the indirection operator (*).
 Here *ptr.x will be interpreted as *(ptr.x) which is wrong. *(ptr.x) means a completely different undefined
structure called ptr that contains a member x, which must be a pointer. Since this is not true, a compile time
error will be generated.

Indirect selection operator:

 To avoid the above confusion (to eliminate the problem with pointers to structures) a special operator
known as indirect selection operator is used.
 The symbol used for indirect selection operator is an arrow formed by minus sign and the grater than
symbol (->).
 The indirection operator is placed between the pointer identifier of structure and the member to be
referenced.

//Example program for indirect selection operator


#include<stdio.h>
typedef struct
{
int x;
int y;
float t;
char u;
}SAMPLE;

void main(void)
{
//declaring, defining and initializing the structure variable sam1
SAMPLE sam1 = {5,4,3.2,'A'};
SAMPLE* strPtr;
strPtr = &sam1;
printf("Accessing sam1 contents through structure variable and direct selection operator (dot(.)):\n");
printf("%d %d %f %c", sam1.x,sam1.y,sam1.t,sam1.u);
printf("\nAccessing sam1 contents through pointer to structure and direct selection operator (dot(.)):\n");
printf("%d %d %f %c", (*strPtr).x,(*strPtr).y,(*strPtr).t,(*strPtr).u);
printf("\nAccessing sam1 contents through pointer to structure and indirect selection operator (->):\n");
printf("%d %d %f %c", strPtr->x,strPtr->y,strPtr->t,strPtr->u);
}
Output:
Accessing sam1 contents through structure variable and direct selection operator (dot(.)):
5 4 3.200000 A
Accessing sam1 contents through pointer to structure and direct selection operator (dot(.)):
5 4 3.200000 A
Accessing sam1 contents through pointer to structure and indirect selection operator (->):
5 4 3.200000 A

COMPLEX STRUCTURES

 Structures within structures (nested structure), arrays within structure, and arrays of structures are some of
the complex forms of structures.
i. Nested Structures
ii. Structures containing Arrays
iii. Structures containing pointers
iv. Array of structures

i. Nested Structures:

 A structure can have another structure as a member.


 When a structure includes another structure it is nested structure.
 There is no limit to the number of structures that can be nested, but for ease of understanding we limit it up
to three.

Example:

//type declarations
typedef struct
{
int month;
int day;
int year;
}DATE;
typedef struct
// A more complex form {
typedef struct int hour;
{ int min;
STAMP startTime; int sec;
STAMP endTime; }TIME;
}JOB;
typedef struct
//variable declaration {
JOB job; DATE date;
TIME time;
}STAMP;

//variable declarations
STAMP stamp;

Referencing Nested structures:

 The most important point to remember when nesting structures is, they must be declared from inside
out. That is they must be declared from lowest level to the highest level. When nesting a structure into
the other structure the inner structure must be declared first before its inclusion.
 To access fields of nested structures the direct referencing operator dot(.) is used from highest level to
inner component level.

stamp stamp
stamp.date stamp.time
stamp.date.month stamp.time.hour
stamp.date.day stamp.time.min
stamp.date.year stamp.time.sec

job.startTime.time.hour
job.endTime.time.hour

Nested Structure Initialization:

 To initialize a Nested Structure simply pass the values using sets to the outermost structure variable using
assignment operator.
 The outermost structure will have the instances of inner structure and hence initializes the values
accordingly.

STAMP stamp = {{05, 10, 2019}, {23, 45, 01}};

// Nested Structure Program


#include<stdio.h>
typedef struct
{
char* month;
int day;
int Year;
}DATE;

typedef struct
{
int hour;
int min;
int sec;
}TIME;

typedef struct
{
DATE date;
TIME time;
}TIMESTAMP;

void main(void)
{
TIMESTAMP tstamp = {{05, 10, 2019}, {23, 45, 01}};
printf("Event Date (mm:dd:yyyy): %d / %d / %d", tstamp.date.month, tstamp.date.day, tstamp.date.Year);
printf("\nEvent Time (hh:mm:ss): %d : %d : %d", tstamp.time.hour, tstamp.time.min, tstamp.time.sec);
}
Output:
Event Date (mm:dd:yyyy): 5 / 10 / 2019
Event Time (hh:mm:ss): 23 : 45 : 1

ii. Structures containing arrays

 Structures can have one or more arrays as members.


 The arrays can be accessed either through indexing or through pointers.

Defining Arrays within structures:

 To define arrays within structures just defined in their regular approach within the structure.

Referencing Arrays within structures:

 Referencing arrays within a structure is same like referencing other elements from the structure.
 First we need to qualify the element with structure name and then with index or pointer the array can be
accessed from the structure.
Initializing Arrays within a structure

 Since array is a separate member and it will have other members as part of it, hence the value for an array
within a structure must be separated using a set of braces.

Example:

STUDENT student = {“John”,{20,18,17},80};

// Arrays within structures example


#include<stdio.h>
typedef struct
{
char name[20];
int midterm[3];
int final;
}STUDENT;

void main(void)
{
STUDENT student = {"John", {18, 17, 15}};
student.final = student.midterm[0]+student.midterm[1]+student.midterm[2];
printf("Student Name: %s",student.name);
printf("\nStudent midterm Marks: %d %d %d", student.midterm[0], student.midterm[1], student.midterm[2]);
printf("\nStudent Final Marks: %d", student.final);
}
Output:
Student Name: John
Student midterm Marks: 18 17 15
Student Final Marks: 50

Point of Consideration:
 A pointer can be used to refer directly the array elements within a structure.
 Consider the above example to store the starting location of midterm array a pointer pScore can be used.
Later using this pScore one can access the complete array midterm without depending on the structure.
Example:
int* pScore = student.midterm;
int total = *pScore + *(pScore+1) + *(pScore+2);

iii. Structures containing pointers:

 A Structure can have pointers as members.


 The pointer in a structure can be used and accessed just like any other variables using the direct selection
operator.
 Pointers in a structure are mostly used with strings to save memory.
typedef struct
{
char* month;
int day;
int Year;
}DATE;

typedef struct
{
DATE date;
}STAMP;

//variable declarations
STAMP tstamp;

//Initialization
stamp.date.month = may;

// Structures containing pointers


#include<stdio.h>
typedef struct
{
char* month;
int day;
int year;
}DATE;

typedef struct
{
DATE date;
}TIMESTAMP;

void main(void)
{
TIMESTAMP tStamp = {"May", 9, 2019};
printf("Event DATE: %dth %s - %d", tStamp.date.day, tStamp.date.month, tStamp.date.year);
}
Output:
Event DATE: 9th May - 2019

iv. Array of Structures:

 In many situations array of structures can be created.


 Example: To manage a group of students, an array of student’s structure can be created.
 By putting the data into an array it will become more flexible and easy to work with the data, to calculate
sum and average for instance.
 To create an array of 50 students the following example can be used:
STUDENT stuAry[50];

// To access individual student data


stuAry[1]; //first student details

//Array of structures Program


#include<stdio.h>
typedef struct
{
char name[20];
int rollno;
int midmarks[3];
}STUDENT;

void main(void)
{
STUDENT std[5];
int i;

printf("Enter information of students:\n");

// storing information
for(i=0; i<5; i++)
{
std[i].rollno = i+1;

printf("\nFor roll number: %d,\n",std[i].rollno);

printf("Enter name: ");


scanf("%s",std[i].name);

printf("Enter 3 Mid Marks: ");


scanf("%d %d %d",&std[i].midmarks[0], &std[i].midmarks[1], &std[i].midmarks[2]);

printf("\n");
}

printf("Displaying Information:\n\n");
// displaying information
for(i=0; i<5; i++)
{
printf("\nRoll number: %d\n",std[i].rollno);
printf("Name: ");
puts(std[i].name);
printf("Marks: %d %d %d",std[i].midmarks[0], std[i].midmarks[1], std[i].midmarks[2]);
printf("\n");
}
}
Output:
Enter information of students:

For roll number: 1


Enter name: John
Enter 3 Mid Marks: 12 13 15

For roll number: 2


Enter name: Asif
Enter 3 Mid Marks: 15 17 19

Displaying Information:

Roll number: 1
Name: John
Marks: 12 13 15

Roll number: 2
Name: Asif
Marks: 15 17 19

UNIONS

 A union is similar to a structure, as it is also a collection of elements of different types.


 A union is a constructs that allows memory to be shared by different types of data. In simple terms the
integer memory locations can be used to store two characters. The union basically works on the same
principle.
 The union follows same format and syntax as structure. The only difference between declaration of
structure and union is that, the keyword union is used when declaring a union.

typedef union
{
char chAry[2];
int num;
}SHAREDATA;

Referencing Unions

 The rules for referencing a union are similar to those of a structure.


 To reference individual fields within a union, the direct selection operator (dot) can be used.
SHAREDATA shareData;
shareData.num
shareData.chAry[0]
shareData.chAry[1]

 When a union is being referenced through a pointer, the indirect selection operator ( ) can be used.

SHAREDATA* ptrShareData;
ptrShareDatanum;
ptrShareDatachAry[0];
ptrShareDatachAry[1];

Initializing a Union:

 Only the first type declared in the union can be initialized when the union variable is defined. The other
types can be initialized by assigning values or reading values into the union.
 When initializing a union, the value must be enclosed in a set of braces, even if there is only one value.

//Demonstration of Unions
#include<stdio.h>
typedef union
{
int num;
char chAry[2];
}SHAREDATA;

void main(void)
{
SHAREDATA shareData;
shareData.num = 16706;
printf("Integer Value: %d", shareData.num);
shareData.chAry[0] = 'X';
shareData.chAry[1] = 'Y';
printf("\nValues from character array: %c %c",shareData.chAry[0], shareData.chAry[1]);
printf("\nInteger Value: %d", shareData.num);
}
Output:
Integer Value: 16706
Values from character array: X Y
Integer Value: 22872
DIFFERENCE BETWEEN UNION AND STRUCTURE

BASIS OF COMPARISON STRUCTURE UNION


Basic The separate memory location is allotted All members of the 'union' share the
to each member of the 'structure'. same memory location.
Declaration struct struct_name{ union u_name{
type element1; type element1;
type element2; type element2;
. .
. .
} variable1, variable2, ...; } variable1, variable2, ...;
keyword 'struct' 'union'
Size Size of Structure= sum of size of all the Size of Union=size of the largest
data members. members.
Store Value Stores distinct values for all the members. Stores same value for all the
members.
At a Time A 'structure' stores multiple values, of the A 'union' stores a single value at a
different members, of the 'structure'. time for all members.
Way of Viewing Provide single way to view each memory Provide multiple way to to view
location. same memory location.
Anonymous feature No Anonymous feature. Anonymous union can be declared.
UNIT-V

POINTERS

 Every computer has addressable memory locations.


 The data manipulations so far we did with the help of variable names (identifiers). We assigned an
identifier to the data location and manipulated the content with the help of it.
 Pointers have many uses in C:
 They are one of an efficient way of accessing the data for manipulations.
 They also provide efficient techniques for manipulating data in arrays.
 They are used in functions as pass by address parameter.
 They are the basis for dynamic allocation of memory.

Introduction:

 A pointer is a constant or variable that contains an address that can be used to access data.
 Pointers are built on the basis of pointer constants.

Pointer constant:

 A pointer constant is an address value that specifically represents a memory location in the computers main
memory.
 Like every other constant in computer world a character constant cannot be changed.
 Every time a program runs all variables in the program will get different addresses, this is because in a
computer modern operating systems can put a program in memory wherever it feels convenient.
 Pointer constants are drawn from the set of addresses of a computer. They exist during the run time of a
computer. We cannot change them but we can only use them.

 Being existed in the computer a pointer constant can be retrieved and saved inside a variable.
 The address operator (&) extracts the address of a variable. Syntax: &variable_name
 To print the address of a variable the conversion code %p can be used.
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
//Printing the address of variables
#include<stdio.h>
int main(void)
{
char a, b;
system(“cls”); //clrscr();
printf(“%p %p”, &a, &b);
getch();
return 0;
}
Output:
142300
142301

Pointer Variables:

 A pointer constant can be saved in a pointer variable, and later can be used to access the value.
 The type of a pointer must be specific to the type of the variable to which it is going to point. That is an
integer type of variables address can be saved into an integer type of pointer.
 To store the address of a variable we need a special type of variable that is Pointer variable.
 A single variables address can be saved into multiple pointers, so that we’ll have more number of pointers
pointing to the same location, and it is possible in C.
 If a Pointer variable not pointing to anywhere, that is if we want to make sure that a pointer is not pointing
to any address, C provides a special null pointer (NULL) in the standard Input/Output stdio.h header file
for this purpose.

Accessing Variables through pointers:

 The indirection operator (*) can be used to dereference the pointer’s address.
 The indirection operator is a unary operator whose operand must be a pointer value. The result is, a pointed
variables value that can be used for inspection or manipulation.
 To access the variable a through pointer p, simply code *p.
To add 1 to the variable a’s content any of the following ways can be used
a++ a=a+1 *p=*p+1 (*p)++

 The indirection and address operators are the inverse of each other, and when combined in an expression
they cancel each other. *&x  SAME  x

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Pointer Declaration and Definition:

 To declare a pointer variable the asterisk symbol (*) can be used along with type specification.
 The following figure shows the declaration and definition of different pointer variables and their
corresponding data variable declarations.

//Demonstrate use of pointers


#include<stdio.h>
int main(void)
{
int a;
int* ptr;
system(“cls”); //clrscr();
a = 4;
ptr = &a;
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
printf("%d %p\n", a, &a);
printf("%d %p", *ptr, ptr);
getch();
return 0;
}
Output:
4 0x7ffd93455594
4 0x7ffd93455594

Declaration Vs Redirection:

 The asterisk operator can be used in two different contexts: for declaration and for redirection.
 When asterisk is used for declaration, it is associated with a type.
Example: int* ptr; will declare an integer pointer.
 When asterisk is used for redirection, it is associated with a pointer variable to get the data value of the
variable whose address is stored in that pointer.
Example: sum = *aptr + *bptr;

Initialization of Pointer variables:

 Like every other object in C, pointers must be initialized, before they can be used in the program.
 Like variables, without initialization pointers will also have an unknown garbage value in them.
 When program starts all uninitialized pointers will hold some unknown addresses which are pointing to
some unknown values.

Pointers to Pointers

 In C, it is possible to use pointers that points to other pointers. That is, we can have a pointer pointing to a
pointer to an integer.
 The following figure demonstrates this two level indirection:
 Each level of pointer indirection requires a separate indirection operator when it is dereferenced.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
//demonstration on Using Pointers to Pointers

#include<stdio.h>
int main(void)
{
int a;
int* p;
int** q;
int*** r;
system(“cls”); //clrscr();
p = &a;
q = &p;
r = &q;
printf("Enter a value:");
scanf("%d",&a);
printf("a's value is:%d",a);

printf("\nEnter a value:");
scanf("%d",p);
printf("a's value: %d %d", a, *p);

printf("\nEnter a value:");
scanf("%d",*q);
printf("a's value: %d %d %d", a, *p, **q);

printf("\nEnter a value:");
scanf("%d",**r);
printf("a's value: %d %d %d %d", a, *p, **q, ***r);
getch();
return 0;
}
Output:
Enter a value:4
a's value is:4
Enter a value:5
a's value: 5 5
Enter a value:6
a's value: 6 6 6
Enter a value:7
a's value: 7 7 7 7

Pointer to void (void*)

 A pointer to void is a generic type that is not associated with a reference type, that is it is not the address of
a character, an integer, a floating point or any other type.
 It is compatible for assignment purpose only with all other types.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 A pointer of any reference type can be assigned to a pointer of void type and a pointer to void type can be
assigned to any reference type.
 As void pointer has no specific object type, it cannot be dereferenced unless it is cast properly.
 The following program demonstrate the usage of void pointer in programming:

// Demonstration of void pointer – Generic Pointer


#include<stdio.h>
int main(void)
{
int a = 20;
char c = 'A';
void* ptr;
ptr = &a;
//printf("a=%d",*ptr); //dereference of void pointer is not allowed, generated an error
printf("a=%d",*(int*)ptr);
ptr = &c;
printf("\nc=%c",*(char*)ptr);
getch();
return 0;
}
Output:
a=20
c=A

ARRAYS AND POINTERS

 The name of an array is a pointer constant to the first element in the array. As it is a pointer constant its
value cannot be changed, that is it cannot be used as an lvalue.
 The name of an array and the first element address both will represent the same memory location in
computer memory.
 When the array name is dereferenced it is like dereferencing the first element of the array; that is it gives
the value of the first element array[0].
 Remember, when array name is dereferenced, it refers only to the first element, not the whole array.

//Demonstration of Pointer to array


Program:
#include<stdio.h>
int main(void)
{
int a[4] = {2,4,3,1};
system("cls"); //clrscr();
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
printf("First location address: %p %p\n", a, &a[0]);
printf("First location value: %d %d\n", *a, a[0]);
getch();
return 0;
}
Output:
First location address: 000000000062FE10 000000000062FE10
First location value: 2 2

POINTER ARITHMETIC AND ARRAYS

 Besides indexing, programmers use another powerful method of moving through an array: pointer
arithmetic.
 Pointer arithmetic offers a set of arithmetic operators for manipulating the addresses in pointer.
 This technique is used to move back and forth through an array from element to element.

Pointer to One – Dimensional Arrays

 Having an array a, then ‘a’ is a constant pointing to the first element and a+1 is a constant pointing to the
second element.
 If a pointer ptr is pointing to the second element of the array, then p-1 is a pointer pointing to the previous
(first) element and p+1 is a pointer to the next (third) element.
 Given an array a, a+2 is the address two elements away from a, and a+3 is the address three elements away
from a. So the generalized notation will be as follows:
Given pointer ptr, ptr±n is a pointer to the value n elements away from ptr.

 Indirection operator can be applied on pointer arithmetic to access the value from the location where the
pointer is pointing after pointer arithmetic.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
//Demonstration Pointer Arithmetic
Program:
#include<stdio.h>
int main(void)
{
int a[5] = {2, 4, 6, 8, 22};
int* ptr;
system("cls"); //clrscr();
ptr = &a[1];
printf("\nPrinting array Elements using Indexing: %d %d %d %d %d", a[0], a[1], a[2], a[3], a[4]);
printf("\nPrinting array Elements using Pointer Arithmetic: %d %d %d %d %d", *(ptr-1), *(ptr+0), *(ptr+1), *(ptr+2), *(ptr+3));
printf("\nPrinting array Elements using Pointer Arithmetic: %d %d %d %d %d", *(a+0), *(a+1), *(a+2), *(a+3), *(a+4));
getch();
return 0;
}
Output:
Printing array Elements using Indexing: 2 4 6 8 22
Printing array Elements using Pointer Arithmetic: 2 4 6 8 22
Printing array Elements using Pointer Arithmetic: 2 4 6 8 22

Self-Referential Structures:

 Self-Referential structures holds one or more pointers which point to the same structure type of structure,
as their member.
 In simple words, structures pointing to the same type of structures are self-referential structure.
 A self-Referential structure is essentially a structure definition which includes at least one member that is a
pointer to the structure of its own type.
 See the following declaration of a tagged structure:

struct NODE
{
int data;
struct NODE* link;
};

 The above illustrated structure declaration describes one NODE that comprises of two logical segments.
One of them stores data and the other one is a pointer indicating where the next component can be found. .
 Several such inter-connected nodes create a chain of structures known as linked list.

Linked list Notation:

 The above declaration of structure can be used to create a chain of nodes, where each node is going to hold
some data and a link to another node.
 Several of such nodes can be created and connected to form a data-structure known as linked list.
 The above NODE is having only one data element and a link to the one other NODE of the same type. As
the NODE is having only a single linking pointer between the NODEs, we can also call the data structure
as single linked list.
 The following program demonstrate the concept of single linked list:

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 A linked list is a chain of structures where each NODE points to the next NODE to create a list. To keep
track of the starting NODE’s address a dedicated pointer (referred as start pointer or head pointer) is used.
The end of the list is indicated by a NULL pointer.
 To create a linked list of integers, we define each of its element (referred as NODE) using the following
declaration.

struct NODE {
int data;
struct NODE* link;
};

 Different operations that can be possible on a linked list are:


 Creating a Linked List.
 Displaying its contents.
 Inserting an element into a list.
 Deleting an existing element.

//Demonstration of Single Linked List

#include <stdio.h>

struct NODE {
int data;
struct NODE* link;
};

int main(void)
{
struct NODE node1, node2, node3; // Node1
system("cls"); //clrscr();
// Initialization node1
node1.link = NULL;
node1.data = 10;

// Initialization node2
node2.link = NULL;
node2.data = 20;

// Linking node1 and node2


node1.link = &node2;

// Initialization node3
node3.link = NULL;
node3.data = 30;

// Linking node2 and node3


node2.link = &node3;
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
printf("Node1 data: %d", node1.data);
// Accessing data member of node2 using node1
printf("\nNode2 data: %d", node1.link->data);
// Accessing data member of node3 using node1
printf("\nNode2 data: %d", node1.link->link->data);
getch();
return 0;
}
Output:
Node1 data: 10
Node2 data: 20
Node3 data: 30

 Self-referential structures are very useful in applications that involve linked data structures, such as linked
lists.
 Unlike a static data structure such as array where the number of elements that can be inserted in the array is
limited by the size of the array, a self-referential structure can dynamically be expanded or contracted.
 Operations like insertion or deletion of nodes in a self- referential structure involve simple and straight
forward alteration of pointers.

MEMORY ALLOCATION FUNCTIONS:

In C, there are two ways to reserve memory locations for variables.

1. Static memory allocation


2. Dynamic memory allocation

Memory Usage:

 Memory allocated to a program is divided into program memory and data memory.
 Program memory consists of memory used for main and all called functions.
 Data memory consists of permanent definitions of global and local data and constants, dynamic data
memory.
 main() function must be in memory all the time. Each called function must be in memory only when it is
called and becomes active.
 If a function called more than once, the copies of the local variables of this function will be maintained
inside stack memory.
 In addition to the stack memory, a separate memory area known as heap is also available. Heap memory is
unused memory allocated to the program and available to be assigned during execution. It is the memory
pool from which the memory is allocated when requested by the memory allocation functions.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Static Memory Allocation:

 Static memory allocation requires that the declaration and definition of memory be fully specified in the
source program.
 The number of bytes reserved cannot be changed during run time of the program.
 So far we used this technique for reserving memory for variables, arrays and pointers.

Dynamic Memory Allocation:

 Dynamic memory allocation uses predefined functions to allocate and release memory for data while the
program is running.
 Unlike static memory allocations, dynamic memory allocations have no identifier associated with it. It can
be accessed only through an address. That is to access data in dynamic memory we need a pointer.

Memory Allocation Functions

 Four memory management functions are used with dynamic memory.


 Three of them malloc, calloc and realloc are used to allocate the memory.
 The fourth one free is used to return the memory when it is no longer needed.
 All these memory management functions are found in the standard library file (stdlib.h).

Block Memory allocation (malloc())

 The malloc() function allocates a block of memory that contains the number of bytes specified in its
parameter.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 The allocated memory is not initialized and contains unknown values.
Syntax: void* malloc(int size);
 On successful allocation it returns a void pointer to the first byte of the allocated memory. If the allocation
of memory is unsuccessful the function will return a NULL pointer.
 Calling a malloc function with a zero size is a problem, the results are unpredictable. It may return a NULL
pointer or it may return some other value. Never call a malloc with a zero size.

//Demonstration of malloc function


#include <stdio.h>
#include <stdlib.h>

void main(void)
{
int* ptr;
int n, i, sum = 0;

printf("Enter the number of elements you need from heap:");


scanf("%d",&n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));

// Check if the memory has been successfully allocated by malloc or not


if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using malloc.\n");
printf("Enter %d elements into the heap:",n);

for (i = 0; i < n; i++) {


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

// Print the elements from the heap


printf("The elements in heap are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
free(ptr);
}
Output:
Enter the number of elements you need from heap:4
Memory successfully allocated using malloc.
Enter 4 elements into the heap:5
6
7
6
The elements in heap are: 5, 6, 7, 6,

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Contiguous Memory allocation (calloc())

 The calloc() function is primarily used to allocate memory for arrays.


 It differs from malloc only in that; it sets memory to null characters.
Syntax: void* calloc(int element_count, int element_size);
 On successful allocation it returns a void pointer to the first byte of the allocated memory. If the allocation
of memory is unsuccessful the function will return a NULL pointer.

//Demonstration of calloc function


#include <stdio.h>
#include <stdlib.h>

void main(void)
{
int* ptr;
int n, i, sum = 0;

printf("Enter the number of elements you need from heap:");


scanf("%d",&n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));

// Check if the memory has been successfully allocated by calloc or not


if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using calloc.\n");
printf("Enter %d elements into the heap:",n);

for (i = 0; i < n; i++) {


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

// Print the elements from the heap


printf("The elements in heap are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
free(ptr);
}
Output:
Enter the number of elements you need from heap:4
Memory successfully allocated using calloc.
Enter 4 elements into the heap:5
6
7
6
The elements in heap are: 5, 6, 7, 6,

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Reallocation of memory (realloc())

 The realloc() function is advised to be used with much care. As a minor issue in the usage will lead to the
crash of the program.
 Given a pointer to a previously allocated block of memory, realloc changes the size of the block by
deleting or extending the memory at the end of the block.
 If the memory cannot be extended because of other allocations, realloc allocates a completely new block,
copies the existing memory locations to the new allocations, and deletes the old locations.
Syntax: void* realloc(void* ptr, int newSize);

//Demonstration of realloc function


#include <stdio.h>
#include <stdlib.h>

void main(void)
{
int* ptr;
int n, i, sum = 0;

printf("Enter the number of elements you need from heap:");


scanf("%d",&n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));

// Check if the memory has been successfully allocated by calloc or not


if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using calloc.\n");
printf("Enter %d elements into the heap:",n);

for (i = 0; i < n; i++) {


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

// Print the elements from the heap


printf("The elements in heap are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
printf("\nEnter the new size of heap:");
scanf("%d",&n);
// Dynamically allocate memory using realloc()
ptr = (int*)realloc((void*)ptr,n * sizeof(int));

// Check if the memory has been successfully allocated by realloc or not


if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
}
else {
printf("\nMemory successfully allocated using realloc.\n");
printf("Enter %d elements into the heap:",n);

for (i = 0; i < n; i++) {


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

// Print the elements from the heap


printf("\nThe elements in heap are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}

free(ptr);
}
Output:
Enter the number of elements you need from heap:2
Memory successfully allocated using calloc.
Enter 2 elements into the heap:4
2
The elements in heap are: 4, 2,
Enter the new size of heap:4
Memory successfully allocated using realloc.
Enter 4 elements into the heap:2
3
4
5
The elements in heap are: 2, 3, 4, 5,
Releasing Memory (free())

 When memory locations allocated by malloc, calloc or realloc are no longer needed, they should be freed
using the free() function.
 It is an error to free memory with a null pointer, a pointer to other than the first element of an allocated
block, a pointer that is different type than the pointer that allocated the memory.
 It is also an error to refer to memory after it has been released.
Syntax: void free(void* ptr);

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
INTRODUCTION TO FILES:

 A file is an external collection of related data treated as a single unit. The primary purpose of a file is to
keep a record of data.
 As the contents of primary memory are not permanent, and they will be lost when the computer is shut
down, we need files to store the data permanently.
 Sometimes the collection of data will become too large to be maintained in main memory; in this case files
can be used to store the data in secondary memory.
 Files are stored permanently in auxiliary or secondary memory, the most common secondary storage
devices are hard disk, CD, DVD and tape.
 When the computer reads, the data move from the external device to memory and when it writes the data
move from memory to the external device.
 This data movement uses a special work area known as a buffer. A buffer is a temporary storage area that
holds data when it is in transfer to or from the memory. The buffer acts like a synchronizer between the
physical devices and memory.
 When a file is processed for data input, the data is read from the file up to the end of file (EOF). End file is
the terminator of the file which indicates the completion of data processing in the file.
 The EOF will be automatically read and supplied to the program and it is the responsibility of the
programmer to keep track of it.

Why files are needed?

 When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if the
program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter them all. If you have a file
containing all the data, you can easily access the contents of the file using few commands in C.
 You can easily move your data from one computer to another without any changes.

Types of Files
There are two types of files:
1. Text files
2. Binary files

1. Text files

 Text files are the normal .txt files that you can easily create using Notepad or any simple text editors.
 Generally text files consists of sequence of characters divided into lines with each line terminated by a
newline (\n).
 When you open those files, you'll see all the contents within the file as plain text. You can easily edit or
delete the contents.
 They take minimum effort to maintain, are easily readable, and provide least security and takes bigger
storage space.

2. Binary files

 Binary files are mostly the .bin files in your computer.


 Instead of storing data in plain text, the data in binary file is stored in as a sequence of data values such as
integers, real or complex using their memory representation.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
 They can hold higher amount of data, are not readable easily and provides a better security than text files.

File Operations (Standard File Handling Functions)

In C, you can perform four major operations on the file, either text or binary:

 Creating a new file


 Opening an existing file
 Reading from and writing information to a file
 Closing a file

Working with files

 When working with files, you need to declare a pointer of type file. This declaration is needed for
communication between the file and program.
Syntax: FILE *fptr;
 Here FILE is a predefined structure definition in stdio.h library file.
 Note the * asterisk after the file type (FILE). It indicates that fptr is a pointer variable that contains the
address of the stream of file.

The fopen() function: Opening a file - for creation and edit

 Opening a file is performed using the library function in the "stdio.h" header file: fopen().
 The syntax for opening a file in standard I/O is: fptr = fopen("file_to_open","mode")
 For Example: fopen("E:\\cprogram\\newprogram.txt","w");
 Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The first function creates a
new file named newprogram.txt and opens it for writing as per the mode 'w'.
 The writing mode allows you to create and edit (overwrite) the contents of the file.

Opening Modes in Standard I/O


File Mode Meaning of Mode During Inexistence of file
r The read mode (r) opens an existing file for If the file does not exist, fopen() returns NULL.
reading. The file marker is positioned at the
beginning of the file (the first character).
w The write mode (w) opens a file for writing. If the file exists, its contents are overwritten. If the file
It is an error to read from a file opened in does not exist, it will be created.
write mode.
a The append mode (a) also opens an existing The append mode will add the content at the end of an
file for writing. existing file. If the file does not exists, it will be
created.
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
w+ Open for both reading and writing. If the file exists, its contents are overwritten. If the file
does not exist, it will be created.
a+ Open for both reading and appending. If the file does not exists, it will be created.
File Marker: File Marker is a logical element in the file structure that keeps track of the current position in the file.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
fprintf() & fscanf() function: Reading and writing to a text file

 The two input/output formatting functions: printf() and scanf().


 The scanf() function will receives a text stream from the keyboard and converts it to data values to be
stored in variables.
 The printf() function will receives data values from the program and converts them into text stream to be
displayed on the monitor.
 The above two functions can be used only with the keyboard and monitor.
 The C standard library defines two more general functions, fscanf and fprintf, they can be used with any
text stream. (Standard Input / Output or files).
 The general input/output functions fscanf and fprintf uses file pointers (stream pointers) to read the data
from a stream or write the data to a stream.
 To read the data from standard input (keyboard) the stream pointer stdin, and to write the data to standard
output (monitor) the stream pointer stdout can be used with general input / output functions.

Terminal Input / Output


scanf(“control string”, … data-values);
printf(“control string”, … data-values);
General Input / Output
fscanf(stream_pointer, “control string”, … data-values);
fprintf(stream_pointer, “control string”, … data-values);

fgetc() & fputc functions: Reading and Writing characters to a text file

 Character input/output functions read/write one character at a time from/to a text stream.
 These functions are divided into two general groups:
1. Input/output functions used only with terminal devices.
2. Input/output functions used with both terminal devices and text files.

Function Purpose of use Syntax


getchar() It reads the next character from the int getchar(void);
standard input stream and returns
its value.
putchar() It writes the specified character int putchar(char);
MD AFZAL Mob: 8179700193
Asst. Professor mdafzal.mbnr@gmail.com
value to the standard output
(display).
getc() / fgetc() These functions read next character int getc(FILE*);
from the file / standard input int fgetch(FILE*);
stream. These functions returns
EOF if end of the file is reached.
putc() / fputc() These functions write a character to int putc(char, FILE*);
the file / standard output stream. int fputc(char, FILE*);
These functions will take two
parameters, first parameter is the
character to be written, and second
parameter is the stream.
EOF will be returned on error.

fclose(): Closing a File

 When the file is no longer needed it should be closed to free the system resources.
 Closing a file is performed using library function fclose().
 Syntax: fclose(fptr); //fptr is the file pointer associated with file to be closed.

Example 1: Write to a text file using fprintf()


#include <stdio.h>
#include <stdlib.h>

void main(void)
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");

if(fptr == NULL)
{
printf("No such file exitst…!");
exit(1);
}

printf("Enter num: ");


scanf("%d",&num);

fprintf(fptr,"%d",num);
fclose(fptr);
}
Output:
 This program takes a number from user and stores in the file program.txt.
 After you compile and run this program, you can see a text file program.txt created in C drive of your
computer. When you open the file, you can see the integer you entered.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Example 2: Read from a text file using fscanf()
#include <stdio.h>
#include <stdlib.h>

void main(void)
{
int num;
FILE *fptr;

if ((fptr = fopen("C:\\program.txt","r")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);


fclose(fptr);
}
Output:
 This program reads the integer present in the program.txt file and prints it onto the screen.
 If you successfully created the file from Example 1, running this program will get you the integer you
entered.

Getting data using fseek()

 If you have many records inside a file and need to access a record at a specific position, you need to loop
through all the records before it to get the record.
 This will waste a lot of memory and operation time. An easier way to get to the required data can be
achieved using fseek().
 As the name suggests, fseek() seeks the cursor to the given record in the file.
 Syntax: void fseek(FILE * stream, long int offset, int whence)
o The first parameter stream is the pointer to the file. The second parameter is the position of the
record to be found, and the third parameter specifies the location where the offset starts.

Different Whence in fseek

Whence Meaning

SEEK_SET Starts the offset from the beginning of the file.

SEEK_END Starts the offset from the end of the file.

SEEK_CUR Starts the offset from the current location of the cursor in the file.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
Example 3: fseek()
// C Program to demonstrate the use of fseek()
#include <stdio.h>

void main(void)
{
FILE *fp;
fp = fopen("test.txt", "r");

// Moving pointer to end


fseek(fp, 0, SEEK_END);

// Printing position of pointer


printf("%ld", ftell(fp));
}
test.txt Output:
"Someone over there is calling you. 81
we are going for work.
take care of yourself."

ftell() in C with example

 ftell() in C is used to find out the position of file pointer in the file with respect to starting of the file.
 Syntax of ftell() is: long ftell(FILE *pointer).
 Consider below C program.
 When the fscanf statement is executed word “Someone” is stored in string and the pointer is moved beyond
“Someone”. Therefore ftell(fp) returns 7 as length of “someone” is 6.

// C program to demonstrate use of ftell()

#include<stdio.h>
void main(void)
{
/* Opening file in read mode */
FILE *fp = fopen("test.txt","r");

/* Reading first string */


char string[20];
fscanf(fp,"%s",string);

/* Printing position of file pointer */


printf("%ld", ftell(fp));
}
Output:
7

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com
rewind() in C with example

 The rewind function sets the file position indicator (file marker) to the beginning of the file irrespective of
its current location.
 General Syntax: void rewind(FILE *fp);
 It is equivalent to: void fseek(stream, 0L, SEEK_SET);

#include <stdio.h>
int main () {
char str[] = "ISL Engineering College.";
FILE *fp;
int ch;

/* First let's write some content in the file */


fp = fopen( "file.txt" , "w" );
fwrite(str , 1 , sizeof(str) , fp );
fclose(fp);

fp = fopen( "file.txt" , "r" );


while(1) {
ch = fgetc(fp);
if( feof(fp) ) {
break ;
}
printf("%c", ch);
}
rewind(fp);
printf("\n");
while(1) {
ch = fgetc(fp);
if( feof(fp) ) {
break ;
}
printf("%c", ch);

}
fclose(fp);

return(0);
}
Output: file.txt
This is ISL Engineering College. This is ISL Engineering College.
This is ISL Engineering College.

MD AFZAL Mob: 8179700193


Asst. Professor mdafzal.mbnr@gmail.com

You might also like