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

BCA C Language 2020-21

Uploaded by

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

BCA C Language 2020-21

Uploaded by

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

Methodology of Programming and C Language

Name : ……………………………..
Roll No : ……………………………..

METHODOLOGY OF PROGRAMMING AND C LANGUAGE


UNIT I

Classification of Computer Languages


A Computer language includes various languages that are used to communicate with a Computer
machine. Some of the languages like programming language which is a set of codes or instructions used
for communicating the machine. Machine code is also considered as a computer language that can be
used for programming. Programming languages generally consist of instructions for a computer.
Programming languages can be used to create programs that implement specific algorithms.
We can classify all computer languages into three categories

1. Machine Language
2. Assembly language
3. High level Language

1. Machine Language
It is a computers natural language, which can be directly understood by the system. The
machine language program is written as strings of 1s and 0s. Every computer can understand
machine language without any translation. It is also called low level programming language. A
machine language instruction normally has two part format. The first part is the operation code
that tells the computer what function to perform, and the second part is operand that tells
where to find or store the data on which the computer has to perform the function.

OPCODE OPERAND
(Operation code) (address/location)

Example : a machine language instruction to print a number on a printer might be


101100111111010011101100

Advantages of Machine Language


1. They are translation free and can be directly executed by the computers
2. The programs written in this language are executed very speedily and efficiently
3. Efficient use of memory because it is possible to keep track of each bit of data

Disadvantages of machine language


1. Machine dependent. The internal design of every computer is different from every
other, machine language also differs from computer to computer. That is they are non
portable.
2. Difficult to program. It is very difficult to develop a program in machine language
because a programmer should memorize the dozens of operation code numbers or
refer to a reference card constantly.

1 BPS College Piramadom


Methodology of Programming and C Language

3. Error prone. The programs written in these languages are so prone to frequent errors
that they are very difficult to maintain.
4. Difficult to modify. It is difficult to correct or modify machine language programs.
Checking instructions to locate errors is very difficult and time consuming.
5. Speed of writing, Testing and Debugging is very slow in machine language.

2. Assembly Language

The computer manufacturers started providing English like words abbreviated as


mnemonics that are similar to binary instructions in machine language. A language that
allows use of letters and symbols instead of numbers for representing instructions and
storage locations is called Assembly Language or Symbolic Language. The program is in
alphanumeric symbols instead of 1s and 0s. The alphanumeric symbols are called
mnemonics in assembly language. The ADD, SUB, MUL, DIV, RLC and RAL are some
symbols called mnemonics. Assembly language programming, introduced in 1952, helped in
overcoming the limitations of machine language in the following manner

1. By using alphanumeric mnemonic codes instead of numeric codes for instructions.


2. By allowing use of alphanumeric names instead of numeric addresses for representing
storage locations
3. By providing pseudo instructions to instruct the system how we want to assemble the
program in computers memory.

Some examples of assembly language mnemonics and its operation codes are mentioned
below

Mnemonic Opcode Meaning


HLT 00 Halt, used at the end of program to stop
CLA 10 Clear and add into A register
ADD 14 Add the contents of A register
SUB 15 Subtract from the contents of A register
STA 30 Store A register

A sample assembly language program for adding two numbers and storing the result is given
below

START PROGRAM AT 0000


START DATA AT 1000
SET ASIDE AN ADDRESS FOR FRST
SET ASIDE AN ADDRESS FOR SCND
SET ASIDE AN ADDRESS FOR ANSR
CLA FRST
ADD SCND
STA ANSR
HLT

2 BPS College Piramadom


Methodology of Programming and C Language

Advantages of Assembly Language

1. Easier to understand and use. Due to the use of mnemonic codes instead of numeric
codes for instructions and symbolic names for data locations instead of numeric
address, assembly language programs are easy to understand and use.
2. Easier to locate and correct errors. The detection and correction of errors are easy in
this language due to the use of mnemonics.
3. Easy to modify. It is easier to locate, correct and modify instructions of an assembly
language program than a machine language program.
4. No worry about address. Programmers need not keep track of storage locations of data
and instructions while writing assembly language program.
5. Easily re-locatable. We can change a programs location by changing the pseudo
instructions.
6. Efficiency of machine language. The length of assembly language program is same as
the resulting machine language program. Hence the execution time for the program
would be the same.

Disadvantages of Assembly Language

1. Machine dependent. Since assembler translates each instruction of an assembly


language program into exactly one machine language instruction, assembly language
programs are machine dependent. That is assembly language differ from computer to
computer.
2. Knowledge of hardware required. Since assembly language is machine dependent, a
programmer must have good knowledge about his computer to write good assembly
language programs.
3. Machine level coding. One assembly language instruction corresponds to one machine
language instruction. Hence, writing assembly language program is also time consuming
and difficult.
4. Not Portable. Assembly language programs are not portable.

3. High Level Language


Procedure oriented languages are high level languages. These languages are employed for easy
and speedy development of a program. The disadvantages observed with assembly languages
are overcome by high level languages. The programmer does not need to remember the
architecture and registers of a CPU for developing a program. Examples of HLL are COBOL,
FORTRAN, BASIC, C and C++.

Advantages of High Level Languages


1. Fast program development
2. Testing and Debugging a program is easier than in the assembly language.
3. Portability of a program from one machine to another, that means they are machine
independent.
4. They do not require programmers to know anything about the internal structure of the
computer.

3 BPS College Piramadom


Methodology of Programming and C Language

5. They do not deal with machine level coding. Rather, they deal with high level coding,
enabling the programmers to write instructions using English words and mathematical
symbols and expressions.

Language Translators
A program is a set of instructions for performing a particular task. A program can be written in
assembly language as well as in high level language. This written program is called source
program. The source program is to be converted to the machine language, which is called an
object program. A translator is required for such translation.

Program translator translates source code of programming language into machine language
instruction code. Programming language translators are classified into
1. Assembler
2. Compiler
3. Interpreter

Assembler
Assembler is a software that translates Assembly Language program into Machine Language. It
is so called because in addition to translating it also “assembles” the machine language
program in main memory of the computer, and makes it ready for execution. The symbolic
language is translated to the machine code in the ratio of one is to one symbolic instructions to
one machine code instructions. Such type of languages are called low level languages.

Input Output
Mnemonic Language Assembler Machine Codes
(Assembly Language)

Compiler
A compiler is a translator program that translates high level language program into its
equivalent machine language program. The entire program will be read by the compiler first
and generates the object code. The compiler translates each high level language instructions
into a set of machine language instructions rather than a single machine language instruction.
Hence, there is a one to many correspondence between the instructions of source program
and the object program. Compilers also detect and indicate syntax errors. Compilers also have
the ability of linking subroutines of the program. Languages such as C, C++ and Java compilers
are employed.

Input Output
High-level language program Compiler Machine language
program

One to Many correspondence


Source program Object program

4 BPS College Piramadom


Methodology of Programming and C Language

Interpreter
This language translator converts a HLL program into machine language by converting and
executing it line by line. If there is any error in one line, it reports and execution of program is
terminated at the same time. We can resume the execution of the program only after
rectification of the error. Interpreter directly executes the program from its source code. Due
to this, every time the source code should be inputted to the interpreter.

The main advantage of interpreters over compilers is that an interpreter flag syntax error in a
program statement as soon as it interprets the statement. This allows the programmer to make
corrections during program development.
The disadvantage of the interpreter is that they are slower than compilers when running a
finished program.

Input Output
High-level language Interpreter (translates and executes Result of
program statement by statement) Execution

program

Linker
C language provides a very large library, which contains numerous functions. Linker is a
program that combines source code and codes from library. Linking is the process of bringing
together source program and library code.

In modular approach of software development, software consists of multiple source program


files. We can modify and compile each source program file independent of other source
program files to create a corresponding object program file. In this case we use a program
called linker to combine all object program files (modules) of the software and to convert them
into a final executable program which is sometimes called load module. Hence a linker is a
software that takes multiple object program files (modules) of some software and fits them
together to assemble them into the software’s final executable form.

Characteristics of a good programming language


1. Simplicity
A good programming language must be simple and easy to learn and use. It should provide a
clear, simple and unified set of concepts to a programmer that he/she can grasp easily.
2. Naturalness
A good language for an application area should be natural for programming applications of that
area. That is it should provide appropriate operators, data structures, control structures and a
natural syntax to facilitate programmers to code their problems easily and efficiently. ForTran
and COBOL are examples of languages possessing naturalness in scientific and business areas
respectively.

5 BPS College Piramadom


Methodology of Programming and C Language

3. Abstraction
Abstraction means the ability to define and then use complicated structures or operations in
ways that allows programmers to ignore many of the details. The degree of abstraction allowed
by a language directly affects its ease of programming. For example object oriented languages
support high degree of abstraction.
4. Efficiency
A program written in a good programming language enables a computer system to translate it
into machine code efficiently, execute it efficiently, and manage it with less memory space.
5. Structured programming support
A good programming language should have necessary features to allow programmers to write
their programs based on the concepts of structured programming. This property affects the
ease with which a programmer can write, test, and maintain his/her programs.
6. Compactness
In a good programming language, programmers should be able to express the intended
operations concisely without loosing readability. Programmers generally do not like a verbose
language because they need to write too much.
7. Extensibility
A good programming language should also allow extension through simple, natural and elegant
mechanism. Almost all languages provide subprogram definition mechanisms for this purpose.
8. Suitability to its environment
A good programming language must be suitable to its operating environment. For example a
language for real time applications must be interactive in nature. On the other hand a language
for data processing applications like payroll, stores accounting etc. may operate in batch mode.

Factors for selecting a language


1. Nature of the application
A programmer should select a language that is suitable for the application area at hand. For
example FORTRAN is suitable for scientific and engineering applications, while COBOL is
suitable for business applications.
2. Familiarity with the language
If he/she finds that multiple languages are suitable for the application area, he/ she should
select the one with which he/she and other programmers in his/her team are most familiar.
3. Ease of learning the language
If he/she finds that multiple languages are suitable for the application area, and the
programmers are not familiar with any of them, he/she should select the language that is easy
to learn and use.

6 BPS College Piramadom


Methodology of Programming and C Language

4. Availability of program development tools


Before selecting a language the programmer must also find out if the programming
environment of the language has good program development tools like compiler, interpreter,
debugger, linker etc. A language with good tools can drastically reduce the time and effort of
the team of programmers involved in coding an application.

5. Execution efficiency

If execution efficiency of an application is important, the programmers can use an assembly


language instead of high level language because assembly language program has a shorter
production run time, and takes less storage space than a high level language program.

6. Features of good programming language

The features of a good programming language discussed above often influence the selection
process.

Subprogram
A subprogram is a program written in a manner that a programmer can use it in other
programs whenever needed without rewriting. Other names used for it are subroutine,
subprocedure, and function.

The structure of a subprogram consists a header and body. The subprogram header which is
the first line of a subprogram, provides a name for the subprogram, and it may optionally
specify a list of parameters( also known as arguments). Other programs use the subprogram
name to refer to the subprogram when they want to use it. The parameters are specific
variable names, numeric values, or other data you want the subprogram to use when it
executes the instructions in its body. The subprogram body contains the instructions that
perform the intended task of the subprogram.

Purpose of program planning


To produce an effective computer program it is necessary to write every instruction in the
correct sequence. Hence to ensure that the instructions of a program are appropriate for the
problem at hand and are in the correct sequence, we must plan the program before writing it.
Planning program involves defining its logic. There are different ways of representing the
logical steps for finding a solution of a given problem. They are:-

1. Algorithm
2. Flowchart
3. Pseudo-code

Algorithm
Step by step method for solving a problem is called algorithm. The algorithm is a very
popular technique used to obtain a solution for a given problem. The algorithm is defined as
‘the finite set of steps, which provide a chain of actions for solving a definite nature of

7 BPS College Piramadom


Methodology of Programming and C Language

problem’. In order to qualify as an algorithm a sequence of instructions must possess the


following characteristics

1. Each instruction should be precise and unambiguous


2. Each instruction should be executed in a finite time
3. No instruction should repeat infinitely.
4. After executing the instructions the desired results are obtained.

Classification of Algorithms
The classification of algorithm is based on repetitive steps and on control transfer from one
statement to another.

Algorithms

Based on repetitive steps Based on control transfer

Direct indirect Deterministic Non- Random


Deterministic

i. Direct Algorithm : In this type of algorithm, the number of iterations is known in advance. For
example for displaying the numeric numbers from 1 to 10, the loop variable should be
initialized from 1 to 10.

ii. Indirect Algorithm: in this type of algorithm, repetitively steps are executed. Exactly how
many repetitions are to be made is unknown. Example- to find the first three palindrome
numbers.

iii. Deterministic: deterministic algorithm is based on either to follow a ‘yes’ path or ‘no’ path
based on the condition. Example- testing whether number is even or odd.

iv. Non-Deterministic: in this type of algorithm to reach to the solution, we have one of the
multiple paths. Example – to find a day of a week.

v. Random Algorithm: after executing few steps, the control of the program transfers to
another step randomly, which is known as a random algorithm. Example is a random search.

Flowcharts
A flowchart is the pictorial representation of an algorithm. Or a flowchart is a visual
representation of the sequence of steps for solving a problem. It uses different symbols to
denote different types of instructions. The symbols used in a flowchart are

8 BPS College Piramadom


Methodology of Programming and C Language

1. Terminal

It is used to denote the beginning (START) and ending (STOP) in the program logic. It is
the first and last symbol in a flowchart. In addition if the program logic has a pause we
also indicate it with a terminal symbol.

Start
Stop

2. Processing

A rectangle is used for processing steps. A processing symbol represents arithmetic and
data movement instructions. It used for data handling, and values are assigned to the
variables in this symbol. There are two flow lines connected with the process symbol.
One line is incoming and the other line goes out.

Z=X+Y X5
P=X*Y AX+Y

3. Decision

Diamond shaped (rhombus) boxes are used to indicate conditions tested. This box shows
branching of control upon conditions. While solving a problem one can take a single, two or
multiple alternatives depending upon the situation.

Single alternative decision: Here more than one flow line can be used depending upon the
condition. It is usually in the form of a ‘yes’ or ‘no’ question, with branching flow line
depending upon the answer.
Entry

Condition ?

True False

Execution of statement(s)

Exit

9 BPS College Piramadom


Methodology of Programming and C Language

Two alternative decisions: in two alternative decision on satisfying the condition statements
pertaining to 1 action will be executed, otherwise the other statements for action 2 will be
executed.
Entry

Condition ?

True False

Execution of Execution of
action 1 action 2

Exit

Multiple alternative decision: every decision block has two branches. In case the condition is
satisfied, execution of statements of appropriate blocks take place, otherwise next condition
will be verified. If condition 1 is satisfied then block 1 statements are executed. in the same
way other decision blocks are executed.

Entry

True
Condition 1 Execution of Block 1

False

True
Condition 2 Execution of Block 2

False

True
Condition 3 Execution of Block 3

False

Exit

4. Flow Lines

Flow lines with arrow heads indicate flow of operation, which is the sequence of
execution of instructions.

10 BPS College Piramadom


Methodology of Programming and C Language

5. Connector

The connector symbol is used to establish the connection, whenever it is impossible to directly
join two parts in a flowchart. The connector symbols are used to continue a flowchart on to the
next page.

6. Loop Symbol

It looks like hexagon. This symbol if used for implementation of for loops only.

Four flow lines are associated with this symbol. Two lines are used to indicate the sequence of
the program and remaining two are used to show the looping area.

Entry

For J = 1 to 10 by step 2

Body of the for loop

To continue for loop

Exit

7. Input / Output

Parallelograms are used to represent input and output operations. It is used to input
and output the data.

Read X, Y Print X, Y

11 BPS College Piramadom


Methodology of Programming and C Language

Delay symbol: Symbol of delay is just like ‘AND’ gate. It is used for adding delay to the process.

Manual input symbol: this is used for assigning the variable values through the keyboard,
whereas in data symbol the values are assigned directly without manual intervention.

Flowcharting Rules
1. First chart the main line of logic and then incorporate detail.
2. Maintain a consistent level of detail for a given flowchart.
3. Do not chart every detail, as the flowchart is only a graphic representation of steps in a
program.
4. Words in the flowchart symbols should be common statements and easy to understand.
5. Be consistent in using names and variables in the flowchart.
6. Go from left to right and top to bottom in constructing flowcharts.
7. Keep the flowchart as simple as possible.
8. If a new flowcharting page is needed, it is recommended that the flowchart be broken
at an input or output point. Moreover properly labeled connectors should be used to
link the portions of the flowchart on different pages.

Advantages of flowchart
1. Better communication
It is easier for a programmer to explain the logic of a program through a flowchart.

12 BPS College Piramadom


Methodology of Programming and C Language

2. Efficient Analysis
The program can be analyzed efficiently through the flowchart.
3. Proper program documentation
It means maintaining a complete record of the program and associated documents.
4. Effective coding
Once a flowchart is ready it is easy to write programs using it.
5. Effective Synthesis
If a problem is divided in to different modules and the solution for each module is
represented in flowchart separately, they can finally be placed together to visualize the
overall system design.
Limitations of Flowcharts
1. Flowcharts are very time consuming and laborious to draw with proper symbols and
spacing, especially for large complex algorithms
2. Any changes or modification in the logic of the algorithm usually require a completely
new flowchart
3. There are no standards determining the amount of detail that should be included in a
flowchart.

Pseudocode
Pseudocode is another program-planning tool used for planning program logic. “Pseudo”
means imitation or false and “Code” refers to the instructions written in a programming
language. Pseudocode, therefore, is an imitation of actual computer instructions. These pseudo
instructions are phrases written in a natural language (eg. English, French, German etc.) that a
computer cannot understand. Since the emphasis of pseudocode is on program design, it is
also known as Program Design Language (PDL).

During early days of program development, many programmers developed program logic for
large programs with mazes of branches (jumps from one portion of the program to another)
that altered the sequence of processing operations. Such programs are now referred to as
“spaghetti code” because their program flowcharts appeared more like a plate of spaghetti
than like logical analysis of programming problems. Understanding the logic of such programs
was very difficult for someone other than the developer. Also these programs are very difficult
to modify.

Researchers later proved that it is possible to express any program logic, no matter how
complex, by using only the following three logic (control) structures.

1. Sequence logic
2. Selection logic
3. Iteration (or looping) logic

Writing of programs by using these three basic control structures was termed structured
programming technique. They also helps in reducing program errors and the time spent in
program testing.

13 BPS College Piramadom


Methodology of Programming and C Language

Sequence Logic

Sequence logic performs instructions one after another in sequence. Thus for writing
pseudocode instructions for sequence logic, we write the instructions in the order (or
sequence) of their execution. Logic flow of pseudocode is from top to bottom.

Pseudocode example for sequence structure:-





Process 1
Process 2


Selection Logic
Selection logic, also known as decision logic, makes decisions. It selects a path out of two or
more paths in program logic. We depict selection as an IF … THEN … ELSE, or an IF…THEN, or a
CASE structure.
IF…THEN…ELSE structure means that if the condition is true, then do Process 1, else if the
condition is not true do Process 2.

Example: 


IF Condition
THEN Process 1
ELSE Process 2
ENDIF



If we do not want to choose between two processes, and simply want to decide whether to
execute a process or not, then we use IF…THEN structure. IF…THEN structure means that if the
condition is true, then do Process 1, otherwise skip over Process 1.

Example: 


IF Condition
THEN Process 1
ENDIF


CASE structure represents multiple way selection logic. It allows choosing from more than two
control paths in a program logic enabling selection of one of any number of statements or
statement groups.

14 BPS College Piramadom


Methodology of Programming and C Language

Example: 


CASE Type
Case Type 1: Process 1
Case Type 2: Process 2



Case Type n: Process n
ENDCASE


The above CASE statement indicates that if the value of Type is equal to Type-1, execute
Process 1, if it is equal to Type-2, execute Process 2, if it is equal to Type-3, execute Process 3,
and so on.
In case of IF…THEN and IF…THEN…ELSE decision structures, ENDIF indicates their end; and in
case of CASE structure, ENDCASE indicates its end.

Iteration (or Looping) Logic


Iteration logic produces loops in program logic whenever there is a need to execute one or
more instructions several times depending on some condition. It uses two structure called
DO…WHILE and REPEAT…UNTIL.

In DO…WHILE looping continues as long as the condition is true, and stops when the condition
is not true. Since program logic tests the condition for looping at the beginning of the loop, if
the condition is false when it first encounters the loop, it will not execute the statements in the
loop at all (not even once). On the other hand, in REPEAT…UNTIL, looping continues until the
condition becomes true. That is, program logic repeats execution of statements within the loop
as long as the condition is not true. Since it tests the condition for looping at the end of the
loop, it will execute the statements in the loop at least once.

In both DO…WHILE and REPEAT…UNTIL, the loop must contain a statement, which changes the
condition that controls the loop. if it does not, looping continue without end, becoming an
infinite loop.

Example: DO…WHILE iteration structure





DO WHILE Condition
Process 1



Process n
ENDDO


15 BPS College Piramadom


Methodology of Programming and C Language

Example: REPEAT…UNTIL iteration structure




REPEAT
Process 1



Process n
UNTIL Condition



Example: Pseudocode to find largest of two numbers
Get numbers a & b
Compare a & b
If a is large max=a
If b is large max=b
Larger number is max

Advantages of Pseudocode
1. As compared to a flowchart, converting a pseudocode to a programming language is
much easier.
2. As compared to a flowchart, it is easier to modify the pseudocode of program logic
when program modifications are necessary.
3. Writing of pseudo code involves less time and effort than drawing an equivalent
flowchart.

Limitations of Pseudocode
1. In case of a pseudocode, a graphic representation of program logic is not available.
2. There are no standard rules to follow in writing pseudocode.
3. As compared to flowchart, beginners often find it more difficult to write pseudocode of
program logic or to follow a program’s logic from its pseudocode.

Software Testing and Debugging


Program errors are known as bugs, and the process of detecting and correcting these errors is called
debugging. In general testing is the process of making sure that the program performs the intended
task, and debugging is the process of locating and correcting program errors.

Types of Program Errors


The following types of errors occur in a computer program.
1. Syntax Errors: Syntax errors occur when the rules or syntax of a programming language are not
followed. Such program errors typically involve incorrect punctuation, incorrect word sequence,
undefined terms, or misuse of terms. A compiler will not compile a program successfully until
its programmer corrects all its syntax errors.
2. Logic Errors: Logic errors occur when we make errors in planning the programs logic or while
converting the logic into program code. They cause the program to produce incorrect result or
behave unexpectedly. For example, if a C instruction should be a=b+c; but the programmer has

16 BPS College Piramadom


Methodology of Programming and C Language

coded it wrongly as a=b-c; it is an example of logic error because the program will not produce
correct result.
3. Run-time Errors: Errors which occur during program execution (run-time) after successful
compilation are called run-time errors. One of the most common run-time error is division by
zero
4. Semantic Errors: This error occurs when the statements written in the program are not
meaningful to the compiler. (Example: a + b = c;)

Testing a Program
Identifying logic errors in a program is the responsibility of the program development and test
team. The testing procedure involves running the program to process input test data, and
comparing the obtained results with the known correct results. If the results obtained for the test
data do not match with the known correct results, most likely the program contains one or more
logic errors.
In order to test the logic of a program completely, its test data must test each logical function of
the program. The test data selected for testing a program should include:
1. All types of possible valid data.
2. All types of possible invalid data (such as incorrect, incomplete, or inappropriate data). This
is necessary to test the error handling capabilities of the program (how the program reacts
in case of abnormal and unusual input data).

Debugging a Program for Syntax Errors


Syntax errors are much easier to locate and correct because almost all language processors detect
syntax errors automatically. When a language processor processes the source code of a program it
indicates on the source listing of the program each program statement having one or more syntax
errors, and gives hints regarding the nature of the error.

Debugging a program for Logic Errors


Unlike syntax errors a computer does not produce any error message for logic errors in a program.
Hence logic errors are more difficult to locate and correct. A programmer uses one or more of the
following methods to locate and correct the error.
1. Doing Hand Simulation of the Program Code. One approach is to take a printout of the
source code and go through its execution manually with the test data input that produced
incorrect results. This method is suitable only for simple and small programs.
2. Putting Print statements in the Program Code. In this approach the programmer puts
several print/write statements at appropriate locations in the program so that during
execution of the program the computer prints/displays values of different variables to
indicate intermediate results. By doing a proper analysis of the printed/displayed
intermediate results the programmer can detect the cause of the problem. After correcting
the detected errors, the programmer removes the print/write statements from the
program.
3. Using a Debugger. Debugger is a software tool that assists a programmer in following a
program’s execution step-by-step by allowing him/her to display intermediate calculation
results and field values whenever desired.
4. Using Memory Dump. Programmers uses this approach when the program “hangs up”
during a test run. In this approach a programmer prints/displays the contents of main

17 BPS College Piramadom


Methodology of Programming and C Language

memory and CPU registers at the time when program hangs up. This information called
memory dump or storage dump lists the data and information in their raw form that is their
binary or equivalent hexadecimal or octal form. By doing a proper analysis of this listing,
the programmer can detect the cause of the problem.

Testing of Software Containing Many Programs


A software system often consists of many modules(programs) linked together. Such software go
through unit and integrated testing process. Moreover commercial software are often subjected to
alpha and beta testing.

Unit and Integrated Testing


In unit testing the programmer who develops module of software tests the module independently
for its functionality. Unit test mainly verifies if a module meets its specifications.
On the other hand, when the team integrates the independently developed and tested modules
into a complete system, the team then tests the integrated system to check if all modules
coordinate properly with each other and the system as a whole behaves as per the specifications.
This is known as integrated testing.

Alpha and Beta Testing


After completion of integrated testing, the team releases the software for further testing to a very
selected user group within or outside the organization. This group tests the software by using it as
if they are its users. This release version of the software is known as alpha version and the test
conducted on it is called alpha testing.

If the software is to be sold commercially, instead of releasing it directly in the commercial market
after alpha testing, the team sometimes releases it for additional testing to a selected set of users
such as long time customers, partner agencies, and at times put for download and trial by anyone.
This release version of the software is known as beta version. The users report any bug found in the
software to the company developing the software. This type of testing is known as beta testing.
After beta testing the team fixes the reported bugs if any, and then the company releases the
software to the commercial market.

Difference between Testing and Debugging


Testing Debugging
Testing is the process of validating the correctness Debugging is the process of eliminating errors in a
of the program. Its objective is to demonstrate program.
that the program meets its design specifications.
Testing is complete when all desired verifications Debugging is complete when all known errors in
against specifications are complete. the program are fixed. Note that debugging
process ends temporarily because it restarts
whenever new errors are detected in the program.
Testing is a definable process that can and should Debugging, being a reactive process, cannot be
be planned and scheduled properly planned ahead of time. it is carried out whenever
errors are detected in a program.
Testing can begin in the early stages of software Debugging can begin only after the program is
development. Although the test runs of a program ready.
are carried out only after the program is coded,
but the decisions of what to test, how to test, and
with what kind of data to test can and should be
done before the coding is started.

18 BPS College Piramadom


Methodology of Programming and C Language

Steps in Program Definition


In order to solve a problem using computer, the problem must be analyzed and a solution
should be developed. Problem solving using computer contains the following stages.
1. Problem identification
2. Deriving the steps to obtain the solution (Algorithm, Flowchart)
3. Implementation of these steps in a computer language (Coding)
4. Translation of the program
5. Debugging
6. Execution and Testing
7. Documentation

1. Problem Identification
The given problem is clearly stated with all assumptions and specifying actions to be taken in the event
of any possibility. Details of inputs, processing and results required are clearly identified.
2. Algorithm and Flowcharts
Once the problem is identified, it is necessary to evolve a detailed and precise step-by-step method of
solution. For this algorithm and flowcharts are used.

Algorithm
Step by step method for solving a problem is called algorithm.

Flowchart
A flowchart is the pictorial representation of an algorithm.

3. Coding the Program


The instructions are expressed in a programming language. The set of instructions expressed in any
programming language is known as computer program and the process of writing such program is
called coding.

4. Translation
The program written in a High Level Language is known as source code. Once the source code is
prepared it should be translated using the concerned language processor. The compiler or interpreter is
used for this purpose. The translated machine language program is called the object code.

5. Debugging
Program errors are known as bugs and the process of detecting and correcting these errors is called
debugging. There are two types of errors – syntax error and logical error. Syntax errors result when the
rules or syntax of the programming language are not followed. A logical error is caused by a wrong or
incorrect program step.

6. Execution and testing


In this step the program is executed and tested with test data to determine whether the results are
correct.

7. Documentation
Documentation is the process of providing sufficient information in a program to understand its
working. A computer program is documented by writing comments in it.

19 BPS College Piramadom


Methodology of Programming and C Language

1. Write an Algorithm and draw a Flowchart to find the sum of Two numbers

Algorithm Flow Chart

Step 1: Start START

Step 2: Read A, B
Read A, B
Step 3: SUM = A + B

Step 4: Print SUM


SUM = A + B
Step 5: Stop

Print SUM

STOP

2. Write an Algorithm and draw a Flowchart to find the sum and average of 3 numbers

Algorithm Flow Chart

Step 1: Start START

Step 2: Read A, B, C
Read A, B, C
Step 3: SUM = A + B + C

Step 4: AVG = SUM / 3 SUM = A + B + C


AVG = SUM / 3
Step 5: Print SUM, AVG

Step 6: Stop
Print SUM,
AVG

STOP

3. Write an Algorithm and draw a Flowchart to find the largest among two numbers
Algorithm Flow Chart
Step 1: Start
START
Step 2: Read A, B
Step 3: IF A > B then go to step 4 else go to step 5
Step 4: Print A Read A, B
Step 5: Print B
Step 6: Stop
Yes No
IF A> B

Print A Print B

STOP

20 BPS College Piramadom


Methodology of Programming and C Language

4. Write an algorithm and draw a flowchart to find the largest among 3 numbers.

Algorithm
Step 1: Start
Step 2: Read A, B, C
Step 3: IF A > B then go to step 4 else go to step 5
Step 4: IF A > C then go to step 6 else go to step 7
Step 5: IF B > C then go to step 8 else go to step 7
Step 6: Display A
Step 7: Display C
Step 8: Display B
Step 9: Stop
Flowchart

START

READ A, B, C

No IF A > B Yes

No Yes No Yes
IF B > C IF A > C

Display C Display B Display C Display A

STOP

5. Write an algorithm and draw a flowchart to print the odd numbers from 1 to 25

Algorithm

Step 1: Start
Step 2: Let N = 1
Step 3: Print N
Step 4: N = N + 2
Step 5: Check IF N < = 25 Then goto step 3 Else goto step 6
Step 6: Stop

21 BPS College Piramadom


Methodology of Programming and C Language

Flowchart

START

N=1

PRINT N

N=N+2

Yes
IF N<= 25

No

STOP

6. Write an algorithm and draw a flowchart to find the sum and average of any 10 numbers

Algorithm

Step 1 : Start
Step 2 : SUM=0, COUNT=1 Flowchart
Step 3 : Read A
Step 4 : SUM = SUM + A START
Step 5 : COUNT = COUNT + 1
Step 6 : If COUNT <= 10 Goto Step 3 Else Goto Step 7
Step 7 : AVG = SUM / 10 S = 0, C = 1
Step 8 : Print SUM, AVG
STEP 9 : Stop Read A

S=S+A
C=C+1

IF c<= 10

AVG = S / 10

22 BPS College Piramadom


Methodology of Programming and C Language

Print S,
AVG

STOP

7. Write an algorithm and draw a flowchart to find the smallest among 10 numbers

Algorithm Flowchart
Step 1 : Start
Step 2 : C = 1
Step 3 : Read N Start
Step 4 : SMALL = N
Step 5 : C = C + 1 C=1
Step 6 : Read N
Step 7 :If N < SMALL Then Goto Step 8 Else Goto Step 9
Read N
Step 8 :SMALL = N
Step 9 : C = C + 1
Step 10: If C< =10 Then Goto Step 6 Else Goto Step 11 SMALL= N
Step 11: Print SMALL
Step 12: Stop C = C+1

Read N

If
N<SMALL No
L
Yes

SMALL = N

C=C+1

Yes
If C <= 10

No

Print
SMALL

Stop

23 BPS College Piramadom


Methodology of Programming and C Language

8. Write an algorithm and draw a flowchart to find the given number is even or odd

Algorithm
START
Step 1: Start
Step 2: Read A
Step 3: IF A% 2 = 0 then go to step 4 else go to step 5 Read A
Step 4: Print Even
Step 5: Print Odd
Step 6: Stop Yes IF No
A%2=0

Print Even Print Odd

STOP

9. Write an algorithm and draw a flowchart to find the sum of first N natural numbers

Step 1 : Start
Step 2 : SUM=0, C=1 Flowchart
Step 3 : Read N
Step 4 : SUM = SUM + C START
Step 5 : C = C+ 1
Step 6 : If C <= N Goto Step 4 Else Goto Step 7
Step 7 : Print SUM SUM = 0, C = 1
STEP 8 : Stop
Read N

SUM = SUM+ C
C=C+1

Yes
IF C<= N

NO
Print SUM

STOP

24 BPS College Piramadom


Methodology of Programming and C Language

10. Write an algorithm and draw a flowchart to find the factorial of a number

Step 1 : Start
Step 2 : FACT=1, C=1 Flowchart
Step 3 : Read N
Step 4 : FACT = FACT * C
START
Step 5 : C = C+ 1
Step 6 : If C <= N Goto Step 4 Else Goto Step 7
Step 7 : Print FACT FACT = 1
STEP 8 : Stop C=1

Read N

FACT = FACT * C
C=C+1

IF C<= N Yes

NO

Print FACT

STOP

11. Write an algorithm and draw a flowchart to swap two numbers without using a third variable.

Step 1: Start
Step 2: Declare two variables a & b
Step 3: Addition of a & b and place result in a.
START
Step 4: Subtraction of a & b and place result in b.
Step 5: Subtraction of a & b and place result in a.
Step 6: Print values of a & b. Declare variables &
Step 7: End. assign values to a & b

a=a+b
b=a-b
a=a-b

Print values
of a & b

END

25 BPS College Piramadom


Methodology of Programming and C Language

UNIT 2

C LANGUAGE
C language has been developed by Dennis Ritchie at Bell Laboratories, USA, in 1972. In 1967,
Martin Richards developed a language called BCPL ( Basic Combined Programming Language)
and in 1970, Ken Thompson created a language using many features of BPCL and called it B.
Several important concepts of C are drawn from BCPL and B language.

C runs under a number of operating systems including MS DOS and UNIX. The UNIX operating
system was coded almost entirely in C.

In 1978, Brian Kernighan and Dennis Ritchie published the first edition of “The C Programming
Language”. This book, known to C programmers as "K&R", served for many years as an
informal specification of the language. The version of C that it describes is commonly referred
to as K&R C.

C is a general purpose structured programming language. The c is very popular because of its
portability. That is a program written in c can be transferred easily from one computer to
another with minimal changes or none at all. Programs written in c are fast and efficient.

In 1983, the American National Standards Institute (ANSI) appointed a committee to define a
standard for C. In 1989, the standard was ratified and this version of the language is often
referred to as ANSI C, Standard C, or sometimes C89. It was then approved by the International
Standards organization (ISO) in 1990.

There is no single compiler* for c. Many different organizations have written and implemented
c compilers. (Eg:- Turbo c, Borland c)

(* A compiler is a language processor which converts High Level Language programs into
Machine Language Program.)

Features of c language
1. It was developed as a compiled language (uses compiler as its translator). So that c
language programs could be easily ported to other computers equipped with a c
compiler.
2. It supports pointers with pointer operations. This feature allows the programmers to
directly access the memory addresses where variables are stored, and to perform bit
level manipulation of data stored in memory or processor registers.
3. It supports user defined data types for greater flexibility in programming.
4. It supports modular and structured programming concepts. Modularity means breaking
up of complex programs into a series of functions or modules.
5. It is a small and concise language providing only the bare essential features, so that a c
language program can be translated by a language translator into an efficient machine
language code.

26 BPS College Piramadom


Methodology of Programming and C Language

6. A large number of compound operators, such as +=, -=, *=, ++, etc. are used to provide
easier and efficient programming.
7. C language provides more accuracy in calculations.
8. C programs are fast and are efficient in memory utilization.

Advantages of ‘C’ language


1. It contains a powerful data definition. The data types supported are characters,
alphanumeric, integers, long integer, floats and double. It also supports string
manipulation in the form of character array.
2. C supports powerful set of operators.
3. It also supports powerful graphics programming and directly operates with hardware.
Execution of program is faster.
4. An assembly code is also inserted into c programs.
5. C programs are highly portable on any type of OS (Operating System) platforms.
6. System programs such as compilers, operating systems can be developed in C. For
example the popular operating system UNIX is developed in C.
7. The C language has 32 keywords and about 145 library functions and near about 30
header files.
8. C works closely with machines and matches assembly language in many ways.
9. C language has its ability to extend itself. A c program is basically a collection of
functions that are supported by the c library. We can add our own functions to the
library with the availability of the large number of functions.

C Programming (Coding) Style

C is a free form language. That is the c compiler does not care, where on the line we begin
typing. C program statements are written in lower case letters. Upper case letters are used
only for symbolic constants. Braces ({ }), group program statements together and mark the
beginning and the end of functions. A proper indentation of braces and statements would
make a program easier to read and debug.
Since c is a free form language we can group statements together on one line.
The program
main()
{
printf(“hello”);
}

May be written in one line like


main() ,printf(“hello”);-

However, this style makes the program more difficult to understand and should not be used.
Properly inserted comments help to understand the program logic.

27 BPS College Piramadom


Methodology of Programming and C Language

Executing a ‘c’ Program

Executing a program written in c involves the following steps.

1. Creation of a Program: The program should be written in C editor. The default


extension is ‘.c’. The c program includes preprocessor directives.
2. Execution of Preprocessor Program: after writing a program, the programmer has to
compile the program with the command (Alt + C). the preprocessor program executes
automatically before the compilation of the program.
3. Compilation and Linking of a program: if there is no error in the program, compilation
proceeds and translated program is stored in another file with the same file name with
extension ‘.obj’. this object file is stored on the secondary storage device.
Linking puts together all other program files and functions that are required by the
program. For example, if the programmer is using pow( ) function, then the object code
of this function should be brought from math.h library of the system and linked to
main() program.
4. Executing the program: After the compilation the executable object code will be loaded
in the computers main memory and the program is executed. the loader performs this
function. All the above steps of c program can be performed using menu options of the
editor.

28 BPS College Piramadom


Methodology of Programming and C Language

The C Character Set

The character set of c is categorized as follows

i. Letters A to Z, a to z (English alphabets)


ii. Digits 0 to 9
iii. Special Characters

iv. White spaces and Escape Sequences

29 BPS College Piramadom


Methodology of Programming and C Language

Delimiters
The language pattern of c uses special kind of symbols, which are called delimiters. A delimiter
is a unique character or series of characters that indicates the beginning or end of a specific
statement, string or function body set.

C Tokens
In a c program/ statement the smallest individual units are known as c tokens. C has six types
of tokens and they are identifiers, keywords, constants, strings, special symbols and operators.
C programs are written using these tokens and the syntax of the language.

C Tokens

Keywords Constants Strings Operators


float -11.2 “abc” + - *
while 502

Identifiers Special Symbols

main
[]
amount {}

Keywords (Reserved words)


Keywords are reserved words by the compiler. The words that convey a special meaning to the
language compiler are called keywords. Keywords serve as basic building blocks for program
statements. All keyword must be written in lower case. The C Keywords are :-

30 BPS College Piramadom


Methodology of Programming and C Language

Identifiers

They are names given to various program elements such as variables, functions, structure,
union, constant, arrays etc. These are user defined names and consist of a sequence of letters
and digits, with a letter as a first character.

Identifier naming rules

1. An identifier can be composed only of upper and lower case letters, the underscore and
digits.
2. There can be no embedded blanks.
3. An identifier cannot start with a digit or the first character must be a letter.
4. Upper and lower case letters are different.
5. Key words cannot be used as an identifier.
6. The length of an identifier varies from one compiler to another. Some versions permits only a
maximum of 8 characters while some other version permits a maximum of 31 characters (ANSI).

Examples for valid identifiers are :- SName , _a , n1


Examples for invalid identifiers are :- Length of Line, S+um, year’s, 3abc

Constants
The value/data that cannot be changed during the execution of the program is called constant.
Constants are classified into the following groups as given in the figure

31 BPS College Piramadom


Methodology of Programming and C Language

Numeric Constants
1. Integer constant

Any numeric value without fractional part is called integer constant. An integer constant must
have at least one digit. It may contain either + or – sign to indicate the positive or negative
nature of the number. Integer constant could be either positive or negative or may be zero.
The decimal point, fractional part, or symbols are not permitted. Neither blank spaces nor
commas are permitted.

There are 3 types of integer constants namely decimal, octal and hexadecimal.
i. Decimal integer constant (Base 10) – A sequence of digits with no zeros in the
beginning. It consists of any combination of digits taken from the set 0 to 9
Example:- 124, 78, -20
ii. Octal integer constant (Base 8)
It consists of any combination of digits from the set 0 to 7 with a leading zero.
Example:- 0123, 072
iii. Hexadecimal integer constant (Base 16)
A hexadecimal integer constant must begin with 0X or 0x. It can be followed by any
combination of characters taken from the set of 0 – 9 and A – F. the letters A
through F represent the numbers 10 through 15.
Example:- 0X79, 0xAF
2. Real constant or Floating point constant

Numbers with decimal part is called floating point constants or real constants.

Example:- 5.12, -7.2


The following concepts are essential to follow real numbers
1. The decimal point is permitted
2. Neither blank space nor comma is permitted
3. Real numbers could be either positive or negative
4. The number without sign is assumed as positive

A real number may also be expressed in exponential notation. For example the value 312.78
may be written as 3.1278e2 in exponential notation. e2 means multiply by 102 .

The general form is:-


mantissa e exponent
The mantissa is either a real number expressed in decimal notation or an integer. The exponent
is an integer number with an optional + or – sign. The letter e can be written either in lower
case or upper case.

Example:- 12e-2(ie. 12*10-2), -1.23E-1

3. Character constant
A character constant is a single character enclosed in single quotes.
Example:- ‘A’ , ’2’, ‘+’

32 BPS College Piramadom


Methodology of Programming and C Language

Character constants have integer values that are determined by the computers particular
character set that is the ASCII character set (American Standard Code for Information
Interchange).
Example: Constant ASCII value
‘A’ 65
‘3’ 51
‘a’ 97
C supports certain non-graphical character, which are those that cannot be typed directly from
the keyboard, and they can be represented by using escape sequences (Backslash character
constants) which consists of a backslash ( \ ) followed by one or more characters.

Escape Sequence Meaning


‘\b’ Backspace
‘\t’ Tab
‘\n’ New line
‘\f’ Form feed
‘\r’ Carriage return
‘ \’ ’ Single quote
‘\” ‘ Double quote
‘\\’ Back slash
‘\v’ Vertical tab
‘\0’ Null
‘\?’ Question mark
‘\a’ audible alert (bell)

4. String Constant

A string constant is a group of characters enclosed within double quotation mark. The compiler
automatically inserts a null character (\0) at the end of the string constant, which is called the
string terminator.
E.g.:- “MG University”, “2017”, “A”
A character constant (eg:- ‘A’) is not equivalent to a single string constant (eg:- “A”). A single
character string constant does not have an equivalent integer value while a character constant
has an integer value.

Data Types in C
Data types are the means to identify the type of data and associated operations of handling it.
ANSI C supports 3 classes of data types:
1. Primary / Fundamental / Basic Data types
2. Derived data types
3. User defined data types

33 BPS College Piramadom


Methodology of Programming and C Language

Basic / Fundamental data types


All C compilers supports 4 Basic data types namely integer (int), character (char), floating point
(float) and double precision floating point (double).

Integer Types
int, short and long

Integers are whole numbers with a range of values supported by a particular machine. The size
of an integer depends on the computer. If we use a 16 bit word length, the size of the integer
value is limited to the range -32768 to +32767 (that is, -215 to +215 - 1). A signed integer uses
one bit for sign and 15 bit for the magnitude of the number. Similarly a 32 bit word length can
store an integer ranging from -2,147,483,648 to 2,147,483,647.

In order to provide some control over range of numbers and storage space c has 3 classes of
integer storage, namely short int, int and long int, in both signed and unsigned forms. The
short int represents small integer values and requires half the amount of storage as a regular
int number uses. We declare long and unsigned integers to increase the range of values. The
use of qualifier signed on integers is optional because the default declaration assumes a signed
number.

Integer Representation
The signed integer has signs positive or negative. The sign are represented in the computer in the
binary format as 1 for – (minus) and 0 for + (plus) or vice versa. The sign bit is always coded as
leftmost bit.
For example, positive signed numbers are represented in the form called signed magnitude form. In
this form the sign is represented by a binary 0 and the remaining magnitude by equivalent binary
form.
+7 is represented as 0 0000111

34 BPS College Piramadom


Methodology of Programming and C Language

The signed negative numbers can be represented in any one of the following form
a. Signed – magnitude form
b. Signed – 1’s complement form
c. Signed – 2’s complement form

In the signed magnitude form the sign of the number is represented as 1 and the magnitude by
equivalent binary form
Example: -7 is represented as 1 000111

In the signed 1’s complement form, the sign of the integer is indicated by 1 and the magnitude in
1’s complement form
Example: -7 is represented as 1 1111000

In the signed 2’s complement form the sign is indicated by 1 and the magnitude by 2’s complement
form
Example: -7 is represented as 1 1111001

Floating Point Types

Floating point (real) numbers are stored in 32 bits (4 bytes) on all 16 bit and 32 bit machines,
with 6 digits of precision. Floating point numbers are defined in c by the keyword float. When
the accuracy provided by a float number is not sufficient, the type double can be used to
define the number. A double data type number uses 64 bits (8 bytes) giving a precision of 14
digits. To extend the precision further we may use long double which uses 80 bits (10 bytes).

Floating Point Representation


The real number is integer part as well as fractional part. The real number is also called floating
point number. These numbers are either positive or negative. The number 454.45 can either be
written as 4.5445 x 102 or 0.45445 x 103. This representation is called scientific representation.
Using scientific representation a number can be expressed as combination of mantissa and
exponent. That is a number n can be represented as n= mre where m is the mantissa and r is
the radix of the number system and e is the exponent.

Character Types

A single character can be defined as a character (char) type data. Characters are usually stored
in 8 bits (1 byte). The qualifier signed or unsigned may be explicitly applied to char. While
unsigned char have value between 0 and 255, signed char have values from -128 to 127. The
format specifier for char data type is %c. But when printed using %d specifier prints ASCII
character.

Type Modifiers
The keywords signed, unsigned, short and long are type modifiers. A type modifier changes the
meaning of basic data type and produces a new data type.

35 BPS College Piramadom


Methodology of Programming and C Language

Size and Range of Data Types on a 16 Bit Machine


Size Format
Data Type Keyword Range
(bytes) Specifier
Character char or signed char 1 -128 to 127 %c
Unsigned character unsigned char 1 0 to 255 %c
Integer int or signed int 2 -32,768 to 32,767 %d or %i
Unsigned integer unsigned int 2 0 to 65535 %u
short int or signed short
Signed short integer 2 -32,768 to 32,767 %d or %i
int or short
Unsigned short
unsigned short int 2 0 to 65535 %u
integer
long int or signed long
Signed long integer 4 -2,147,483,648 to 2,147,483,647 %ld
int or long
Unsigned long
unsigned long int 4 0 to 4,294,967,295 %lu
integer
Floating point float 4 3.4E-38 to 3.4E+38 %f or %g
Double precision
double 8 1.7E-308 to 1.7E+308 %lf
floating point
Extended double
precision floating long double 10 3.4E-4932 to 1.1E+4932 %lf
point

Void Types
The void type has no values. This is usually used to specify the type of functions. The type of a
function is said to be void when it does not return any value to the calling function.

VARIABLES
Variables are the names given to storage locations. A variable may take different values at
different times during execution. A variable can be defined in any data type. The size and
nature of data stored in a variable depends of the data type it is declared.

Declaring Variables
The declaration of variables should be done in declaration part of the program. The variable must
be declared before they are used in program. Declaration ensures the following two things:
1) compiler obtains the variable name and 2) it tells the compiler data type of the variable being
declared and helps in allocating the memory.

The variables are associated with two values – l-value which is the address (location value) of the
memory location and r-value which is the content of the location.

The syntax of declaring a variable is :-


data-type variable name;

Example:- int num;


float p,q,r;
char m;
int a=25;
1001 1002

2 5
Here lvalue (address) is 1001 and content (r-value) is 25
a

36 BPS College Piramadom


Methodology of Programming and C Language

Rules for Defining Variables


i. A variable must begin with a character or an underscore without space
ii. The length of the variable varies from compiler to compiler. Most of the compilers
support eight characters excluding extension. However ANSI standard recognizes
the maximum length of a variable up to 31 characters.
iii. The variable should not be a c keyword.
iv. The variable names may be combination of upper case and lowercase characters.
For example suM and sum are not same.
v. The variable name should not start with a digit.
vi. Blanks and commas are not permitted within a variable name.

Initializing Variables
Variables declared can be assigned or initialized using assignment operator ‘=’. The declaration
and initialization can also be done in the same line.
Syntax:
Variable_Name = Constant;
Or
Data_Type Variable_Name = constant;

Example:
x=5; where x is an integer variable
int y = 4;

Dynamic Initialization
The initialization of variable at run time is called dynamic initialization. Dynamic refers to the
process during execution.
Example:
void main()
{
int r=2;
float area=3.14*r*r;
clrscr();
printf(“Area=%g”,area);
}
Output
Area=12.56
In the above example area is calculated and assigned to variable area. The expression is solved
at run time and assigned to area at runtime. Hence it is called dynamic initialization.

TYPE CONVERSION
1. Implicit Type conversion (type promotion)
C permits mixing of constants and variables of different types in an expression. In C
automatically ‘lower’ data type is promoted to ‘upper’ data type. This automatic conversion
is known as implicit conversion. For example, data type char or short is converted to int.

37 BPS College Piramadom


Methodology of Programming and C Language

In case an expression contains one of the operands as unsigned operands and another non-
unsigned, the later operand is converted to unsigned.

Similarly, in case an expression contains one of the operands as float operands another
non-float, the later operand is converted to float.

Similarly, in case an expression contains one of the operands as double operands another
non-double, the later operand is converted to double.

Example :

short a=5;
long int b=123456;
float c=234.56;
double d=234567.78695;
clrscr();
printf(“%lf”,((a+b)*c)/d);

in the above example the expression ((a+b)*c)/d) gives the result as double float.

Explicit Type conversion (type casting)


Here the user is responsible for the conversion to a specific type
Consider an example:-
int a=5, b=2;
float c;
c=a/b;

here c will be 2, which is not accurate. This is because a/b is an integer expression and
returns 2 only. This problem can be overridden by the following statement.
c = (float)a/b;
the type of a is changed into float explicitly by the user and hence b will automatically
change into the higher type i.e. from int to float. This modification makes the value of c to
2.5, which is accurate.
WRAPPING AROUND
When the value of variable goes beyond its limit, the compiler would not flag any error
message. It just wraps around the value of the variable.
Example:
unsigned u=65537;
printf(“u=%u”,u);

Here the output will be u=1

The range of unsigned integer is 0 to 65535. In the above example unsigned integer u=65537.
After reaching the last range 65535, the compiler starts from beginning. The value 65536 refers
to 0 and 65537 refers to 1.

38 BPS College Piramadom


Methodology of Programming and C Language

Constant Variable

The keyword const is used to declare a variable constant.


Example: const float pi = 3.14;
Here variable pi will be allocated 4 bytes of memory and the value 3.14 will be stored in it. This
value cannot be changed during program execution.

Volatile Variable
The volatile variables are those variables that can be changed at any time by other external
program or the same program. The syntax is
volatile int d;

Overflow of Data
Problem of data overflow occurs when the value of a variable is either too big or too small for
the data type to hold. Floating point values are rounded off to the number of significant digits
allowed, an overflow normally results in the largest possible real value, whereas an under flow
results in zero.

OPERATORS
Operators are pre-defined symbols that can carry out operations. The participants of an
operation are called operands. Operators are classified into unary operators (contains one
operand), binary operators (contains two operands) and ternary operators (contains three
operands).

Arithmetic operators
The basic arithmetic operator in ‘c’ are

Operator Meaning

+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Remainder of division)

Modulus Operator (%)


Modulus / Mod / Modular division operator gives the remainder value during arithmetic
division. This operator can only be applied over integer operands.

Example: let x=11 and y=3 then


x%y will be 2

Example: suppose A = 20 and B = 10


The following table shows the result of various arithmetic operations.
A+B A–B A*B A/B A%B
30 10 200 2 0

39 BPS College Piramadom


Methodology of Programming and C Language

Division of one integer quantity by another is referred to an integer division. This operation
always results in a truncated quotient.
That is if A=10 and B=3 then A/B will be 3 (decimal part truncated).

A real operand may assign values either in decimal or exponential notation. If x and y are float
data types and x=5.0 and y=2.0 then x/y will be 2.5

Suppose C1 and C2 are character type variable and C1=’A’ and C2= ‘B’ then C1+C2 will be 65 +
66 that is 131 because the corresponding ASCII values of A and B are added.

Unary operators
Unary operators operate on a single operand.
Unary +

Positive sign operator (+) indicates that the number is positive.

Unary –

Negative sign operator indicates that a number is negative.


Eg:- -5

Increment (++) and Decrement operators (- -)


C provides two operators for incrementing and decrementing variables. The increment
operator ++ adds 1 to its operand, while the decrement operator - - subtracts 1.

The ++ and - - may be used either as prefix operators (before the variable ie. ++n) or postfix
(after the variable ie. n++). In both cases the effect is to increment n. but the expression ++n
increments n before its value is used, while n++ increments n after its value has been used.

Example:- if n=5 then


x = n++;
sets x to 5, but
x = ++n;
sets x to 6.
In both cases n becomes 6. The increment and decrement operators can only be applied to
variables.

Relational operators
Relational operators are used for comparing the values of variables. These are binary
operators. The result of relational operations is either True or False. True is represented as 1
and false is represented as 0. There are 6 relational operators in c and they are
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to

40 BPS College Piramadom


Methodology of Programming and C Language

Example:-
M n m<n m>n m <= n m >= n m != n m == n
7 2 0 1 0 1 1 0
4 4 0 0 1 1 0 1
3 5 1 0 1 0 1 0

Logical operators

Logical operators are used with expressions. The result of logical expression will be either 0 or
1. The logical operators used in c are && (and), || (or), ! (not).

When two or more conditions are connected with the logical && operation, the result is true
only if all the conditions are true, otherwise the result is false.
(Example: 5>3 && 5<10)

When two or more conditions are connected with logical || operator, the result is true, when
either of the condition is true or both are true otherwise the result is false.
(Example: 8>5 || 8<2)

Example:-
A B A&&B A||B
F F F F
F T F T
T F F T
T T T T *Where A and B are conditional expressions.

The not (!) operator has the effect of reversing the truth value of the expression to its
immediate right.
(Example: 8!=8)
Example:-
A !A
F T
T F

Assignment operator
This is a binary operator that assigns the right side value to a left side variable. The symbol = is
used as the assignment operator. The general form of assignment statement is

Variable = expression;

Where expression represents a constant, a variable or an expression.

Example: a = 3; Here 3 is assigned to a


sum = x * y;

c also contains the following arithmetic assignment operators.

+= , -= , *= , /= , %=, <<= , >>=, &=, ^=, |=

41 BPS College Piramadom


Methodology of Programming and C Language

The assignment expression


exp1 += exp2; is equivalent to exp1 = exp1 + exp2;

Example: a -= 5 means a = a – 5;
n /= 10 means n = n / 10;

The sizeof() operator


The sizeof operator returns the size in bytes of its operand.

Syntax
i. sizeof (data type)
ii. sizeof (variable name)

Example:-
float s;
sizeof(s);  gives the value 4
sizeof(int)  gives the value 2

Conditional operator ( ? : )
The conditional operator returns a value depending on a condition. It is a ternary operator,
which requires 3 operands to operate upon.

Syntax:
exp1 ? exp2 : exp3;
where exp1, exp2 and exp3 are expressions
exp1 is evaluated first. If it is true, then the expression exp2 is evaluated and becomes the
value of the expression. If exp1 is false, exp3 is evaluated and its value becomes the value of
the expression.
Example:- result = mark > 50 ? ‘P’ : ‘F’;
if value of mark is greater than 50 then the value ‘P’ is assigned to result else the value ‘F’ is
assigned to result.

Bitwise Operators
Bitwise operators are used to perform operations at binary digit level. Following are the bitwise
operators used in c language

<<
>>
~
&
|
^

42 BPS College Piramadom


Methodology of Programming and C Language

1. << left shift bit operator

Let a = 13; its binary equivalent is 00001101


Consider a<<2;
This shifts 2 bits to the left. That is 2 zeros are inserted at the right to shift two bits at the left to
move out. The result will be 00110100. (ie. 52)

2. >>right shift bit operator

Let a = 13; its binary equivalent is 00001101


Consider a>>2;
This shifts 2 bits to the right. That is 2 zeros are inserted at the left to shift two bits at the right
to move out. The result will be 00000011. (ie. 3)

3. ~ bitwise inversion (one’s complement)

Let a = 13; its binary equivalent is 00001101


Consider ~a;
Which converts all the 0’s to 1’s and all the 1’s to 0’s.
The result will be 11110010.

4. & bitwise logical and

Let a = 13; its binary equivalent is 00001101


b = 6; its binary equivalent is 00000110
a & b produces the result 00000100

5. | bitwise logical or

Let a = 13; its binary equivalent is 00001101


b = 6; its binary equivalent is 00000110
a | b produces the result 00001111

6. ^ bitwise exclusive or

Let a = 13; its binary equivalent is 00001101


b = 6; its binary equivalent is 00000110
a ^ b produces the result 00001011

The Comma operator (,)


The comma operator can be used to link the related expressions together. A comma linked lists of
expressions are evaluated left to right and the value of the right most expression is the value of the
combined expression.
Example:- value = (x = 10, y = 5, x+y);
First 10 is assigned to x, then 5 is assigned to y and finally 15 is assigned to value.

Special operators
C supports some special operators such as pointer operators and member selection operators.
Pointer operators
& returns the address of a variable
* indirection operator is a pointer to a variable
Member selection operators
. and -> are used to select members of a structure

43 BPS College Piramadom


Methodology of Programming and C Language

Operator precedence
The order or priority in which the operations are performed in an expression is called the precedence of
operations. Some of the operators of the same level of precedence are evaluated from left to right or
right to left. This is referred to associativity. The following table shows the list of operators in
descending order of precedence.

44 BPS College Piramadom


Methodology of Programming and C Language

The operators at the higher level of precedence are evaluated first.

Arithmetic Expressions
An arithmetic expression is a combination of variables, constants and operators arranged as
per the syntax of the language.
Example:- a * b – c

3.14* r * r
Evaluation of expressions
Expressions are evaluated using an assignment statement of the form
variable = expression;
When the statement is encountered, the expression is evaluated first and the result then
replaces the previous value of the variable on the left hand side
Example:- x=a*b+c

Structure of a C program

The structure of a c program is given below

Documentation Section
Link Section
Definition Section
Global Declaration Section
main()
{

Declaration Part;
Executable Part;

Sub Program Section


Function 1
Function 2 (User defined Functions)
--
--
Function n

Documentation section

The documentation section consists of a set of comment lines giving the name of the program,
the author and other details, which the programmer would like to use later.

45 BPS College Piramadom


Methodology of Programming and C Language

Link section

The link section provides instructions to the compiler to link functions from the system library.
Example- #include<stdio.h>

Definition section

The definition section defines all symbolic constants.


Example - #define pi 3.14;

Global declaration section

There are some variables that are used in more than one function. Such variables are called
global variables and are declared in the global declaration section that is outside of all the
functions. This section also declares all the user defined functions.

main() function

This is a function from which the operating system will start executing the program. Every c
program must have one and only one main function.
Now the function definition starts with an opening brace { and ends with a closing brace }. This
section contains 2 parts, declaration part and executable part.

Declaration Part

The declaration part declares all the variables used in the executable part. All variables that are
used in c program must be declared. Variable declaration includes the type and variable name.
The initialization of variables are also possible with the declaration.
Example:- int a;
float x,y;
int num=10;

Executable Part

The function definition constitutes the statements representing the instructions to be carried
out by the computer. There is at least one statement in the executable part.
All statements in the declaration and executable parts end with a semicolon (;).

Sub program section

The sub program section contains all the user defined functions that are called in the main
function.
All sections except the main function section may be absent when they are not required.

Comments

Comments can be written anywhere in the program but the line should start with /* and end
with */. Anything written in between these symbols is identified as comments and the
compiler ignores them.

Example:- /* this is a comment */

46 BPS College Piramadom


Methodology of Programming and C Language

The #include Directive


Library functions are grouped category wise and stored in different files known as header
files. If we want to access the function stored in the library, it is necessary to tell the
compiler about the files to be accessed. This is achieved by using the preprocessor directive
#include as follows:
#include<file name>
File name is the name of the library file that contains the required function definition.
For example sqrt() is a library function in c to calculate the square root of a number. To use
this function we need to include the header file math.h
e.g. - #include<math.h>

UNIT 3

Input and Output in C


There are a number of I/O functions in C, based on data types. The input/output functions are
classified into two types:
i) Formatted functions
ii) Unformatted functions

Formatted Functions
With formatted functions, the input or output is formatted as per our requirement. The
readability in easy way is possible in formatted functions. The formatted input/output
functions read and write, respectively, all types of data values. They require format strings to
produce formatted results. The formatted functions return values after execution. The return
value is equal to the number of variables successfully read/written. Using this value, the user
can find out the error that occurred during reading or writing of data.
Streams performs all input and output operations. The streams are nothing but a sequence of
bytes. In input operations, the bytes (data) flow from input device such as keyboard, a disc
drive or network connection to main memory. Similarly, in output operations bytes flow from
main memory to output devices such as monitor, printer, disc drive, network connection.

47 BPS College Piramadom


Methodology of Programming and C Language

Unformatted Functions
The unformatted input/output functions work only with character data type. They do not
require format conversion symbol because they work only with character data type. in case,
values of other data types are passed to these functions, they are treated as character data.

FORMATTED FUNCTIONS

1) printf() Statement
The library function printf() is used to print out a message, either on screen or paper. This
function can be used to output any combination of numeric value, single character and strings.

Syntax
printf(“control string”, arg1,arg2,arg3,……………… argn);

The control string consists of 3 types of items.


1. Character that may be printed in the screen as they appear
2. Format specifications that defines the output format for display of each item
(argument) such as %d, %s, %c, %g, %f.
3. Escape sequence characters such as \n, \t, \b.

The arg1, arg2, ……. Are arguments that represent the individual data items. The arguments
can be written as constants, single variable, array names or expressions. Function references
may also be included.

The control string consists individual or group of characters with one character group for each input
data item. Each character group must begin with a % sign followed by a conversion character which
indicates the type of the corresponding data item. Commonly used format codes are given below.
Character Input Data
%d Decimal integer
%i Integer
%o Octal integer
%ld Long signed integer
%lu Long unsigned integer
%u Unsigned decimal integer
%x Hexadecimal
%c Character
%s Character string
%e,%f,%g Floating point numbers
%lf Double floating point
%% Literal %

Example 1:-
int x=2;
float y=2.2;

48 BPS College Piramadom


Methodology of Programming and C Language

char z=’c’;
printf(“%d %f %c”, x,y,z);
Output
2 2.2000 c
Example 2:-
int y=65;
printf(“%c %d”, y,y);
Output
A 65
In the above example %c converts numeric value 65 to its corresponding character A. %d prints
value 65 because y is integer.

FLAGS, WIDTHS AND PRECISION WITH FORMAT STRING

Flags are used for output justification, numeric signs, decimal points, trailing zeros. The flag (-)
left justifies the result. If it is not given, the default is right justification. The plus (+) signed
conversion results always starts with a plus (+) or minus (-) sign.
Width specifier sets the minimum field width for an output value. Width can be specified
through a decimal point or using an asterisk (*).

Example 3:-
printf(“\n%.2s”,”abcdef”);
printf(“\n%.3s”,”abcdef”);
printf(“\n%.4s”,”abcdef”);

Output
ab
abc
abcd

Explanation: in the above example width specifiers 2, 3 and 4 are used with format specifier
character %s with each printf() statement. The actual string length is 6 characters, the number
of printed characters is 2, 3 and 4 respectively.
Example 4:-
int x=55, y=33;
printf(“\n %3d”,x-y);
printf(“\n %6d”,x-y);

Output
22
22
Explanation: The results are displayed on different positions on the screen.

Example 5:-
int x=55, y=33;
printf(“\n %*d”,15,x-y);

49 BPS College Piramadom


Methodology of Programming and C Language

printf(“\n %*d”,5,x-y);

Output
22
22

Explanation: here * is used with format string. The values 15 and 5 indicate the position from
where printing on screen begins.

Precision specifiers: The precision specifier always starts with a period or a dot in order to
separate it from any preceding width specifiers

Example 6:-
float g=123.456789;
printf(“\n %.1f”,g);
printf(“\n %.2f”,g);
printf(“\n %.3f”,g);
printf(“\n %.4f”,g);

Output
123.5
123.46
123.457
123.4568

Formats for various outputs

Example 7:

50 BPS College Piramadom


Methodology of Programming and C Language

Output

2) scanf() Statement
The input data can be entered into the computer from a standard input device by using the library
function scanf(). This function can be used to enter any combination of numerical values, single
characters and strings.

Syntax
scanf(“control string”, arg1, arg2, ……………. argn);

The control string specifies the field format in which data is to be entered and the arguments arg1,
arg2, arg3, ………. specifies the address or locations where the data is stored. Control string and
arguments are separated by commas.

Example1: scanf(“%d”, &num);

The control string %d specifies that an integer value is to be read from the terminal. The value is
assigned to the variable num.

The scanf() statement requires ‘&’ operator called address operator. The ‘&’ operator indicate the
memory location of the variable, so that the value read would be placed at that location.

Some compilers permit the use of prompt message as a part of the control string in scanf.

Example2: scanf(“Enter the number %d”, &num);

Formats for various inputs

Example 3:
void main()
{
int a,b;

51 BPS College Piramadom


Methodology of Programming and C Language

float x;
char name[20];
printf(“enter 2 integers:- \n”);
scanf(“%4d %4d”, &a,&b);
printf(“\n entered integers are”);
printf(“\n %4d %4d”,a,b);
printf(“\n”);
printf(“\n enter a real number: \n”);
scanf(“%f”, &x);
printf(“\n entered float number is:”);
printf(“\n%f”, x);
printf(“\n”);
printf(“\n enter a string: \n”);
scanf(“%7s”, name);
printf(“\n entered string is:”);
printf(“\n %7s”, name);
}
Output
enter two integers:
1 2
Entered integers are
1 2
Enter a real number:
12.3
entered float number is:
12.300000
enter a string:
mahatmagandhi
entered string is:
mahatma

UNFORMATTED FUNCTIONS
C has 3 types of I/O functions
i) Character I/O
ii) String I/O
iii) File I/O

Character I/O Functions


1. getchar()
This function reads a character type data from a standard input. It reads one character at a
time till the user presses enter key.
Syntax:
Variable name = getchar()
Example:
char c;
c = getchar();

52 BPS College Piramadom


Methodology of Programming and C Language

2. putchar
This function prints one character on the screen at a time, read by the standard input.
Syntax:
putchar(variable name);
Example:
char c=’S’;
putchar(c);

3. getch()
It is used to read a single character the instant it is typed without waiting for the enter key to
be hit. The character entered is not displayed by the getch() function.
Syntax:
getch();

4. getche()
This function read any alpha numeric character from the standard input device.
Syntax:
getche();

5. putch()
This function prints any alphanumeric character taken by the standard input device.
Syntax:
putch(variable name);

String I/O Functions


1. gets()
This function is used for accepting any string through keyboard until enter key is pressed. The
header file stdio.h is needed for using this function.
Syntax:
gets(str);

2. puts()
This function prints the string or character array. It is opposite to gets().
Syntax:
puts(str);

3. cgets()
This function reads string from the console. It requires character pointer as an argument.
Syntax:
cgets(char *st);

4. cputs()
This function displays string on the console.
Syntax:
cputs(char *st);

53 BPS College Piramadom


Methodology of Programming and C Language

COMMONLY USED LIBRARY FUNCTIONS


1. clrscr()
This function is used to clear the screen. It is defined in conio.h header file
Syntax:
clrscr();

2. exit()
This function terminates the program. It is defined in process.h header file.
Syntax:
exit();

3. sleep()
This function pauses the execution of the program for a given number of seconds. It is defined
in dos.h header file.
Syntax:
sleep(5);

4. system()
This function is used to execute different DOS commands. It returns 0 on success and -1 on
failure.
Syntax:
system(“dir”);
The above command will display the directory.

Control Statements
The control flow statements specify the order in which computations are performed.

Decision making and Branching


Decision making statements helps to transfer the control from one part to other part of the
program. C language provides decision making capabilities and supports the following
statements known as decision making or selection statements. The control statements in c
are:-

1. if statement
2. if – else statement
3. if – else – if ladder statement
4. switch case statement
5. conditional operator statement
6. goto unconditional jump
7. loop statement

Besides, the C also supports other control statements such as continue, break.

54 BPS College Piramadom


Methodology of Programming and C Language

The if statement
The if statement is a powerful decision making statement and is used to control the flow of
execution of statements. It is basically a two way decision statement and is used in conjunction
with an expression. The if statement can be implemented in the following forms

1. Simple if statement
2. if …… else statement
3. Nested if….. else statement
4. if ….. else if ladder

Simple if statement
The general form of a simple if statement is

if (test expression)
{
Statement-block;
}
Statement- x;

The statement-block may be a single statement or a group of statements. If the test expression
is true, the statement-block will be executed; otherwise the statement-block will be skipped
and the execution will jump to the statement-x. Remember, when the condition is true both
the statement-block and the statement-x are executed in sequence.
Entry

Test True
expression
?

Statement-block

False

Statement-x

Example:- void main()


{
int age;
printf(“enter age in years”);
scanf(“%d”,&age);
if(age>17)
printf(“Eligible for voting”);
}

55 BPS College Piramadom


Methodology of Programming and C Language

The if ….. else statement


The if ….. else statement is an extension of the simple if statement. The general form is:

if (test expression)
{
True-block statement(s);
}
else
{
False-block statement(s);
}
statement-x;

if the test expression is true then the true-block statements are executed, otherwise the false-block
statements are executed. In both the cases the control is transferred subsequently to statement-x.

Entry

True Test False


expression
?

True-block False-block
statements statements

Statement-x

Example:- ………………….
………………….
if (a > b)
{
printf ( “ a is big”);
}
else
{
printf (“b is big”);
}
…………………..
……………………

56 BPS College Piramadom


Methodology of Programming and C Language

Nested if …………. Else Statement


A nested if is an if…………. else statement that has another if in its if’s body or in its else’s body.
This kind of nesting will be unlimited. The general form is:-

if ( test condition-1)
{
if ( test condition-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
if ( test condition-3)
{
statement-3;
}
else
{
statement-4;
}
}
statement-x

If condition-1 is true, then condition-2 is evaluated and if it is true then statement 1 will be
executed; otherwise statement 2 is executed. If condition-1 is false then condition-3 is
evaluated and if it is true, the statement-3will be executed; otherwise the statement-4 will be
executed.
Entry

False 1st Test


True
condition
?

False 3rd Test True False True


2nd Test True
condition condition
? ?

Statement-3 Statement-3 Statement-2 Statement-1

Statement-x
57 BPS College Piramadom
Methodology of Programming and C Language

Example:-Program to find largest among 3 numbers using nested if statement.


void main ( )
{
int a, b, c;
printf(“enter 3 numbers”);
scanf(“%d%d%d”, &a,&b,&c);
if (a>b)
{
if(a>c)
{
printf(“%d is largest”, a);
}
else
{
printf(“%d is largest”, c);
}
}
else
{
if(b>c)
{
printf(“%d is largest”, b);
}
else
{
printf(“%d is largest”, c);
}
}
getch();
}

The if else if Ladder


There is another way of putting if’s together when multipath decisions are involved. It takes
the following general form.
if (condition 1)
statement-1;
else if ( condition-2)
statement-2;
else if ( condition-3)
statement-3;
:
else if ( condition-n)
statement-n;
else
default-statement;
statement-x;

58 BPS College Piramadom


Methodology of Programming and C Language

A multipart if is a chain of if’s in which the statement associated with each else is an if. This
construct is known as the if else if ladder. The conditions are evaluated from top to bottom. As
soon as a true condition is found the statement associated with it is executed and the
remaining statements are skipped. When all the n conditions becomes false then the final else
containing the default statement will be executed.

Entry

True False
condition

Statement-1 True False


condition

Statement-2 True False


condition

Statement-3 False
True
condition

Statement-n Default
statement

Statement-x

Example : program to input a mark and print the class

Mark Class
>=80 distinction
>=60 &<80 first class
>=50 &<60 second class
>=40 &<50 third class
<40 failed
Program
void main ( )
{
int mark;
printf(“enter the mark”);
scanf(“%d”, & mark);
if (mark >= 80)
printf (“distinction”);
else if (mark >= 60)
printf (“first class”);
else if (mark >= 50)
printf (“second class”);
else if (mark >= 40)

59 BPS College Piramadom


Methodology of Programming and C Language

printf (“third class”);


else
printf(“failed”);
getch();
}

1. Switch statement
Switch statement is a multi-way branch statement. Switch statement is used to execute a block
of statements depending on the value of a variable or an expression. It has the following form.

switch ( variable or expression)


{
case value-1 : block-1;
break;
case value-2 : block-2;
break;
……………………..
………………………
default : default-block;
}
statement-x

The expression is an integer expression or characters. Value-1, value-2, ……..are constants or constant
expressions and are known as case labels. block-1, block-2, ……….. are statement lists and may contain
zero or more statements. The switch statement tests the value of a given variable or expression against
a list of case values and when a match is found, a block of statements associated with that case is
executed. The break statement at the end of each block signals the end of a particular case. The default
is an optional case. When present, it will be executed if the value of the expression does not match with
any of the case values.

Switch
(variable)

case
Statement 1 Break
constant 0

case Statement 2 Break


constant 1

Default Statement 3 Break

End of switch
60 BPS College Piramadom
Methodology of Programming and C Language

Example: Program to enter a number between 1 and 7 and print the day of the week.

void main ()
{
int no;
printf (“Enter a number between 1 and 10”);
scanf (“%d”, &no);
switch (no)
{
case 1 : printf (“Sunday”);
break;
case 2 : printf (“Monday”);
break;
case 3 : printf (“Tuesday”);
break;
case 4 : printf (“Wednesday”);
break;
case 5 : printf (“Thursday”);
break;
case 6 : printf (“Friday”);
break;
case 7 : printf (“Saturday”);
break;
default :printf (“Wrong Entry”);
}
getch();
}

Nested switch case


C supports nested switch. The inner switch can be a part of an outer switch. The inner and
outer switch case constants may be the same.
Example:
void main()
{
int x,y;
printf(“enter a number”);
scanf(%d”,&x);
switch(x)
{
case 0: printf(“number is even”);
break;
case 1: printf(“number is odd”);
break;
default: y=x%2;

61 BPS College Piramadom


Methodology of Programming and C Language

switch(y)
{
case 0: printf(“number is even”);
break;
default: printf(“number is odd”);
}
}
}

Difference between if and switch statements


switch case Nested if
The switch can only test for equality, i.e. only The if evaluate relational or logical
constant values are applicable. expressions.

No two case statements have identical Same condition may be repeated for the
constants in the same switch. number of times.

Character constants are automatically Character constants are automatically


converted into integers. converted into integers.

In switch case statement nested if can be used In nested if statement switch case can be used

The goto Statement

The goto statement is an unconditional branching statement. It is used to transfer the control
from one part of the program to another. It has the following form.

goto label;

the general form of goto statement is shown below

goto label; label :


………………… statement;
………………… …………………
label : …………………
statement; goto label;
Forward jump Backward jump

The label: can be anywhere in the program either before or after the goto label; statement.

Example:
void main()
{
int x;
printf(“enter a number”);
scanf(“%d”,&x);

62 BPS College Piramadom


Methodology of Programming and C Language

if(x%2==0)
goto even;
else
goto odd;
even: printf(“even number”);
return;
odd: printf(“odd number”);
}
Looping (Iteration) statements

A loop is defined as a block of statements, which are repeatedly executed for a certain number
of times. The loops are of two types.
i) Counter-controlled repetition: this is also called definite repetition action, because the
number of iterations to be performed is defined in advance in the program itself.
The steps in counter-controlled repetitions include Loop Variable, Initialization and
Incrimination/decrimination.
ii) Sentinel-controlled repetition: this is also called indefinite repetition. One cannot
estimate how many iterations are to be performed. In this type, loop termination
happens on the basis of certain conditions using the decision-making statement.

Looping statements allow a set of instructions to be executed repeatedly based on some


condition. A program loop consists of two segments, one known as the body of the loop and
the other known as the control statement. The control statement tests some conditions and
then directs the repeated execution of the statements contained in the body of the loop. The
conditions are set with relational expressions in which a variable is involved and this variable is
called the loop control variable.

Depending on the position of the control statement in the loop, a control structure may be
classified either as the Entry controlled loop or as the Exit controlled loop. In the entry
controlled loop, the conditions are tested before the start of the loop execution. If the
conditions are not satisfied, then the body of the loop will not be executed. In the case of an
exit controlled loop, the test is performed at the end of the body of the loop and therefore the
body is executed unconditionally for the first time.

There are 3 kinds of loops in c.


1. for loop
2. while loop
3. do … while loop

1. The for statement OR for loop


It is an entry controlled loop. The general form is:-

for (initialization expression ; test expression ; update expression )


{
loop body
}

63 BPS College Piramadom


Methodology of Programming and C Language

1. Firstly initialization expression is executed


2. Then the test expression is evaluated.
3. If the test expression is true, the body of the loop is executed.
4. After executing the loop body, the update expression is executed.
5. Again the test expression is evaluated. If it is true the sequence repeats from step 3,
otherwise the loop terminates.

Execution of the for loop

Initialization

No
Test Out of the loop
Condition?
Yes

Statements

Update expression

Example:- the following statements will print numbers from 1 to 10


for (i = 1 ; i <= 10 ; i++)
printf (“%d \n”, i);

In the above code fragment


Initialization expression is i=1
Test expression is i<=10
Update expression is i++
Here the loop control variable is i.

Various formats of for loop


Syntax Output Remarks
1. for( ; ; ) Infinite loop No arguments

2. for(a=0;a<20; ) Infinite loop ‘a’ is neither incremented nor


decremented.

3. for(a=0;a<=10;a++) Displays value from 0 to 10 ‘a’ is incremented from 0 to 10. Curly


printf(“%d”,a); braces are not necessary. Default
scope of the for loop is one
statement after the for loop.

4. for(a=10;a>=0;a--) Displays values from 10 to 0 ‘a’ is decremented from 10 to 0


printf(“%d”,a);

64 BPS College Piramadom


Methodology of Programming and C Language

The for loop in c has several capabilities and they are


1. More than one variable can be initialized at a time in the for statement
Example 1:- for (n=0, p=1 ; n<10 ; n++)
In the above code initialization part has 2 part p=1 and n=0 separated by comma.

2. Like the initialization section the update section may also have more than one part
Example 2:- for(n=0, m=10 ; n!=m ; n++ , m--)

3. The test condition may have any compound relation and testing need not be limited only
to the loop control variable
Example 3 :-
sum = 0;
for( i=1; i<= 20 && sum < 100 ; i++)

Example 4 :-
void main()
{
int i,c=0;
for(i=0;i<10; )
{
i++;
printf(“%5d”,i);
}
}
Output
1 2 3 4 5 6 7 8 9 10

Example 5 :-
void main()
{
int i=0;
for( ;i<10; )
{
printf(“%5d”,i);
i=i+2;
}
}
Output
0 2 4 6 8 10

Example 6 :-
void main()
{
char i=97;
for( ; ; )

65 BPS College Piramadom


Methodology of Programming and C Language

{
printf(“%5c”,i++);
if(i==107)
goto stop;
}
stop:;
}
Output
a b c d e f g h I j

Nested Loops

A loop may contain another loop in its body. This form of loop is called nested loop. In a nested
loop the inner loop must terminate before the outer loop.

Nested for Loops


In nested for loops one or more for statements are included in the body of the loop.
Example:- A nested for loop

for(i = 1 ; i < 5 ; i ++)


{
printf( “ \n“);
for( j = 1 ; j <= i ; j++)
{
printf( “ * “);
}
}

The output will be


*
**
***
****

2. The while statement OR while loop

The while loop is an entry controlled loop. In a while loop the loop control variable should be
initialized before the loop begins. The loop control variable should be updated inside the body
of the while. The syntax of the while statement is:-

while (test condition)


{
loop body
}

66 BPS College Piramadom


Methodology of Programming and C Language

Here the condition is evaluated first and if it is true then the body of the loop is executed. After
execution of the body the test condition is once again evaluated, and if it is true the body is
executed again. This process continues until the test condition becomes false and the control
is transferred out of the loop.
Entry

Initialize

False
Test
Out of the loop
condition

True

Body of the Loop

Update

Example :- while statement to print numbers from 1 to 10

int i= 1;
while (i<=10)
{
printf(“%d \n”,i);
i = i +1;
};

3. The do while statement OR do while loop

The do while loop is an exit controlled loop. The syntax is:-

do
{
loop body;
}
while (test condition);

On reaching the do statement the program proceeds to the body of the loop. At the end of the
loop the test condition is evaluated. If it is true the loop body is executed once again. This
process continues as long as the condition is true. When the condition becomes false the loop
will be terminated.

67 BPS College Piramadom


Methodology of Programming and C Language

Entry

Body of loop

True
Test
condition

False

Out of the loop

Example:
do
{
printf(“enter a number \n”);
scanf(“%d”, &n);
}
while (n > 0);

This segment of program reads a number from the keyboard until a zero or negative number is
entered.
Comparison of the while and do while loop

while loop do-while loop


1. Condition is specified at top Condition is mentioned at bottom

2. Body statement(s) are executed when Body statement(s) executes even when the
condition is satisfied. condition is false.

3. No brackets for single statement. Brackets are essential even when a single
statement exits.

4. It is an entry controlled loop It is an exit-controlled loop.

Jumping out of a loop


An early exit from a loop can be accomplished by using the break statement or goto statement.

Break statement
An early exit from a loop can be done by using the break statement. When a break statement is
encountered inside a loop, the loop is immediately exited and the program continues with the
statement immediately following the loop. When the loops are nested, the break would only
exit from the loop containing it, i.e. the break will exit only a single loop.

68 BPS College Piramadom


Methodology of Programming and C Language

Example: Program to find the sum of any 10 numbers. If the input number is 0 then the
program will exit.

void main()
{
int no, i, sum=0;
for (i=1 ; i<=10 ; i++)
{
printf(“Enter a number”);
scanf(“%d”, &no);
if (no == 0)
{
break;
}
sum = sum + no;
}
printf(“Sum is %d”, sum);
getch();
}

Difference between break and exit()


break exit()
1. It is a keyword. It is a function.

2. No header file is needed. Header file process.h must be included.

3. It stops execution of the loop. It terminates the program.

Continue statement
The continue statement is similar to break statement as both statements skip over a part of the
code. But the continue statement is different from break. Instead of forcing termination, it
forces the next iteration of the loop to take place, after skipping any statements in between.

Example:- for (i=1 ; i<10 ; ++i)


{
if (i ==5) continue;
printf(“%d\t”, i);
}

Here the output will be 1 2 3 46 7 8 9


Example:- Program to find square root of any 5 numbers. If we enter a negative number do not
count it as a number.
#include<math.h>
void main()
{

69 BPS College Piramadom


Methodology of Programming and C Language

int n, srt, i=1;


while(i< 5)
{
printf(“Enter a no”);
scanf(”%d”, &n);
if (n < 0)
{
printf(“negative number”);
continue;
}
srt = sqrt(n);
printf(“square root is %d”, srt);
i++;
}
getch();
}

Difference between break and continue.


break continue
1. Exits from current block or loop. Loop takes the next iteration.

2. Control passes to the next statement. Control passes at the beginning of the loop.

3. Terminates the loop. Never terminates the loop.

UNIT 4

Data Structure:
Arrays
An array is a grouping of same type of data items referenced under a common name.
Or it is a collection of consecutive locations referenced by a single variable.

An array is a linear and homogeneous data structure. It is also called a composite data
structure. An array permits homogeneous data. It means that similar types of elements are
stored contiguously in the memory and that too under one variable name. An array can be
declared any standard or custom type.

Use of arrays has definite advantages over using simple variables. For example suppose we
want to prepare the rank list of 100 candidates. It would be inconvenient to use 100 different
variables. This will make the program complex. Furthermore, it would be difficult to process
the data. But if we make use of arrays to solve this problem it will become easy to read, and
process the data.
Advantages
1. It is easy to represent and manipulate array variables.
2. Array uses a compact memory structure.
3. Readability of program will be increased.

70 BPS College Piramadom


Methodology of Programming and C Language

Types of Arrays
Arrays are classified into three
I. One Dimensional array (Single Dimensional Array)
II. Two dimensional Array
III. Multi-Dimensional Array
One Dimensional Array
It can store linear set of values. Each element is referenced by only one index (subscript) that
indicates its position. The general form of array declaration is
type arrayname [ size ];

Where type refers to the data type of array such as int, float, double, char and the size
indicates the maximum number of elements that can be stored in the array.
Example: int mark [5 ];
Here mark is the integer array that can hold 5 integer values. The compiler reserves 5 storage
locations as shown below
mark [ 0 ]
mark [ 1 ]
mark [ 2 ]
mark [ 3 ]
mark [ 4 ]

The locations are denoted by mark*0+, mark*1+, ………., mark*4+.


Here 0, 1, 2, 3, 4 are called subscripts or indices of array variable mark.

Example: char name[10];


It declares the name as a character array (string) variable that can hold 10 characters.

Initialization of One dimensional array

We can initialize the element of arrays when they are declared. The general form is

type array name[size] = { list of values };

Example: int number[3] = { 1,2,3};

In the above example all elements are initialized. It is also possible to initialize individual
element by specifying the subscript number in the square bracket following the array name.
number[0]=1;
number[1]=2;
number[2]=3;

Character arrays may be initialized as


Eg :- char name* + = ,‘J’ , ‘o’ , ‘h’ , ‘n’ , ‘\0’-; OR char name = “John”;

71 BPS College Piramadom


Methodology of Programming and C Language

Array Terminology
Size : number of elements to store elements in an array is called its size. It is always mentioned
in brackets( [ ] )
Type: type refers to data type. It decides which type of element is stored in the array. It also
instructs the compiler to reserve memory according to data type.
Base: the address of the first element is the base address. The array name itself stores address
of the first element.
Index : the index value is always an integer value. It begins from 0 to onwards depending the
size of the array. For example, n[x], n is array name and x is index.
Range: the index value varies from lower bound to upper bound while writing or reading
elements from an array. For example, in num[100], the range of index is 0 to 99.
Word : it indicates the space required for an element.

CHARACTERISTICS OF AN ARRAY
1. The declaration int a[5] is nothing but creation of five variables of integer types in
memory. Instead of declaring five variables for five values, the programmer can define
them in an array.
2. All the elements of the array share the same name and they are distinguished from one
another with the help of the element number.
3. The element number in an array plays a major role for calling each element.
4. Any particular element of an array can be modified separately without disturbing the
other elements.
Example: int a[5] = {1,4,6,8,9};
If a programmer needs to replace 9 with 10 then the statement a[4]=10; can be used.
Here other four elements are not disturbed.
5. Any element of an array a[ ] can be assigned/equated to another ordinary variable of its
type.
Example : b=a[2];
a[2] = a[3];
6. Array elements are stored in contiguous memory locations.
7. Once the array is declared, its lowest boundary cannot be changed but upper boundary
can be expanded.
Example:
int num[5]={1,2,3,4,5};
num[5]=6;
printf(“num*5+=%d”,num*5+);
Output
num[5]=6
8. An array name itself is a pointer. It does not require ‘*’ operator. The brackets( [ ] )
automatically denote that the variable is a pointer.
9. The amount of memory required for an array depends upon the data type and the
number of elements. The total size in bytes for a single dimensional array is computed
as:
Total bytes = size of data type x size of array

72 BPS College Piramadom


Methodology of Programming and C Language

10. The operation such as insertion, deletion of an element can be done with the list but
cannot be done with an array. An element can be deleted, replaced but memory
location remains as it is.
One Dimensional Array and Operations
Frequently performed operations with arrays are:-
i. Traversing
ii. Deletion
iii. Insertion
iv. Searching
v. Merging
vi. Sorting

Traversing
The operation of displaying or listing all elements of an array is called traversing.
Example:
void main()
{
int num[5],j;
Output
clrscr();
Enter 5 elements: 4 2 6 2 1
printf(“enter 5 elements:”);
Elements Address
for(j=0;j<5;j++)
4 65516
scanf(“%d”,&num*j+);
2 65518
printf(“\n Elements Address”);
6 65520
for(j=0;j<5;j++)
2 65522
printf(“\n %d %u”,num*j+,&num*j+);
1 65524
getch();
}

Deletion
This operation involves deleting specified elements from an array.

Example:
void main()
{
int num[20]={0},j,n,p,t;
clrscr();
printf(“enter number of elements:”);
scanf(“%d”,&n);
printf(“enter elements”);
for(j=0;j<n;j++)
scanf(“%d”,&num*j+);
printf(“\n elements are”);
for(j=0;j<n;j++)

73 BPS College Piramadom


Methodology of Programming and C Language

printf(“\n %d %u”, num*j+,&num*j+);


printf(“enter element number to delete:”); Output
scanf(“%d”,&p); enter number of elements: 4
p--; enter elements: 5 4 1 2
for(j=0;j<n;j++) elements are
5 65482
{
4 65484
if(j>=p)
1 65486
num[j]=num[j+1]; 2 65488
} Enter element number to delete : 3
for(j=0;j<n;j++) 5 65482
if(num[j] != 0) 4 65484
printf(“\n %d %u”,num*j+,&num*j+); 2 65486
getch();
}
Insertion
This operation is used to insert an element at a specified position in an array.
Example
void main()
{
int num[20]={0},j,n,p,t,s;
clrscr();
printf(“\n enter number of elements:”);
scanf(“%d”,&n);
printf(“\n enter elements:”); Output
for(j=0;j<n;j++) enter number of elements: 4
scanf(“%d”, &num*j+); enter elements: 1 2 3 4
printf(“\n elements and their locations are:”); elements and their locations are:
for(j=0;j<n;j++) 1 65450
printf(“\n %d %u”,num*j+,&num*j+); 2 65452
printf(“enter element and position to insert at:”); 3 65454
scanf(“%d %d”,&s,&p); 4 65456
enter element and position to insert at: 9 2
p--;
1 65450
for(j=n; j != p; j--)
9 65452
num[j]=num[j – 1];
2 65454
num[j] = s; 3 65456
for(j=0; j<=n; j++) 4 65458
printf(“\n %d %u”, num*j+, &num*j+);
getch();
}

Searching
An array element can be searched. The process of seeking specific elements in an array is called
searching.

74 BPS College Piramadom


Methodology of Programming and C Language

Example:
void main()
{
int array[100], search, c, n;
printf("Enter the number of elements \n");
scanf("%d",&n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search)
{
printf("%d is present at location %d.\n", search, c+1); Output
enter the number of elements: 4
break;
enter 4 integers : 6 4 7 2
}
enter the number to search : 7
} 7 is present at location 3
if (c == n)
printf("%d is not present in array.\n", search);
getch();
}

Merging
The elements of two arrays are merged into a single one.
i. Elements of one array can be appended to end of the second array
ii. Elements of two arrays can be merged in alternate order.

Example
void main()
{
int j,h=0,k=0;
int x[4] ={1,2,3,4};
int y[4] ={5,6,7,8];
int z[8];
clrscr();
printf(“array 1:”);
for(j=0;j<4;j++)
printf(“%d”,x*j+);
printf(“array 2:”);
for(j=0;j<4;j++)
printf(“%d”,y*j+);
j=0;

75 BPS College Piramadom


Methodology of Programming and C Language

while(j<8)
{
if(j%2==0)
z[j]=x[k++]
else
z[j]=y[h++];
j++ Output
} array 1: 1 2 3 4
printf(“\n array 3:”); array 2: 5 6 7 8
for(j=0; j<8; j++) array 3: 1 5 2 6 3 7 4 8
printf(“%d”,z*j+);
getch();
}

Sorting
Arranging elements in a specific order either in ascending or in descending order is known as
sorting.
Example
void main()
{
int num[5],j,k,s=0;
clrscr();
printf(“\n enter five elements:”);
for(j=0; j<5; j++)
{
scanf(“%d”,&num*j+);
s=s+num[j];
}
for (k=0; k<s; k++)
{
for(j=0; j<5; j++) Output
{ Enter five elements: 5 8 9 7 2
if (num[j]==k) 2 5 7 8 9
printf(“%d”,num*j+);
}
}
}

Two Dimensional Array


A two dimensional array is analogous to a table having data arranged in rows and columns.
Two dimensional arrays are declared as follows.

datatype ArrayName[row size] [ column size ];

76 BPS College Piramadom


Methodology of Programming and C Language

Example:- int a[2][3];

Columns

0 1 2

0
Rows
1

a[1][1]

A two dimensional array can be initialized as follows

int a[2][3]={0,0,0,1,1,1};
or
int a[2][3]= { {0,0,0} , {1,1,1}};

Insert operation with two dimensional Array


Example:
void main( )
{
int num[5][5]={0,0},j,*p,at,e,n;
clrscr();
printf(“\n enter how many elements (<=25):”);
scanf(“%d”,&n);
p=&num[0][0];
for(j=0;j<n;j++)
scanf(“%d”,p++);
p=&num[0][0];printf(“\n”);
for(j=0;j<n;j++,p++)
printf(“%2d”,*p);
printf(“\n enter a number & position to insert:”);
scanf(%d %d”,&e,&at);
for(j=n;j>=at;j--)
{
Output
*p=*(p-1);
Enter how many elements (<=25): 5
p- -;
1 2 3 4 5
} 1 2 3 4 5
*p=e; Enter a number & position to insert: 8 3
p=&num[0][0]; 1 2 8 3 4 5
for(j=0;j<=n;j++,p++)
printf(“%2d”,*p);
}

77 BPS College Piramadom


Methodology of Programming and C Language

Delete operation with two dimensional Array


Example
void main( )
{
int num[5][5]={0,0}, j, *p, at, e, n;
clrscr();
printf(“\n enter how many elements (<=25):”);
scanf(“%d”,&n);
p=&num[0][0];
for(j=0;j<n;j++)
scanf(“%d”,p++);
p=&num[0][0]; printf(“\n”);
for(j=0;j<n;j++,p++)
printf(“%2d”,*p);
printf(“\n enter element number to delete:”);
scanf(%d”,&at);
at--;
p=&num[0] [0];
p+ = at;
for(j=at; j<n; j++)
{
*p = *(p+1);
Output
p++;
Enter how many elements (<=25): 7
}
1 2 3 4 5 6 7
*p = 0;
1 2 3 4 5 6 7
p = &num[0][0]; Enter element number to delete: 5
while(*p != 0) 1 2 3 4 6 7
{
printf(“%d”,*p);
p++;
}
}

Multi-dimensional array
The general form of a multi-dimensional array is
datatype ArrayName[size1] [ size2 ] [size3+……………*size n] ;

Example:- int survey[3][5][12];

Strings and standard Functions


Strings
A string constant is a one dimensional array of characters terminated by a null (‘\0’). Any group
of characters defined between double quotation marks is a string.
Example:- “Baselios”

78 BPS College Piramadom


Methodology of Programming and C Language

Declaring and Initializing string variables


The general form of declaring a string variable is

char stringName [size];

The size determines the number of characters in the string.

Example:- char name [10];

Character arrays may be initialized as


Example :- char name* + = ,‘J’ , ‘o’ , ‘h’ , ‘n’ , ‘\0’-;
OR
char name* + = “John”;
In this declaration c automatically inserts a null character ‘\0’ at the end of the string.

The value of the string is its base address, i.e. address of the first character.

Example:
char name* + = ,‘I’,’N’,’D’,’I’,’A’,’\0’-;

Each character of the string occupies 1 byte of memory. The last character is always ‘\0’. It is
not compulsory to write ‘\0’ in string. The compiler automatically puts ‘\0’ at the end of the
character array or a string. The characters of a string are stored in contiguous locations. In the
above example the compiler automatically determines the size of the array.

Reading Strings using scanf()


The input function scanf( ) can be used with %s format specifier to read a string.
Example:- char name [20];
scanf(“%s”, name);

The scanf() is not capable of reading multiword strings, i.e. it cannot read white spaces. In the
case of character arrays the amphersand(&) is not required before the variable.

String Standard Functions


C supports a large number of string handling library functions. String manipulation functions
are given in string.h header file.

1. strlen( )
This function returns the number of characters in a string.
Syntax:
n =strlen (string);
Where n is an integer variable which receives the value of the length of the string.
Example:- int n;
char str1* + = “mgu”;
n = strlen(str1); ------- here n will get 3

79 BPS College Piramadom


Methodology of Programming and C Language

2. strcpy( )
This function copies the contents of one string into another.

Syntax: strcpy (char *s2,char *s1);


Where s1 is the source string, s2 ids the destination string i.e., s1 is copied to s2.

Example:- char source* + = “baselios”;


char target[20];
strcpy (target, source);

Here the string “baselios” is copied to target.

3. strncpy()
This function copies specified length of characters from the source to destination string. The
strcpy() function copies whole source string to destination string.
Syntax:
strncpy (char *destination, char *source, int n);
Example:
char s1* +=”wonderful”;
char s2* +=”beautiful”;
strncpy(s2,s1,6);
printf(“%s”, s2); it will print wonderful

4. stricmp()
This function compares two strings without regard to case. If the strings are the same it returns
zero otherwise non zero value.

Syntax:
stricmp(char *s1,char *s2)
Example:
#include<string.h>
void main()
{
char sr[10],tar[10];
int diff;
printf(“enter string 1:”);
gets(sr);
printf(“enter string 2:”); Output
gets(tar); Enter string 1:
diff=stricmp(sr,tar); HELLO
if (diff==0) Enter string 2:
puts(“two strings are identical”); hello
else two strings are identical
puts(“two strings are different”);
getche();
}

80 BPS College Piramadom


Methodology of Programming and C Language

5. strcmp ( )
This is a function which compares two strings to find out whether they are same or different.
This function discriminates lower case and upper case letters. 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, the function returns a value 0, otherwise
it returns the numeric difference between the ASCII values of the first non-matching pairs of
characters.
Syntax:
strcmp(string1, string2);

Example:- char s1* += ”New”;


char s2* + = “Delhi”;
int i;
i = strcmp (s1,s2);
6. strncmp()
This function is same as strcmp() but it compares the character of the string to the specified
length.
Syntax: strncmp(char *source, char *target, int argument);

Example:
#include<string.h>
void main()
{
char sr[10],tar[10];
int n,diff;
printf(“enter string 1:”);
gets(sr);
printf(“enter string 2:”);
gets(tar);
printf(“enter length up to which comparison is to be made :”);
scanf(“%d”,&n);
Output
diff=strncmp(sr,tar,n); Enter string 1:
if (diff==0) HELLO
printf(“two strings are identical up to %d characters”,n); Enter string 2:
else HE MAN
puts(“two strings are different”); Enter length up to which comparison is to
getche(); be made: 2
} two strings are identical up to 2 characters
7. strlwr( )
It converts a string to lowercase.
Syntax:
strlwr(char *string);

Example:- strlwr(“HELLO”); here the output will be hello

81 BPS College Piramadom


Methodology of Programming and C Language

8. strupr()
It converts a string to upper case.
Syntax:
strupr(char *string);

Example:- strupr(“hello”); here the output will be HELLO

9. strdup()
This function is used for duplicating a given string at the allocated memory which is pointed by
the pointer variable.
Syntax:
text2=strdup(text1)
Where text1 is string and text2 is a pointer.
Example:
#include<string.h>
void main() Output
{ Enter text: Good Morning
char text1[20],*text2; Original string=Good Morning
printf(“enter text:”); Duplicate string=Good Morning
gets(text1);
text2=strdup(text1);
printf(“Original string=%s \n Duplicate string = %s”,text1,text2);
}

10.strchr()
This function returns the pointer position to the first occurrence of the character in the given
string. strchr() function returns null if character is not found otherwise it returns a pointer to
the first occurrence of the given character.
Syntax:
chp = strchr(string , ch);
Example:
#include<string.h>
void main()
{
char string[30],ch,*chp;
printf(“enter a string:”);
gets(string);
printf(“enter a character to find:”);
ch=getchar();
chp=strchr(string,ch);
Output
if(chp) enter a string: hello
printf(“character is found in string”); enter a character to find: l
else character is found in string
printf(“character is not found in string”);
}

82 BPS College Piramadom


Methodology of Programming and C Language

11.strstr()
It finds first occurrence of a given string in another string. This function finds the second string
in the first string. it returns the pointer location from where the second string starts in the first
string. if not found it returns NULL.
Syntax:
strstr(char *string1, char *string2);
Example:
#include<string.h>
void main()
{
char line1[30],line2[30],*chp;
puts(“enter line1:”);
gets(line1);
puts(“enter line2:”);
gets(line2);
chp=strstr(line1,line2); Output
if(chp) enter line1: india is my country
printf(“string is present”); enter line2: india
else string is present
printf(string is not present”);
}

12.strcat( )
This function joins(concatenates) two strings together. That is this function appends the target
string to the source string.
Syntax:
strcat (string1, string2);

Example:- char s1* + = “New”;


char s2* + = “Delhi”;
strcat (s1, s2);
printf(“%s”, s1);

The output will be NewDelhi

13.strncat
This function concatenates the string with another up to the specified length.
Syntax:
strncat(text1,text2,n) where n is the number character to append
Example:
#include<string.h>
void main()
{
char text1[30],text2[10],n;
puts(“enter text1:”);

83 BPS College Piramadom


Methodology of Programming and C Language

gets(text1);
puts(“enter text2:”);
Output
gets(text2);
enter text1: MAY I
printf(“enter number of characters to add:”);
enter text2: COME IN
gets(n); enter number of characters to add: 4
strcat(text1,” “); MAY I COME
strncat(text1,text2,n);
printf(“%s”,text1);
}

14.strrev()
It reverses a given string.
Syntax:
strrev( char *s);
Example:
char text*+=”ABCD”;
strrev(text); it will return DCBA

15.strset()
This function replaces every character of a string to a given symbol/character.
Syntax:
strset(char * string, char symbol);
Example:
#include <string.h>
void main()
{
char string[10], symbol;
puts(“enter a string:”); Output
gets(string); enter a string: COLLEGE
puts(“enter a symbol for replacement:”); enter a symbol for replacement: Y
scanf(“%c”,&symbol); YYYYYYY
strset(string,symbol);
printf(“%s”,string);
}

16.strnset()
It is same as strset() function. Here, the specified length is provided.
Syntax:
strnset(char *string, char symbol, int n);
Where n is the number of characters to replace
Example:
char string*+=”ABCDE”;
char symbol=”#”;
strnset(string,symbol,2); it will return ##CDE

84 BPS College Piramadom


Methodology of Programming and C Language

17.strspn()
This function returns the position of the string from where the source array is not matching the
target one.
Syntax:
strspn(char *string1, char *string2);
Example:
#include<string.h>
void main()
{
char text1[10],text2[10];
int length;
printf(“enter first string:”); Output
gets(text1); enter first string: GOOD MORNING
printf(“enter second string:”); enter second string: GOOD BYE
gets(text2); after 5 characters there is no match
length=strspn(text1,text2);
printf(“after %d characters there is no match”, length);
}

18.strpbrk()
This function searches the first occurrence of the character in a given string, and then it
displays the string starting from the character.
Syntax:
strpbrk(char *text1, char text2);
Example:
#include<string.h>
void main()
{
char *ptr;
char text1[10],text2[2];
printf(“enter string:”); Output
gets(text1); enter string: INDIA IS GREAT
printf(“enter character:”); enter character: G
gets(text2); string from given character: GREAT
ptr=strpbrk(text1,text2[0]);
printf(“string from given character:”);
puts(ptr);
}
String Conversion Functions
Function Name Description
double atof(const char *s ); Converts the given string to double
int atoi(const char *s ); Converts the given string to int
long atoi(const char *s); Converts the given string to long
double strtod(char *s, char **endptr); Separates char and float data from the given string
long strtol(char *s, char **endptr, int radix); Separates char and long int data from the given string.

85 BPS College Piramadom


Methodology of Programming and C Language

 Program to demonstrate atof( ) function


#include<stdlib.h>
void main()
{
double d;
d=atof(“99.1234”);
printf(“%f”,d);
}
Output
99.1234

 Program to demonstrate atoi( ) function


#include<stdlib.h>
void main()
{
int i;
i=atoi(“99.11”);
printf(“%d”,i);
}
Output
99

 Program to demonstrate strtod( ) function


#include<stdlib.h>
void main()
{
const char *string=”12.2% is interest”);;
char *stp;
double d;
d=strtod(string,&stp);
printf(“%g”,d);
printf(“\n%s”,stp);
}
Output
12.2
% is interest

POINTERS
A pointer is a variable that stores the address of another variable. The computer’s memory is a
sequential collection of storage cells. Each cell commonly known as a byte, has a number called
address associated with it. Pointer is a special data type in c.

Example:- int a = 3;

86 BPS College Piramadom


Methodology of Programming and C Language

a location name

3 value at location

6525 location number (address)

Since memory addresses are simply numbers, they can be assigned to some variables. Such
variables that hold memory addresses are called pointers.

Features of Pointers
1. Pointers are fundamental tool in developing code in c.
2. Pointers save memory space.
3. The pointer assigns the memory and also releases it. Pointers are used to allocate
memory dynamically.
4. Pointers are used with data structures. They are useful for representing two
dimensional and multi-dimensional arrays.
5. Access elements of an array of any data type irrespective of its subscript range.
6. Execution time with pointer is faster because data is manipulated with the address.

Accessing the address of a variable

The & symbol which is known as address of operator is used to access the address of a variable.

Example:- ptr = &a;

Declaration and initialization of Pointers

Pointer variables are declared like normal variables except for the addition of unary character
* (asterisk). The syntax is

dataType *ptrvarname;
Example:-
int *iptr; --------- creates an integer pointer
float *fptr; --------- creates a float pointer
char *cptr; --------- creates a character pointer

Two unary operators * and & are used with pointers. The & returns the memory address of its
operand. The operator * returns the value of the variable located at the address following it. So
& is known as address of operator and * is known as value at operator.

Example:-
main( )
{
int i=3;
int *j;
j = &i;
printf (“\n Address of i = %u”, &i);

87 BPS College Piramadom


Methodology of Programming and C Language

printf(“\n Address of i = %u”, j);


printf(“\n address of j = %u”, &j);
printf(“\n value of j = %u”, j);
printf(“\n value of i = %d”, i);
printf(“\n value of i = %d”, *(&i));
printf(“\n value of i = %d”, *j);
}
i j

3 6524
6524 6522

Output
Address of i = 6524
Address of i = 6524
Address of j = 6524
Value of j = 6524
Value of i = 3
Value of i = 3
Value of i = 3
Program to find the sum of two given numbers using pointer variable.
void main( )
{
int a, b, *ptr1, *ptr2;
ptr1 = &a;
ptr2 = &b;
printf (“Enter 2 numbers”);
scanf(“%d%d”, ptr1, ptr2);
printf (“Sum = %d”, *ptr1 + *ptr2);
}

The void Pointers

Pointers can also be declared as void types. A void pointer can point any type of variable with
proper type casting. When a pointer is declared as void two bytes are allocated to it.
Void variables cannot be declared because memory is not allocated to them and there is no
place to store address.
Example:
int p;
char c;
void *pt=&p;
void main()
{
*(int *)pt=12;

88 BPS College Piramadom


Methodology of Programming and C Language

printf(“p=%d”,p);
pt=&c;
*(char *)pt=’S’;
printf(“c=%c”,c);
}
Output
p=12
c=S
In the above example p and c are variables of type int and char respectively. pt is pointer of
type of void. The pt is initialized with address of integer variable p. The statement *(int *)
pt=12 assigns the integer value 12 to pointer pt i.e. to variable p. the declaration *(int *) tells
the compiler the value assigned is of integer type. Thus the assignment of char type is carried
out.

WILD Pointers
When a pointer points to an unallocated memory location or data value whose memory is de-
allocated, such a pointer is called a wild pointer. The wild pointer generates garbage memory
location and dependent reference. The pointer becomes wild due to the following reasons.
i) Pointer declared but not initialized
ii) Pointer alternation
iii) Accessing the destroyed data

Example:
void main()
{
int k,*x;
for(k=0;k<=2;k++)
printf(“%u”,x*k+);
}

Output
7272 24330 30559
In this program pointer x is not initialized. The successive locations are displayed.

CONSTANT Pointers
The address of the constant pointer cannot be modified.

char *const str=”constant”;

In the above example, it is not possible to modify the address of the pointer str. The following
operations will generate error message

str=’san’; --------- cannot modify a constant object


++str; --------- cannot modify a constant object

89 BPS College Piramadom


Methodology of Programming and C Language

Example:
void main()
{
int k=10;
int const *pm=&k;
k=40;
/* *pm=50; invalid operation*/
printf(“k=%d”,k);
}
Output
k=40

In the above example the value of k cannot be changed through the constant pointer pm.

ARITHMETIC OPERATIONS WITH POINTERS


C allows us to add integers to or subtract integers from pointers as well as to subtract one
pointer from another. For example if p1 and p2 are properly declared and initialized pointers
then p1+4, p2-2 and p1-p2 are allowed. If p1 and p2 are both pointers to the same array, then
p2-p1 gives the number of elements between p1 and p2. Increment, decrement, prefix and
post fix operations can also be performed with the pointers.

Data Type Initial Address Address after Address after Required Bytes
operation ++ operation - -
int i=2 4046 4048 4044 2
char c=’x’ 4053 4054 4052 1
float f=2.2 4058 4062 4054 4
long l=2 4060 4064 4056 4

POINTERS AND ARRAYS


Array name by itself is an address or pointer. It points to the address of the first element (0th
element of an array). The elements of the array together with their addresses can be displayed
by using array name itself. Array elements are always stored in contiguous memory locations.
Example:
int x[5]={1,2,3,4,5};
suppose the base address of x is 1000, the five elements will be stored as follows:

Elements  x[0] x[1] x[2] x[3] x[4]


Value  1 2 3 4 5
Address  1000 1002 1004 1006 1008

The name x is defined as a constant pointer pointing to the first element, x[0] and therefore
the value of x is 1000, the location where x[0] is stored. That is,
x = &x[0] = 1000

90 BPS College Piramadom


Methodology of Programming and C Language

If we declare p as an integer pointer( int *p) , then we can make the pointer p to point to the
array x by the following assignment
p = x;
This is equivalent to
p = &x[0];
Now we can access every value of x using p++ to move from one element to another. The
relationship between p and x is shown as:
p = &x[0] (=1000)
p + 1= &x[1] (=1002)
p + 2= &x[2] (=1004)
p + 3= &x[3] (=1006)
p + 4= &x[4] (=1008)

Example: program to access elements of an array through different ways using a pointer.
void main()
{
int arr[5]={10,20,30,40,50},p=0;
clrscr();
for(p=0;p<5;p++)
{
printf(“value of arr*%d+=”,p);
printf(“%d |”,arr*p+);
printf(“%d |”,*(arr+p));
printf(“%d |”,*(p+arr));
printf(“%d |”,p*arr+);
printf(“address of arr*%d+=%u\n”,p,&arr*p+);
}
}
Output
value of arr[0]=10 | 10 | 10 | 10 | address of arr[0]=4056
value of arr[1]=20 | 20 | 20 | 20 | address of arr[1]=4058
value of arr[2]=30 | 30 | 30 | 30 | address of arr[2]=4060
value of arr[3]=40 | 40 | 40 | 40 | address of arr[3]=4062
value of arr[4]=50 | 50 | 50 | 50 | address of arr[4]=4064
Explanation
In the above program elements displayed using different syntax
arr[p], *(arr+p), *(p+arr), p[arr]. The results of all of them would be the same.
1. arr[p] – here ‘arr’ refers to the address and ‘p’ refers to the element number.
2. *(arr+p) – the arr+p is the addition of constant with base address of the array. The
*(arr+p) points to the pth element of the array.
3. *(p+arr) – this statement is same as *(arr+p)
4. p[arr] – this is same as arr[p]. here ‘p’ refers the element number and ‘arr’ refers to the
base address. By varying ‘p’ and ‘arr’ the various elements of the array are displayed.

91 BPS College Piramadom


Methodology of Programming and C Language

Pointers and Two Dimensional Arrays


A matrix can represent two dimensional elements of an array. Here, the first argument is row
number and second the column number. To display the 1st element of two dimensional array
using a pointer, it is essential to have ‘&’ operator as prefix with an array name followed by
element number; otherwise the compiler shows an error.
Example:
void main()
{
int i,j=1,*p;
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
clrscr();
printf(“elements of an array with their address \n”);
p=&a[0][0];
for(i=0; i<9; i++,j++)
{
printf(“%5d *%5u+”,*(p),p);
p++;
if(j==3)
{
printf(“\n”);
j=0;
}
}
}
Output
elements of array with their address
1 [4052] 2 [4054] 3 [4056]
4 [4058] 5 [4060] 6 [4062]
7 [4064] 8 [4066] 9 [4068]

Here the base address of the array is assigned to integer pointer ‘p’. the pointer ,p, is printed
and incremented in the for loop till it prints the entire array elements.

Array of Pointers

An array of pointers is a collection of addresses. That is, addresses of memory locations can be
stored in an array and the array is called array of pointers or pointer array.
Syntax:
dataType *ptrArrayName [size];

Example:- int *ptr[10];

Here ptr can contain addresses of 10 locations containing integer data. The expression ptr[0]
returns the first address and *ptr[0] returns the content of that address.

92 BPS College Piramadom


Methodology of Programming and C Language

Example:- int a = 5, b=10;


int *ptr[10];
ptr[0] = &a;
ptr[1] = &b;
The expression ptr[0] will return address of a and *ptr[0] will return 5.

UNIT 5

Functions

Functions in can be defined as a named group of statements that can act on data and return a
value.

C functions can be classified in to two categories


1. Library functions
2. User defined functions

main( ) is an example of user defined function. printf( ), scanf( ), sqrt( ), strlen( )………….. are
examples of library functions. Library functions are pre defined set of functions. One can only
use the function but cannot change or modify them. The user need not worry about its source
code, but the results should be provided by the function.

Need for user defined functions


i) If we want to perform a task repetitively, then it is not necessary to rewrite the
particular block of program again and again. Shift the particular block in a user defined
function. The function defined can be called any number of times to perform the task.
ii) Using functions, large programs can be reduced to smaller ones. It is easy to debug
and find out the errors in it.
iii) It also increases readability.

How a Function works

i) Once a function is defined and called, it takes some data from the calling function
and returns a value to the called function.
ii) Whenever a function is called, control passes to the called function and working of
calling function is paused. When the execution of a called function is completed,
control returns back to the calling function and executes the next statement.
iii) The values of the actual arguments passed by the calling function are received by
the formal arguments of the called function.
iv) The function operates on formal arguments and sends back the result to calling
function. The return( ) statement performs this task.

93 BPS College Piramadom


Methodology of Programming and C Language

Example:
int abc(int, int, int); Function declaration
void main()
{
int x,y,z;
-----------
abc(x,y,z); Function call

------------ Actual arguments


------------ Formal Arguments
}
int abc(int l, int k, int j)
{
------------- Function definition
-------------
return();
}
A c program can contain any number of functions. The creation and usage of user defined
functions involves 3 steps namely
1. Function Declaration
2. Function Definition
3. Invoking a function

Function Declaration
A function has to be declared in a program before using it. The declaration informs the
compiler the name of the function, return type and the number and type of arguments passed
to the function.
Syntax:- returnType functionName (arg1, arg2, …………….);

Example:- int sum (int, int);

Function Definition
The definition of a function consists of the function header and its body. The function header
specifies the type of data returned by the function, name of the function and list of
parameters. The body of a function is a set of statements enclosed in braces.
Syntax :
returnType functionName (argument list)
{
local variable declaration;
statement 1;
statement 2;
.
.
statement n;
return (expression);
}
94 BPS College Piramadom
Methodology of Programming and C Language

Argument list (Parameter list)

It is a comma separated list of variables used to supply data to the function from the caller. A
function can be without any parameters.
The arguments appearing in the function call statement is known as actual arguments. The
arguments in the function definition is called formal arguments. The actual and formal
arguments must match in number, type and order.

Return Statement

The return statement is used to return the control as a value to the called function. This is also
an optional statement. Its absence indicates that no value is being returned to the called
function. exit from the called function to the calling function is done by the use of the return
statement. when the return statement is executed without argument, it always return 1.
The return statement can take any of the following forms.

i) return;
ii) return (expression);
The first statement does not return any value, it returns the program execution control back to
the caller. A function can return only a single value back to the calling function.

Examples:- return (a+b);


return 0;
return;
return(&p) --------- it returns the address of the variable
return(*p) ---------- it returns the value of a variable through the pointer.

A function may use one or more return statements. It is used when we want to return a value
depending upon certain conditions.
Example1:
if(a>b)
return(a);
else
return (b);
Example2:
switch(x)
{
case 1:
return(1);
break;
case 2:
return(1*2);
break;
default:
return(0);
}

95 BPS College Piramadom


Methodology of Programming and C Language

Invoking a Function

A function is called (invoked) by providing the name of the function followed by the values of
parameters. A function can be called simply using its name like other c statement, terminated
by a semi colon(;).
Example:- sum(5, 10);
sum(a, b);

Types of Functions
A function, depending on whether arguments are present or not and whether a value is
returned or not, may belong to one of the following categories.
1. Function with no arguments and no return values
2. Functions with arguments and no return values
3. Functions with arguments and one return value
4. Functions with no arguments but return a value
5. Functions that return multiple values
1. Function with no arguments and no return values

When a function has no arguments, it does not receive any data from the calling function.
Similarly when it does not return a value the calling function does not receive any data from
the called function.
Calling function Analysis Called function
void main() abc()
{ {
-------------- No arguments are passed. ------------
-------------- No values are sent back ------------
abc(); ------------
-------------- }
--------------
}

Eg:- void main()


{
void message( ); calling function
message();
}
void message( )
{ called function
puts(“ Have a nice day”);
}

Output
Have a nice day

This program contains a user defined function named message. it requires no


arguments and returns nothing.

96 BPS College Piramadom


Methodology of Programming and C Language

2. Functions with arguments and no return values


The called function can send arguments (data) to the calling function. But the called function
does not return any value to the calling function.
Calling function Analysis Called function
void main() abc(y)
{ {
-------------- Argument(s) are passed. ------------
-------------- No values are sent back ------------
abc(x); ------------
-------------- }
--------------
}

Example:- void main ( )


{
int a, b;
printf(“Enter 2 numbers”);
scanf(“%d%d”, &a, &b); actual arguments
sum(a,b);
}
sum (int x, int y) formal arguments
{
int s;
s = x + y;
printf(“sum = %d”, s);
}
3. Functions with arguments and return value
Here data is transferred between the calling function and called function.
Calling function Analysis Called function
void main() abc(y)
{ {
int z; Argument(s) are passed. ------------
-------------- Values are sent back. y++;
z=abc(x); ------------
-------------- ------------
-------------- return(y);
} }
Example:- void main ( )
{
int sum (int, int);
int a, b, s;
printf (“Enter 2 numbers”);
scanf(“%d%d”, &a,&b);
s = sum (a, b);
printf(“sum is %d”, s);
}

97 BPS College Piramadom


Methodology of Programming and C Language

sum (int x, int y)


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

4. Functions with no arguments but return a value


We can design functions that may not take any arguments but returns a value to the calling
function.

Calling function Analysis Called function


void main() abc()
{ {
int z; No arguments are passed. int y=5;
-------------- values are sent back. ------------
-------------- ------------
z=abc(); ------------
-------------- return(y);
-------------- }
}

Example:- int get_number(void);


main()
{
int m = get_number( );
printf(“%d”, m);
}
int get_number(void)
{
int number;
scanf(“%d”, &number);
return(number);
}

5. Functions that return multiple values

Function can return more values using call by reference method. The mechanism of sending
back information through arguments is achieved using what are known as the address operator
(&) and indirection operator(*).

Example:- void mathoperation (int x, int y, int *s, int *d)


main( )
{
int x = 20, y = 10, s, d;
mathoperation(x, y, &s, &d);
printf(“s=%d\n d=%d\n, s, d);
}

98 BPS College Piramadom


Methodology of Programming and C Language

void mathoperation (int a, int b, int *sum, int *diff)


{
*sum = a+b;
*diff = a-b;
}

Parameter Passing
There are two ways of passing arguments to a function.

1. Call by value method


2. Call by reference method

Call by Value method


In call by value method, only the values of the arguments are copied to the formal parameters.
The function creates its own copies of the argument values and uses them. Therefore any
change of the formal parameters in the function does not affect the original arguments (actual
arguments). The advantage is that a called function will not accidently modify the actual
parameters.

Example:- void reset (int, int);


void main()
{
int a = 5, b = 7;
printf(“Before call a=%d and b=%d”, a, b);
reset(a,b);
printf(“After call a=%d and b=%d”, a, b);
}
void reset(int x, int y);
{
x = y = 0;
}

Call by Reference Method


In call by reference the address(reference) of actual arguments in the calling function are
copied into formal arguments of the called function. So the changes made in the formal
arguments do affect the actual arguments.

Example:- void main()


{
int swap(int *, int *);
int a = 5, b = 7;
printf(“Before swap a=%d and b=%d”, a, b);
swap(&a,&b);
printf(“After swap a=%d and b=%d”, a, b);
}

99 BPS College Piramadom


Methodology of Programming and C Language

swap(int *x, int *y)


{
int *t;
*t = *x;
*x = *y;
*y = *t;
}

Output
Before swap a=5 and b=7
After swap a=7 and b=5

Advantages of Functions
 Reduces the length of the program.
 Facilitates top down programming approach.
 A function can be used to keep away from rewriting the same block of codes which we
are going use two or more locations in a program.
 It is easy to locate and separate a faulty function for further study.
 Easy to debug the program.

Recursion
Recursion is the property of a function to call itself. When a function calls itself a new copy of
that function is executed every time. Recursive function should always have a stop condition
otherwise the process continues infinitely.

Example:- Program to read a number and find factorial using recursive function

void main()
{
int a, fact;
printf(“Enter a number”);
scanf(“%d”, &a);
fact = rec (a);
printf(“Factorial value = %d”, fact);
getch();
}

rec(int x)
{
int f;
if (x == 1)
return (1);
else
f = x * rec(x-1);
return (f);
}

100 BPS College Piramadom


Methodology of Programming and C Language

Rules for Recursive Function


1. In recursion, it is essential to call a function itself, otherwise recursion would not take
place.
2. Only the user defined function can be involved in recursion. Library function cannot be
involved in recursion because their source code cannot be viewed.
3. A recursive function can be invoked by itself or by other function.
4. To stop the recursive function, it is necessary to base the recursion on test condition,
and proper terminating statement such as exit(), or return must be written using the if
statement.
5. The user defined function main() can be invoked recursively. To implement such
recursion, it is necessary to mention prototype of function main. (void main(void)).

Types of Recursion
Recursion are of two types.
1. Direct recursion
2. Indirect recursion
When a function calls itself, this type of recursion is direct recursion. In this type, only one
function is involved. In indirect recursions, two function calls each other.

int num() int num()


{ {
---------- ----------
num(); sum();
} }

Direct Recursion int sum()


-------------
num();
}

Indirect Recursion

Direct Recursion
In this type, only one function is involved which calls itself until the given condition is true.

Example: a program to calculate triangular number using recursion.


#include<process.h>
void main()
{
int trinum(int);
int t,x;
clrscr();
printf(“\n enter a number:”);

101 BPS College Piramadom


Methodology of Programming and C Language

scanf(“%d”,&x);
t=trinum(x);
printf(“\n triangular number of %d is %d”,x,t);
}
int trinum(int x)
{
int f=0;
if(x==0) return f;
else f=f+x+trinum(x-1);
return f;
}
Output
enter a number: 4
triangular number of 4 is 10

Explanation:
Triangular of number means that the sum of all the numbers between 1 to entered number. In
the above program, a function trinum() is defined which calls itself. An integer is entered and is
stored in x. in function trinum() the function calls itself and decreases the value of x passed by
one. The return values are added to f. when the value of x becomes zero, the recursive process
ends and the total sum is returned to variable t in function main().

Indirect Recursion
In this type of recursion, two or more functions are involved in the recursion. The indirect
recursion does not make any overhead as direct recursion. When control exits from one
function and enter into another function, the local variables of former function are destroyed.

Example: program to show recursion between two functions


int s=0;
void show(void);
void main()
{
if (s==5) exit(0);
show();
}
void show()
{
printf(“%d”,s);
s++; Output
main(); 01 2 3 4
}

Explanation: The s is a global variable. The main() function invokes show() function and
show() function invokes main() function. The value of s is incremented and displayed. When
the value of s reaches to 5, the program is terminated.

102 BPS College Piramadom


Methodology of Programming and C Language

Recursion versus Iteration


Recursion Iteration
Recursion is the term given to the mechanism The block of statements is executed
of defining a set or procedure in terms of itself repeatedly using loops.
A conditional statement is required in the The iteration control statements itself contain
body of the function for stopping the function statements for stopping the iteration. At every
execution execution, the condition is checked
At some places recursion generates extra All problems cannot be solved with iteration
overhead.
Recursion is expensive in case of speed and Iteration does not create any overhead.
memory.

Advantages of Recursion
1. At most of the times, a problem can be solved without recursion, but in some situations
in programming, it is a must to use recursion
2. The recursion is very flexible in data structure like stacks, queues, linked list and quick
sort.
3. Using recursion the length of the program can be reduced.

Disadvantages of Recursion
1. It requires extra storage space. For every recursive calls, separate memory is allocated
to automatic variables with the same name.
2. If the programmer forgets to specify the exit condition in the recursive function, the
program will execute out of memory.
3. The recursive function is not efficient in execution speed and time
4. If possible, try to solve problem with iteration instead of recursion.

Scope and Life time of a variable


The area or block of the C program from where the variable can be accessed is known as Scope
of variables. The area or scope of the variable depends on its storage class, i.e. where and how
it is declared. There are four scope variables
(i) Function
(ii) File
(iii) Block
(iv) Function Prototype

The storage class of a variable tells the compiler


(i) The storage area of a variable
(ii) The initial value of a variable if not initialized
(iii) The scope of a variable
(iv) The life of a variable

Life time of a Variable


Life time means how long the variable will exist (i.e. keep its value available).

103 BPS College Piramadom


Methodology of Programming and C Language

Visibility of a Variable
Visibility of a variable is another property. It defines its scope. The scope is of two types, i.e.
local and global.

Variables declared within a function are called local variables. The scope of such variable is limited
to the function where it is declared. Variables declared outside of all functions (declared at the
beginning of c program, before main function) is called global variable. Global variables are
accessible to all functions in the program. Global variables are also known as an external variable.
Example:
int m;
main()
{
int i;
float balance;
………
………
function1();
}
function1()
{
int i;
float sum;
………………
……………..
}

The variable m which has been declared before the main is called global variable. The variables i,
balance and sum are called local variables because they are declared inside a function. Note that
the variable i has been declared in both the functions. Any change in the value of i in one function
does not affect its value in the other.

Storage Class Specifiers


C provides a variety of storage class specifiers that can be used to declare explicitly the scope
and life time of variables.
The general form is:
storageSpecifier dataType variableName;

There are 4 storage class specifiers: auto, register, extern, static.

1. Automatic Variables
The auto variables refer to automatic variables. The auto variables are defined inside a
function. A variable declared inside a function without storage class name is, by default, an
auto variable. They are automatically created when function is called and automatically
destroyed when the function terminates. The lifetime of such variable is the time during which
the parent function is running. These variables have function scope; that is they are accessible
only within the parent function.

104 BPS College Piramadom


Methodology of Programming and C Language

Example:
void main()
{
auto int v=0;
call2();
printf(“v=%d”);
}
void call1()
{
auto int v=20;
printf(“v=%d”,v);
}
call2
Output
{
auto int v=30; V=20
V=30
call1();
V=10
printf(“v=%d”,v);
}

Explanation: In the above program, the variable ‘v’ is declared and initialized in three different
functions. Each function, when called, prints the local values of variable ‘v’.

2. External variables
The extern variables provide access from different files, if a program spreads over many files.
Thus the lifetime is the life of the entire program. The scope of such variable is file scope. The
variable declaration generally appears before main() and use of keyword extern is optional.

Example:
int j=4;
void main()
{
extern int j;
j=j*3;
printf(“j=%d”,j);
fun();
printf(“j=%d”,j); Output

} j=12
Fun() j=144
{
j=j*j;
}

Explanation: in the above program j is declared and initialized with 4. The second declaration
inside main with keyword extern indicates that it is declared already.

105 BPS College Piramadom


Methodology of Programming and C Language

3. Static Variables
The static variable may be of internal or external type, depending where it is declared. When a
variable is declared as static its garbage value is removed and initialized to NULL value. A static
variable is initialized only once. It is not destroyed when the function terminates, rather it
holds its value even after the functions termination.
Example:
void main()
{
for( ; ; )
print();
}
print()
{
int static m; Output
m++; m=1
printf(“m=%d”,m); m=2
if(m==3) m=3
exit(1);
}
Explanation: in the above program print function is called. The variable m of print() function is
the static variable. in the first call its value is changed from 0 to 1, in the second call from 1 to
2, and in the third call from 2 to 3.

4. Static External Variables


The static external variable can be accessed as external variables only in the file in which they
are defined. No other file can access the static external variables that are defined in another
file.

Example
#include<stdio.h>
#include<conio.h>
static int i;
int main()
{
i=20;
printf(“the value if i is %d”,i);
return 0;
}
Output
the value of i is 20

in the above program, the external variable ‘I’ is accessed within the scope of this program
only. Other files cannot access a static external variable that is defined in another file.

106 BPS College Piramadom


Methodology of Programming and C Language

5. Register Variables
The register variables are similar to auto variables except that the register variables provide
faster access, as they are stored inside CPU registers.
Example:
void main()
{
Output
register int m=1;
1 2 3 4 5
for( ; m<=5;m++)
printf(“\t%d”,m);
}
Explanation: in the above program variable ‘m’ is declared and initialized to 1. The for loop
displays values from 1 to 5. The register class variable is used as a loop variable.

Structure
A structure is a collection of one or more variables of different types, grouped together under a
single unit. It is a user defined data type.
The data items enclosed within a structure are known as members and they can be of the same
or different types.
Features of Structure
1. It is possible to copy the contents of all structure elements to another structure variable
of its type using assignment (=) operator.
2. Nesting of structure is possible
3. It is possible to pass structure elements to a function.
4. It is also possible to create structure pointers. For this -> operator is used.

Difference between Array and Structure


Array Structure
Collection of same type of data types Collection of different data types
Variable of a pre-defined data type User defined data type
Subscript is used to refer each element Dot operator is used to refer member elements
Only declaration Both declaration and definition
It is not a keyword struct is a keyword.
Does not have bit fields May contain bit fields

Structure Declaration and Definition


The syntax for declaring a structure is
struct structureName
{
dataType member1;
dataType member2;
………………………………
……………………………..
};
The structure declaration starts with the key word struct followed by a tag. The tag serves as a
structure name, an identifier that can be used for creating structure variables.

107 BPS College Piramadom


Methodology of Programming and C Language

The following is a structure declaration to hold the students information.


struct student
{
int roll;
char name[25];
char course[15];
};

Creation of structure variables


The structure tag is used as data type to create variable to handle record type data or grouped
data item.
Syntax:
struct structureName var1, var2, …………..;
The following statement creates variables of structure student.
struct student s1;

The structure variable can also be created during the declaration of a structure as follows
struct student
{
int roll;
char name[25];
char course[15];
} s1;

Accessing structure members


The period or dot ( . ) operator is used to access members of a structure.

Syntax:
structureVar .memberName;
Example:-
s1.roll;
s1.name;
s1.course;

Initialization of structure
Structure can be initialized as:
struct student s1 = ,1,”amit”,”BCA”);

Here all the members of structure are related to variable s1.

We can directly assign values to members as given below:


s1.roll=1;
s1.name=”amit”;
si.course=”BCA”;

108 BPS College Piramadom


Methodology of Programming and C Language

Program to store name, rollno and marks of 3 subjects of a student into a structure and print it.
void main( )
{
struct student
{
int rno;
char name[20];
int m1;
int m2;
int m3;
};
struct student s;
printf(“Enter rollno, name and 3 marks”);
scanf(“%d%s%d%d%d”, &s.rno, s.name, &s.m1, &s.m2, &s.m3);
printf(“Roll No = %d \n”, s.rno);
printf(“Name = %s \n, s.name);
printf(“Mark1 = %d \n”, s.m1);
printf(“Mark2 = %d \n”, s.m2);
printf(“Mark3 = %d \n”, s.m3);
getch();
}

Array of Structures
It is possible to define array of structures, each array element is similar to a variable of that
structure. The syntax for defining an array of structure is

structureName arrayName [size];

The syntax for accessing a particular member of the structure of an element of the array is
arrayName [subscript] . memberName;
Example:- struct book
{
char name[10];
float price;
};
struct book b[10];
This provides space in memory for 10 structure variables of type book.

Pointer to Structure
We can define pointer to structure. Here, starting address of the member variables can be
accessed. Thus, such pointers are called structure pointers.
Example: struct book
{ char name[25];
char author[25];
int pages;
};
struct book *ptr;

109 BPS College Piramadom


Methodology of Programming and C Language

In the above example, *ptr is pointer to structure book. The syntax for using pointer with
member is as given below:

ptr -> name


ptr-> author
ptr->pages

Program to declare pointer to structure and display the contents of the structure
void main()
{
struct book
{
char name[25];
char author[25];
int pages;
};
struct book b1=,“c language”,”ashok n”,672-;
struct book *ptr;
ptr=&b1;
printf(“%s by%s of %d pages”, ptr->name,ptr->author,ptr->pages);
}

Output
c language by ashok n of 672 pages

Explanation: to print structure elements using pointer an arrow operator (->) is used. The
reason is that ptr is not a structure variable but pointer to a structure.

Structures and Functions


Structure variables may be passed to the function by value or address just like any other
variables. It is also possible for functions to return structure through the use of the return
statement. Any number of structure variables can be passed to the function as arguments in
the function call, but only one structure variable can be returned from the function by return
statement. whenever a structure element requires to pass to any other function, it is essential
to declare the structure outside the main() function, i.e. global.
Syntax:
struct book
{
char name[35];
char author[35];
int pages;
}; b1;
void main()
{
------------

110 BPS College Piramadom


Methodology of Programming and C Language

------------
show(&b1);
--------------
--------------
}
show(struct book *b2)
{
---------------
---------------
}
Example: Program to pass address of a structure variable to a user defined function and
display the contents.
struct book
{
char name[25];
char author[25];
int pages;
};
void main()
{
struct book b1=,“c language”,”ashok n”,672-;
show(&b1);
}
show(struct book *b2)
{
printf(“%s by%s of %d pages”, b2->name,b2->author,b2->pages);
}
Output
c language by ashok n of 672 pages

Union
union is a variable, which is similar to the structure. it contains number of members like
structure but it holds only one object at a time.
The syntax for union is identical to that for structures. In structure each member has its own
storage location whereas all the members of union use the same location. This implies that
although a union may contain members of different types it can handle only one member at a
time. A union is declared using the keyword union.

Example:- union sample


{
int integer;
float real;
} example;

111 BPS College Piramadom


Methodology of Programming and C Language

This declares a variable example of the type union sample. The members of example are
referred to as example. Integer and example.real.

If a value is assigned to example.integer then the value is placed in integer format. A union can
contain as many members as desired, of any type, but it allocates only enough memory to hold
the largest member.

Example: write a program to find the size of union and the number of bytes reserved for it.
void main()
{
union result
{
int marks;
char grade;
};
struct res
{
char name[15];
int age;
Output
union result perf;
size of union: 2
}
size of structure: 19
data;
printf(“size of union:%d\n”, sizeof(data.perf));
printf(“size of structure:%d\n”,sizeof(data));
}

Explanation: union contains two variable of data type int and char. The int and char require 2
bytes and 1 byte, respectively, for storage. The union reserves two bytes because int takes
more space than the char type.
The structure res is defined immediately after union, which contains data types char, int and
union variable. the total size of structure is 19, i.e. sum of 15 bytes of char array, two bytes of
int and two bytes of union variable perf.

Self Referential Structures


A structure having reference to itself is called self-referential structure. It is a special type of
structure in which one members of the structure is a pointer variable of the same structure
type.

Example:- struct student


{
int roll;
char name[20];
student *ptr;
}s1;

112 BPS College Piramadom


Methodology of Programming and C Language

Now ptr can hold the address of a structure variable of the type student. The element ptr can
be accessed by the expression s1.ptr and the element roll of the structure variable pointed to
by ptr is referenced by s1.ptrroll

The #define preprocessor directive


The preprocessor directive #define associates a constant value to a symbol and is visible
throughout the module in which it is defined. The symbols defined using #define are called
macros.

Syntax
#define symbolic-name value of constant;

Example:
#define pi 3.14
#define max_val 100

typedef
c supports a feature known as type definition that allows users to define an identifier that
would represent an existing data type. The user-defined data type identifier can later be used
to declare variable.

General form
typedef type identifier;

where type refers to an existing data type and identifier refers to the new name given to the
data type. Typedef cannot create a new data type.

Example:- typedef float marks;


Here marks symbolizes float. It can be later used to declare variables as follows:
marks hindi,it;
Here hindi, it are declared as floating point variables. The main advantage of typedef is that we
can create meaningful data type names for increasing the readability of the program.

Example
#define h 60
void main()
{
typedef int hours;
hours hrs;
printf(“enter hours:”);
scanf(“%d”,&hrs);
printf(“minutes=%d”,hrs*h);
}
Output
enter hours: 2
minutes = 120

113 BPS College Piramadom


Methodology of Programming and C Language

Bit Fields
Bit field provides exact amount of bits required for storage of values. If a variable value is 0 or 1
then a single bit is needed to store it. Similarly if the value is between 0 and 3 then 2 bits are
needed. In the same way if the value is between 0 and 7 then three bits will be sufficient to
hold the variable and so on.
An integer variable uses 2 bytes to hold data. Instead of using complete integer if bits are used,
space of memory can be saved.
For example, to know the information about a vehicle, the following information has to be
stored in memory
1. Petrol vehicle
2. Diesel vehicle
3. Two wheeler vehicle
4. Four wheeler vehicle
5. Old model
6. New model
In order to store the status of the above information, we may need 2 bits for the type of fuel
(petrol or diesel). Three bits for its type as to whether the vehicle is a two wheeler or four
wheeler. Similarly, 3 bits for model of the vehicle. Total bits required for storing the
information would be 8 bits, i.e. 1 byte.
The structure for the above problem would be as follows:
struct vehicle
{
unsigned type: 3;
unsigned fuel: 2;
unsigned model: 3;
};

The colon(:) tells the compiler that bit fields are used in the structure and the number after it
indicates how many bits are required to allot for the field.
Program:

#define petrol 1
#define diesel 2
#define two_wh 3
#define four_wh 4
#define old 5
#define new 6
void main()
{
struct vehicle
{
unsigned type: 3;
unsigned fuel: 2;
unsigned model: 3;
};

114 BPS College Piramadom


Methodology of Programming and C Language

struct vehicle v;
v.type=four_wh;
v.fuel=diesel;
v.model=old;
printf(“\n Type of vehicle: %d”, v.type);
printf(“\n Fuel: %d”, v.fuel);
printf(“\n Model: %d”, v.model);
getch();
}
Output
Type of vehicle: 4
Fuel:2
Model:5

enum (enumerated data type)


An enumerated data type is a user defined data type, with values ranging over a finite set of
identifiers called enumeration constants. The keyword enum is used to define such a type.

Syntax
enum identifier ,value1, value2, …….. value n-;

The identifier can be used as the data type that represents the list of values separated by
commas. The compiler automatically assigns integer digits beginning with 0 to all the
enumeration constants.
Example: enum week {sun,mon,tue,wed,thu,fri,sat};

The above statement creates an enumerated data type week, by which 7 identifiers are
assigned 7 values called ordinal values 0,1,2,3,4,5,6. The number 0 is given to the identifier sun,
1 is given to mon, 2 is given to tue, …………….., and 6 is given to sat. These are the default
ordinal values.
The format specifier for enum is %d and the range is -32768 to +32767

Changing Ordinal values

The default ordinal values of the enumerators can be changed by explicitly specifying them for
the identifiers.
Example: enum color {red=5, green, blue=10};

In the above definition, the enumerators red and blue are assigned with the specified values,
whereas green will be assigned the value 6.

Enumerated variable declaration

The enumerated data type is used to declare variables like any other data types. The following
statement creates a variable day of the type week.
week day;

115 BPS College Piramadom


Methodology of Programming and C Language

Internally c compiler treats day as integer and hence 2 bytes of memory will be allocated for it.
Use of enumeration constants, in general makes the program easier to read.

Example: 1) day = mon;

2) if (day==sun) printf(“holiday”);
Example:
void main()
{
enum month
{ jan=1, feb,mar,apr,may,june,july,aug,sep,oct,nov,dec };
printf(“\n Jan = %d”, jan);
printf(“\n Feb = %d”, feb);
printf(“\n Dec = %d”, dec);
}

Output
Jan = 1
Feb = 2
Dec = 12

Dynamic Memory Allocation


The method of allocation of memory at the time of execution of a program is called dynamic
memory allocation. Acquiring main memory by a program and freeing it are done by some
library functions provided in c .
The free region of the memory is called heap. The size of heap changes during execution of
programs. This is due to creation and destruction of variables.

Memory Allocation Process


The following figure shows the storage of conceptual view of storage of a c program in
memory.

Local variables Stack


Free memory Heap
Global variables
Permanent storage area
C program

The instructions and global and static variables are stored in a region known as permanent
storage area and the local variables are stored in another area called stack. The memory space
that is located between these two regions is available for dynamic allocation during execution
of the program. This free memory region is called the heap. The size of the heap keeps
changing when program is executed due to creation and death of variables that are local to
functions and blocks.

116 BPS College Piramadom


Methodology of Programming and C Language

Memory Models
The memory model specifies the memory size assigned to each of the different parts or
segments of a program. The memory model directive specifies the size of the memory the
program needs. Based on this directive, the compiler assigns the required amount of memory
to data and code.
Each one of the segments (stack, data and code), in a program, is called a logical segment.
Depending on the model used, segments may be in one or in different physical segments.
There are six types of memory models.

1. Tiny: Tiny model places all data and code in a single segment. Therefore, the total
program file size can occupy no more than 64KB. Programs are executed quickly in this
case.
2. Small: Small model supports one data segment and one code segment. Used when
code under 64KB is and data is under 64KB. Execution speed is same as tiny model.
3. Medium: Medium model supports multiple code and single data segments. Used when
code is over 64KB and data is under 64KB. Fast access to data but slower program
execution.
4. Compact: Compact model supports multiple data segments and a single code segment.
Used when code is under 64KB and data is over 64KB. Slow access to data and quick
code execution.
5. Large: Large model supports multiple code and multiple data segments. Used when
code is over 64KB and data is over 64KB. No single data item can exceed 64KB. There is
slower code execution.

6. Huge: Huge model supports multiple code and multiple data segments. Used when
code is over 64KB and data is over 64KB. Single data item can exceed 64KB. There is
slowest code execution.

Memory allocation functions


In c there are 4 library functions under "stdlib.h" and “alloc.h” for dynamic memory allocation.
Function Use of Function
malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
Allocates space for an array elements, initializes to zero and then returns a pointer to
calloc()
memory
free() deallocate the previously allocated space
realloc() Change the size of previously allocated space

1. malloc()
This function is used to allocate memory space in bytes to the variables of different data types.
The function reserves bytes of determined size and returns the base address to pointer
variable. The format of malloc() is:
pnt = (data type*) malloc(given size);
Example:
pnt = ( int * ) malloc(20);

117 BPS College Piramadom


Methodology of Programming and C Language

Here, 20 bytes are allocated to pointer variable pnt of type int and base address is returned to
pointer pnt.

Example: program to allocate memory to a pointer variable based on the number of subjects
marks to be entered. Compute average marks.

#include<alloc.h>
void main()
{
int k,*p,j=0,sum=0;
float avg;
puts(“how many subjects marks to be entered:”);
scanf(“%d”,&k);
p=(int *) malloc(k * sizeof(int));
while(j!=k)
{
printf(“subject %d marks=”,j+1);
scanf(“%d”,p+j); Output
j++; how many subjects marks to be entered: 5
} subject 1 marks=88
j=0; subject 2 marks=89
printf(“sum of marks :”); subject 3 marks=90
while(j!=k) subject 4 marks=91
sum=*(p+j++)+sum; subject 5 marks=92
printf(“%d”,sum);
avg=sum/k; sum of marks : 445
printf(“average marks=%f:”,avg); average marks =89.000000
getch();
}
Explanation: the size declared by sizeof function and the number entered (k) are multiplied and
the result obtained is nothing but the number bytes to be allocated to a pointer ‘*p’. The
pointer ,*p, contains the base address. The first ‘while’ loop reads marks of the subjects
through the keyboard. Each time while entering the marks, ‘j’ variables value is added to
pointer ‘*p’, which indicates successive address of its type and entered subjects marks are
stored in the successive locations. This process continues till the value of ‘j’ reaches to ‘k’. Thus
in a single variable by allocating memory, a programmer can store multiple subjects marks. In
the second while loop, sum and average of marks are calculated.

2. calloc()
This function is useful for allocating multiple blocks of memory. It is declared with two
arguments. The prototypes are declared in alloc.h and stdlib.h. the format of calloc is as
follows:
pnt = (int *) calloc(4,2);

118 BPS College Piramadom


Methodology of Programming and C Language

The above declaration allocates four blocks of memory; each block containing two bytes. The
base address is stored in the integer pointer. This function is usually used for allocating
memory for array and structure.

Example: Program to allocate memory based on requirement of the number of books to a


pointer variable using the calloc( ) function.

#include<alloc.h>
void main()
{
int k,j=0,sum=0;
int *p;
puts(“how many books to be purchased”);
scanf(“%d”,&k);
p = (int *) calloc(k,2);
while(j!=k)
{ Output
printf(“cost of the book (%d)=”,j+1); how many books to be purchase: 4
scanf(“%d”,p+j); cost of the book (1) = 100
sum=sum+*(p+j); cost of the book (2) = 200
j++; cost of the book (3) = 400
} cost of the book (4) = 500
printf(“total cost of books:”); total cost of books: 1200
printf(“%d”,sum);
}

Explanation: in the above program the function calloc() is used to allocate the memory instead
of malloc().

3. free()
The free() function is used to release the memory if not required. Thus the wastage of memory
is prevented. The declaration is as follows:
free(pnt);
The free() function releases the memory occupied by the pointer variable pnt.

Example: Based on the requirement of the number of e-books, write a program to allocate
memory using calloc() and release it using free(). Display the memory locations where cost of
the each e-book is stored and total cost of e-books.

#include<alloc.h>
void main()
{
int j=0,k=5;
int *p;
float sum=0.0;

119 BPS College Piramadom


Methodology of Programming and C Language

p=(int *) calloc(k * sizeof(int),2);


Output
printf(“first location %u”,p); first location 3176
printf(“\n”); cost of the e-book (1) = 1000
while(j != k) (1) location 3176
{ cost of the e-book (2) = 2000
printf(“cost of the e-book(%d)=”,j+1); (2) location 3178
scanf(“%d”,p+j); cost of the e-book (3) = 3000
printf(“(%d) location %u \n”,j+1, p+j); (3) location 3180
sum=sum+*(p+j); cost of the e-book (4) = 4000
(4) location 3182
j++
cost of the e-book (5) = 5000
}
(5) location 3184
printf(“\n total cost of the e-books:”);
total cost of the e-books: 15000
printf(“%g”,sum); after freeing the memory the location:3176
free(p);
printf(“\n after freeing the memory the location:%u”,p);
}

Explanation: program logic is same as used in the earlier programs where calloc() is used. The
function free() is used for freeing the memory.

4. realloc( )
This function reallocates the main memory. This is needed as and when allocated memory is
different from the required memory. The prototype are declared in alloc.h and stdlib.h. if the
block cannot be reallocated or size==0, realloc() returns NULL. The declaration of function is as
follows:
str = (char*) realloc (str, 30)

In the above declaration, str is a pointer. The realloc() function reallocates the memory
previously allocated by pointer variable str to the new size 30.

Program
#include<alloc.h>
#include<string.h>
void main()
{
char *str;
str = (char *)malloc(6);
str = (“india”);
printf(“str = %s”, str);
str = (char *)realloc(str,30);
strcpy(str, “great researchers of india”);
printf(“now str=%s”,str); Output
free(str); str = india
} now str = great researchers of india

120 BPS College Piramadom


Methodology of Programming and C Language

Explanation: In the above program, using malloc() function 6 bytes are allocated to character
pointer str. the character pointer is initialized with string ‘india’. Using realloc() function the
pointer contains 30 bytes. The pointer str is again initialized with ‘ great researchers of india’.

5. coreleft( )
This function returns a measure unused memory. If the memory model declared is tiny, small
or medium, then follow the function declaration as per statement (a). if the memory model
selected is compact, large or huge, follow the declaration (b).

(a) unsigned coreleft(void);


(b) unsigned long coreleft (void);

Example:
#include<alloc.h>
void main()
{
clrscr();
printf(“measuer of unused memory = %u”, coreleft( ));
}

Output
measure of unused memory = 56936
Explanation:
In the above program, the coreleft( ) is invoked without any argument. The function displays
unused memory i.e. 56936

Header files and Library functions


Character functions (ctype.h)
Function Use
isalnum() Tests alphanumeric character
isalpha() Tests for alphabetic character
isdigit() Tests for decimal digit
islower() Tests for lowercase character
isupper() Tests for uppercase character

Mathematical Functions
Some standard mathematical functions under math.h header file
Function Use Example
sqrt() Finds square root sqrt(25) will return 5
pow() Calculates a value raised to a power pow(x,y) means xy
abs() Returns the absolute value of a number abs(-5) will return 5
log() Finds natural logarithm log(a)
log10() Finds base 10 log log10(b)
floor() Rounded down to the nearest integer floor(1.23)
ceil() Rounded up to the nearest integer ceil(a)
sin() Calculates sin sin(a)
cos() Calculates cosine cos(a)
tan() Calculates tangent tan(a)

121 BPS College Piramadom


Methodology of Programming and C Language

Date and time functions (time.h)


Function Use
time() Gets current system time
getdate() Gets system date
difftime() Computes the difference between two times

Department of Computer Applications | Baselios Poulose Second College Piramadom : 2020– ‘21

SPJ

Model Questions
Short Answer (2 marks)

1. What is algorithm?
2. What are the different types of algorithm?
3. What is a sub program?
4. Differentiate between syntax errors and logic errors.
5. What is testing a program? Why do we need to test a program?
6. What is alpha and beta version of a software?
7. Differentiate between testing and debugging.
8. What do you mean by data type?
9. What is pseudo code?
10. What is an assembler?
11. Differentiate implicit and explicit conversions in c.
12. Give an example for input operator in c.
13. What is a string?
14. What is loop?
15. Write the statement to create a constant in c.
16. What are the logical operators used in c?
17. Distinguish between break and continue statements.
18. What are the parameter passing techniques used in c?
19. What is an expression?
20. How is a variable declared to be a pointer?
21. What is the difference between the type int and unsigned int in c?
22. How do you define a constant in a c program?
23. What is wrong in the following program segment?
for (i = 0; i <10; i++)
, ……………….
………………….
i++;
…………………
}

122 BPS College Piramadom


Methodology of Programming and C Language

24. Define identifier in c.


25. What is meant by logical operators?
26. What is typedef statement?
27. What do you mean by entry controlled loop?
28. How do you initialize a pointer?
29. Point out the types of integers.
30. What is branching?
31. What is operator?
32. What is meant by conditional operator?
33. Define keyword in c?
34. What is a token?
35. What is object code?
36. What is dynamic memory allocation?
37. Describe bit fields in c.
38. What is operator precedence?

Short Essay (5 marks)


39. What are the characteristics of a good programming language?
40. What are the factors for selecting a language?
41. Explain the use of structure.
42. How does structure differ from arrays?
43. What is flow chart? What is its use?
44. Differentiate compiler and interpreter.
45. What is machine language? What are the advantages and limitations of machine
language?
46. What is a linker? Why it is required?
47. Explain different operators in c.
48. What is function in programs?
49. Describe the use of array.
50. What is union in c?
51. Describe the use of pointers in c.
52. What is enumerated data type?
53. What are the data types used in c?
54. Distinguish between scope and lifetime of a variable.
55. What are the escape sequences used in c?
56. Define external variable in c.
57. What are user defined functions?
58. Differentiate call by value and call by reference method.
59. How do you declare character strings in c?
60. Write a set of statements to exchange the values of two integer variables x and y.
61. Define local variables in c.
62. Explain printf() and scanf() statements in c.
63. Explain formatted and unformatted I/O functions in c.
64. Explain void, wild and constant pointers.

123 BPS College Piramadom


Methodology of Programming and C Language

65. What are the storage class specifiers?


66. Explain memory models.
67. Explain dynamic memory allocation functions in c.
68. What is a global variable?
69. Explain logical and bitwise operators in c.
70. Explain switch statement.
71. What is recursion?
72. How can you pass a structure to a function?
73. Explain direct and indirect recursion.
74. What are constants? Point out different types.
75. Differentiate between recursion and iteration.
76. What are the rules for recursive function?
77. What are the advantages and disadvantages of recursion?
78. Explain pointers and arrays in detail.

Long Essay (15 marks)

79. Describe the features of c language.


80. Explain different types of tokens in c.
81. Explain the steps in program development.
82. Describe the use of pointers in c?
83. What are the decision making statements used in c?
84. What are the string manipulation functions used in c?
85. Write a program to sort a group of numbers in ascending order.
86. Describe the structure of a c program.
87. Draw the flowchart to find the sum of 10 numbers.
88. What are header files? Give suitable example and explain?
89. Write a c program to read n integers and separate them into even and odd numbers.
90. Describe the data types used in c language.
91. Explain the use of file in c.
92. Explain string manipulation functions.
93. Explain the use of user defined functions.
94. What are the looping statements in c?
95. Explain different types of computer languages in detail.
96. Explain array in detail.
97. Explain different array operations.
98. What is an array of structures? Why do you use it?
99. Explain the different category of functions.
100. Explain different operators in c.

Department of Computer Applications,


Baselios Poulose Second College Piramadom

124 BPS College Piramadom

You might also like