C
C
DECAP172
Edited by
Sartaj Singh
Programming Methodology
Edited By:
Sartaj Singh
CONTENT
Unit 1: Introduction 1
Ashwani Kumar, Lovely Professional University
Objectives
After studying this unit, you will be able to:
• Characteristics of programing
• Programing methodologies
Introduction
A computer is an electronic machine that operates according to the user's instructions. Since the
machine does not understand natural language, the instructions must be written in a computer-
friendly language. It is understood that such a machine understandable language is known as
Programming language.
A computer programming language is made up of a collection of symbols, characters, sentences, and
grammar rules that allow people to write instructions in a readable format by the computer system
The practise of making a machine do what you want it to do is known as computer programming.
Software programming is the process of creating source code that can be used to customise computer
systems analytically. Computer programmers can specialise in one aspect of the creation, support, or
maintenance of computers for the home or office, or they can operate in a wide range of programming
functions. Programmers are the foundation for the development and continued operation of the
systems that many people rely on for all types of knowledge sharing, both for business and for
entertainment.
1. Input: Get data from the keyboard, a file, or some other device.
2. Output: Display data on the screen or send data to a file or other device.
3. Math: Perform basic mathematical operations like addition and multiplication.
4. Conditional execution: Check for certain conditions and execute the appropriate sequence
of statements.
5. Repetition: Perform some action repeatedly, usually with some variation.
BeanShell C C++ C#
We already know that all commuters perform operations with binary digits (0s and 1s).
As a result, most computers' machine language is made up of strings of binary numbers, and it is the
only one that the CPU understands explicitly. The symbols that make up the machine language
programme are made up of 1s and 0s while they are stored within the computer.
A typical program instruction to print out a number on the printer might be.
101100111111010011101100110000111001
The program to add two numbers in memory and print the result look something like the
following:
001000000000001100111001
001111000000111111000111
100111100011101100110101
101100010101010101110000
000000000000000000000000
This is clearly not an easy language to learn, partly because it is difficult to read and understand, and
partly because it is written in a numerical format that we are unfamiliar with. However, it's worth noting
that some of the first programmers, working with the first few machines, wrote their programmes in
binary form, as seen above.
Since most human programmers are more familiar with the decimal number system, they tend to write
machine instructions in decimal and leave the conversion to the input device. In reality, a machine can
be wired so that instead of fusing long numbers, short numbers are fused.With this change, the preceding
program appears as follows:
10001471
14002041
30003456
50773456
00000000
The set of instruction codes, whether in binary or decimal, which can be directly understood by the
CPU of a computer without the help of a translating program, is called a machine code or machine
language. Thus, a machine language program need not necessarily be coded as strings of binary
digits (1s and 0s). it can also be written using decimal digits if the circuitry of the computer being
used permits this.
number 14 every time it sees the symbol ADD, substitute the number 15 every time it sees the
symbol SUB, and so forth. In this way, the computer can be trained to translate a program written
with symbols instead of numbers into the computer’s own machine language. Then we can write
program for the computer using symbols instead of numbers, and have the computer do its own
translating. This makes it easier for the programmer, because he can use letters, symbols, and
mnemonics instead of numbers for writing his programs.
Example: The preceding program that was written in machine language for adding two
numbers and printing out the result could be written in the following way:
CLA A
ADD B
STA C
TYP C
HLT
Which would mean “take A, add B, store the result in C, type C, and halt.” The computer by
means of a translating program, would translate each line of this program into the corresponding
machine language program.
Advantages of Assembly Language
There are two ways of converting an assembly language program into machine language:
1. Manual assembly
2. By using an assembler.
Manual Assembly: It was an old method that required the programmer to translate each opcode
into its numerical machine language representation by looking up a table of the microprocessor
instructions set, which contains both assembly and machine language instructions. Manual
assembly is acceptable for short programs but becomes very inconvenient for large programs. The
Intel SDK-85 and most of the earlier university kits were programmed using manual assembly.
Using an Assembler: The symbolic instructions that you code in assembly language is known
as - Source program.
An assembler program translates the source program into machine code, which is known as
object program.
The steps required to assemble, link and execute a program are:
1. The assembly step involves translating the source code into object code and generating an
intermediate .OBJ (object file) or module.
The assembler also creates a header immediately in front of the generated .OBJ module;
part of the header contains information about incomplete addresses. The .OBJ module is
not quite in executable form.
2. The link step involves converting the .OBJ module to an .EXE machine code module. The
linker’s tasks include completing any address left open by the assembler and combining
separately assembled programs into one executable module.
The linker:
(a) combines assembled module into one executable program
(b) generates an .EXE module and initializes with special instructions to facilitate its
subsequent loading for execution.
3. The last step is to load the program for execution. Because the loader knows where the
program is going to load in memory, it is now able to resolve any remaining address still
left incomplete in the header. The loader drops the header and creates a program segment
prefix (PSP) immediately before the program is loaded in memory
ADA
ADA was named after lady Augusta Ada Byron (the first computer programmer). It was
designed by the US Defence Department for its real time applications. It is suitable for parallel
processing.
APL
Developed by Dr Kenneth Aversion at IBM, APL is a convenient, interactive programming
language suitable for expressing complex mathematical expressions in compact formats. It
requires special terminals for use.
Pascal
Developed in 1968, Pascal was named after a French inventor Blaise Pascal and was developed
by a Swiss programmer NiKolus Wirth. Pascal was the first structured programming language
and it is used for both scientific and business data processing applications.
C
Developed by Denis Ricthie at the Bell Laboratories in 1970, it is a general purpose programming
language, which features economy of expression, modern control flow and data structures, and
a rich set of operators. Its programs are highly portable (machine independent). C language
supports modular programming through the use of functions, subroutines, and macros.
When the features of a language are orthogonal, language is easier to learn and programs are easier
to write because only few exceptions and special cases to be remembered.
3) Support for Abstraction:- There is always found that a substantial gap remaining between the
abstract data structure and operations that characterize the solution to a problem and their particular
data structure and operations built into a language.
4) Programming Environment: An appropriate programming environment adds an extra utility
and make language to be implemented easily like
The availability of- Reliable- Efficient - Well documentation
Speeding up creation and testing by-special Editors- testing packages
Facility- Maintaining and Modifying- Multi Version of program software product.
5) Reusability: The reusability of program written in a language is always a central concern. A
program is checked by various testing technique like
Formal verification method Desk checking Input output test checking.
We verify the program by many more techniques. A language that makes program verification
difficult maybe far more troublesome to use. Simplicity of semantic and syntactic structure is a
primary aspect that tends to simplify program verification.
6) portability of programs: Programming language should be portable means it should be easy to
transfer a program from which they are developed to the other computer.
1.6 Algorithms
An algorithm is a step-by-step process that specifies a series of instructions that must be carried out
in a specific order to produce the desired result. Algorithms are usually written without regard to
the underlying programming languages; that is, an algorithm may be written in more than one
programming language.
An algorithm is a finite set of steps that must be followed to solve any problem. Algorithms are
usually created before the actual coding takes place. It is written in an English-like language so that
even non-programmers can understand it.
Algorithms are often written in pseudocodes, which are languages that are identical to the
programming language that would be used.
Characteristics of an Algorithm
Clear and Unambiguous: Algorithm should be clear and unambiguous. Each of its steps should be
clear in all aspects and must lead to only one meaning.
Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined inputs.
Well-Defined Outputs: The algorithm must clearly define what output will be yielded and it
should be well-defined as well.
Finite-ness: The algorithm must be finite, i.e. it should not end up in an infinite loops or similar.
Feasible: The algorithm must be simple, generic and practical, such that it can be executed upon will
the available resources. It must not contain some future technology, or anything.
Language Independent: The Algorithm designed must be language-independent, i.e. it must be just
plain instructions that can be implemented in any language, and yet the output will be same, as
expected.
Advantages of Algorithms:
It is easy to understand.
Algorithm is a step-wise representation of a solution to a given problem.
In Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for the
programmer to convert it into an actual program.
Disadvantages of Algorithms:
Writing an algorithm takes a long time so it is time-consuming.
Branching and Looping statements are difficult to show in Algorithms
Example Of Algorithms
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a > b
If a > c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b > c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop
Flowchart Symbols
Different flowchart shapes have different conventional meanings. The meanings of some of the more
common shapes are as follows:
Terminator
The terminator symbol represents the starting or ending point of the system.
Process
Document
This represents a printout, such as a document or a report.
Decision
A diamond represents a decision or branching point. Lines coming out from the diamond indicates
different possible situations, leading to different sub-processes.
Data
It represents information entering or leaving the system. An input might be an order from a customer.
Output can be a product to be delivered.
On-Page Reference
This symbol would contain a letter inside. It indicates that the flow continues on a matching symbol
containing the same letter somewhere else on the same page.
Flow
Lines represent the flow of the sequence and direction of a process.
Off-Page Reference
This symbol would contain a letter inside. It indicates that the flow continues on a matching symbol
containing the same letter somewhere else on a different page.
Delay or Bottleneck
Identifies a delay or a bottleneck.
Procedural Programming
The problem is broken down into procedures, or code blocks, that each perform a single task. The
whole curriculum is made up of all procedures. It is only appropriate for small programmes with a
low degree of complexity.
Object-oriented Programming
Here the solution revolves around entities or objects that are part of problem. The solution deals with
how to store data related to the entities, how the entities behave and how they interact with each
other to give a cohesive solution.
Functional Programming
The problem, or the desired solution, is divided into functional units in this step. Each unit completes
its own job and is self-contained. The full solution is then stitched together from these modules.
Rather than functional units, the problem is broken down into logical units here. Users in a school
management system, for example, have positions such as class instructor, subject teacher, lab
assistant, coordinator, academic in-charge, and so on. As a result, the programme can be divided into
units based on the positions of the users. Each consumer may have a unique gui, permissions, and
other features.
Software developers may use one or a combination of these methodologies to create a piece of
software. The problem must be broken down into smaller units in each of the methodologies
discussed.
Summary :
1. Different programming languages support different styles of programming. The choice of
language used is subject to many considerations, such as company policy.
2. An assembly program is written according to a strict set of rules. An editor or word processor is
used for keying an assembly program into the computer as a file, and then the assembler is used
to translate the program into machine code.
3. Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain
order to get the desired output. Algorithms are generally created independent of underlying
languages, i.e. an algorithm can be implemented in more than one programming language
4. A flowchart is a visual representation of the sequence of steps and decisions needed to perform a
process. Each step in the sequence is noted within a diagram shape. Steps are linked by connecting
lines and directional arrows
5. A programming methodology is nothing but a type of technique to solve some given requirements
using programming languages.
Keywords
Compiler: A compiler is a computer program that transforms source code written in a computer
language into another computer language.
Computer Programming: Computer programming is a field that has to do with the analytical
creation of source code that can be used to configure computer systems.
Debugger: The debugger is a program that allows the user to test and debug the object file.
Loader: Loader is a program which assigns absolute addresses to the program
Programming language
Machine language
High level language
Algorithms
Flowcharts
Self-Assessment
1. Compiler is a…..
A. Source code
B. Object code
C. Translator
D. None of above
2. How many bits in 1 byte?
A. 9
B. 7
C. 6
D. 8
3. What is extension of C language?
A. .x
B. .p
C. .c
D. .d
4. Who developed C language?
A. Dennis M. Ritchie
B. Steve Jobs
C. Steve Smith
D. James Gosling
A. Procedural language
B. Machine Language
C. Assembly Language
D. High Level Language.
7. Which of the following is part of computer system.
A. Hardware
B. Programming
C. Software
D. Hardware & Software
8. ___________ is a computer language.
A. Binary Language
A. % c
B. %d
C. %f
D. % h
Answer
C 2 D 3 C 4 A 5 A
1
6 B 7 D 8 A 9 d
Review Questions:
1. Describe assembly language in detail. Also explain the advantages of the same.
2. Describe various tools required for assembly language programming.
4. Explain various advantages and limitations of machine language.
5. Distinguish between OPCODE and OPERAND.
7. List various version of FORTRAN language.
8. Write short notes on:
Input
Output
Further Readings
Brian Kerrighen and Dennis Ritchie, The C Programming language
D. Bharioke, Fundamentals of IT, Excel Books
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett,
1997.
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett,
1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
R.G.Dromey, How to solve it by Computer, 2007, Pearson Education, India
Objectives
After studying this unit, you will be able to:
• Discuss C Programming
• Programing methodologies
Introduction
Computer is an electronic device which works on the instructions provided by the user. As the
computer does not understand natural language, it is required to provide the instructions in some
computer understandable language. Such a computer understandable language is known as
Programming language.
A computer programming language consists of a set of symbols and characters, words, and
grammar rules that permit people to construct instructions in the format that can be interpreted by
the computer system Computer Programming is the art of making a computer do what you want it
to do. Computer programming is a field that has to do with the analytical creation of source code
Instruction Format
We already know that all commuters use binary digits (0s and 1s) for performing operations.
Hence, most computers machine language consists of strings of binary numbers and is the only one
the CPU directly understands. When stored inside the computer, the symbols which make up the
machine language program are made up of 1s and 0s.
Example: A typical program instruction to print out a number on the printer might be.
101100111111010011101100110000111001
The program to add two numbers in memory and print the result look something like the
Following:
001000000000001100111001
001111000000111111000111
100111100011101100110101
101100010101010101110000
000000000000000000000000
This is obviously not a very easy language to learn, partly because it is difficult to read and
understand and partly because it is written in a number system with which we are not familiar. But
it will be surprising to note that some of the first programmers, who worked with the first few
computers, actually wrote their programs in binary form as above. Since human programmers are
more familiar with the decimal number system, most of them preferred to write the computer
instructions in decimal, and leave the input device to convert these to binary. In fact, without too
much effort, a computer can be wired so that instead of using long numbers. With this change, the
preceding program appears as follows:
10001471
14002041
30003456
50773456
00000000
The set of instruction codes, whether in binary or decimal, which can be directly understood by the
CPU of a computer without the help of a translating program, is called a machine code or machine
language. Thus, a machine language program need not necessarily be coded as strings of binary
digits (1s and 0s). It can also be written using decimal digits if the circuitry of the computer being
used permits this.
1. Machine dependent
Because the internal design of every type of commuter is different from every other type of
computer and needs different electrical signals to operate, the machine language also is different
from computer to computer. It is determined by the actual design or construction of the LU, the
control unit, and the size as well as the word length of the memory unit. Hence, suppose after
becoming proficient in the machine code of a particular computer, a company decides to change to
another computer, the programmer may be required to learn a new machine language and would
have to rewrite all the existing programs.
2. Difficult to program
Although easily used by the computer, machine language is difficult to program, it is necessary for
the programmer either to memorize the dozens of code numbers for the commands in the
machine’s instruction set or to constantly refer to keep track of the storage location of data and
instructions. Moreover, a machine language programmer must be an expert who knows about the
hardware structure of the computer.
3. Error code
For writing programs in machine language, since a programmer has to remember the opcodes and
he must also keep track of the storage location of data and instructions, it becomes very difficult for
him to concentrate fully on the logic of the problem. This frequently results in program errors.
Hence, it is easy to make errors while using machine code.
4. Difficult to modify
It is difficult to correct or modify machine language programs. Checking machine instructions to
locate errors is about as tedious as writing them initially. Similarly, modifying a machine language
program at a later date is so difficult that many programmers would prefer to code the new logic
afresh instead of incorporating the necessary modifications in the old program.
Here mnemonic MOV represents ‘transfer’ operation and AX, DX are used to represent the
registers. One of the first steps in improving the program preparation process was to substitute
letter symbols mnemonics for the numeric operation codes of machine language. A mnemonic is
any kind of mental trick we use to help us remember. Mnemonics come in various shapes and sizes,
all of them useful in their own way.
All computers have the power of handling letters as well as numbers. Hence, a computer can be
taught to recognize certain combination of letter or numbers. It can be taught to substitute the
number 14 every time it sees the symbol ADD, substitute the number 15 every time it sees the
symbol SUB, and so forth. In this way, the computer can be trained to translate a program written
with symbols instead of numbers into the computer’s own machine language. Then we can write
program for the computer using symbols instead of numbers, and have the computer do its own
translating. This makes it easier for the programmer, because he can use letters, symbols, and
mnemonics instead of numbers for writing his programs.
Example: The preceding program that was written in machine language for adding two
numbers and printing out the result could be written in the following way:
CLA A
ADD B
STA C
TYP C
Which would mean “take A, add B, store the result in C, type C, and halt.” The computer by means
of a translating program, would translate each line of this program into the corresponding machine
language program.
Manual Assembly
It was an old method that required the programmer to translate each opcode into its numerical
machine language representation by looking up a table of the microprocessor instructions set,
which contains both assembly and machine language instructions. Manual assembly is acceptable
for short programs but becomes very inconvenient for large programs. The Intel SDK-85 and most
of the earlier university kits were programmed using manual assembly.
Using an Assembler
The symbolic instructions that you code in assembly language is known as - Source program.
An assembler program translates the source program into machine code, which is known as object
program.
1. The assembly step involves translating the source code into object code and generating an
intermediate .OBJ (object file) or module. The assembler also creates a header immediately in front
of the generated .OBJ module; part of the header contains information about incomplete addresses.
The .OBJ module is not quite in executable form.
2. The link step involves converting the .OBJ module to an .EXE machine code module. The linker’s
tasks include completing any address left open by the assembler and combining separately
assembled programs into one executable module.
3. The last step is to load the program for execution. Because the loader knows where the program
is going to load in memory, it is now able to resolve any remaining address still left incomplete in
the header. The loader drops the header and creates a program segment prefix (PSP) immediately
before the program is loaded in memory.
Linker
For modularity of your programs, it is better to break your program into several sub routines. It is
even better to put the common routine, like reading a hexadecimal number, writing hexadecimal
number, etc., which could be used by a lot of your other programs into a separate file. These files
are assembled separately. After each file has been successfully assembled, they can be linked
together to form a large file, which constitutes your complete program. The file containing the
common routines can be linked to your other program also. The program that links your program
is called the linker.
Loader
Loader is a program which assigns absolute addresses to the program. These addresses are
generated by adding the address from where the program is loaded into the memory to all the
offsets. Loader comes into action when you want to execute your program. This program is brought
from the secondary memory like disk. The file name extension for loading is .exe or .com, which
after loading can be executed by the CPU.
The machine-level language comes at the The assembly language comes above the
lowest level in the hierarchy, so it has zero machine language means that it has less
abstraction level from the hardware. abstraction level from the hardware.
It does not require any translator as the In assembly language, the assembler is used to
machine code is directly executed by the convert the assembly code into machine code.
computer.
LET X = 7
LET Y = 10
LET sum = X+Y
PRINT SUM
END
The time and cost of creating machine and assembly languages was quite high. And this was the
prime motivation for the development of high level languages. Because of the difficulty of working
with low-level languages, high-level languages were developed to make it easier to write computer
programs. High level programming languages create computer programs using instructions that
are much easier to understand than machine or assembly language code because you can use
words that more clearly describe the task being performed.
When writing a program in a high-level language, then the whole attention needs to be
paid to the logic of the problem. A compiler is required to translate a high-level language into a
low-level language.
Example: High-level languages include FORTRAN, COBOL, BASIC, PASCAL, C, C++ and
JAVA.
execute.
It requires the assembler to convert the It requires the compiler to convert the high-
assembly code into machine code. level language instructions into machine code.
The machine code cannot run on all machines, The high-level code can run all the platforms,
so it is not a portable language. so it is a portable language.
Debugging and maintenance are not easier in a Debugging and maintenance are easier in a
low-level language. high-level language.
C programming language can be used to design the system software like operating system
and Compiler.
To develop application software like database and spread sheets.
For Develop Graphical related application like computer and mobile games.
To evaluate any kind of mathematical equation use c language.
C programming language can be used to design the compilers.
UNIX Kernel is completely developed in C Language.
For Creating Compilers of different Languages which can take input from other language
and convert it into lower level machine dependent language.
C programming language can be used to design Operating System.
C programming language can be used to design Network Devices.
To design GUI Applications. Adobe Photoshop, one of the most popularly used photo
editors since olden times, was created with the help of C.
Evolution of C
By the late fifties, there were many computer languages into existence. However, none of them
were general purpose. They served better in a particular type of programming application more
than others. Thus, while FORTRAN was more suited for engineering programming, COBOL was
better for business programming. At this stage people started thinking that instead of learning so
many languages for different programming purposes, why not have a single computer language
that can be used for programming any type of application.
In 1960, to this end, an international committee was constituted which came out with a language
named ALGOL-60. This language could not become popular because it was too general and highly
abstract.
In 1963, a modified ALGOL-60 by reducing its generality and abstractness, a new language, CPL
(Combined Programming Language) was developed at Cambridge University. CPL, too turned out
to be very big and difficult to learn.
In 1967, Martin Richards, at Cambridge University, stripped down some of the complexities from
CPL retaining useful features and created BCPL (Basic CPL). Very soon it was realized that BCPL
was too specific and much too less powerful.
In 1970, Ken Thompson, at AT&T labs. Developed a language known by the name B as another
simplification to CPL. B, too, like its predecessors, turned out to be very specific and limited in
application.
In 1972, Ritchie, at AT&T, took the best of the two BCPL and B, and developed the language C. C
was truly a general purpose language, easy to learn and very powerful.
In 1972, Ritchie, at AT&T, took the best of the two BCPL and B, and developed the language C. C
was truly a general purpose language, easy to learn and very powerful.
Code blocks is an IDE for running C and C++ programs on different operating systems like
Windows, Linux and Mac OS.
Editor
This program is used for writing the Source Code, the first thing that any programmer writing a
program in any language would be doing.
Debugger
This program helps us identify syntax errors in the source code.
Pre Processor
There are certain special instructions within the source code identified by the # symbol that are
carried on by a special program called a preprocessor.
Compiler
The process of converting the C source code to machine code and is done by a program called
Compiler.
Linker
The machine code relating to the source code you have written is combined with some other
machine code to derive the complete program in an executable file. This is done by a program
called the linker.
Writing a C Program
The following rules are applicable to all C-statements:
1. Blank spaces may be inserted between two words to improve the readability of the statement.
However, no blank space is allowed within a word.
2. Most of the C-compilers are case-sensitive, and hence statements are entered in small case letters.
3. C has no specific rules about the position at which different parts of a statements be written. Not
only can a C statement be written anywhere in a line, it can also be split over multiple lines. That is
why it is called free-format language.
4. A C-statement ends with a semi-colon (;)
5. Every C program contains one main() function.
C Program Code
#include<stdio.h>
main(){
printf(“Hello World”);
}
Click on empty file link and save that file with name hello.c and write code.
Letters
• Uppercase characters (A-Z)
• Lowercase characters (a-z)
Numbers
White spaces
• Blank space
• New line
• Carriage return
• Horizontal tab
Special characters
• Special characters in 'C' are shown in the given table,
28 LOVELY
LOVELY
PROFESSIONAL
PROFESSIONAL
UNIVERSITY
UNIVERSITY
Unit 02: Constant and Variable Notes
~ (tilde) / (division)
2.12 Constants in C
A constant is a non-changing token with a fixed value. It can be stored in a place in the computer's
memory and accessed using that memory address. In C, constants are divided into four categories:
integer constants, floating-point constants, character constants, and string constants. Constants can
be present in composite forms.
Integer and floating-point constants represent numbers. They are often referred to collectively as
numeric-type constants.
C imposes the following rules while creating a numeric constant type data item:
1. Commas and blank spaces cannot be included within the constants.
2. The constant can be preceded by a minus (-) sign if desired.
3. Value of a constant cannot exceed specified maximum and minimum bounds. For each
type of constant, these bounds will vary from one C-compiler to another.
Constants are the fixed values that remain unchanged during the execution of a program and are
used in assignment statements. Constants can also be stored in variables.
The declaration for a constant in C language takes the following form:
<Data type ><variable_name> = <value>
This declaration defines a constant named pi whose value remains 22/7 throughout the program in
which it is defined.
C language facilitates five different types of constants.
1. Character
2. Integer
3. Real
4. String
5. Logical
Integer Constants
An integer constant refers to a sequence of digits and has a numeric value. There are three types of
integers in C language: decimal, octal and hexadecimal.
String Constants
A string constant is a sequence of one or more characters enclosed within a pair of double quotes
(““). If a single character is enclosed within a pair of double quotes, it will also be interpreted as a
string constant and not a character constant.
1. “ Hello World”
2. ”A”
Actually, a string is an array of characters terminated by a NULL character. Thus, “a” is a string
consisting of two characters, viz. ‘a’ and NULL(‘\0’).
Logical Constants
The value of a logical constant may be true or false. In C, a non-zero value is considered true, while
0 is considered false.
2.13 Variables
A variable is an object whose value can change while a programme is running. A variable is a
symbolic representation of the address in memory space where values can be stored, accessed, and
updated. Each variable has a memory location or address assigned to it, and the value of that
variable is stored there.
Each variable has its own name, data type, size, and value. All variables must have a type so that
the compiler can record all necessary information about them, generate the appropriate code
during translation, and allocate the necessary memory space.
Every programming language has its own set of rules that must be observed while writing the
names of variables. If the rules are not followed, the compiler reports compilation error. Rules for
Constructing Variable Name in C language are listed below:
Declaration of Variables
C language is strongly typed language, meaning that all the variables must be declared before their
use. Declaration does two things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold
In C language, a variable declaration has the form:
<Type-specifier><comma-separated-list-of-variables>;
Here <type-specifier> is one of the valid data types (e.g. int, float, char, etc.). List-of-variables is a
comma-separated list of identifiers representing the program variables.
Once variable has been declared in the above manner, the compiler creates a space in the memory
and attaches the given name to this space. This variable can now be used in the program.
A value is stored in a variable using assignment operation. Assignment is of the form:
<Variable-name> = <value>;
Obviously, before assignment, the variable must be declared.
C also allows assignment of a value to a variable at the time of declaration. It takes the following
form:
<Type-specifier><variable_name> = <value>;
e.g. :int I = 5;
Let us consider some of programming examples to illustrate the matter further.
/* Example of assignments */
/* declaration */
int a1, b1;
/* declaration & assignment */
intvar = 5;
int a, b = 6, c;
/* declaration & multiple assignment */
int p, q, r, s;
p = q = r = s = 5;
}
values stored in various variables are:
var = 5
a = 0, b = 6
c = garbage value
p = 5, q = 5, r = 5, s = 5
32 LOVELY
LOVELY
PROFESSIONAL
PROFESSIONAL
UNIVERSITY
UNIVERSITY
Unit 02: Constant and Variable Notes
Output:-
Summary
A computer programming language consists of a set of symbols and characters, words,
and grammar rules that permit people to construct instructions in the format that can be
interpreted by the computer system Computer Programming is the art of making a
computer do what you want it to do.
Machine language, or machine code, is a low-level language comprised of binary digits
(ones and zeros).
Assembly languages are also known as second generation languages. These languages
substitute alphabetic symbols for the binary codes of machine language.
High-level languages include FORTRAN, COBOL, BASIC, PASCAL, C, C++ and JAVA.
C is a general-purpose, structured programming language. Structured Languages have a
characteristic program structure and associated set of static scope rules. C was originated
in Bell Telephone Laboratories presently known as AT & T Bell Laboratories by Dennis
Ritchie in 1970.
To develop application software like database and spread sheets.
For Develop Graphical related application like computer and mobile games.
Keywords have fixed meanings, and the meaning cannot be changed. They act as a
building block of a 'C' program. There are a total of 32 keywords in 'C'
Code blocks is an IDE for running C and C++ programs on different operating systems
like Windows, Linux and Mac OS.
Keywords
Programming:Computer programming is the process of designing and building an executable
computer program to accomplish a specific computing result or to perform a specific task.
Self-Assessment
1. A computer program is?
A. a sequence of English language statements.
B. a sequence of images to create a picture.
C. a sequence of instructions to perform an specific task
D. none of above
2. A program that can converts high-level language programs into machine understandable
form is known as…..
A. Compiler
B. Sensor
C. Translation
D. None of these
3. An error is also known as
A. Bug
B. Insect
C. Worm
D. virus
4. A high-level language is a
A. Human understandable language with proper syntax to write programs
B. Machine understandable language that can be processed on a machine
C. Both (a) and (b) statements defines it
D. None of these
5. A low-level language is a
A. Human understandable language with proper syntax to write programs
B. Machine understandable language that can be processed on a machine
6. C 7. C 8. D 9. B 10 C
11. D 12. B
https://www.tutorialspoint.com/index.htm
www.webopedia.com
www.web-source.net
36 LOVELY
LOVELY
PROFESSIONAL
PROFESSIONAL
UNIVERSITY
UNIVERSITY
Ashwani Kumar, Lovely Professional University Unit 03: Unformatted and Formatted I/O Notes
OBJECTIVES
After studying this unit, you will be able to:
INTRODUCTION
If a user is unable to communicate with a computer programme, it is unlikely that the programme
would be useful. The software must read input values from the user console and generate the
expected useful output to the user in most programming assignments.
C is unique in that, unlike other high-level languages, it does not have any built-in I/O statements in
its syntax. We'll look at how C handles different I/O operations in this unit. We'll also hear about the
standard library functions in C, as well as the header files that go with them.. This unit is not intended
to be a complete treatment of these topics, but it provides enough information so that you can start
writing real programs.
Depending on the compiler and necessary functions, various methods may be used to access these
library functions from the standard library. Some compilers scan libraries for named functions
automatically. Most of the time, the programmer must specifically state the library file name during
the linking process, resulting in the executable programme only containing the necessary functions.
These functions are stored in a special file with the extension.h (such as stdio.h), which is referred to
as a header file. The #include compiler directive can be used to insert a header file into a C
programme file, as shown below.
#include<stdio.h>
The #include directive tells the compiler to read the stdio.h (standard input output header file) file
and substitute this line with the contents of that file. Similarly, in order to use other predefined
functions, their respective header files must be included in a programme such that the function
declaration can be accessed by the programme.
C has a rich set of standard I/O library functions. However, these I/O functions are not the part of
C’s formal definition. C’s standard library function for I/O can be broadly divided in to the following
categories:
1. Port I/O functions
2. Disk I/O function
3. Console I/O function
The Port I/O function handles various I/O operators on various ports, such as a mouse port or a
printer port. The scope of this text does not include a thorough examination of the port I/O functions.
The disc I/O functions are used to manipulate files on secondary storage devices such as a floppy
disc or a hard disc. Since files are stored in secondary storage, such as discs, disc I/O functions are
nothing more than file handling functions.
The term "console" refers to the regular input and output devices in its broadest sense. These basic
input or output devices, which are also known as the keyboard and display by default, are dealt with
by console I/O functions. These functions take keyboard input and display the results on the
computer.
C takes all input and output as stream of characters. A stream is nothing,
but a series of bytes. C language treats all streams equally i.e., whether a program gets input from
the keyboard, a disk file or a modem, it consider it as only a stream of characters.
Different steams are used to represent different kinds of data flow. In C, there are three streams
associated with console I/O operations.
1. stdin: A stream that supplies data to the program i.e., standard input, usually from the keyboard.
2. stdout: A stream that receives data from the program i.e., standard output; usually to the monitor.
3. stderr: A stream used to keep error messages separate from program’s output i.e., standard error;
usually points to your terminal screen.
For conducting console I/O operations, C offers a number of functions. These functions allow
information to be transferred between the computer's standard input and output devices (i.e.,
keyboard and monitor). Only a few of them allow you to format input and output operations. Some
of them, on the other hand, do not allow you to monitor the format of I/O operations.
From this aspect, console I/O operations can be further categories as:
1. Unformatted console I/O functions
2. Formatted console I/O functions
It is important to include the standard I/O library header file in order to use these functions. The
declarations for these functions can be found in the stdio.h header file. As a result, before using these
console I/O features, always include the header file stdio.h in your C programme.
1. How much field width is required to display the various values on the monitor?
2. How many decimal places are required to display the fractional part of a real number?
3. Should data values be left aligned or right aligned, and how much?
4. How much space between two data values is to be given?
5. How various type of data i.e. integer, character, and string can be used together I/O
operators, etc.
Printf() and scanf() are the two most commonly used functions for formatted I/O. (). The printf()
function is used to view formatted data items on a standard output device, such as a monitor, while
the scanf() function is used to read formatted data input from a standard input device, such as a
keyboard. However, due to their greater complexity, both functions are slower than the previous
classes of functions. These functions are specified in the stdio.h header file and return EOF if an error
or the end of the file occurs. Let's take a closer look at each of these functions one by one.
3.3 printf()
The printf() in one of the most important and useful functions to display data on monitor. We have
seen the use of printf() for printing messages in the various example given previously in this book.
For example, the statement
printf(“ this section will discuss printf() in detail”);
will simple print this message on the monitor. Beside these text messages, a program frequently
required numeric values and the value of other variables to be displayed on the screen.
Example: In order to print the sum of two numbers say a and b, in a new line along with some
identifying text, the printf() will take the following form:
printf(“\n the sum of %d and %d is %d.”, a, b, c);
If the value of a and b is 5 and 6 respectively, then the output would be as follows:
The sum of 5 and 6 is 11.
Undoubtedly, a little more complicated then printing a simple message. Before getting the detail of
the various section of this printf(), Let’s discuss the general format of a printf(), shown below:
printf(“Format string”, arg1, arg2,...., argn);
Where format string refers to a string in enclosed in double quotes that contain formatting
information and arg1, arg2, ...., argn are arguments (may be constants, variable, or other complex
expressions) whose values are formatted and printed according to the specification of the format
string.
The format string in a printf() contains the format specifies that defines how the output is formatted.
Following are the three possible components of a format string:
1. Literal text that is simply printed as entered in the format string.
2. An escape sequence that begins with a \ (backslash) sign, provides special formatting
control.
3. A conversion specifier that begins with a % sign and followed by a single character, that
tells printf() how to interpret the arguments being used. To understand the various sections
of previously used printf() statement,
The output of given statement if the value of a and b is 5 and 6 respectively, would be as:
The sum of 5 and 6 is 11
Let’s see how this output is evaluated:
The printf() function reads the format string from left to right and sends the characters that follow to
the standard output unit. It takes action as soon as it encounters the (backslash) (that is, the signal of
the existence of an escape sequence). When it comes across the percent (conversion specifier) symbol,
it grabs the corresponding argument and prints its value in the format defined. When the closing pair
of double quotes is encountered, the process comes to an end.
In our case, the first character after the opening pair of double quote is \ , followed by a character n,
so the effect of \n will take place i.e., output of the coming characters will start from the starting of
the next line. Output up to this stage appears as:
The sum of
Then comes the character % followed by character d (that is, the indication to treat the corresponding
variable as assigned decimal integer), so it picks up the variable a and will print
its value on the screen. At this stage the output will be looking like as:
The sum of 5
In the same manner, this process will go on until there comes an end point of format string. The final
output would be appears as:
The sum of 5 and 6 is 11
The following program will help you to understand the concept more closely as it uses the printf()
statement to print the result of the calculations.
Write a program to print the sum of two numbers .
Program:
#include<stdio.h>
void main()
{
int a, b, c;
a = 5;
b = 6;
c = a + b;
Format Specifiers
%d -- displays a decimal (base 10) integer
%i -- used with other specifiers to indicate a "long"
%e -- displays a floating point value in exponential notation
%f -- displays a floating point value
%c -- displays a single character
%s -- displays a string of characters
Program shows the usage by some of the frequently used escape sequences
#include<stdio.h>
void main()
{
printf(“\n 1..\t2..\t3....\n”);
printf(“The question is, \” said Humpty Dumpty,\”which is to be masterthat\’s all.\””);
}
Output:
1.. 2.. 3....
“The questions is, “said Humpty Dumpty,” which is to be master-that’s all”.
3.5 scanf()
As previously stated, in order to write an interactive application, certain statements in the
programme must be able to collect data from the user. We provided a few functions in this sense,
such as getchar(), gets(), and getch(), among others. A programmer, on the other hand, needs more
flexibility in terms of:
1. Read the data from keyboard according to a specified format
2. Instruct the compiler to receive the particular type of value from the keyboard. For instance, integer
value or floating point value.
Instruct the compiler to read the specified number of digits of a given number. Reading mixed data
types from the keyboard using single function.
But the use of above mentioned functions is restrict with the character values only. There is a need of
more flexible and general function that could address the problems mentioned above.
scanf(), the complement of the printf(), can actually be used to read the different type of data from
the keyboard in a specified format. Due to what, it is referred to as formatted input functions.
Like printf(), scanf() also uses a format string to describe the format of the input, but with some little
variations as given below:
1. It doesn’t allow escape sequences in the format string.
2. It requires a special operator & called as “address of” to be prefix with the variable
identifiers.
So, a scanf() takes the following from:
scanf(“ format string”, arg1, arg2,.......argn);`
Where format string contains the formatting information by using which the data is to be entered
and arg1, arg2,...., argn are the arguments (normally variables preceded by an ampersand &) specify
the address of location where the data is stored. Both the section i.e., format string and arguments
(within itself also) must be separated by commas.
The format string in a scanf() describe the format of the input and it may contain:
1. Conversion specifiers as in the printf() functions.
2. White space characters i.e., tabs, blanks, and newlines.
3. Other characters than white spaces, that are matching characters and asteric
In layman's terms, the preceding statement is an instruction to the compiler to obtain an integer value
from the keyboard and store it in a variable called a. Where an is an integer variable that was
previously declared. Following this argument, the value stored in the variable can be used anywhere
for any reason. Let's take a closer look at the different components of this sentence.
Conversion Specifier in scanf()
As mentioned earlier, a conversion specifier instruct the scanf() to convert the input stream of binary
data coming from the keyboard in to the data type specified by the conversion character.
For instance, integer in case of %d as it utilizes the same conversion specifiers as the printf() except
one i.e., [...]. More than one conversion specifier can be used in a single scanf() to read more than one
value.
In such a case, corresponding variables each preceded by & must include in the same statement.
As white spaces are required is input stream, they just can be used to identify the end of each input
value.
For real time experience, consider the following program which demonstrate the usage of scanf() to
read integer values from the keyboard. This program will accept two numbers from the user and will
print their sum on the monitor
int main()
{
int var1;
printf(“Enter value of var1”);
scanf(“%d”,&var1);
printf(“Value of Var1 is = %d”,var1);
return 0;
}
If execution is not provided with the proper input, result may be unexpected
#include <stdio.h>
void main( )
{
int c;
printf("Enter a character");
c = getchar();
putchar(c);
}
gets() function
The gets() function allows the user to type a string of characters and then press the enter key. A
character list is used to store all of the characters entered by the user. To render the array a string, the
null character is inserted. The user will enter space-separated strings using the gets() method. It
returns the string that the user typed in. The gets() function is problematic to use because it doesn't
search for array bounds and keeps reading characters until the new line (enter) is encountered.
Decleration
char[ ] gets(char[]);
puts() function
The puts() function looks a lot like the printf() function. The puts() function is used to print the string
that was previously read using the gets() or scanf() functions on the console. The integer value
returned by the puts() function represents the number of characters printed on the console. Since it
prints an extra newline character with the string, which transfers the cursor to a new line on the
console, the integer value returned by puts() will always be the number of characters in the string
plus 1.
Declaration
int puts(char[])
#include<stdio.h>
#include <string.h>
int main(){
char name[30];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}
• Formatted input and output functions contain format specifier in their syntax.
• Unformatted input and output functions do not contain format specifier in their syntax.
• printf() and scanf() are examples for formatted input and output functions.
• getchar(), gets(), puts(), putchar() etc. are examples of unformatted input output functions.
Program
#include<stdio.h>
void main()
{
char str [11]; /* declar a character array str of size 11 */
printf(“\n enter a string (Maximum 10 characters):”);
gets(str); /* will read a string from the keyboard*/
printf(“\n the entered string \n:”);
puts(str); /* will print the under of str on the monitor and */
print(“ /* and advances the cursor to the .......*/ thank you”);
}
Output:
Enter a string (maximum 10 characters): GoodDay
The entered string is: GoodDay
Thank you
Summary
• I/O operations deal with the transfer of data to peripheral devices such as monitor, key
board, printer or secondary storage etc.
• A library is nothing more than one or more files that contain a group of predefined
functions. In its most general form the word ‘console’ refers to the standard input and
output devices.
• Unformatted console I/O functions doesn’t allow input and output to be formatted as per
the user requirements. getchar() function is used for reading a character from the keyboard.
• The putchar() is complementary function of getchar(). It is used to display a character on the
monitor.
• The another possible use of getch() is to temporarily halt the execution of a program
intentionally. gets() function is used to accept a string from the keyboard whereas puts()
function is used to print a string on the monitor.
• Formatted I/O Functions allows input and output operations to be performed in a fixed
format.
• The printf() in one of the most important and useful functions to display data on monitor.
• Except for double quotes, escape sequences and conversions specifiers, all characters with
in a pair of double quotes will be treated as literal text (string context) and will be display
as it is a on the monitor.
• Any character that is prefix with a backslash is suppose to be treated as an escape sequence.
• A conversions specifiers always begin with the percent sign (%) and immediately followed
by one or more conversions characters
Keywords
printf() scanf()
getchar() putchar()
gets() puts()
Header files: A text file that contains prototype of functions, definitions of constants etc. and which
can be included in a C program file to access those functions and constants.
#include compiler directive : This compiler directive instructs the compiler to insert the contents
of the specified file in place of this line.
Standard library: A group of in-built functions stored in a single file as a unit
Self Assessment
1. Which format specifier is used for integer
A. % c
B. %d
C. %f
D. % h
2. Which is correct file pointer for standard input
A. Stdout
B. Stdin
C. Stderr
D. Stdab
3. Which function is used for output on screen
A. Main ()
B. Scanf ()
C. Printf ()
D. Get ()
4. What is extension of header file?
A. .c
B. .b
C. .e
D. .h
5. main ( ) is a
A. Keyword
B. Function
C. Integer
D. Pointer
6. Which format specifier is used for float?
A. % c
B. %d
C. %h
D. % f
7. Input is taken using function….
A. Printf ()
B. Fprintf ()
C. Scanf ()
D. Main ()
8. Putchat( ) is used for..
A. As input function for string
B. display exactly one character as output.
C. Display one string on screen
D. Input from user
9. Getchar( ) having similarities with..
A. Puts ( )
B. Gets ( )
C. Main ( )
D. Putchar ( )
Review Questions
1. Define stdin, stdout, and stderr.
2. Differentiate the followings:
(a) printf() and puts()
(b) getche() and getch()
(c) scanf() and gets()
3. How format string is associated with printf()? Discuss the various possible components of a format
string in detail.
4. What happens if one uses variables in scanf() without using the address of operator (&)?
Discuss.
5. An amount of rupees, say R, is deposited in a bank for Y years, which pays simple interest at the
rate of ‘rt’ annually. Write a C program that prints the amount after Y years
6. Write down two functions xgets( ) and xputs( ) which work similar to the standard library functions
gets( ) and puts( ).
7. What is the differences between getchar( ), fgetchar( ), getch( ) and getche( )? With the help of
suitable example.
8. Write down two functions xgets( ) and xputs( ) which work similar to the standard library functions
gets( ) and puts( ).
9. Write down a function getint( ), which would receive a numeric string from the keyboard, convert
it to an integer number and return the integer to the calling function. A sample usage of getint( ) is
shown below:
main( )
{
int a ;
a = getint( ) ;
printf ( “you entered %d”, a )
}
10. What is the differences between getchar( ), fgetchar( ), getch( ) and getche( )?
Answers: Self-Assessment
1. B 2. B 3. C 4. D 5. B
6. D 7. C 8. B 9. B
Further Readings
Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson Education, Year of
Publication: 2008
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall of India,
New Delhi
Byron Gottfried, “Programming With C”, Tata McGraw Hill Publishing Company
Limited, New Delhi
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
Yashvant Kanetkar, Let us C
Greg W Scragg, Genesco Suny, Problem Solving with Co mputers, Jones and Bartlett,
1997.
Objectives
After studying this unit, you will be able to:
Introduction
The term "data types" refers to a comprehensive framework for defining variables and functions of
various types. The type of a variable decides how much storage space it takes up and how the stored
bit pattern is interpreted. A value's data form identifies a set of properties that it shares.
An expression is a set of constants, variables, and operators that follow the grammatical rules of the
language C and evaluate to a valid value. Activity refers to the impact that operators have on their
operands.
Valid or well-formed expression refers to an expression that follows the grammar rules of the C
programming language. An expression that is true or well evaluates to a single value of a valid C
data form. C expression can be of the following types:
1. Numerical expressions always evaluates to a numeric value on which arithmetic operations can be
performed. They can be further divided into the following two categories:
(a) Integer expression: those evaluating to integer value
(b) Real expression: those evaluating to a real (floating point) value
Thus, 3 + 5 is an integral expression and 3.8 – 6.97 is a real expression.
2. Logical or conditional expressions always result into either of the two values – true or false.
Thus 3 > 5 and x <= 7 are conditional expressions.
C has two distinct categories of data types – primary, and composite. Primary data types are the ones
that are in-built with C language while composite data types allow the programmers to create their
own data types.
There are five primary data types in C language.
1. char: stores a single character belonging to the defined character set of C language.
char a;
int b;
3. float: stores real numbers with single precision (precision of six digits after decimal points).
float c;
4. double: stores real numbers with double precision, i.e., twice the storage space required by
float.
double d;
The following table shows the meaning and storage spaces required by various primary data types.
Reserves a sequence of five locations of 2 bytes, each, for storing integers num[0], num[1],
num[2], num[3] and num[4].
4.3 Operators
An operator is a symbol that instructs the machine to perform mathematical or logical operations on
data held in variables. Data items (variables and constants) can be manipulated arithmetically in a C
program using operators.
C operators can be classified into a number of categories.
• Unary operator
• Binary operator
• Arithmetic operators
• Relational operators
• Logical operators
• Conditional operators
• Assignment operators
• Bitwise operators
• Increment and decrement operators
• Special operators
Unary operator
Unary operators are operators that act upon a single operand to produce a new value.
There are following types unary operators in C
Binary operator
Binary operators are those that operate on two operands. For example, a + b—the addition operator
(+) surrounded by two operands—is a popular binary expression. Arithmetic, relational, logical, and
assignment operators are all subsets of binary operators.
The binary operators are categorized as follow:
• Relational operators: less than (<), less than or equal to (<=), greater than (>), and greater
than or equal to (>=)
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations include addition, subtraction,
multiplication and division on one or more operands.
It is used to performed operations on numeric data types like int, float and double Arithmetic
operators work on numeric type of operands. C provides all the basic arithmetic operators. There are
five arithmetic operators in C.
The division operator (/) requires the second operand to be non-zero, though the operands need
not be integers. When an integer is divided by another integer, the result is also an integer. In
such instances the division is termed as integer division. Consider the following:
int x;
x = 10;
What do you expect the value of x/4 to be? If you guessed 2.5, you are wrong.
The result is of course 2.5 however, since it is integer division (division operation in which both
the operands are integers), the result 2.5 will be truncated to 2 to make the result an integer. In
case you wish to get the correct value you make this division a float type as x/4.0.
The % operator is known as modulus operator. It produces the remainder after the division of
two operands. The second operand must be non-zero.
Rest all the other operators work in their normal arithmetic way. Normal BODMAS rules are also
applicable to these arithmetic operators.
Relational Operators
The relational operator compares two operands to see if they are equivalent, unequal, or if one is
greater or inferior than the other.
The consequence is always a numeric value equal to true or false, regardless of whether the
operands are variables, constants, or expressions. As previously stated, a non-zero result indicates
fact, while a zero result indicates false. Six relational operators are available in the C programming
language.
== equal to
!= not equal to
A simple relation contains only one relational expression and takes the following form:
<ae-1> <relational operator> <ae-2>
<ae-1> and <ae-2> are arithmetic expressions, which may be constants, variables or combination
of these. The value of the relational operator is either 1 or 0. If the relation is true, result is 1
otherwise it is 0.
Example:
Expressions Result
Logical Operators
Using logical operators, several relational expressions may be combined to create a single compound
relational expression. To combine two or more relational statements, logical operators are used. Three
logical operators are available in C. A compound relation behaves in the same way as a single
relation generating a real or false value
1. (age > 50 && weight < 80) will evaluate to true if age is more than 50 and also weight is less than
80. Otherwise it will evaluate to false.
2. (a < 0 ¦ ch = = ‘a’) will evaluate to true if a is less than 0 while ch is equal to ‘a’, false otherwise.
3. (!(a < 0)) will evaluate to true if a is greater than or equal to 0, false otherwise.
Assignment Operators
Assignment operators are used to store the result of an expression to a variable. The most
commonly used assignment operator is (=). Be careful not to mistake assignment operator (=) for
mathematical equality operator which is indicated by the same symbol.
An expression with assignment operator is of the following form:
<identifier> = <expression>;
When this statement is executed, <expression> is evaluated and the value is stored in the
<identifier>.
Let us consider the following usage of assignment operator in C language.
int i;
i = 5;
i = i + 10;
The value now stored in the variable “i” will be 15. In this program, the current value stored in
variable i is 5. Thus, while executing i = i+10, the right hand side will be evaluated to give a value
15. This value will then be assigned to the left hand side. As a result, the current value of I after
execution of this statement will become 15.
C language provides a short cut to write arithmetic assignment expressions which takes the
following form:
<Variable> op = <expression>;
Example:
int i = 5;
i++;
++i;
––i;
i––;
When used in an isolated C statement, both prefix and postfix operators have the same effect, but
when they are used in expressions, each of them has a different effect.
In expressions, postfix operator uses the current value and then increments/decrements while
in the prefix form the value is incremented/decremented first and then used in the expression.
Consider the following examples:
E.g.: b = a ++;
this is postfix increment expression. This statement is equivalent to:
{b = a;
a = a+1;}
E.g. b = - - a;
this is prefix decrement expression. This statement is equivalent to:
{ a= a-1;
b = a; }
Consider the following C code that illustrates the usage of postfix and prefix increment
operators.
int a = 10; b = 0; //a = 10 and b = 0
a++; //a = 11 and b = 0
b = ++a; //a = 12 and b = 12
b = a++; //a = 13 and b = 12
Conditional Operators
C provides a ternary operator called the conditional operator which is represented
by :?. The syntax of this operator is given below.
A?B:C
Where “A” is a conditional expression resulting in either of the two values – true or false. The
value generated by this operator in the expression depends on the value of the conditional
expression “A”. If the value of “A” is true then the expression evaluates to “B” otherwise it
results in “C”.
Bitwise Operators
You're aware that a numeric value is stored in binary form in a variable. Data is manipulated at the
bit level using bitwise operators. These operators are used to measure bits or to move them left or
right. Only integer data types are supported by bitwise operators. The following is a list of the
various bit wise operators available in the C language, along with their corresponding meanings.
| (Bit-wise OR): Binary operator takes two operands of int type and performs bit-wise OR
operation. With assumption that int size is 8-bits:
int a = 5; [binary : 0000 0101]
int b = 9; [binary : 0000 1001]
a | b yields [binary : 0000 1101]
& (Bit-wise AND): Binary operator takes two operands of int type and performs bit-wise AND
operation. With same assumption on int size as above:
int a = 5; [binary : 0000 0101]
int b = 9; [binary : 0000 1001]
a & b yields [binary : 0000 0001]
^ (Bit-wise Logical XOR): XOR gives 1 if only one of the operand is 1 else 0. With same assumption
on int size as above:
int a = 5; [binary : 0000 0101]
int b = 9; [binary : 0000 1001]
a ^ b yields [binary : 0000 1100]
<< (Shift left): This operator shifts the bits towards left padding the space with 0 by given integer
times.
int a = 5; [binary : 0000 0101]
a << 3 yields [binary : 0010 1000]
>> (Shift right): This operator shifts the bits towards right padding the space with 0.
int a = 5; [binary : 0000 0101]
a >> 3 yields [binary : 0000 0000]
~ (one’s complement operator): It is a unary operator that causes the bits of its operand to be
inverted so that 1 becomes 0 and vice-versa. The operator must always precede the operand and
must be integer type of all sizes. Assuming that int type is of 1 byte size:
inr a = 5; [binary: 0000 0101]
~a; [binary: 1111 1010]
Special Operators
The C programming language also includes a variety of special operators that are not
found in other languages. The comma operator, sizeof operator, pointer operators (& and
*), and member selection operators (. and ->) are among these operators. When we
introduce pointers, we'll talk about pointer operators, and when we talk about structures
and unions, we'll talk about member selection operators.
We will discuss comma operator and sizeof operator in this section.
Comma Operator
This operator is used to link the related expressions together.
Example: int x, y, z;
z = (x = 10, y=20, x+y);
Here, the first statement will create three integer type variables – x, y and z. In the second
statement, right-hand side will be evaluated first. Consequently, 10 will be stored in
variable x, then 20 will be stored in variable y, and then values in x and y will be
multiplied result of which will be stored in variable z. Thus, the value stored in the
variable z will be 200 at the end
of execution.
Sizeof Operator
The sizeof operator works on variables, constants and even on data types. It returns the
number
of bytes the operand occupies in the memory.
Consider the following C code for illustration.
sizeof(int); //Gives number of bytes occupied by an
//integer type variable
sizeof(float); //Gives number of bytes occupied by a
//float type variable
The output of this code will be 2, 4. Don’t get disheartened if you get different result. This
is only because the machine on which this program was run allotted 2 bytes for int type
and 4 bytes for float type. The result that you get depends on the number of bytes
allocated to these types on your machine. Nevertheless in all cases sizeof operator returns
the number of bytes occupied by its operand on that particular machine.
Summary
Precedence defines the sequence in which operators are to be applied on the operands, while
evaluating the expressions involving more than one operator.
Keywords
Expression: A combination of identifiers and operators according to some rule that yields a value
Operator Proceeding: The precedents of an operator determine the order in which expression will
be evaluated
Operator: A symbol that works on one or more values to yield another value
The Size of Operator: The size of operator which is used to measure the date sizes. It a unary
compile type operator that is to return the length of the variable or parenthesized type specifiers.
Self-Assessment
1. Which one is not assignment operator?
A. +=
B. *=
C. &
D. >>=
2. (&= ) operator is used for…..
A. <<=
B. %=
C. /=
D. None of these
4. In c which operators having highest priority
A. Logical operator
B. Relational operator
C. Arithmetic operator
D. Conditional operator
5. Conditional operator in c is also called
A. Relational operator
B. Logical operator
C. Ternary operator
D. None of these
6. Which are the data types
A. Basic
B. Derived
C. Void
D. Above all
7. Which is not Derived Data Type
A. Array
B. Pointer
C. Union
D. Char
8. Which is correct basic data type
A. Int
B. Char
C. double
D. Above all
9. Find wrong statements
A. int a, b;
B. float rate;
C. int =2.5;
D. char = ‘B’;
10. Which is not unary operator
A. ++
B. --
C. &
D. +
11. Relational operator is used with
A. 1 operand.
B. 2 operands
C. Both 1 and 2
D. none of above
12. Which among the following is NOT a logical operator
A. &&
B. ||
C. !
D. @
6. d 7. d 8. d 9. c 10. d
11. b 12. d
Review Questions
1. What are the different classes of operators available in C language?
2. Define the term “Expression”. Explain the various types of expression in C.
3. What are the various logical and relational operators supported by C. Explain them with
proper examples.
4. Draw a table that will provide a complete list of operators, their precedence level and
their rules of association.
5. List down the advantages and limitations of using conditional operator in a C program.
6. Write short notes on:
Further Readings
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall of India,
New Delhi
Byron Gottfried, “Programming With C”, Tata McGraw Hill Publishing Company
Limited, New Delhi
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett,
1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
Yashvant Kanetkar, Let us C
Objectives
• After studying this unit, you will be able to:
• Explain decision making in C
• Explain branching
• Describe if, if-else statement in C
• Explain switch statement
• Explain looping concept in C
• Describe do-while loop
• Describe goto statement
Introduction
To write a realistic programme, don't think of it as a collection of statements put in a specific order.
It takes a lot more than that. Take a look at a real-life example. Life does not always go as planned:
1. There are some situations when you have to take decisions like whether to purchase this book or
not.
2. There are also some situations where you have to perform the particular action again and again
like for better understanding read this unit 5 times continuously.
In the same way, it's rare that we write a computer programme that doesn't run into similar issues.
Depending on the circumstances, most programmes require a statement or combination of
statements to be executed numerous times or not at all.
The C programming language offers a number of programme control statements that allow you to
influence the order in which your programmes are executed. This unit looks at different iteration-
based programme control statements and how to use them in a programme. The break and continue
jump statements in C are also discussed in this section.
Documentation Section
The documentation area of the programme is where the programmer provides information about the
programme. He normally offers the program's name, author information, and other facts such as
coding time and description. It provides a high-level overview of the code to anyone reading it.
**
* Author: Name
* date: DD/MM/YYYY
* no input needed
*/
Link Section
This part of the code is used to declare all the header files that will be used in the program. This leads
to the compiler being told to link the header files to the system libraries.
#include<stdio.h>
Definition Section
In this section, we define different constants. The keyword define is used in this part.
#define PI=3.14
int a = 10;
double b = 50.5,sum;
sum=a + b;
#include<stdio.h>
int main(){
int a=10;
double b=9.34,sum;
sum=a+b;
printf("%lf",sum);
return 0;
}
double a = 4.5,b=3.5;
//explicitly defined by user
int sum=(int)a+(int)b;
#include<stdio.h>
int main(){
double a = 10.5,b=5.5;
//explicitly defined by user
int sum=(int)a+(int)b;
printf("%d",sum);
return 0;
}
Long
This can be used to increased size of the current data.it is applied on int or double data type.
long double a;
#include<stdio.h>
int main(){
long double a ;
printf("%d",sizeof(a));
return 0;
}
Short
In general int data type occupies different memory spaces for a different operating system; to allocate
fixed memory space short keyword can be used.
short int a;
#include<stdio.h>
int main(){
short int a ;
printf("%d",sizeof(a));
return 0;
}
Unsigned
This keyword can be used to make the accepting values of a data type is positive data type.
#include<stdio.h>
int main(){
unsigned int a=-10 ;
printf("%u", a);
return 0;
}
Signed
This keyword accepts both positive and negative value.
#include<stdio.h>
int main(){
signed int a=-10 ;
printf("%d", a);
return 0;
}
Sequence
In the sequence construct, as the name implies, statements are executed sequentially i.e. one after the
other. In this, neither the statement are repeated nor in the order of execution changed as shown in
Figure.
You probably noticed in the previous unit that a C programme is executed top down, that is,
execution begins with the beginning of the main() function and continues, statement by statement,
until the end of the main (). In a C programme, the following programme illustrates the sequential
execution of statements.
#include<stdio.h>
main(){
printf("\n First statement");
printf("\n Second statement");
printf("\n Third statement");
printf("\n Second last statement");
printf("\n Last statement");
}
Output : -
Selection
Only appropriate statements are often performed instead of all of them, depending on the input and
the circumstance. A condition test is used to execute statements in the selection construct. You advise
the computer to do one course of action if the test returns true; otherwise, you advise the programme
to take an other course of action. The selection construct contains two or more sets of statements, but
only one of them is executed, as shown in the Figure.
The selection construct can be implemented by means of the if construct. The if construct makes
use of relational and logical operators for decision making, as shown in the pseudo code given
below:
#include<stdio.h>
main(){
int marks=50;
if(marks>40)
printf("Pass");
else
printf("Fail");
}
Output: -
Iteration
The iteration constructs are an efficient method of handling a series of statements that must be
repeated a variable number of times. Sometimes the required number of repetitions is known in
advance and sometimes the statements repeats over and over until certain specified conditions on
met, as shown in the Figure.
The iteration construct is also called as loop. The statements that are to be executed is called
as body of the loop and the condition on which a loop terminates is called as exit condition as
demonstrated by the program given below:
#include<stdio.h>
main(){
int i=0;
while(i<=20){
printf("\n %d ",i);
i++;
}
}
Output: -
Simple if Statement
In its basic form, the if statement evaluates a test condition (i.e., nothing but an expression) and direct
program execution depending on the result of that evaluation. The general form of a simple if
statement is as shown below:
if (expression)
statement;
Where a statement may consist of a single statement, a compound statement or nothing as an empty
statement. The expression also referred so as test condition must be enclosed in parentheses, which
causes the expression to be evaluated first. If it evaluate to true (i.e., a non-zero value), then the
statement associated with it will be executed otherwise ignored and the control will pass to the next
statement.
The above code fragment will printf “Pass” on the monitor if the value of marks is greater than 9.If
the value of marks is not grater than 9, the control simple ignore this statement and will pass to the
next statement. The follow program shows the use of simple if as it accepts the marks of a student
and printfs his/her result.
#include<stdio.h>
void main
{
int marks;
printf( “\n enter your marks”);
scanf(“%d”, marks);
if (marks>9) /* if construct with test condition */
printf (“ \n Pass”); /* statement associated with if */
printf(“ Thank you”); //next statement
}
output: run 1-> run 2->
Enter your marks : 77 ↵ Enter your marks : 9 ↵
Pass Thank you
Thank you
“Pass” has been displayed only if the expression evaluated to true otherwise if it evaluated
to false, the control ignores the associated statement and executed the next statement i.e., “Thank
you”.
As mentioned earlier, an if statement can control the execution of multiple statements, called as
compound statement or a block. Where a block is a group of two or more statements enclosed in
braces. So if these multiple statements are to be executed than they must be placed with in a pair of
braces, as illustrated by the following program.
Program:
# include<stdio.h>
void main()
{
int marks;
printf (“\n Enter your marks: “);
scanf (“ %d “, &marks) ;
if (marks > 39)
{
printf(“\n Pass”);
printf (“ \n Congratulation …”);
}
if (marks <40)
{
printf (“\n Fail”);
printf (“\n sorry. Good luck next time …”);
}
printf (“\n Thank you”);
}
Output: run 1-> run 2->
Enter your marks: 77↵ Enter your marks : 20↵
Pass Fail
Congratulations… Sorry. Good luck next time….
Thank you Thank You
Default an if construct when evaluates to true executes only the first statement associated
with it. If multiple statements are not enclosed with in parentheses, results may be unexpected.
Write a program if candidate got more than 50% in year exam screen show “Pass” otherwise
“Fail”.
if-else statement
When the specified expression evaluates to true, the basic if statement runs a single statement or a
collection of statements, as you may have noticed in the previous section (i.e. non-zero value). When
the expression evaluates to false (i.e. a zero value), it does nothing and proceeds to the next step in
the programme.
If you want a statement or a set of statements to be performed, however. Only when an expression
evaluates to false can it be mentioned in the else part, as demonstrated below in the if else statement's
standard structure.
if (expression)
statement1;
else
statement 2;
If expression evaluates to true, statement 1 is executed. If expression evaluates to false, statement 2 is
executed, but never both. Both statement 1 and statement 2, as mentioned earlier, may be single
statement, a compound statement, or an empty statement.
Actually, the simple if statement described in previous section is a simplification of its parent
statement i.e. if else statement, where the else section in optional. Without it, however, an if-else
construct look like a simple if construct.
if-else construct is particularly useful when you have the statements to be executed in both the cases
i.e. when the expression evaluates to true or false.
The code segment will display “Pass” on the monitor if the value of marks is greater than or equals
to 40. If the marks are less than 40 (obviously the else case), then the statement in the else section will
be executed and will printf “Fail” on the monitor. Let’s write the Program by using an if-else
construct.
#include<stdio.h>
void main ()
{
int marks;
else section required their own pair of braces as more than one statement is to be executed
when the expression evaluates to false.
In the above segment of code, the inner if executes only if the expression1 evaluates to true. The other
possible combination of nested if may take one of the following form:
· if (expression1)
{
if (expression2)
statement1;
}
· if (expression1)
{
if (expression 2)
statement1;
else
statement 2;
}
· if(expression1)
{
statement1;
}
else
{
if(exp2)
statement 2;
}
· if (exp 1)
{
statement1;
}
else
{
if (exp2)
statement 2;
else
statement3;
}
if(exp 1)
{
if (exp 2)
statement1;
else
statement 2;
}
else
{
if (exp3)
statement3;
else
statement4;
}
if (exp1)
{
if (exp2)
statement1;
}
else
{
if (exp3)
statement 2;
}
Let’s write a couple of programs to explore the various combination of nested if. The following
program not only print the request after accepting marks from the students but also print his/her
grade.
Program
#include<stdio.h>
void main ()
{
int marks;
printf (“\n Enter your marks:”);
scanf (“% d”,&marks”);
if (marks >=40)
{
printf (“\n Pass”);
if (marks > = 80)
printf (“ with distinction”);
}
else
printf (“\n Fail”);
}
Output: run 1 ->
Enter your marks : 77↵
Pass
Run 2->
Enter your marks : 88↵
Pass with distinction
Run 3->
Enter your marks : 38↵
Fail
The execution of the inner if only be there if first expression evaluates to true and the
message “with distinction” will printf only if both the expressions evaluates to true.
Program:
# include<stdio.h>
void main ()
{
int marks;
char grade;
printf (“\n Enter your marks:”);
scanf (“% d”, & marks”);
if (marks > = 90)
grade = ‘0’;
else
if (marks > = 80)
grade = ‘D’;
else
if( marks > =75)
grade = ‘M’;
else
if (marks > = 60)
grade = ‘I’;
else
if (marks > =50)
grade = ‘II’;
else
if (marks > 40)
grade = ‘III’;
else
grade = ‘F’;
printf( “\n Your grade is : % c”, grade),
}
Output: run 1 →
Enter your marks: 77 ↵
Your grade is: M
Run 2 →
Enter your marks: 39 ↵
Your grade is: F
This whole section of code is actually one statement that is comprised of six hierarchically
nested is else constructs, so there is no need to put them in the braces. At any time during the
general top to bottom execution of these expressions, if an expression evaluates to true, then the
associated statement will be executed and control flow will pass to the statement immediately
following the entire nested chain.
Switch statement
The switch statement is another useful C feature for dealing with scenarios where numerous
decisions must be made based on an expression with multiple values. The switch is a multiple branch
statement that compares the value of an expression to a list of case values and, if a match is found,
executes the statement associated with that case. A switch-case statement can take the following
general form:
switch (expression)
{
case value1: statement1;
case value2: statement2;
case value3: statement3;
:
case valuen: statementn;
[default: statement x ;]
}
statement;
Where switch is a keyword and the expression is any expression that evaluates to an integer value,
may be of type int, or char, or long. The case is a keyword followed by value 1, value 2, value n.
where value 1, value 2, .. value n may be an integer or character constant, normally referred to as case
labels. And the statement1, statement2, .. statementn may be single statement or set of statements, or
may be an empty statement.
The switch statement evaluates the expression first and then compare the return value against the
values value1, value2,.. valuen, and then one of the following happens:
1. If a case is found whose value matches with the value of the expression then the statement
associated with that case is executed.
2. If no match is found then the statement followed by the keyword default is executed.
3. If no match is found and there is no default label as it is an optional case, then no action takes place
and control passes to the statement next which is a statement immediately followed the switch
statements closing braces.
Consider the following program, which gives you an example of using the switch statement. This
program will receive a number between 1 to 5 and will display it’s English counterpart.
Program:
#include<stdio.h>
void main ()
{
int num;
printf (“\n Enter any number between 1 to 5 : “);
scanf (“ % d”, &num ) ;
switch (num)
{
case 1 : printf(“\n One”);
case 2 : printf (“\n Two”);
case 3 : printf (“\n Three”);
case 4 : printf (“\n Four”);
case 5 : printf (“\n Five”);
default : printf (“\n Wrong input”);
}
printf (“\n Thank You”);
}
Output: run 1 → run 2 →
Enter any number between 1 to 5: 2↵ Enter any number between
1 to 5: 4↵
Two Four
Three Five
Four Wrong input
Five Thank you
Wrong input
Thank you
Run 3->
Enter any number between 1 to 5 = 9↵
Wrong input
Thank you
There is no need to put braces with the individual case labels as they each contains single
statement, although a pair is required to group the entire case section.
5.7 Looping
Iteration statements are also known as loops or looping statements because the program execution
typically loops through the statement more than once. In this category, C provide the following
statement or you call loops.
1. for loop
2. while loop
3. do-while loop
Looping must not continue indefinitely as an analogy to real life you would not like to crack the same
joke again and again, so a mechanism is required to break out the loop and to allow the executives of
the next set of statements.
As a result, a general structure for implementing a loop expression has been designed. Which can be
better understood by grasping the following elements/parts/components of a loop that regulates the
amount of repetitions:
1. Initial Expression(s): Initial expression(s) is usually an assignment expression(s) which initializes
the control variable(s) of a loop, as they must be initialized before entering in a loop. The initial
expression(s) is executed only once, in the beginning of the loop. But if this expression(s) occurs in
the loop body, control variable(s) would be reassigned to initial values with every loop pass, and the
condition expression would never fail.
2. Condition Expression: Conditional expression is typically a relational expression that is set up to
terminate the execution of a loop. If the condition expression evaluates, to true i.e. 1, the loop body
gets executed, otherwise the loop is terminated. A condition expression may be evaluated before
entering in to a loop or before exiting from the loop called as entry-controlled loop and exit controlled
loop respectively. In C, the for loop and while loop are entry-controlled loops whereas do while loop
is exit-controlled loop.
3. Update Expression(s): The update expression(s) is essentially an increment expression or
decrement expression that changes the value(s) of loop variable(s), so that they could come to the
boundary values. The update expression(s) normally execute at the end of the loop body. It may
appear in the body of loop as it is updating expressions that assign the variable a new updated value
every time the loop passes.
4. The Loop Body: The loop body consists of statement(s) that is supposed to be executed again and
again as long as the condition expression evaluator to true i.e. 1. In an entry-controlled loop, the
condition expression evaluated first and if it evaluates to true, the loop-body is executed and if it
evaluate to false, the loop-body is terminated. Whereas, in exit controlled loop, the loop body
executed first and then the condition expression are evaluated. It is evaluate to false i.e. o, the loop is
terminated, otherwise repeated.
The above mentioned components are the essential component of a statement to be called as a loop
statement. Messing any of them may change the basic meaning of a perfect loop. The for, while and
do-while statements of C, comprises of all these essential components, hence referred to as loop
statements.
for loop
The for loop in C is the simplest, fixed and entry controlled loop. It is simplest as the structure of for
loop is divided into two segments i.e. control statement and the body of the loop. All its loop control
elements are placed together in the control statement where as body of the loop consists of statements
to be executed repeatedly.
It is fixed as number of repetitions is known is advance and can be useful in a situation when you
want to do something a fixed number of times. It is an entry controlled loop as the control statement
placed before the loop body i.e. condition expression will be evaluated first. The general form of the
for loop is:
for(initial expression(s) ; condition expression ; update expression(s)) loop-body;
When the above statement is encountered during program execution, the following events occur:
1. Initial expression is evaluated first and i will be assigned an initial value 1 i.e. i =1.
2. Then the condition expression is evaluated i.e. i < =10 and the result will be true as 1 < = 10 is true.
3. Since the condition expression is true, the statement in the loop body is executed i.e. printf(“\n
Hello World!”); which prints the message Hello World! on the screen.
4. After the execution of the loop body, the update expression i.e. ++i is executed which increment
the value of i by 1. In this way after the first execution of the loop the value of I becomes 2 as initially
it was 1.
5. After the execution of the update expression the condition expression is again evaluated. If it
evaluates to true the sequence is repeated from step no. 3, otherwise the loop terminates.
Also note that the loop body never executes if condition expression is evaluated to false in its first
execution. Figure shows the operation of a for loop.
Program :
#include<stdio.h>
int main(){
int i,n;
printf("Enter Number");
scanf("%d",&n);
for(i=1;i<=10;i++)
{
printf("%d*%d=%d\n",i,n,i*n);
}
return 0;
}
Output : -
While loop
The while loop, the second type of loop, is an entry controlled loop because it tests the conditions
first and only the control enters the loop body if the condition is true.
When the loop's iterations are complete, the control returns to the while statement, which repeats the
condition test. If the condition is false the first time, the loop does not iterate and control is passed to
the statement after the loop statement. Because we don't know the precise amount of iterations, it's a
kind of variable loop. The statements keep repeating themselves until specific conditions are met.
The while loop has the following form:
while (condition expression)
loop body;
Where the loop-body may contains a single statement, a compound statement or an empty statement.
The while loop iterates the loop body as long as the specified condition expression evaluates to true.
The while loop doesn’t explicitly contains the initialization expression and update expressions of the
loop. These two expressions are normally provided by the programmers as the initialization
expression(s) should be placed before the loop begins and updation expression(s) should be inside
the loop body. By using all these expressions the general farm of while loop may looks like as:
:
initialization expression(s);
while (conditional expression)
{:
: Loop Body
updation expression;
}
And the statements between the { and } forms the body of the loop. But the braces can be discarded,
if there is only one statement in the loop body
When the program execution readers a while statement, the following events occur:
1. First of all the conditional expression is evaluated i.e. i < 10.
2. The conditional expression is evaluated to true as i was 1 initially and 1 < 10 is true. But if it evaluate
to false, the loop will be terminated and the control moves to the first statement following loop body.
3. Since the condition expression is true, the loop body will be executed i.e. the printf statement and
the updation expression.
4. With the closing braces ( } ), it is assumed that the loop is finished and the control moves back to
the while statement, which repeats the test again and proceeds accordingly.
Program : -
#include<stdio.h>
int main()
{
int n, reverse=0, rem;
printf("Enter a number: ");
scanf("%d", &n);
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n/=10;
}
printf("Reversed Number: %d",reverse);
return 0;
}
Output : -
do-while loop
C’s third loop statement is the do-while loop, is an exit controlled loop i.e. it tests the conditions after
having executed the statement with in loop body. This means unlike the for and while loops, a do
while loop always executes at least once. The statement of the do-while loop is as follows:
do
{
loop-boody ;
}while (conditional expression) ;
The braces { } can be discarded when the loop-boody contains a single statement. The do-while loop
iterates the loop body as long as the specified condition is true while testing the condition at the end
of the loop each time, rather than at the beginning, as is done by the for and the while loop.
Like while loop, do-while loop also doesn’t contain the initialization and updation expression as part
of loop statement. However, these expressions can be associated with do-while loop by the
programmer according to required logic. Then the new form of do-while loop may looks like as:
Initialization expression(s);
do
{
Loop body;
Updating expression;
}while ( conditional expression(s) );
When the program control reaches at a ‘do while’ loop, the following events occur:
1. The loop body will be executed i.e. the print statement and the updation statement.
2. The conditional expression will be evaluated i.e. i <=10.
3. The conditional expression will evaluates to true as the value as i is 2 this time (initially=1).
4. Since the condition expression is true, the control will move back to execute the loop-body once
again.
The output of the above code may looks likes as:
Hello World !
Hello World !
:
Hello World ! (10 times)
Program :-
#include<stdio.h>
int main(){
int number;
printf("Enter a number:");
scanf("%d",&number);
do{
}while(number<=20);
return 0;
}
Output:-
While loop
do-while loop
do
{
scanf (“%d”, &x);
if (x < 0)
{
printf (“Negative value entered”);
break;
}
} while (x < = 10);
for loop
for (i = 1; x < = 10; ++i)
{
scanf (“%f”, &x);
if (x < 0)
{
printf (“Negative value entered!!”);
break;
}
}
When break is used in nested while, do-while, for or switch statements, it will cause a transfer of
control out of the immediate enclosing statement, but not out of the outer surrounding statements.
Consider the following code snippet in which a while loop is nested within a for loop.
for (i = 0; i < = n; ++i)
{
while (( c = getchar( ))! = ‘\n’)
{
if (c = ‘*’) break;
}
}
goto label;
…..
…..
label: statements;
........
statement;
int i;
for(i=0;i<=10;i++)
{
if(i==5)
{
goto STATUS;
}
printf("%d\n",i);
}
STATUS:
printf("Value of i is = 5 than goto working");
return 0;
}
Output :-
Summary
• Most of the programs require a statement or set of statements to be executed multiple times
or not to execute at all, depending on the circumstances.
• The statement by which we can control the flow of the program execution is called as control
flow statement or program control statement.
• In the sequence construct, as the name implies, statements are executed sequentially i.e. one
after the other.
• In selection construct, the execution of statements depends upon a condition test.
• The iteration constructs are an efficient method of handling a series of statements that must
be repeated a variable number of times.
• If multiple statements are to be executed than they must be placed with in a pair of braces.
• A simple if or if else construct may be placed with in another if or if-else construct.
• The switch statement is another convenient tool provided by C to handle the situations in
which multiple decisions to be made based on an expression that can have multiple values.
• The for loop in C is the simplest, fixed and entry controlled loop. An infinite for loop can be
created by skipping the conditional expression.
• A conditional expression cannot have multiple expression like initialization and updation
expression, but it may contain several conditions linked together using logical operators.
• The second type of loop, the while loop is an entry controlled loop as it tests the conditions
first and if the condition is true, then only the control will enter into the loop body. An empty
loop can also be configured using while statement and could used as a time delay loop.
• C’s third loop statement is the do while loop, is an exit controlled loop i.e. it tests the
conditions after having executed the statement with in loop body. Unlike the for and while
loops, a do while loop always executes at least once.
• The break statement is used in a program to skip the particular part of program code. The
jump statement continue is the compliment of the break statement.
Keywords
Conditional statement: A statement that evaluates to either true or false.
Continue statement: The statement that ignores execution of further statements and forces the loop
to evaluate the loop condition once again.
Default statement: An optional statement in a switch that is executed if none of the conditions
evaluates to true.
Switch statement: A multi-selection statement that branches to that statement whose specified
condition evaluates to true.
Control Statements: The statements that allow programmers to alter the sequential flow of execution
of the program and control the flow are called control statements.
For Loop: A for loop allows execution of a statement (or a block of statements) repeatedly a number
of times.
While Loop: In case the number of times a statement is to be executed is not known in advance, while
loop is used.
goto statement : The goto statement is known as jump statement in C.
Self-Assessment
1. What are the components of design structure of C?
A. Documentation
B. Link Section
C. Definition Section
D. Above all
2. Every C program must have ___________ function.
A. Printf ( )
B. Scanf ( )
C. main ( )
D. none of above
void main()
{
int x = 5;
if (true);
printf("hello");
}
A. It will display hello
B. It will throw an error
C. Nothing will be displayed
D. Compiler dependent
15. Which keyword is used to come out of a loop only for that iteration?
A. break
B. continue
C. return
D. none of the mentioned
Review Questions
1. Write a program using if-else statement.
2. Explain nested-if statement with example.
3. What do you mean by switch statement? How it used
4. A five-digit number is entered through the keyboard. Write a program to obtain the reversed
number and to determine whether the original and reversed numbers are equal or not.
5. Write a program to check whether a triangle is valid or not, when the three angles of the triangle
are entered through the keyboard. A triangle is valid if the sum of all the three angles is equal to 180
degrees.
6. Given the length and breadth of a rectangle, write a program to find whether the area of the
rectangle is greater than its perimeter. For example, the area of the rectangle with length = 5 and
breadth = 4 is greater than its perimeter.
7. What is the use of if-else statement?
8. Define selection in c programming.
9. Write a program in C to enter five integer values as age of five boys and calculate the average age
of all the boys.
10. Write a program to calculate the area of a square. All values enter with the help of keyboard.
11. What do you mean by looping?
12. Describe for loop with the help of suitable example.
13. Differentiate while loop and do-while loop.
14. What is the advantage of break statement in while loop?
15. Write a program to find the factorial value of any number entered through the keyboard.
16. Write a program to print all the ASCII values and their equivalent characters using a while loop.
The ASCII values vary from 0 to 255.
6. b 7. c 8. a 9. b 10. a
Further Readings
Ashok N. Kamthane, "Programming with ANCI & Turbo C", Pearson Education,
Year of Publication, 2008.
B.W. Kernighan and D.M. Ritchie, "The Programming Language", Prentice Hall of
India, New Delhi.
Byron Gottfried, "Programming with C", Tata McGraw Hill Publishing Company
Limited, New Delhi.
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett,
1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
Yashvant Kanetkar, Let us C
https://www.tutorialspoint.com/index.htm
www.webopedia.com
www.web-source.net
Objectives
After studying this unit, you will be able to:
Introduction
A function is a programming unit with a unique name that may be identified. It can be invoked by a
programme once it has been defined. When called, it may accept zero or more inputs. The code placed
inside the function specification determines what should be done with the incoming input(s). The
function generates a single output after doing the given transformation. The caller of the function
receives this output.
{
int j = 10;
printf (“Inside the main() function\n”);
function1 ();
printf (“after the function 1\n”);
printf (“main function () \n”);
printf (“j = %d\n”, j);
}
function1 ()
{
int i,n;
n = 3;
for(i = 0; i<=n-1; ++){
printf(“inside a function 1\n”);
printf(“i = %d\n”, i);
function2 ();
}
}
function2 ()
{
printf (“transfer of control\n);
printf (“inside a function 2\n”);
}
Definition of Functions
A function is a standalone piece of executable code that can be called from any other function. The
idea of functions comes to mind in many systems when a group of statements must be executed
repeatedly at various points in the programme and possibly with different sets of data. Those
repeating statements are stored in a function and called as needed. When a function is called, control
is sent to the called function, which is then run, before being returned to the calling function (to the
statement following the function call). Let us see an example as shown below:
Example:
/* Program to illustrate a function*/
#include <stdio.h>
main ()
{
void sample( );
printf(“\n You are in main”);
}
void sample( )
{
printf(“\n You are in sample”);
}
Output:
You are in sample
You are in main
Here we are calling a function sample ( ) through main( ) i.e. control of execution transfers from main(
) to sample( ) , which means main( ) is suspended for some time and sample( ) is executed. After its
execution the control returns back to main( ), at the statement following function call and the
execution of main( ) is resumed.
The syntax of a function is:
return data type function_name (list of arguments)
{
datatype declaration of the arguments;
executable statements;
return (expression);
}
where,
1. Return data type is the same as the data type of the variable that is returned by the function using
return statement.
2. A function_name is formed in the same way as variable names/identifiers are formed.
3. The list of arguments or parameters are valid variable names as shown below, separated by c
4. Arguments give the values which are passed from the calling function.
5. The body of function contains executable statements.
6. The return statement returns a single value to the calling function.ommas: (data type1 var1,data
type2 var2,…….. data type n var n) for example (int x, float y, char z).
Example: Let us write a simple function that calculates the square of an integer.
/*Program to calculate the square of a given integer*/
/* square( ) function */
{
int square (int no) /*passing of argument */
int result ; /* local variable to function square */
result = no*no;
return (result); /* returns an integer value */
}
/*It will be called from main()as follows */
main( )
{
int n ,sq; /* local variable to function main */
printf (“Enter a number to calculate square value”);
scanf(“%d”,&n);
sq=square(n); /* function call with parameter passing */
printf (”\nSquare of the number is : %d”, sq);
} /* program ends */
Output:
Enter a number to calculate square value: 5
Square of the number is: 25
Important Points
1. You can pass any number of arguments to a function but can return only one value at a
time.
Example: The following are the valid return statements
(a) return (5);
(b) return (x*y);
Example: The following are the invalid return statements
(a) return (2, 3);
(b) return (x, y);
2. If a function does not return anything, void specifier is used in the function declaration.
Example:
void square (int no)
{
int sq;
sq = no*no;
printf (“square is %d”, sq);
}
3. All the function’s return type is by default is “int”, i.e. a function returns an integer value,
if no type specifier is used in the function declaration.
Examples:
(a) square (int no); /* will return an integer value */
(b) int square (int no); /* will return an integer value */
(c) void square (int no); /* will not return anything */
4. What happens if a function has to return some value other than integer? The answer is very
simple: use the particular type specifier in the function declaration.
Example: Consider the code fragments of function definitions below:
(a) Code Fragment – 1:
char func_char( …….. )
{
char c;
……………
……………
……………
}
(b) Code Fragment – 1:
float func_float (……..)
{ fl
oat f;
…………..
…………..
…………..
return(f);
}
Thus from the above examples, we see that you can return all the data types from a function, the only
condition being that the value returned using return statement and the type specifier used in function
declaration should match.
5. A function can have many return statements. This thing happens when some condition
based returns are required.
Example:
/*Function to find greater of two numbers*/
int greater (int x, int y)
{
if (x>y)
return (x);
else
return (y);
}
6. And finally, with the execution of return statement, the control is transferred to the calling function
with the value associated with it.
In the above example, if we take x = 5 and y = 3, then the control will be transferred to the calling
function when the first return statement will be encountered, as the condition (x > y) will be satisfied.
All the remaining executable statements in the function will not be executed after this returning.
Function Calls
A function can be called by supplying its name followed by a list of arguments separated by commas
and surrounded in parentheses. If a function call does not require any parameters, it must be followed
by an empty pair of parenthesis.
The arguments appearing in the function call are referred to as actual arguments, in contrast to the
formal arguments that appear in the first line of function definition.
Function Declaration
A function is declared in the following manner:
<return_data_type> <function_name>(arg1, arg2, arg3)
<data_type_1> arg1; <data_type_2> arg2; <data_type_3> arg3;
{
statement-1;
statement-2
:
:
statement-n;
return(<expression of return_data_type>);
}
Example: The following function (name being getsq) returns the square of the input
number of float type. Clearly the <return_data_type> will also be float type.
float getsq(x)
float x;
{
return(x*x);
}
Another form of a function definition is:
<return_data_type><function_name>(formal argument list)
{
statement-1;
statement-2;
----------
statement-n;
return (<expression of return_data_type>);
}
Where formal argument list is a comma separated list of variables and their corresponding data
types.
The following function, addthem, takes two int type arguments and returns the sum of the two.
int addthem(int a, int b)
{
return(a+b);
}
The <return_data_type> always represents the data type of the value which is returned. The type
specification can be omitted if the function returns an integer or a character.
An empty pair of parenthesis must follow the function name if the function definition does not
include any arguments.
The argument declarations follow the first line. Each formal argument must have the same data type
as its corresponding actual argument.
The remainder of the function definition is a compound statement that defines the action to be taken
by the function. It is referred to as the body of the function.
The last statement in the body of function is return (expression). It is used to return the computed
result, if any, to the calling program.
void message()
{
printf(“Control is in message function\n”);
} /* does not return anything */
Output:
Control is in main
Control is in message function
Control is again in main
Call by Value
Call by value means sending the values of the arguments to functions. When a single value is passed
to a function via an actual argument, the value of the actual argument is copied into the function.
Therefore, the value of the corresponding formal argument can be altered within the function, but
the value of the actual argument within the calling routine will not change. This procedure for
passing the value of an argument to a function is known as passing by value or call by value.
int a = 2;
printf(“\na = %d (from main, before calling the function)”,a);
modify(a);
printf(“\na = %d (from main, after calling the function)”,a);
}
modify (int a)
{
a * = 3;
printf(“\na = %d (from the function, after being modified)”,a);
return;
}
output: a = 2 (from main, before calling the function)
a = 6 (from the function, after being modified)
a = 2 (from main, after calling the function)
The original value of a (i.e.=2) is displayed when main is executed. This value is then passed to the
function modify, where it is multiplied by three and the new value of the formal argument that is
displayed within the function. Finally, the value of a within main (i.e., the actual argument) is again
displayed, after control is transferred back to function main from function modify.
These results show that a is not altered within main, even though the corresponding value of a is
changed within modify.
Passing an argument by value has certain advantages and disadvantages.
On the positive side, it allows a single valued actual argument to be written as an expression rather
than being restricted to a single variable. Moreover, if the actual argument is expressed as a single
variable, it protects the value of this variable from alterations within the function.
On the negative side, it prevents information from being transferred back to the calling portion of the
program via arguments. Thus, passing by value is restricted to a one-way transfer of
information.
Call by Reference
Call by reference means sending the addresses of the arguments to the called function. In this method
the addresses of actual arguments in the calling function are copied into formal arguments of the
called functions. Thus using these addresses we would have an access to the actual arguments and
hence we would be able to manipulate them. Using a call by reference intelligently, it is possible to
make a function return more than one value at a time, which involves the study of pointer.
Function Prototype
Before defining the function, it is desired to declare the function along with its prototype. In function
prototype, the return value of function, type, and number of arguments are specified.
The declaration of all functions statement should be first statement in
main( ).
The general form of function declaration using ANSI Prototype is
data_type function_name (type1 arg1, type2 arg2 - - - - );
where arg1, arg2. . . are the list of arguments.
Function prototypes are desirable because they facilitate error checking between calls to a function
and corresponding function definition. They also help the compiler to perform automatic type
conversions on function parameters. When a function is called, actual arguments are automatically
converted to the types in function definition using normal rules of assignment.
Recursive Functions
Recursion is a process by which a function calls itself repeatedly, until some specified condition has
been satisfied. The process is used for repetitive computation in which each action is stated in terms
of previous result.
In order to solve a problem recursively, two conditions must be satisfied:
1. The problem must be written in recursive form.
2. The problem statement must include a stopping condition.
Example: /*To calculate the factorial of an integer recursively * /
# include <stdio.h>
main( )
{
int n;
long int fact (int);
printf (“\n n = “);
scanf (“%d”, &n);
printf (“\n n! = % ld” fact (n));
}
long int fact (int n)
{
if (n < = 1)
return 1;
else
return (n * factorial (n-1));
}
Library functions
The C programming language comes with a set of standard library functions that perform a variety
of useful tasks. Library functions implement all input and output operations (e.g., writing to the
terminal) as well as all math operations (e.g., sine and cosine evaluation).
It is important to call the proper header file at the start of the programme in order to use a library
function. All of the functions in the library in question have a header file that tells the programme
their name, type, and number and type of arguments. The preprocessor statement calls a header
file.#include <filename>
where filename represents the name of the header file.
A library function is accessed by simply writing the function name, followed by a list of arguments,
which represent the information being passed to the function. The arguments must be enclosed in
parentheses, and separated by commas: they can be constants, variables, or more complex
expressions. Note that the parentheses must be present even when there are no arguments.
Summary
• In this unit, we learnt about “Functions”: definition, declaration, prototypes, types, function
calls datatypes and storage classes, types function invoking and lastly Recursion.
• All these subtopics must have given you a clear idea of how to create and call functions
from other functions, how to send values through arguments, and how to return values to
the called function.
• We have seen that the functions, which do not return any value, must be declared as “void”,
return type.
• A function can return only one value at a time, although it can have many return
statements.
• A function can return any of the data type specified in ‘C’.
Keywords
Call by Reference: It means sending the addresses of the arguments to the called function.
Data types: It refers to the type of information while storage class refers to the life-time of a variable
and its scope within the program.
Function Call: A function can be called by specifying its name followed by a list of arguments
enclosed in parentheses and separated by commas.
Return Statement: Information is returned from the function to the calling portion of the program
via return statement.
Self-Assessment
1. Which one is not a library function
A. printf ( )
B. scanf ( )
C. gets ( )
D. abc ( )
2. Function call is _____________
D. All of above
4. Scope of variable in C is______
A. local
B. global
C. intermediate
D. both a and b
5. Variable used inside function is called _____________
A. Global variable
B. Local variable
C. Both a and b
D. None of these
6. In program a and b is a_______
int sum()
{
int a=15, b =20;
return x+y;
}
A. Global variable
B. Local variable
C. Intermediate variable
D. None of above
7. int x and int y is a______
add(int x,int y)
{
int z;
z=x+y;
printf(“result is= %d",z);
}
A. formal Parameter
B. actual Parameter
C. intermediate
D. both a and b
8. Actual parameter is_______
A. pointers
B. array
C. functions
D. loops
10. In program we can modify original value in
A. Call by value
B. Call by reference
C. above all
11. A function is called indirect recursive ______
A. Static function
B. Auto function
C. Recursive function
D. above all
Review Questions
1. Takes two integer inputs and produces the remainder when the larger is divided by the
smaller.
2. Swaps the two given integers.
3. What do you mean by function call.
4. Describe return value and their types.
5. Evaluates the following series for a specified n: 12 + 22 + 32 + 42 + ……..n2
6. A positive integer is entered through the keyboard. Write a function to obtain the prime
factors of this number.
7. Write a function which receives a float and an int from main( ), finds the product of these
two and returns the product which is printed through main( ).
8. Write a function that receives marks received by a student in 3 subjects and returns the
average and percentage of these marks. Call this function from main( ) and print the results
in main( ).
9. Given three variables x, y, z write a function to circularly shift their values to right. In
other words if x = 5, y = 8, z = 10 after circular shift y = 5, z = 8, x =10 after circular shift y =
5, z = 8 and x = 10. Call the function with variables a, b, c to circularly shift values.
10. Write a function to compute the distance between two points and use it to develop
another function that will compute the area of the triangle whose vertices are A(x1, y1), B(x2,
y2), and C(x3, y3). Use these functions to develop a function which returns a value 1 if the
point (x, y) lines inside the triangle ABC, otherwise a value 0.
11. Write a function to find the binary equivalent of a given decimal integer and display it.
Answer: Self-Assessment
1. d 2. c 3. d 4. d
5. b 6. c 7. a 8. a
Further Readings
Books Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson Education,
Year of Publication, 2008
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall of India,
New Delhi
Byron Gottfried, “Programming With C”, Tata McGraw Hill Publishing Company
Limited, New Delhi
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett, 1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
Yashvant Kanetkar, Let us C
www.en.wikipedia.org
www.web-source.net
www.webopedia.com
www.programiz.com
Objectives
• After studying this unit, you will be able to:
• Explain arrays
• Describe two dimensional array
• Describe array initialization
Introduction
An array is a group of data items of same data type that share a common name. Ordinary variables
are capable of holding only one value at a time. If we want to store more than one value at a time in
a single variable, we use arrays.
An array is a collective name given to a group of similar quantities. Each member in the group is
referred to by its position in the group.
Arrays are alloted the memory in a strictly contiguous fashion. The simplest array is one dimensional
array which is simply a list of variables of same data type. An array of one dimensional arrays is
called a two dimension array.
7.1 Arrays
Arrays are allocated the memory in a strictly contiguous fashion. The simplest array is one
dimensional array which is a list of variables of same data type. An array of one dimensional arrays
is called a two dimensional array; array of two dimensional arrays is three dimensional array and so
on.
The members of the array can be accessed using positive integer values (indicating their order in the
array) called subscript or index. Look at an array of integers as shown below:
Advantages of Arrays
Arrays offer a number of advantages, some of which are elucidated below:
1. If only a limited number of variables of a particular data type is required ion a program, one can
choose the variable names to suite the situation. Let us say we require five integer type variables, we
can define them as follows:
int v_one, v_two, v_three, v_four, v_five;
Now, consider if we require hundred integer type variables, is the above approach convenient?
Obviously not. We can, instead, use an array of integer type having 100 elements as shown below:
int num[100];
2. Array elements can be accessed using index. Therefore, all the elements can be processed in a
desired manner in a single for loop that runs for each element, as shown below:
for(i=0; i<100; i++)
num[i]=num[i]+10;
In a single for loop, all the elements have been incremented by 10.
3. Since array elements are physically created contiguously in the memory, they can be accesses using
pointers (as you will learn later). Therefore, there are more than one way to reference array elements.
One-dimensional Array
A list of items can be given one variable name using only one subscript and such a variable is called
a one dimensional array.
Example: If we want to store a set of five numbers by an array variable number. Then it will be
accomplished in the following way:
int number [5];
This declaration will reserve five contiguous memory locations capable of storing an integer type
value each, as shown below:
As C performs no bounds checking, care should be taken to ensure that the array indices are within
the declared limits. Also, indexing in C begins from 0 and not from 1.
This is a table of four rows and three columns. Such a table of items can be defined using two
dimensional arrays.
General form of declaring a 2-D array is
data_type array_name [row_size] [colum_size];
Example: int marks [4] [2];
It will declare an integer array marks of four rows and two columns. An element of this array can be
accessed by the manipulation of both the indices. printf (“%d”, marks [2] [1]) will print the element
present in third row and second column.
C allows arrays of three or more dimensions. Multi-dimensional arrays are defined in much the same
manner as one-dimensional arrays, except that a separate pair of square brackets is required for each
subscript.
The general form of a multi-dimensional array is
data_type array_name [s1] [s2] [s3] . . . [sm];
E.g.: int survey [3] [5] [12];
float table [5] [4] [5] [3];
Here, survey is a 3-dimensional array declared to contain 180 integer type elements. Similarly, table
is a 4-dimensional array containing 300 elements of floating point type.
Let us consider some applications of multidimensional array programming.
1. Sorting an integer array.
# include <stdio.h>
void main( )
{
int arr [5];
int i, j; temp;
printf (“\n Enter the elements of the array:”};
scanf (“%d”, & arr [i]);
for (i = 0; i < = 4; i ++);
{
for (J = 0; J < = 3; J ++)
if (arr [J] > arr [J+1])
{
temp = arr [J];
arg [J] = arr [J+1];
arr [J+1] = temp;
}
}
printf (“\ n The Sorted array is:”);
for (i = 0; i < 5; i++)
printf (“\ t %d”, arr [i]);
}
Character Arrays
Just as a group of integers can be stored in an integer array, group of characters can be stored in a
character array or “strings”. The string constant is a one dimensional array of characters terminated
by null character (‘\0’). This null character ‘\0’ (ASCII value0) is different from ‘O’
(ASCII value 48).
The terminating null character is important because it is the only way the function that works with
string can know where the string ends.
Example: Static char name [ ] = {‘K’, ‘R’, ‘I’, ‘S’, ‘H’, ‘\0’};
This example shows the declaration and initialization of a character array. The array elements of a
character array are stored in contiguous locations with each element occupying one byte of memory.
Two-dimensional Arrays
Two dimensional arrays may be initialized by a list of initial values enclosed in braces following their
declaration.
E.g.: static int table[2][3] = {0, 0, 0, 1, 1, 1};
initializes the elements of the first row to 0 and the second row to one. The initialization is done by
row.
The aforesaid statement can be equivalently written as
static int table[2][3] = {{0, 0, 0}, {1, 1, 1}};
Multi-dimensional Array
Example: Example of initializing a 4-dimensional array:
static int arr [3] [4] [2] = {{{2, 4}, {7, 8}, {3, 4}, {5, 6},},
{{7, 6}, {3, 4}, {5, 3}, {2, 3}, },
{{8, 9}, {7, 2}, {3, 4}, {6, 1}, } };
In this example, the outer array has three elements, each of which is a two dimensional array of
four rows, each of which is a one dimensional array of two elements.
{
int num [6];
int count;
for (count = 0; count < 6; count ++)
{
printf (“\n Enter %d element:” count+1);
scanf (“%d”, &num [count]);
}
}
In this example, using the for loop, the process of asking and receiving the marks is accomplished.
When count has the value zero, the scanf( ) statement will cause the value to be stored at num [0].
This process continues until count has the value greater than 5.
Each element of the array has a memory address. The following program prints an array limit value
and an array element address.
Program:
#include <stdio.h>
void printarr(int a[]);
main()
{
int a[5];
for(int i = 0;i<5;i++)
{
a[i]=i;
}
printarr(a);
}
void printarr(int a[])
{
for(int i = 0;i<5;i++)
{
printf(“value in array %d\n”,a[i]);
}
}
void printdetail(int a[])
{
for(int i = 0;i<5;i++)
{
printf(“value in array %d and address is %16lu\n”,a[i],&a[i]);
\\ A
}
}
Explanation
1. The function printarr prints the value of each element in arr.
2. The function printdetail prints the value and address of each element as given in statement A. Since
each element is of the integer type, the difference between addresses is 2.
3. Each array element occupies consecutive memory locations.
4. You can print addresses using place holders %16lu or %p.
Questions
1. Write a program to add two 6 x 6 matrices.
2. Write a program to multiply any two 3 x 3 matrices.
3. Write a program to sort all the elements of a 4 x 4 matrix.
4. Write a program to obtain the determinant value of a 5 x 5 matrix.
}
Example:
Now, consider the following function, which takes an array as an argument along with another
argument and based on the passed arguments, it returns the average of the numbers passed through
the array as follows −
double getAverage(int arr[], int size)
{
int i;
double avg;
double sum = 0;
#include <stdio.h>
double getAverage(int arr[], int size);
int main () {
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
avg = getAverage( balance, 5 ) ;
printf( "Average value is: %f ", avg );
return 0;
}
Summary
• An array is a group of memory locations related by the fact that they all have the same name
and same data type.
• An array including more than one dimension is called a multidimensional array.
• The size of an array should be a positive number. If an array in declared without a size and
in initialized to a series of values it is implicitly given the size of number of initializers.
• Array subscript always starts with 0. Last element’s subscript is always one less than the
size of the array e.g., an array with 10 elements contains element 0 to 9. Size of an array must
be a constant number.
Keywords
Array: A user defined simple data structure which represents a group of same type of
variables having same name each being referred to by an integral index
Multidimensional array: An array in which elements are accessed using multiple indices
One dimensional array: An array in which elements are accessed using a single index
Subscript/Index: The integral index by which an array element is accessed
Two dimensional array: An array in which elements are accessed using two indices
Self Assessment
Choose the appropriate answers:
1. Array is a group of data items of
(a) Same data type that share a common name
(b) Same data type that share a uncommon name
(c) Not data type that never common name
(d) None of the above
2. The general form of array declaration is
(a) array_name [size];
(b) data_type array_name [size];
(c) data_type [size];
(d) None
3. What will be the output of the following program if the input is - “tomorrow never
comes!”.
main( )
{
char letter [80];
int count;
for (count = 0; count < 80; count++)
letter[count] = getchar( );
for (count = 0; count < 80; count++)
putchar (toupper (letter[count]));
}
4. The members of the array can be accessed using positive integer values called .....................
5. While initializing a two dimensional array, it is necessary to mention the .....................
dimension, whereas the ..................... is optional.
6. The ..................... is a one dimensional array of characters terminated by null character
(‘\0’).
State whether the following statements are true or false:
7. All the members of an array share a common name and memory location.
8. Array elements contain garbage values till the time they are initialized.
9. 3-dimensional array declared to contain 180 integer type elements.
10. Array element can be accessed using index.
Review Questions
1. Explain the usefulness of Arrays in C.
2. What do you mean by ‘Array’? How it can be declared & initialized in a C program?
3. Draw a diagram to represent the internal storage of an Array.
4. Describe the different types of Array. Give suitable programs.
tomorrow
second(column),first
1. a 2. b 3. never 4. subscript 5.
dimesion(row)
comes
Straight
6. 7. False 8. True 9. True 10. True
Constant
Further Readings
Books Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson
Education, Year of Publication, 2008
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall of
India, New Delhi
Byron Gottfried, “Programming With C”, Tata McGraw Hill Publishing Company
Limited, New Delhi
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett,
1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
Yashvant Kanetkar, Let us C
www.en.wikipedia.org
www.web-source.net
www.webopedia.com
Objectives
After studying this unit, you will be able to:
Introduction
One of the most important topics in DSA is sorting and searching. One of the most prevalent uses
of computers nowadays is for storing and retrieving data. The amount of data and information kept
and accessed by computer has grown over time, resulting in massive databases. To properly
manage and process information in databases, a plethora of approaches and algorithms have been
developed. Searching is the process of finding up a specific data record in a database. Sorting is the
process of arranging records in a database. Combining sorting and searching is an important topic
of research in computational algorithms. Both are crucial areas of research in data structures.
8.1 Searching
Searching is an operation or a strategy for locating a certain element or value inside a list. Whether
or not the element being searched is found determines whether a search is successful or
unsuccessful.
The practise of looking through the data in a data structure to see if a given value is present is
known as searching. (As well as perhaps returning it.) For example, the contains method of the
Array List searches the list for a given item and returns true or false.
Some of the standard searching technique that isbeing followed in data structure is listed below:
1. Linear Search
2. Binary Search
Linear search
Linear search is a simple and straightforward search strategy. In linear search, we look for an
element or value in an array by traversing it from the beginning until the element or value we want
is discovered.
It compares the element to be searched with all of the items in the array and returns the index of the
element in the array if the element is successfully matched, otherwise it returns -1. When there are
fewer elements in a list, Linear Search is used on unsorted or unordered lists.
Algorithm
Linear Search ( Array A, Value x)
Step 1: Set i to 1
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 8: Exit
Pseudo code
procedure linear_search (list, value)
for each item in the list
if match item == value
return the item’s location
end if
end for
end procedure
Complexity of algorithm
Space O(1)
Let us take an example of an array A[7]={5,2,1,6,3,7,8}. Array A has 7 items. Let us assume
we are looking for 7 in the array. Targeted item=7.
Here, we have
A[7]={5,2,1,6,3,7,8}
X=7
Linear search is rarely used practically. The time complexity of above algorithm is O(n).
return 0;
}
Binary Search
Binary Search is used with sorted array or list. In binary search, we follow the followingsteps:
1. We start by comparing the element to be searched with the element in the middle ofthe
list/array.
2. If we get a match, we return the index of the middle element.
3. If we do not get a match, we check whether the element to be searched is less orgreater than in
value than the middle element.
4. If the element/number to be searched is greater in value than the middle number, then we pick
the elements on the right side of the middle element(as the list/array is sorted, hence on the right,
we will have all the numbers greater than the middle number), and start again from the step 1.
Algorithm
Step 1: Data list must be ordered list in ascending order.
Step 2: Probe middle of list
Step 3: If target equals list[mid], FOUND.
Step 4: If target < list[mid], discard 1/2 of list between list[mid] and list[last].
Step 5: If target > list[mid], discard 1/2 of list between list[first] and list[mid].
Step 6: Continue searching the shortened list until either the target is found, or there are no
elements to probe.
Pseudo code
The pseudo code of binary search algorithms
A ← sorted array
n ← size of array
x ← value to be searched
if A[mid Point] = x
EXIT: x found at location mid Point
end while
end procedure
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
Sorting
A sorting algorithm is an algorithm that puts elements of a list in a certain order. The mostused
orders are numerical order and lexicographical order. Efficient sorting is important tooptimizing
the use of other algorithms that require sorted lists to work correctly and for producinghuman -
readable input.
Sorting is the process of placing elements from a collection in some kind of order. For example, a
list of words could be sorted alphabetically or by length. Efficient sorting is important to optimize
the use of other algorithms that require sorted lists to work correctly.
Importance of sorting
To represent data in more readable format.
Optimize data searching to high level.
Bubble Sort
The simplest sorting algorithm is bubble sort. It works by comparing each adjacent pair of elements
and swapping them if they are out of order. It works by stepping through the list to be sorted
multiple times, comparing two items at a time and exchanging them if they are out of order. The
process is repeated until no swaps are required, indicating that the list is sorted. For large data sets,
this approach is ineffective. This approach has an average and worst case time complexity of O(n2),
where n is the number of elements..
6 4 2 >> 4 6 2
4 6 2>> 4 2 6
4 26 >> 2 4 6
Algorithm
for i=N-1 to 2 {
set swap flag to false
for j=1 to i {
if list[j-1] > list[j]
swap list[j-1] and list[j]
set swap flag to true
}
if swap flag is false, break. The list is sorted.
}
Selection Sort
Selection Sort finds the smallest element in the array and exchanges it with the element in the first
position, it then finds the second smallest element and exchanges it with the element in the second
position and continues this process until the entire list is sorted.
Algorithm
Step 1: Set MIN to location 0
Step 2: Search the minimum element in the list
Step 3: Swap with value at location MIN
Step 4: Increment MIN to point to next element
Step 5: Repeat until list is sorted
22 10 15 18 >> 10 22 15 18
10 22 15 18 >> 1015 22 18
10 15 22 18 >> 10 15 1822
10 15 18 22
arr[] = 64 25 12 22 11
Merge Sort
Merge sort is a recursive algorithm that involves splitting and merging the array.
Algorithm
The algorithm works as follows:
merge(arr, l, m, r);
}
}
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
/* Driver code */
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
Quick Sort
Quick sort is an interesting algorithm because while its worst case is technically O(N2), in practice it
is almost always O(N log N)
Quick sort is a recursive algorithm based around the idea of choosing a pivot item and sorting
around it.
Algorithm
#include<stdio.h>
int main(){
char a[]={'h','e','l','l','o','\0'};
for(int i=0;i<=6;i++){
printf("%c",a[i]);
}
return 0;
}
Output:
hello
Summary
Searching is the process of looking through the data contained in a data structure and determining
if a specific value is present.
Binary Search Algorithm follows the Divide and Conquer strategy where it finds the item from the
sorted list of items
In a linear search, array is traversed sequentially and each element is checked until a match is found
A Sorting process is used to rearrange a given array or elements based upon selected algorithm/
sort function
Bubble sort, swap neighbours the larger items drop down while the smaller ones bubble up, in n-1
passes through the array
Self Assessment
1. Every element in an array is searched against some searching key, special for
A. Linear search
B. Bubble sort
C. All of them
D. Binary search
A. Insertion sort
B. Heap sort
C. Bubble sort
D. Quick sort
A. Bubble sort
B. Insertion sort
C. Quick sort
D. Merge sort
6. If the given input array is sorted or nearly sorted, which of the following algorithm gives the
best performance?
A. Insertion sort
B. Selection sort
C. Quick sort
D. Merge sort
A. Bubble Sort
B. Merge Sort
C. Tree Sort
D. Insertion Sort
A. Merge
B. Bubble
C. Heap
D. Radix
A. Floats value
B. A string literal
C. Integer values
D. None of them
1. A 2. A 3. A 4. A 5. C
6. A 7. C 8. B 9. D 10. B
11. B
Review Questions
1. Write a program to implement a Linear Search Algorithm?
2. Differentiate between linear search and binary search.
3. Write down algorithm for binary search.
4. What is significance of sorting, give an example?
5. How selection sort is different form merge sort?
6. What is complexity in algorithm?
Further Readings
Books Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson Education,
Year of Publication, 2008
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall of India,
New Delhi
Byron Gottfried, “Programming With C”, Tata McGraw Hill Publishing Company Limited,
New Delhi
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett, 1997.
www.en.wikipedia.org
www.web-source.net
www.webopedia.com
www.geeksforgeeks.org
www.tutorialspoint.com
Objectives
After studying this unit, you will be able to:
Explain strings
Describe reading and writing strings
Explain string handling functions
Introduction
Computers process a variety of data kinds in addition to numeric data. The data to be processed is
frequently textual, such as words, names, and addresses. String type variables are used to store and
process this type of data. There is no explicit string data type in C.
Character arrays, on the other hand, can be used to simulate the same thing. In this session, we'll
look at strings and how to manipulate them in C.
9.1 Strings
In C, a string is defined as a collection of characters. The NULL character, which signifies the end of
the string, is used to end each string. Any group of characters enclosed in double-quote marks is
referred to as a string constant.
When characters in a string constant are stored, the NULL character is automatically appended to
the end of them. The escape sequence ‘0' is used to represent the NULL character within a
programme. A string constant is an array with a lower bound of 0 and an upper bound of the
string's length in characters.
Now, if we want to pick a substring of size k from the string of size n, the time required to achieve
this would be O(k) plus the time needed to locate a free space big enough to hold the string.
In the above figure memory is divided into nodes of size 4 with a link field that is two characters
long. Deletion of a substring can be carried out by replacing all characters in this substring by 0 and
freeing nodes in which the data fields consist of only 0’s.
Storage compaction can be carried out when there are no free nodes. String representation with
variable size is similar.
Each node in the purest version of a linked list representation of strings would be one in size.
Normally, this would be considered a huge waste of space. With a two-character link field, this
means that only 1/3 of the available Memory will be used to store string data, while the remaining
2/3 will be used exclusively for link data.
char string9[10];
substr(string9, string8, 5, 4);
printf(“%s\n”, string9);
The idea is that we’ll extract a substring of length 4, starting at character 5 (0-based) of string8,
andcopy the substring to string9. Just as with strcpy, it’s our responsibility to declare the
destinationstring (string9) big enough. Here is an implementation of substr. Not surprisingly, it’s
quitesimilar to strcpy:
substr(char dest[], char src[], int offset, intlen)
{
inti;
for(i = 0; i<len&&src[offset + i] != ‘\0’; i++)
dest[i] = src[i + offset];
dest[i] = ‘\0’;
}
If you compare this code to the code for mystrcpy, you’ll see that the only differences are
thatcharacters are fetched from src[offset + i] instead of src[i], and that the loop stops when
lencharacters have been copied (or when the src string runs out of characters, whichever
comesfirst).
In this unit, we’ve been careless about declaring the return types of the string functions, and(with
the exception of mystrlen) they haven’t returned values. The real string functions do returnvalues,
but they’re of type ``pointer to character,’’ which we haven’t discussed yet.When working with
strings, it’s important to keep firmly in mind the differences betweencharacters and strings. We
must also occasionally remember the way characters are represented,and about the relation
between character values and integers.
As we have had several occasions to mention, a character is represented internally as a
smallinteger, with a value depending on the character set in use. For example, we might find
that‘A’ had the value 65, that ‘a’ had the value 97, and that ‘+’ had the value 43. (These are, in
fact,the values in the ASCII character set, which most computers use. However, you don’t need
tolearn these values, because the vast majority of the time, you use character constants to referto
characters, and the compiler worries about the values for you. Using character constants
inpreference to raw numeric values also makes your programs more portable.)
As we may also have mentioned, there is a big difference between a character and a string, evena
string which contains only one character (other than the \0).
‘A’ is not the same as “A”. To drive home this point, let’s illustrate it with a fewexamples.
If you have a string:
char string[] = “hello, world!”;
you can modify its first character by saying
string[0] = ‘H’;
(Of course, there’s nothing magic about the first character; you can modify any character in
thestring in this way. Be aware, though, that it is not always safe to modify strings in-place like this;
we’ll say more about the modifiability of strings in a later unit on pointers.) Since you’re replacing a
character, you want a character constant, ‘H’. It would not be right to write
string[0] = “H”; /* WRONG */
because “H” is a string (an array of characters), not a single character. (The destination of the
assignment, string[0], is a char, but the right-hand side is a string; these types don’t match.) On the
other hand, when you need a string, you must use a string. To print a single newline, you could call
printf(“\n”);
It would not be correct to call
printf(‘\n’); /* WRONG */
charstr [50]
gets (str);
puts (str);
}
Out of the above list, We shall discuss the functions strlen( ), strcpy( ), strcat( ) and strcmp( ), since
these are the most commonly used functions. This will also illustrate how the library functions in
general handle strings. Let us study these functions one by one.
9.5 strlen( )
This function counts the number of characters present in a string. Its usage is illustrated in the
following program.
main( )
{
chararr[ ] = “Bamboozled” ;
int len1, len2 ;
len1 = strlen( arr ) ;
len2 = strlen( “Humpty Dumpty” ) ;
printf( “\nstring = %s length = %d”, arr, len1 ) ;
printf( “\nstring = %s length = %d”, “Humpty Dumpty”, len2 ) ;
9.6 strcpy( )
This function copies the contents of one string into another. The base addresses of the
source and target strings should be supplied to this function. Here is an example of strcpy(
) in action...
main( )
{
char source[ ] = “Sayonara” ;
char target[20] ;
strcpy( target, source ) ;
printf( “\nsource string = %s”, source ) ;
printf( “\ntarget string = %s”, target ) ;
}
And here is the output...
source string = Sayonara
target string = Sayonara
On supplying the base addresses, strcpy( ) goes on copying the characters in source string into the
target string till it doesn’t encounter the end of source string (‘\0’). It is our responsibility to see to it
that the target string’s dimension is big enough to hold the string being copied into it.
Thus, a string gets copied into another, piece-meal, character by character. There is no short cut for
this. Let us now attempt to mimic strcpy( ), via our own string copy function, which we will call
xstrcpy( ).
main( )
{
char source[ ] = “Sayonara” ;
char target[20] ;
xstrcpy( target, source ) ;
printf( “\nsource string = %s”, source ) ;
printf( “\ntarget string = %s”, target ) ;
}
xstrcpy( char *t, char *s )
{
while ( *s != ‘\0’ )
{
*t = *s ;
s++ ;
t++ ;
}
*t = ‘\0’ ;
9.7 strcat( )
This function concatenates the source string at the end of the target string. For example,
“Bombay”and “Nagpur” on concatenation would result into a string “BombayNagpur”. Here is an
exampleof strcat( ) at work.
main( )
{
char source[ ] = “Folks!” ;
char target[30] = “Hello” ;
strcat( target, source ) ;
printf( “\nsource string = %s”, source ) ;
printf( “\ntarget string = %s”, target ) ;
}
And here is the output...
source string = Folks!
target string = HelloFolks!
9.8 strcmp( )
This is a function which compares two strings to find out whether they are same or different. The
two strings are compared character by character until there is a mismatch or end of one of the
strings is reached, whichever occurs first. If the two strings are identical, strcmp( ) returns a value
zero. If they’re not, it returns the numeric difference between the ASCII values of the first non-
matching pairs of characters. Here is a program which puts strcmp( ) in action.
main( )
{
char string1[ ] = “Jerry” ;
char string2[ ] = “Ferry” ;
inti, j, k ;
i = strcmp( string1, “Jerry” ) ;
j = strcmp( string1, string2 ) ;
k = strcmp( string1, “Jerry boy” ) ;
printf( “\n%d %d %d”, i, j, k ) ;
}
And here is the output...
0 4 -32
Summary
A string is defined in C as an array of characters. Each string is terminated by the NULL
character, which indicates end of the string.
A string constant is denoted by any set of characters included in double-quote marks.
The NULL character is automatically appended to the end of the characters in a string
constant when they are stored. Within a program, the NULL character is denoted by the
escape sequence ‘\ 0’.
A string constant represents an array whose lower bound is 0 and whose upper bound is
the number of characters in the string.
Strings are stored in three types of structures - Fixed length structure, Variable length
structure, and Linked structure.
Keywords
gets( ): A C library function used to read a character entered at the keyboard and to place
it at theaddress pointed to by its character pointer argument
puts( ): A C library function that writes its string argument to the screen followed by the
newline
strcat(): The C library function that appends one string to another returning a pointer to
concatenated string
strcmp(): The C library function that compares two strings
string.h: A C header file that contains string manipulating library functions
String: An array of characters terminated by the NULL character
Self Assessment
1. Which one is correct method for Initializing string?
A. Puts ( )
B. Gets ( )
C. Print ( )
D. None of above
A. Scanf( )
B. Gets ( )
C. Puts ( )
D. Printf( )
4. String is an______________
A. an array of characters
B. sequence of characters terminated with a null character
C. both a and b
D. none of above
5. Which of the following function is more appropriate for reading in a multi-word string?
A. gets ( )
B. Puts ( )
C. Printf( )
D. Sizeo( )
6. Format specifier is used to print a string is ___________
A. % d
B. % c
C. % s
D. % f
7. Is there any difference between the two statements?
char *ch = "string ";
charch[] = "String";
A. Yes
B. No
8. Function of strcat( ) is_______________
A. 1
B. 0
C. 2
D. -1
10. The library function used to computes string's length
A. strlwr( )
B. strcpy( )
C. strlen( )
D. strpr( )
11. What will strupr( ) function do?
A. 16 characters
B. 8 characters
C. 32 characters
D. None of above
14. What will strlwr( ) function do?
A. char input[100];
B. puts(‘Input string’);
C. gets(input);
D. puts("Entered string is");
1. D 2. B 3. C 4. C 5. C
6. C 7. A 8. C 9. B 10. C
Review Questions
1. Write a C program that reads a sentence from the keyboard and prints the frequency of each
letter.
2. How can you create a string type C variable? Can they be assigned to each other in the same way
as other data types? Explain.
3. Write a program that converts a string like “124” to an integer 124.
4. Write a program that replaces two or more consecutive blanks in a string by a single blank.
For example, if the input is
Grim return to the planet of apes!!
the output should be
Further Readings
Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson Education, Year of
Publication, 2008
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall of India,
New Delhi
Byron Gottfried, “Programming With C”, Tata McGraw Hill Publishing Company Limited,
New Delhi
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett, 1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
YashvantKanetkar, Let us C
www.en.wikipedia.org
www.web-source.net
www.webopedia.com
Objectives
After studying this unit, you will be able to:
• storage classes
• Scope of a variable
• Auto, Static, Extern and Register
Introduction
Storage Classes are used to characterise a variable's or function's characteristics. These
characteristics include scope, visibility, and life-time, which allow us to track the presence of a
variable through the course of a program's execution. The following items are described by a
storage class in C:
The variable scope.
The location where the variable will be stored.
The initialized value of a variable.
A lifetime of a variable.
Who can access a variable?
main( )
{
int m = 1000;
function 2( );
printf (“%d \n”, m);
}
function 1( )
{
int m = 10;
printf (“%d \n”, m);
}
function 2( )
{
int m = 100;
function 1( );
printf (“%d \n”, m);
}
output: 10
100
1000
An external variable is also known as a global variable. It is not confined to a single function. Its
scope extends from the point of definition through the remainder of the program.
External variables can be accessed from any function that falls within their scope. They are declared
outside a function. If a local variable and a global variable have the same name, local variable will
have precedence over global in the function where it is declared.
Notes
function ( )
{
int count = 0;
-------
-------
count ++;
When the function references the variable count, it will be referencing only its local variable, not the
global one. The value of count in main( ) will not be affected.
Explanation
In Case 1, the function is written after main, so you have to write the prototype definition in main
as given in statement D.
Questions
1. Write a function which receives a float and an int from main( ), finds the product of these
two and returns the product which is printed through main( ).
2. Write a function that receives 5 integers and returns the sum, average and standard
deviation of these numbers. Call this function from main( ) and print the results in main( ).
Write a function that receives marks received by a student in 3 subjects and returns the average and
percentage of these marks. Call this function from main( ) and print
voidautoStorageClass()
{
printf("\nDemonstrating auto class\n\n");
voidregisterStorageClass()
{
printf("--------------------------------");
}
voidexternStorageClass()
{
printf("--------------------------------");
}
voidstaticStorageClass()
{
inti = 0;
printf("\nLoop started:\n");
printf("\nLoop ended:\n");
printf("--------------------------------");
}
int main()
// exiting
printf("\n\nStorage Classes demonstrated");
return 0;
}
Summary
• Auto, extern, register, static are the four different storage classes in a C program.
• In this unit, we learnt about “storage classes”. A keyword auto is used to define an auto
storage class.
• Extern storage class is used when we have global functions or variables which are shared
between two or more files
• The static variables are used within function/ file as local static variables. They can also be
used as a global variable
• Register is used to store the variable in CPU registers rather memory location for quick
access.
• Storage class represents the scope and lifespan of a variable.
• It also tells who can access a variable and from where?
Keywords
Auto Register
Extern Static
Self Assessment
1. What is the initial value of register storage class specifier?
A. 0
B. Null
C. Garbage
D. Infinite
A. Within block
B. Within Program
C. Global Multiple files
D. None of the above
A. Within block
B. Within Program
C. Global Multiple files
D. None of the above
A. Auto
B. Struct
C. Typedef
D. Static
A. 0
B. 1
C. 2
D. 3
A. Garbage value
B. 0 0
C. 1 0
D. 1 1
7. In case of a conflict between the names of a local and global variable what happens?
8. Where will the space be allocated for an automatic storage class variable?
A. In CPU register
B. In memory as well as in CPU register
C. In memory
D. On disk.
return 50;
}
A. -1
B. 50
C. 0
D. Compiler error
A. Declaration
B. Definition
C. Initialization
D. None of the above
A. Internal
B. External
C. External and Internal are not valid terms for functions
D. Both Internal and External
A. External
B. Internal
C. Both internal and external
D. None of above
A. Register
B. Auto
C. Extern
D. Static
A. Register
B. Auto
C. Extern
D. Static
Review Questions
1. Write a program to demonstrate static storageclasses
2. What is significance of storageclasses.
3. Write a program to demonstrate auto storage classes
4. Write a program to demonstrate extern storage classes
5. Write a program to demonstrate register storage classes
6. C 7. B 8. C 9. B 10. A
Further Readings
Books Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson
Education,Year of Publication, 2008
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall ofIndia,
New Delhi
Byron Gottfried, “Programming With C”, Tata McGraw Hill Publishing CompanyLimited,
New Delhi
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett,1997.
www.en.wikipedia.org
www.web-source.net
www.webopedia.com
Objectives
After studying this unit, you will be able to:
Introduction
Computers use their memory for storing instructions of the programs as well as the values of the
variables. Since memory is a sequential collection of storage cells each cell has an address
associated with it. Whenever we declare a variable, the system allocates, somewhere in the
memory, a memory location and a unique address is assigned to this location. Whenever a value is
assigned to this variable the value gets stored in the location having a unique address in the
memory associated with that variable. Therefore, the values stored in memory can be manipulated
using their addresses. Pointer is an extremely powerful mechanism to write efficient programs.
Incidentally, this feature makes C stand out as the most powerful programming language. Pointers
are the topic of this unit.
int n;
int *ptr; /* pointer to an integer*/
The following statement assigns the address location of the variable n to ptr, and ptr is a pointer to
n.
ptr=&n;
Since a pointer variable points to a location, the content of that location is obtained by prefixing the
pointer variable by the unary operator * (also called the indirection or dereferencing operator)like,
*<pointer_variable>.
# include<stdio.h>
main()
{
int a=10, *ptr;
ptr=&a; /* ptr points to the location of a */
printf(“The value of a pointed by the pointer ptr is: %d”, *ptr);
/* printing the value of a pointed by ptr through the pointer ptr*/
}
A null value can be assigned to a pointer when it does not point to any data or in the other words,
as a good programming habit every pointer should be initialized with the null value. A pointer
with a null value assigned to it is nothing but a pointer which contains the address zero.
The precedence of the unary operators ‘&’ and ‘*’ are same in C language. Here as a special casewe
can mention that ‘&’ operator cannot be used or applied to any arithmetic expression, it canonly be
used with an operand which has unique address.
Pointer is a variable which can hold the address of a memory location. The value stored in apointer
type variable is interpreted as an address. Consider the following declarative statement:
intnum = 197;
As the memory addresses are numbers, they can be assigned to some other variable. Let ptr bethe
variable which holds the address of variable num. We can access the value of num by thevariable
ptr. Thus, we can say “ptr points to num”. Diagrammatically, it can be shown as:
main( )
{
inti = 3;
printf (“\n Address of i: = %u”, &i); /* returns the address * /
printf (“\t value i = %d”, * (&i)); /* returns the value of address of i */
}
: int x, *p=&x; statement declares x as an integer variable and p as a pointer variable and then
initializes p to the address of x. This is an initialization of p, not *p. On the contrary, the statement
int *p = &x, x; is invalid because the target variable x is declared first.
#include <stdio.h>
// Driver Code
int main()
{
// Integer variable
// Pointer to an integer
int *ptr1, *ptr2;
// Pointer stores
// the address of N
ptr1 = &N;
ptr2 = &N;
return 0;
}
Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to
variables that are related to each other, such as elements of the same array, then p1 and p2 can be
meaningfully compared.
The following program modifies the previous example − one by incrementing the variable pointer
so long as the address to which it points is either less than or equal to the address of the last
element of the array, which is &var[MAX - 1]
int main () {
return 0;
}
Summary
• Pointers are often passed to a function as arguments by reference. This allows data items
within the calling function to be accessed, altered by the called function, and then returned
to the calling function in the altered form.
• There is an intimate relationship between pointers and arrays as an array name is really a
pointer to the first element in the array.
• Access to the elements of array using pointers is enabled by adding the respective
subscript to the pointer value (i.e. address of zeroth element) and the expression
proceeded with an indirection operator.
• As pointer declaration does not allocate memory to store the objects it points at, therefore,
memory is allocated at run time known as dynamic memory allocation.
• The library routine malloc can be used for this purpose.
Keywords
Array of Pointer: A multi-dimensional array can be expressed in terms of an array of
pointers rather than as a pointer to a group of contiguous arrays.
Pointer: It is a variable which can hold the address of a memory location rather than the
value at the location.
Pointer Expression: Like other variables, pointer variables can be used in expressions.
Arithmetic and comparison operations can be performed on the pointers
Self Assessment
1 What are the correct statements about pointers?
A. +
B. -
C. *
D. /
4. What format specifier is used for pointers?
A. %c
B. %d
C. %p
D. %s
5. Which statements are true about NULL pointers
A. 1
B. 2
C. 0
D. 4
7. Which one is incorrect statement?
A. int x=90;
B. int *ptr1,*ptr2;
C. ptr1=@x;
D. ptr2=ptr1;
8. What type of arithmetic operations can performed on pointers?
A. Addition
B. Subtraction
C. Multiply
D. Above all
9. What is the output of following program?
#include<stdio.h>
int main(){
int x=90,y=10,result;
int *ptr1,*ptr2;
ptr1=&x;
ptr2=&y;
result=*ptr1**ptr2;
printf("Product of x and y using pointers is %d\n",result);
return 0;
}
A. 100
B. 80
C. 900
D. 10
10. Which one is incorrect statement?
A. int a=10,*ptr;
B. ptr=/a;
C. ptr--;
D. above all
6. C 7. C 8. D 9. C 10. C
Review Questions
1. Define ‘Pointer’. List down the various advantages of using pointers in a C program.
2. How pointer are initialized and implemented in C? Write a program to explain the concept.
3. Explain with the help of a C program, the concept of Pointer Arithmetic in C.
4. How printer in C incorporates the concept of Arrays? Write a suitable program to demonstrate
the concept.
5. Differentiate the followings:
(a) Pointer and arrays
(b) Pointer to a variable and pointer to a pointer
(c) Pointer and variable
(d) Value in a function and address in a function
Further Readings
Books Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson
Education,Year of Publication, 2008
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall ofIndia,
New Delhi
Byron Gottfried, “Programming With C”, Tata McGraw Hill Publishing CompanyLimited,
New Delhi
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett,1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-
HallInternational, 1982.
YashvantKanetkar, Let us C
www.en.wikipedia.org
www.web-source.net
www.webopedia.com
Objectives
After studying this unit, you will be able to:
• Dynamic Memory Management functions
• malloc() and calloc()
• realloc() and free()
Introduction
The Dynamic Memory Allocation concept is utilised to solve the array problem. An array is a set of
values with a fixed number of elements. You can't adjust the size of an array once it's been declared.
Programmers can use Dynamic Memory Allocation to allocate memory during runtime.
Because the static representation of a linear ordered list using an array wastes resources and, in
some situations, causes overflows. We no longer want to pre-allocate memory to any linear list;
instead, we want to allocate memory to elements as they are added to the list. This necessitates
memory allocation that is dynamic.
variables get allocated permanently variables get allocated only if your program
unit gets active
Allocation is done before program execution Allocation is done during program execution
It uses the data structure called stack for It uses the data structure called heap for
implementing static allocation implementing dynamic allocation
Syntax
ptr = (cast-type*) malloc(byte-size)
Example
ptr = (int*) malloc(20 * sizeof(int));
That is to say it returns a pointer of type void * that is the start in memory of the reserved portion of
size number_of_bytes. If memory cannot be allocated a NULL pointer is returned.
Since a void * is returned the C standard states that this pointer can be converted to any type. The
size_t argument type is defined in stdlib.h and is an unsigned type.
So:
char *cp;
cp = malloc(100);
attempts to get 100 bytes and assigns the start address to cp.
Also it is usual to use the sizeof() function to specify the number of bytes:
int *ip;
ip = (int *) malloc(100*sizeof(int));
Some C compilers may require to cast the type of conversion. The (int *) means coercion to
aninteger pointer. Coercion to the correct pointer type is very important to ensure pointer
arithmeticis performed correctly.
It is good practice to use sizeof() even if you know the actual size you want – it makes for
deviceindependent (portable) code.
#include <stdlib.h>
int main(){
int *ptr;
ptr = malloc(10 * sizeof(*ptr));
if (ptr != NULL) {
*(ptr + 7) =80;
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
realloc
: Calloc
#include <stdio.h>
int main() {
int * ptr;
ptr = calloc(10, sizeof(int));
if (ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Dynamically Building 10 Blocks ");
return 0;
: realloc
#include<stdio.h>
int main()
{
char *ptr;
ptr = NULL;
ptr = realloc(ptr,10);
if(ptr != NULL)
printf("Memory created successfully\n");
return 0;
}
12.4 free
The memory allocated using functions malloc() and calloc() is not de-allocated on their ownIt is
used to dynamically de-allocate the memory.
Syntax :free(ptr);
: free
#include <stdio.h>
int main() {
int* ptr = malloc(10 * sizeof(*ptr));
if (ptr != NULL){
*(ptr + 4) = 50;
printf("Value of the 4th integer is %d\n",*(ptr + 4));
}
free(ptr);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, *ptr1;
int n, i;
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
Malloc Memory successfully freed.
Memory successfully allocated using calloc.
Calloc Memory successfully freed.
malloc malloc (sz ) Allocate a block of size sz bytes from memory heap and return a pointer
to the allocated block
e.g., ptr = (cast.type*) malloc (byte_size);
calloc calloc in (sz) Allocate a block of size n x sz bytes from memory heap, initialize it to
zero and return a pointer to the allocated block
e.g., ptr = (cast_type*) calloc (n, elem_size);
realloc realloc (bl,; sz) Adjust the size of the memory block blk allocated on the heap
to sz, copy the contents to a new location if necessary and return a
pointer to the allocated block
e.g., ptr = realloc (ptr, newsize);
free free (blk) Free block of memory blk allocated from memory heap
e.g., free (ptr);
• When we don't know how much memory will be required for the software ahead of time.
• When we need data structures that don't have a memory restriction.
• When you wish to make better use of your memory space.
• For example, if you allocate memory space for a 1D array like array[20] and only use 10
memory spaces, the remaining 10 memory spaces will be squandered, and this wasted
memory will be unavailable to other programme variables.
• Insertions and deletions in dynamically constructed lists may be done quickly and easily
by manipulating addresses, whereas insertions and deletions in statically allocated
memory result in additional movements and memory waste.
• Dynamic memory allocation is required when using the concepts of structures and linked
lists in programming.
Summary
Dynamic memory allocation is to allocate memory at “run time”.
Dynamically allocated memory must be referred to by pointers.
Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure
(like Array) is changed during the runtime.
mallocmethod in C is used to dynamically allocate a single large block of memory with the
specified size.
free method in C is used to dynamically de-allocate the memory.
realloc method in C is used to dynamically change the memory allocation of a previously allocated
memory.
Keywords
Dynamic memory allocation
Self-Assessment
1. Among 4 header files, which should be included to use the memory allocation functions
like malloc(), calloc(), realloc() and free()?
A. #include<string.h>
B. #include<stdlib.h>
C. #include<memory.h>
D. All of above
2. Which of the following statement is correct prototype of the malloc() function in c ?
A. int* malloc(int);
B. Char* malloc(char);
C. unsignedint* malloc(unsigned int);
D. void* malloc(size_t);
3. malloc() returns a float pointer if memory is allocated for storing float's and a double
pointer if memory is allocated for storing double's. A.
A. TRUE
B. FALSE
C. May Be
D. Can't Say
4. DMA stands for
A. More efficient
B. Less efficient
C. Don’t know
D. None of above
8. Which function is used to delete the allocated memory space?
A. Dealloc()
B. free()
C. Both A and B
A. calloc() allocates the memory and also initializes the allocates memory to zero,
while memory allocated using malloc() has random data.
B. malloc() and memset() can be used to get the same effect as calloc()
C. Both malloc() and calloc() return 'void *' pointer
D. All of the above
10. Specify the 2 library functions to dynamically allocate memory?
A. Zero
B. Null
C. Nothing
D. One
12. Which one is used during memory de allocation in C?
A. remove(p);
B. delete(p);
C. free(p);
D. terminate(p);
13. In which technique memory allocated at run time
A. int
6. A 7. A 8. B 9. D 10. C
Review Questions
1. What are the disadvantages of static memory allocation?
2. Differentiate between static memory allocation and dynamic memory allocation.
3. Write a program to demonstrate the malloc function.
4. Differentia between free and realloc function.
5. What are the advantages of dynamic memory allocation?
Further Readings
Books Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson Education,
Year of Publication, 2008
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall of India,
New Delhi
Byron Gottfried, “Programming with C”, Tata McGraw Hill Publishing Company Limited,
New Delhi
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
YashvantKanetkar, Let us C
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett, 1997
www.en.wikipedia.org
www.web-source.net
www.webopedia.com
www.geeksforgeeks.org
Objectives
After studying this unit, you will be able to:
• Define structure
• Identify array within structure
• Define union and deceleration
• Explain union of structures
• Differentiate between union and structure
Introduction
Arrays can be used to aggregate groups of variables of the same type, as you've seen. The difficulty
now is how to combine data that isn't typed in the same way. The explanation is that C is a
language that can be easily extended. It can be extended by defining data types that are built from
the basic types. That example, you can use a data type called a structure to organize variables of
various types.
The following topics are concerned in this unit:
1. Declaring and defining structures
2. Assigning values to structure members
3. Array within structures
4. Structure within structures
: struct book
{
char name [30];
char author [25];
float price;
}
struct book book1, book2;
2. It is also allowed to combine structure declaration and variable declaration in one statement.
This declaration is given below:
struct person
Arrays of Structures
The most common use of structures is in arrays of structures. To declare an array
of structures, first the structure is defined then an array variable of that structure
is declared. In such a declaration, each element of the array represents a structure
variable.
struct marks
{
int number;
float subject [3];
}
student [2];
: struct pay
{
int dearness;
inthouse_rent;
int city;
};
struct salary
{
char name [20];
char department [10];
struct pay allowance;
struct pay arrears;
}
struct salary employee [100];
The pay template is defined outside the salary template and is used to define the structure of
allowance and arrears inside the salary structure.
It is also permissible to nest more than one type of structures:
structpersonal_record
{
structname_part name;
struct date date_of_birth;
------
------
};
structpersonal_record person1;
The first member of the structure is name which is of the type structname_part. Similarly, other
members have their structure types.
1. The called function be declared for its type, appropriate to the data type is expected to
return. For example, if it is performing a copy of the entire structure, then it must be
declared as struct with an appropriate tag name.
2. The structure variable used as the actual argument and the corresponding formal
argument in the called function must be of the same struct type.
3. The return statement is necessary only when the function is returning some data. The
expression may be any simple variable or structure or an expression using simple
variables.
4. When a function returns a structure, it must be assigned to a structure of identical type in
function.
5. The called function must be declared in calling function for its type if it is placed after the
calling function.
e.g.: /* Program showing passing of structure member as function parameters * /
struct stores
{
char name [20];
float price;
int quantity;
};
main( )
{
struct stores update( );
floatmul( ), p_increment, value;
:
#include <stdio.h>
typedefstruct
{
char *name;
intacct_no;
characcttype;
float balance;
}
record;
/* transfer a structure-type pointer to a function */
main( )
{
void adjust (record *pt); /* function declaration * /
static record customer = {“Smith”, 3333, ‘C’, 33.33};
printf (“%s %d %c %.2f\n”, customer.name, customer.acct_no,
customer.acct_type, customer.balance);
adjust (&customer);
printf (“%s %d %c %.2f\n”, customer.name, customer.acct_no,
customer.acct_type, customer.balance);
The compiler allocates a piece of storage that is large enough to hold the largest variable type in the
union. As shown in the example declaration, the member x requires 4 bytes which is the largest
among the members. It is assumed that a float variable requires 4 bytes of storage and the figure
above shows how all the three variables share the same address.
main( )
{
struct a
{
inti;
char c[2];
};
struct b
:
#include <stdio.h>
main()
{
union id
{
char color;
int size;
};
struct
{
char manufacturer[20];
float cost;
union id description;
} shirt, trouser;
printf(“%d\n”, sizeof(union id));
shirt.description.color = ‘ w ‘ ; /* assigns a value to color */
printf(“%c %d\n”, shirt.description.color, shirt. description. size);
shirt.description.size = 12; /* assigns a value to size */
printf(“%c %d\n”, shirt.description.color, shirt.description. size);
}
Uses of Union
Unions, like structures, contain members whose individual data types may differ from one another.
But the members that compose a union share the same storage area within the computer’s memory,
whereas each member within a structure is assigned its own unique storage area. Thus, unions are
used to conserve memory.
Unions are useful for applications involving multiple members, where values need not be assigned
to all of the members at any one time. Unions are also used wherever the requirement is to access
the same memory locations in more than one way. This is often required while calling Basic
Input/Output System functions (often simply called BIOS routines) present in the read only
memory (ROM) of the computer.
Many DOS based application software’s need to access DOS internal data structures. The breakup
of these internal data structures however, is not consistent and often changes from one version of
DOS to another. Therefore, to make the application programs compatible with different versions of
DOS, these programs create unions which take into account the variations in the breakup of these
DOS data structures. These programs when executed first test the version member of DOS being
used on the machine and then access the appropriate part of the union.
Summary
• Structure is a derived data type used to store the instances of variables of different data
types.
• Structure definition creates a format that may be used to declare structure variables in the
program later on.
• The structure operators like dot operator “.” are used to assign values to structure
members.
• Structure variable can be initialized as any other data type. An array of structure can be
declared as any other array. In such an array, each element is a structure. Structures may
contain arrays as well as structures.
• Union is a memory location that is shared by two or more variables.
• When union variable is declared, compiler automatically allocates enough storage to hold
to largest member of union. Only the unions with storage class external or static can be
initialized.
• Unions are useful for applications involving multiple members. They are also used in
many
• DOS based application softwares. typedef and enum are two user defined data types.
Keywords
Random access file: A file, which allows accessing its records without restriction on the order of
access.
Sequential file: A file, which allows accessing its records only from the first record onwards.
Structure: A grouped data type created by user.
Structure: A structure is a collection of variables referenced under one name providing a
convenient means of keeping related information together. Structures within structure: It means
nesting of structures.
Union: A data type that allows more than one variable to share the same memory area. User
defined data types: The way you are not creating any new data type but are referring to an existing
data type by a different name. Such data types are known as user defined data types.
Self-Assessment
1. A structure is a __
A. :
B. .
C. >
D. <
3. Which keyword is used to define structure in C__
A. structure
B. struct
C. structC
D. none of above
4. Passing structure in function using___
A. function by value
B. function by reference
C. both function by reference and function by value
D. none of above
5. How to access members using Pointer__
A. have one or more pointers which point to the same type of structure, as their
member.
B. can dynamically be expanded or contracted
C. both of them
D. none of above
8. What are the types of Self Referential Structures?
A. (->)
B. (+)
C. (:)
D. (:)
11. Union differs from structure in the following way
6. C 7. C 8. C 9. D 10. A
11. C
Review Questions
1. What do you mean by ‘Structure’? How it can be declared and initialized in a C program?
2. Draw a diagram to represent the internal storage of a structure.
3. What do you mean by ‘Union’? How it can be declared and initialized in a C program?
4. Differentiate the followings:
(a) Arrays and structures
(b) Local and global structure
(c) Array of structure and structure within array
(d) Structure and union
5. Write short note on:
(a) Internal storage of union
(b) Function returning structures
(c) Structure within a structure
6. Write a program that compares two given dates. To store date use structure say date that
contains three members namely date, month and year. If the dates are equal then display message
as “Equal” otherwise “Unequal”.
8. Explain the usefulness of structures and unions in C.
Further Readings
Books Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson Education,
Year of Publication, 2008
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall of India,
New Delhi
Byron Gottfried, “Programming With C”, Tata McGraw Hill Publishing Company Limited,
New Delhi
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett, 1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
YashvantKanetkar, Let us C
Objectives
After studying this unit, you will be able to:
Introduction
Data is only stored in variables and arrays for a limited time. When a programme ends, all of this
data is lost. Files are used to store enormous volumes of data indefinitely. Secondary storage
devices, particularly disc storage devices, are used by computers to store files. We'll go through
how C programmes edit, update, and process data files in this unit.
A file is a set of data or characters that can be text or a programme. In the C programming
language, there are two sorts of files: sequential and random access. Random access files are more
difficult to create than sequential ones. The data or text will be stored or read back sequentially. In
random access file, the data can be accessed and processed randomly
Filename
It is a string of characters that makes up a valid filename for an operating system. It may contain
two parts, a primary name and an optional period with an extension.
Example:
Input.dat
Store
PROG.C
Student.C
Text.out
Data Structure
Data structure of a file is defined as file in the library of standard I/O function definitions. All files
should be declared as of type file before they are used.
Purpose: When we open a file, we must specify what we want to do with the file.
Following is the general format for declaring and opening a file:
File *fp;
fp = fopen ( “filename”, “mode”);
The first statement declares the variable fp as a “pointer to the data type file”.
The second statement opens the file named filename and assigns an identifier to the file type
pointer fp. This pointer which contains all the information about the file is subsequently used as a
communication link between the system and the program.
Modes Description
Whenever a file is opened using fopen function, a file pointer is returned. If the file cannot be
opened for some reason, then the function returns a null pointer.
This facility can be used to test whether a file has been opened or not.
if (fp == NULL)
printf (“File could not be opened.\n”);
13.3 Closing a File
Once all the operations on a file have been completed, the file is closed. This is done to clear the
buffers and flush all the information associated with the file. It also prevents any accidental misuse
of the file. In case there is a limit to the number of files that can be kept open simultaneously,
closing of unwanted files might help open the required files. When there is a need to use a file in a
different mode, the file has to be first closed and then reopened in a different mode.
.........
FILE *p1, *p2;
p1 = fopen (“INPUT”, “w”);
p2 = fopen (“OUTPUT”, “r”);
.........
fclose(p1);
fclose(p2);
This program opens two files and closes them after all operations on them are completed.
Once a file is closed, its file pointer can be reused for another file. All files are closed automatically
whenever a program terminates. However, closing a file as soon as all operations related to it have
been completed is a good programming habit.
#include<stdio.h>
int main(){
FILE *fp;
fp=fopen(“abc.txt",“r");
if(fp==NULL)
{
printf("Error, In opening file");
exit(1);
}
fclose(fp);
return 0;
}
fprintf&fscanf Functions
The functions fprintf and fscanf perform I/O operations that are identical to the familiar printf and
scanf functions.
The general syntax of fprintf is
fprintf (fp, “control string”, list);
wherefp is a file pointer associated with a file that has been opened for writing. The control string
contains output specifications for items in the list. The list may include variables, constants and
strings.
Example: fprintf (f1,”%s %d %f”, name, age, 7.5); here name is an array variable of type char and
age in an int variable.
The general syntax of fscanf is
fscanf (fp, “control string”, list);
This statement would cause the reading of the items in the list from the file specified by fp,
according to the specifications contained in the control string.
feof( ) Function
The feof function can be used to test for an end of file condition. It takes a file pointer as its only
argument and returns a non-zero integer value if all of the data from the specified file has been
read, and returns zero otherwise. If fp is a pointer to the file that has just been opened for reading,
then the statement
if (feof (fp))
printf (“End of data.\n”);
would display the message “End of data.” on reaching the end of file condition.
Syntax
fp=fopen(“filename", “r");
while(fscanf(fp, "%s", str)!=EOF)
{
printf("%s",str);
}
Example:
#include<stdio.h>
int main()
Writing in file
In C programming writing data block in file is possible.
Syntax
fp=fopen(“filename", “w");
#include<stdio.h>
int main()
{
char name[20]=“this is C";
FILE *fp;
fp=fopen("abc.txt","w");
fprintf(fp, "%s",name);
printf("Contents written");
fclose(fp);
return 0;
}
Append in file
In C Programming appends the content of file at the end of another is possible with append mode
of file.
Syntax
fp=fopen(“filename", "a");
Example:
#include<stdio.h>
int main()
{
Preprocessor
Preprocessor Syntax/Description
Syntax: #define
Macro This macro defines constant value and can be any of the basic data
types.
#include<stdio.h>
#include"header.h"
int main(){
printf("%d",fact(5));
return 0;
}
Macros
A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define
directive.
C Macros
Predefined
User-defined
: Predefine
#include<stdio.h>
int main(){
printf("File name : %s\n",__FILE__);
printf("File name : %s\n",__DATE__);
printf("File name : %s\n",__TIME__);
return 0;
}
: User define
#include<stdio.h>
#define pi 3.14
int main(){
int r=10,area;
area=pi*r*r;
Summary
• File is a collection of data or set of characters may be a text or program.
• There are two types of files used in the C language: sequential file and random access file.
• While creating a file, fopen() function is used which opens a stream for use and link it with
program and file. fopen() function has two string arguments which represent the name of
the file and the type of I/O to be performed. fclose() function closes a stream that was
opened by a call to fopen(). putc() is used to transfer one character into file. getc()
functions allows you to read data from a file.
• Similarly to read or write strings, fgets and fputs functions are used.
• The fgets() function reads a string from the file and copies it in a string variable lying in
memory.
• fputs() is used to write a string in a data file.
• getw() function is used to read an integer from a file.
• putw() is used to write as integer value in a file. fprintf() and fscanf() are similar to printf()
and scanf()
Keywords
Data Structure: Data structure of a file is defined as file in the library of standard I/O
function definitions.
NULL: A system-defined value (not 0) that indicates various exceptional conditions such
as end of a string, a pointer referencing nothing, etc.
Random access file: A file, which allows accessing its records without restriction on the
order of access. You can access 60th record without accessing the 59th record, and so on.
Macros
User Define
Predefine
Self Assessment
1. Text files are______
A. fp=fopen(“abc*txt","a");
B. fprintf(fp, "\n of programming");
C. printf("contents added in file");
D. fclose(fp);
8. Which one is used for append mode_______
A. r
B. a
C. rb
D. none of above
9. Header files are ______
A. #endif
B. #define
C. #undef
D. None of above
6. B 7. A 8. B 9. D 10. A
Review Questions
1. What do you mean by the “File Handling”? Explain the concept of file handling in C.
2. Explain the various type of files and their access mechanisms.
3. Write in detail about any five file-handling functions in C.
4. What do mean by random file access? How C implements the concept of random file access?
5. Write a program to read a file and display contents with its line numbers.
6. What is significance of Macros in programming?
7. Differentiate between user define and predefine Macros.
Further Readings
Books Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson Education,
Year of Publication, 2008
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall of India,
New Delhi
Byron Gottfried, “Programming with C”, Tata McGraw Hill Publishing Company Limited,
New Delhi
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett, 1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
YashvantKanetkar, Let us C
www.en.wikipedia.org
www.web-source.net
www.webopedia.com