[go: up one dir, main page]

0% found this document useful (0 votes)
38 views140 pages

C Notes

The document discusses different types of computer languages: 1) Machine language is directly understood by computers but difficult for humans. 2) Assembly language uses mnemonics instead of binary but requires assembly. 3) High-level languages like C, C++, and Java are easier for humans but require compilation to machine language.

Uploaded by

arafaiic2022
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)
38 views140 pages

C Notes

The document discusses different types of computer languages: 1) Machine language is directly understood by computers but difficult for humans. 2) Assembly language uses mnemonics instead of binary but requires assembly. 3) High-level languages like C, C++, and Java are easier for humans but require compilation to machine language.

Uploaded by

arafaiic2022
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/ 140

Methodology of Programming & C Language BCA/BSc CS

METHODOLOGY OF PROGRAMMING
AND C LANGUAGE (CORE)

BCA/BSc Computer Science


Semester 1

1 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

METHODOLOGY OF PROGRAMMING AND C LANGUAGE (CORE)


UNIT 1
Introduction to programming, Classification of computer languages, Language translators
(Assembler, Compiler, Interpreter), Linker, Characteristics of a good programming language,
Factors for selecting a language, Subprogram, Purpose of program planning, Algorithm, Flowchart,
Pseudo code, Control structures (sequence, selection, Iteration), Testing and debugging. (12 hours)
UNIT 2
C Character Set, Delimiters, Types of Tokens, C Keywords, Identifiers, Constants, Variables, Rules
for defining variables, Data types, C data types, Declaring and initialization of variables, Type
modifiers, Type conversion, Operators and Expressions- Properties of operators, Priority of
operators, Comma and conditional operator, Arithmetic operators, Relational operators, Assignment
operators and expressions, Logical Operators, Bitwise operators. (12 hours)
UNIT 3 (15 hours)
Input and Output in C – Formatted functions, unformatted functions, commonly used library
functions, Decision Statements If, if-else, nested if-else, if-else-if ladder, break, continue, goto,
switch, nested switch, switch case and nested if, Loop control- for loops, nested for loops, while
loops, do while loop.
UNIT 4
Array, initialization, array terminology, characteristics of an array, one dimensional array and
operations, two dimensional arrays and operations. Strings and standard functions, Pointers, Features
of Pointer, Pointer and address, Pointer declaration, void wild constant pointers, Arithmetic
operations with pointers, pointer and arrays, pointers and two dimensional arrays. (15 hours)
UNIT 5
Basics of a function: function definition, return statement, Types of functions, call by value and
reference. Recursion -Types of recursion, Rules for recursive function, direct and indirect recursion,
recursion vs iterations, Advantages and disadvantages of recursion. Storage class, Structure and
union, Features of structures, Declaration and initialization of structures, array of structures, Pointer
to structure, structure and functions, typedef , bitfields , enumerated data types, Union, Dynamic
memory allocation, memory models, memory allocation functions.. (18 hours)
Book of Study:
1. Ashok Kamthane - Programming in C, Third Edition, Pearson Education
2. P K Sinha & Priti Sinha - Computer Fundamentals, Fourth Edition, BPB Publications.

2 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

MODULE 1
Introduction to programming
A program is a set of instructions given to a computer to perform a specific operation. This
code is written by programmers. Programming is the process of giving machines a set of instructions
that describe how a program should be carried out. While executing the program, raw data is
processed into the desired output format.
These computer programs are written in a programming language which is high-level
languages. High level languages are nearly human languages that are more complex than the
computer understandable language which are called machine language, or low level language. So
after knowing the basics, we are ready to create a very simple and basic program. Like we have
different languages to communicate with each other, likewise, we have different languages like C,
C++, C#, Java, python, etc. to communicate with the computers. The computer only understands
binary language (the language of 0’s and 1’s) also called machine-understandable language or low-
level language but the programs we are going to write are in a high-level language which is almost
similar to human language.
Classification of computer languages
They are of three types
1. Machine Language ( Low level language)
2. Assembly language
3. High level language
Machine Language
Machine Language is the only language which can be understood by the computer. Machine
Language is also known as Low-level language. All the instructions of machine language are written
in the form of binary numbers 1's & 0's. A computer can directly understand the machine language.
A machine language usually has two parts as shown in the following figure.

The first part is the operation code, which tells the computer what function to perform, and
the second part is the operand, which tells the computer where to find or store the data. Every
language has a set of operation codes, called its instruction set. Typical operations included in the
instruction set of a computer are as follows:
 Arithmetic operations
 Logical operations
 Data movement operations for moving data between memory locations.

3 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

 Data movement operations for moving data from or to one of the computer’s
input/output devices.
Advantages and Limitations of Machine language
Programs written in machine language can be executed very fast. This is because machine
instructions are directly understood by the computer, and no translation is required.
Limitations
 Machine Dependent
Because the internal design of every computer is different, the machine language also differs
from computer to computer.
 Difficult to program
Machine language programs are directly and efficiently executed by the computer, it is
difficult to program in machine language. It is necessary for the programmer to memorize
the dozens of operation codes for the commands in the machine’s instruction set.
 Error prone
For writing programs in machine language, since the programmer has to define the opcodes
and must keep track of the storage locations of data and instructions, it becomes very difficult
for him to concentrate fully on the logic of the problem. This results in program errors.
 Difficult to modify
It is difficult to modify a machine language program. Checking instructions to errors is very
difficult and time consuming.
Assembly language
Assembly language is a computer language in which the instructions are created using
symbols such as letters, digits and special characters. A program written in assembly language is
called assembly language program. In assembly language, we use predefined words called
mnemonics. Binary code instructions in low-level language are replaced with mnemonics and
operands in middle-level language. But the computer cannot understand mnemonics, so we use a
translator called Assembler to translate mnemonics into machine language.
Assembly languages use numbers, symbols, and abbreviations instead of 0’s and 1’s.For
example: For addition, subtraction and multiplications it uses symbols likes ADD, SUB and MUL
etc.

4 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Advantages and disadvantages of Assembly language


Advantages
 The bugs in assembly language can be easily tracked and solved.
 The mistakes in assembly language are fewer compared to other languages.
 Assembly language is not portable; therefore differently used in different computers.
 It can perform and compile more complex tasks.
Disadvantages
 The syntax used in assembly language is complicated to learn.
 The code written in assembly language is lengthy and takes more time and effort to write and
compile code.
 The programmer needs knowledge regarding hardware before coding.
 It is a machine dependent language.
High-level language
High-level language is a computer language which can be understood by the users. The high-
level language is very similar to human languages and has a set of grammar rules that are used to
make instructions more easily. Every high-level language has a set of predefined words known as
Keywords and a set of rules known as Syntax to create instructions. The high-level language is
easier to understand for the users but the computer cannot understand it. High-level language needs
to be converted into the low-level language or machine language to make it understandable by the
computer. We use Compiler or interpreter to convert high-level language to machine language.
Some of the high level languages are FORTRAN, BASIC, COBOL, PASCAL, C, C++,
JAVA etc.

Advantages
 Ease of use: High-level programming languages are designed to be user-friendly and easy to
learn. They use simple, intuitive syntax and are easier to read and understand than low-level
languages.
 Portability: High-level languages are platform-independent, meaning that they can run on
any operating system without modification. This makes them ideal for developing
applications that can be used on multiple devices and platforms.
 Efficiency: High-level languages are designed to be more efficient than low-level languages,
as they abstract hardware-specific functions and low-level details. This makes them easier to
optimize and more efficient in terms of memory usage and execution time.

5 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Disadvantages
 Slower execution: High-level languages are generally slower than low-level languages, as
they require more processing time to convert their code into machine code.
 Higher Memory Usage: High level language requires more memory than low level
languages as they use additional functions and structures.

Language translators
Computer knows only machine language, so other language programs should be converted
into an equivalent machine language program. For conversion some translators are used. They are
given below.
 Assembler
 Compiler
 Interpreter
Assembler
An assembler of a computer system is a system software supplied by the computer
manufacturer, and translates an assembly language program into machine language instructions. It
is so called because, in addition to translating an assembly language program into its equivalent
machine language program, it also, “assembles” the machine language program in the main memory
of the computer, and makes it ready for execution. The output of an assembler is called an object
file, which contains a combination of machine instructions as well as the data required to place these
instructions in memory. The translation is shown ion the following figure.

During the process of translation of a source program into equivalent object program by the
assembler, the source program is not being executed. It is only being converted into a form which
can be executed by the computer’s processor.
Compiler
A Compiler is a translator which translates a high-level program into its equivalent machine
language program. A compiler will consider the entire program as a whole code and then translates.
The main job of the compiler is that it checks all kinds of limits, ranges, errors, etc. Before the
compiler can successfully execute the code, the errors must be removed from the source code.
Example of compiled languages is C, C++, Java, C#, etc.

6 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Since high level language instructions are macro instruction, 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 a high level
language program into machine language program.
Compilers are large programs, resides permanently on secondary storage. When a source
program is to be translated, the compiler and the source program are copied from secondary storage
into the main memory of the computer. The compiler, being a program, is then executed with the
source program as its input data. It generates the object program as its output, which normally saved
in a file on secondary storage. Whenever there is a need to execute the program, the object program
is copied from secondary storage into main memory of the computer and executed.

Interpreter
Interpreter is a program that converts the high level language program into the machine
language program. The function of the interpreter and compiler is the same but the interpreter
translates one line at a time and executes it.
An interpreter is a program which translates statements of a program into machine code. It
translates only one statement of the program at a time. It reads only one statement of program,
translates it and executes it. Then it reads the next statement of the program again translates it and
executes it. While the compiler merely translates the entire source program into an object program,
and is not involved in its execution. The translation process is shown below.

7 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Difference between compiler and interpreter

Compiler Interpreter
Scans the entire program and translates it Translates program one statement at a
as a whole into machine code. time.
Compilers usually take a large amount of Interpreters usually take less amount of
time to analyze the source code. However, time to analyze the source code. However,
the overall execution time is the overall execution time is
comparatively faster than interpreters. comparatively slower than compilers.
Generates Object Code which further No Object Code is generated, hence are
requires linking, hence requires more memory efficient.
memory.
Programming languages like C, C++, Programming languages like JavaScript,
Java use compilers. Python, Ruby use interpreters.

Linker
In high level languages, some built in header files or libraries are stored. These libraries are
predefined and contain basic functions which are essential for executing the program. These
functions are linked to the libraries by a program called Linker. If linker does not find a library of a
function then it informs to compiler and then compiler generates an error. The compiler automatically
invokes the linker as the last step in compiling a program.

8 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Loader
Loader is a program that loads machine codes of a program into the system memory. In
computing, a loader is the part of an Operating System that is responsible for loading programs.
Because it places programs into memory and prepares them for execution. Loading a program
involves reading the contents of executable file into memory. Once loading is complete, the operating
system starts the program by passing control to the loaded program code. All operating systems that
support program loading have loaders. In many operating systems the loader is permanently resident
in memory.
Characteristics of a good programming language
Following are the characteristics of programming language
 Simplicity
The language must offer clear and simple concepts that facilitate its learning and application,
in a way that is simple to understand and maintain.
 Structuring
The language allows programmers to write their codes according to structured programming
concepts, to avoid creating errors.

 Modularity

Many programs can be broken down into a series of identifiable subtask. It is a good
programming practice to implement each of the subtasks as a separate program module. The use of
a modular programming structure enhances the accuracy and clarity of a program, and it facilitates
future program alterations.

 Portability (Machine Independent)


A program should be supported by many different computers. The program should compile
and run smoothly on different platforms. Because of rapid development in the hardware and the
software, these days platform change is a common phenomenon. So, portability is measured by how
a software application can be transferred from one computer environment to another without failure.
A program is said to be more portable if it is easily adopted in different computer systems.
Subsequently, if a program is developed only for a particular platform, then the life expectancy of
the program is seriously influenced.
 Maintainability
It is the process of fixing program errors and improving the program. If a program is easy to
read and understand, then its maintenance will be easier. It should also prevent unwanted works so
that the maintenance cost in the future will be low. It should also have quality to easily meet new

9 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

requirements. Maintainable software allows us to quickly and easily fix a bug, increase usability and
performance, add new features, make changes to support multiple platforms etc.
 Efficient
Program is said to be more efficient if it takes least amount of memory and processing time
and is easily converted to machine language. The algorithm should be more effective. Every program
needs certain processing time and memory to process the instructions and data. The program
efficiency is also high if it has high speed during runtime execution of the program.
 Reliable

The user's actual needs will change from time-to-time, so the program is said to be reliable if
it works smoothly in every version. It is measured as reliable if it gives same performance in all
simple to complex conditions.

 Cost Effectiveness

Cost Effectiveness is the key to measure the program quality. Cost must be measured over
the life of the program and must include both cost and human cost of producing these programs.

 Flexible

The program should be written in such a manner that it allows adding new features without
changing the existing module. The majority of the projects are developed for a specific period and
they require modifications from time to time. It should always be ready to meet new requirements.
Highly flexible software is always ready for a new world of possibilities.

Factors for selecting a language

Factors for selecting a good programming language:-

 Purpose
It specifies the objective for which the program is being developed. In the event one needs to
develop commercial applications, then a business oriented programming language like COBOL is
the best one.
 Programmer Experience
When more than one programming language is available for the development of the same
program, the programmer should choose the programming language as per his comfort level.
 Ease of development and maintenance
Any programmer always develop program using the language in which he feels comfort.
Generally the object oriented languages are preferred over the procedural oriented language.

10 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

 Suitability
Suitability of programming language can be checked on the base of these two points.
1) The programming language will work on all platforms.
2) The programming language has the appropriate features that are required.
 Performance and efficiency
The language in which the programs can be developed and executed rapidly should always
be preferred. In addition the language, which require less amount of memory for the storage of
programs should be chosen.
 Error checking
A programmer must choose a programming language, which contains efficient error handling
features.

Subprogram

Subprograms are small programs that are written within a larger, main program that can be
reused any number of times. The purpose of a subprogram is to perform a specific task.
Characteristics of a Subprogram:
 A Subprogram is implemented using the Call & Return instructions in Assembly Language.
 The Call Instruction is present in the Main Program and the Return (Ret) Instruction is present
in the subprogram itself.
 It is important to note that the Main Program is suspended during the execution of any
subprogram. Moreover, after the completion of the subprogram, the main program executes
from the next sequential address present in the Program Counter.
 The Main advantage of Subprogram is that it avoids repetition of Code and allows us to reuse
the same code again and again.

Purpose of program planning

Program planning is the outline of events and activities that follows to reach the goals.
Program planning involves multiple steps including the identification of a problem, selection of
desired outcomes, and assessment of available resources, implementation, and evaluation of the
program. Program planning is sometimes called program design or program design planning.
Algorithm
An algorithm is a finite sequence of instructions which can be carried out to solve a particular
problem in order to obtain the desired results.
 A finite sequence of instructions

11 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

 The program must be planned before writing.


 Represents the logic of the program
 Instructions are to be written in the proper sequence.
 Expressed in the programming language, becomes the program

Characteristics of an algorithm
An algorithm must satisfy the following criteria:
 Input: An algorithm has certain precise inputs. That is quantities which are specified to it
initially, before the execution of algorithms begin.
 Output: At least one quantity as output is produced.
 Finiteness: An algorithm terminates after a finite number of steps.
 Definiteness: Each instruction must be clear and unambiguous.
 Effectiveness: Every instruction must be very basic (division, multiplication, comparison
etc.) and can be performed exactly in a fixed duration of time.

Example 1: Algorithm for sum of two numbers


Step 1: Start
Step 2: Declare A, B, Sum.
Step 3: Read the values of A & B.
Step 4: Calculate Sum=A+B.
Step 5: Display the Sum.
Step 6: Stop.

Example 2: Swapping of Two Numbers


Step 1: Start.
Step 2: Declare A, B, C.
Step 3: Read the values of A & B.
Step 4: Assign C=A, A=B and B=C.
Step 5: Print A and B
Step 6: Stop.

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

12 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Algorithms

Based on repetitive steps Based on control transfer

Direct Indirect Deterministic Non-deterministic Random

Direct Algorithm:-
In this type of algorithm, the number of iterations is known in advance. For example, for
displaying numerical numbers from 1 to 10, the loop variable should be initialized from 1 to 10. The
statement would be as follows:
for (j=1; j<=10;j++)
In the above statement, it is predicted that the loop will iterate 10 times.
Indirect Algorithm:-
In this type of algorithm repetitively steps are executed. Exactly how many repetitions are to
be made is unknown.
For example, the repetitive steps are as follow:
i) To find the first Armstrong numbers from 1 to n,
ii) To find the first three palindrome numbers.
Based on the control transfer, the algorithms are categorized in the following three types.
Deterministic:-
Deterministic algorithm is based on either to follow a ‘yes’ path or ‘no’ path based on the
condition. In this type of algorithm when control comes across a decision logic, two paths ‘yes’ or
’no’ are shown. Program control follows one of the routes depending upon the condition.
Example:
Testing whether a number is even or odd. Testing whether a number is positive or negative.
Non-deterministic:-
In this type of algorithm to reach the solution, we have one of the multiple paths.
Example:

13 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

To find a day of the week.


Random algorithm:-
After executing a few steps, the control of the program transfer to another step randomly, this
is known as a random algorithm.
Example:
A random search
Flowchart
The flowchart is a diagram which visually presents the flow of data through processing
systems. The pictorial representation of a program/algorithm is also known as flowchart.
A completed flowchart enables you to organize your problem in to plan of action.
Commonly used flowchart symbols are shown below:-

General Rules for flowcharting


1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other entry points.
The exit point for all flowchart symbols is on the bottom except for the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom and one
side.
4. Generally a flowchart will flow from top to bottom. However, an upward flow can be shown
as long as it does not exceed 3 symbols.

14 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

5. Connectors are used to connect breaks in the flowchart. Examples are:


 From one page to another page.
 From the bottom of the page to the top of the same page.
 An upward flow of more than 3 symbols
6. Subroutines and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal
8. All flowcharts end with a terminal

Example1: Sum of two numbers entered by user

15 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Example 2: Greatest of two numbers.

Example3: Largest among three numbers.

Example 4: Fibonacci series up to N

16 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Example 5: Factorial of a number

Pseudo code
In pseudo codes English like words are used to represent the various logical steps. It is a
prefix representation. Here solution of each step is described logically. The pseudo code is just the
raw idea about the problem.
The meaning of pseudo code is false code. The syntax rule of any programming language cannot be
applied to pseudo code.
Example: Assume a and b are two numbers and find the larger out of them.

17 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Algorithm Pseudo code


Input a and b Get number a & b
Is a>b. Compare a &b
If yes a is larger than b. If a is large max=a.
If no b is larger than a. If b is large max=b.
Print the larger number Large number is max
Control structures
A control structure is like a block of programming that analyses variables and chooses a
direction in which to go based on given parameters. The term flow control details the direction the
program takes (which way program control "flows").
Hence it is the basic decision-making process in computing; it is a prediction.
Basically there are 3 types of control structures
 Sequence logic, or sequential flow
 Selection logic, or conditional flow
 Iteration logic, or repetitive flow
Sequential
Sequential logic as the name suggests follows a serial or sequential flow in which the flow
depends on the series of instructions given to the computer. (One line after another)

Selection
It selects a statement to execute on the basis of condition. Statement is executed when the
condition is true and ignored when it is false eg. if, if else, switch structures.

18 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Repetition:
In this structure the statements are executed more than one time. It is also known as iteration
or loop
eg:- while loop, for loop do-while loops etc.

Testing
Testing is the process of verifying and validating that a software or application is bug free,

meets the technical requirements as guided by its design and development and meets the user

requirements effectively and efficiently finding errors and identifying their causes, revising or

modifying the software and other components to eliminate errors, tracking the status of errors etc.

Testing is front end process intended to discover errors and problems.

Debugging

Debugging is the process of fixing a bug in the software. It can be defined as the identifying,

analyzing and removing errors. This activity begins after the software fails to execute properly and

concludes by solving the problem and successfully testing the software. It is considered to be an

extremely complex and tedious task because errors need to be resolved at all stages of debugging.

A method used for debugging is a single step control. By this technique, program is

executed step by step and intermediate results are observed. At a time only one instruction is

executed. This type of checking becomes very difficult and time consuming in case for a long

program, particularly when the error towards the end of the program. For such situations, there is

another technique called break point. In this technique, a break point, using a software interrupt

can be introduced at the suitable point in the program. When the breakpoint is inserted in a

program, the program is executed only up to the break point. So by inserting breakpoint at

19 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

appropriate points, the program can be checked and confirm that which part of the program contain

errors. The part which contains errors can be executed by single-step control method to find which

instruction contains errors. Other tools for debugging are given below:

 Simulators
 Logic Analyzers
 Trace routines
 Memory dumps

20 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

MODULE 2

A brief history of C

C is one of the high-level programming languages developed by Dennis Ritchie in 1972. C


is one of the most popular computer languages today because it is structured, high-level, machine
independent language. It allows software developers to develop programs without worrying about
the hardware platforms where they will be implemented.
The root of all modern languages is ALGOL (Algorithmic Language), introduced in
1960.ALGOL gave the concept of structured programming to the computer science community. In
1967, Martin Richards developed a language called BPCL (Basic Combined Programming
Language) primarily for writing system software. In 1970, Ken Thompson developed B language
using many features of BPCL language. B was used to create early versions of UNIX OS at Bell
Laboratories. C evolved from ALGOL, BPCL and B. C uses many concepts from these languages
and added concepts of data types and other powerful features.
Features of C
 Simple
C is a simple language in the sense that it provides a structured approach (to break the problem
into parts), the rich set of library functions, data types, etc.
 Machine Independent
C is a Machine Independent language. A language that can run on any machine is known as
a Machine Independent language.

 Structured
C is a structured programming language in the sense that we can break the program into
parts using functions. So, it is easy to understand and modify. Functions also provide code
reusability.

 Rich Library

C provides a lot of inbuilt functions that make the development fast.


 Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the
allocated memory at any time by calling the free() function.
 Speed
The compilation and execution time of C language is fast since there are lesser inbuilt
functions and hence the lesser overhead.

21 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

C Character Set
The characters which are used to form words, numbers and expressions in C are grouped
into the following two categories:
Source character
 Alphabets
 Digits
 Special Characters.
 White Spaces

Execution character set


 Escape Sequence

Delimiter
A delimiter in C is a unique character or string that marks the start or stop of a particular
statement, string, or function body set. Commas (,), semicolons (;), quotes (“”), braces ({}), pipes
(|), and slashes (/) are common delimiters in C.
Types of Tokens
Tokens in C are the most important element to be used in creating a program in C. We can
define the token as the smallest individual element in C. For `example, we cannot create a sentence
without using words; similarly, we cannot create a program in C without using tokens in C.
Therefore, we can say that tokens in C are the building block or the basic component for creating a
program in C language.
Tokens in C language can be divided into the following 6 categories:
 Keywords
 Identifiers
 Constants
 Strings
 Operators
 Special Symbols

22 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Keywords in C

Keywords in C can be defined as the pre-defined or the reserved words having its own
meaning, and these meanings cannot be changed. Since keywords are the pre-defined words used by
the compiler, so they cannot be used as the variable names. If the keywords are used as the variable
names, it means that we are assigning a different meaning to the keyword, which is not allowed. All
the keywords are written in lower case letters. C language supports 32 keywords given below:

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

Identifiers in C

Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers in C
are the user-defined words. It can be composed of uppercase letters, lowercase letters, underscore,
or digits, but the starting letter should be either an underscore or an alphabet. Identifiers cannot be
used as keywords. Rules for constructing identifiers in C are given below:
 The first character of an identifier should be either an alphabet or an underscore, and then it
can be followed by any of the character, digit, or underscore.
 It should not begin with any numerical digit.
 In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that
identifiers are case sensitive.
 Commas or blank spaces cannot be specified within an identifier.
 Keywords cannot be represented as an identifier.
 The length of the identifiers should not be more than 31 characters.

Eg: Amount, age, area,Volume1, Sum, etc..

Constants in C
A constant is a value assigned to the variable which will remain the same throughout the
program, i.e., the constant value cannot be changed.

23 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Types of constants in C

Constant Example

Integer constant 10, 11, 34, etc.

Floating-point constant 45.6, 67.8, 11.2, etc.

Octal constant 011, 077, 022, etc.

Hexadecimal constant 0x1a, 0x4b, 0x6b, etc.

Character constant 'a', 'b', 'c', etc.

String constant "c", "c++", ".net", etc.

There are two ways of declaring constant:


 Using const keyword
 Using #define pre-processor
Backslash character constant
C supports some special character constants that are used in output functions. A list of
backslash character constants are given below:
‘\n’ – Newline
‘\t’ – Horizontal Tab
‘\’’ – Single quote
‘\”’ – Double quote
‘\0’ – Null
The backslash tells the computer to escape from the way that characters would normally be
worked. Therefore the combination of a backslash and this special character are called as escape
sequences.
Strings in C
Strings in C are always represented as an array of characters having null character '\0' at the
end of the string. This null character denotes the end of the string. Strings in C are enclosed within
double quotes, while characters are enclosed within single quotes. The size of a string is a number
of characters that the string contains.
Eg: “Hello”
char a[10] = {'W','E','L','C','O','M','E','\0'};
Operators in C

24 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Operators in C are special symbol used to perform the functions. The data items on which
the operators are applied are known as operands. Operators are applied between the operands.
Depending on the number of operands, operators are classified as follows:
Unary operator
A unary operator is an operator applied to the single operand. For example: increment
operator (++), decrement operator (--), sizeof, (type)*.
Binary Operator
The binary operator is an operator applied between two operands. The following is the list of
the binary operators:

 Arithmetic Operators

 Relational Operators

 Logical Operators

 Bitwise Operators

 Conditional Operators

 Assignment Operator

 Increment/Decrement operator

 Misc. Operator (size of ( ))

Special Symbols
Some special symbols are used in C, and they have a special meaning which cannot be used for
another purpose.
 Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
 Simple brackets ( ): It is used in function declaration and function calling. For example,
printf() is a pre-defined function.
 Curly braces { }: It is used in the opening and closing of the code. It is used in the opening
and closing of the loops.
 Comma (,): It is used for separating for more than one statement and for example, separating
function parameters in a function call, separating the variable when printing the value of more
than one variable using a single printf statement.
 Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes that we
are using the header file.
 Asterisk (*): This symbol is used to represent pointers and also used as an operator for
multiplication.
 Period (.): It is used to access a member of a structure or a union.
Variables

25 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Variables are data names that may be used to store data values. A variable is a name of the
memory location. It is used to store data. Its value can be changed, and it can be reused many times.

Syntax
data type variable name;

Eg: int a; //here a is a variable name and used to store integer value.

float b; // here b is a variable name and used to store floating point value.

char c; // here c is a variable name and used to store character value.

There are two types of variables local and global variables.


Variables that are declared inside a function is called local variables because that are local to that
function.
main()
{
int a, b;
float avg;
}
Here a, b, and avg are local variables.
Global variables are those variables which are used in more than one functions in the same
program. Such variables are declared outside the main() function. That is in the global declaration
section.
int a, b;
float avg;
main()
{
…………….
}
Here a, b and avg are global variables.
Rules for defining variables

1. A variable can have alphabets, digits, and underscore.


2. A variable name can start with the alphabet, and underscore only. It can’t start with a digit.
3. The maximum number of characters in a variable is 31.
4. No whitespace is allowed within the variable name.
5. A variable name must not be any reserved word or keyword.

26 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Declaration of variables
A variable that must be declared before they are used in the program. Declaration tells two things.
1) It tells the compiler what the variable name is ,
2) It specifies what type of data the variable will hold.
The syntax of declaring variable is,
Datatype V1, V2 ---- Vn
Where V1, V2 and Vn are the names of the variables and these are separated by commas. A
declaration must end with semicolon.
Eg:- int a;
float d;
Initialization of variables
The variables can be initialized by means of an assignment operator. The initialization means
giving an initial value to the variable. If the variable will not be initialized, the value of variables
may be ‘0’ or garbage depending on the storage class.
a=1;
It means the variable a stores initial value to 1 by using an assignment operator ‘=’.
A variable can also be initialized at the declaration time itself.
int a = 1;
A variable can be declared as a constant using the keyword const.
const int av = 30;
Structure of a C program
The structure of a C program consists of different sections and they are illustrated below:
Documentation Section
Linkage Section
Definition Section
Global Declaration Section
Main() Function Section
{
Declaration Part
Executable Part
}

Subprogram Section
Function1;
Function2;

27 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Documentation Section
This section consists of the description of the program, the name of the program, and the
creation date and time of the program. It is specified at the start of the program in the form of
comments. Documentation can be represented as:
// description, name of the program, programmer name, date, time etc.
Or
/* description, name of the program, programmer name, date, time etc. */
Linkage Section
The link section provides instructions to the compiler to link functions from the system
library, by using preprocessor directive. All the functions in C are grouped category wise and stored
in files known as header files. The extension of these files is .h.
#include<stdio.h>
#include<math.h>
#include is known as the preprocessor directive.
Definition Section
This section defines all symbolic constants. The definition is done with the preprocessor
#define. Preprocessors are the programs that process our source code before the process of
compilation. There are multiple steps which are involved in the writing and execution of the program.
Preprocessor directives start with the ‘#’ symbol. The #define preprocessor is used to create a
constant throughout the program. Whenever this name is encountered by the compiler, it is replaced
by the actual piece of defined code.
#define PI 3.14
#define M “welcome”
Global Declaration Section
There are some variables that are used in more than function. Such variables are called global
variables and are declared in global declaration section that is outside of all the functions.
Main() Function Section
This is a special function which indicates where the program begins. This section contains
two parts.
Declaration Part
Executable Part
In the declaration part, all the variables which are used in the program must be declared. There is
atleast one executable statement in the executable part. All the statements in this section ends with a
semicolon.
Subprogram Section
This section contains all the user defined functions which must be called in the main function
section.

28 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Symbolic Constants
The symbolic constants are used repeatedly in number of places in the same program. They will not
be declared anywhere in the program. Symbolic name are also called constant identifiers.
Rules for defining the symbolic constants
 No blank space between the ‘#’ and the word define.
 Symbolic names are written in uppercase letters
 Blank space is required between the #define and the symbolic name and the constant.
 #define statement must not end with semicolon.
 Data type of symbolic name depends on the type of constant.
The syntax is
#define symbolic-name value
Eg:- #define PI 3.14
Data types in C

A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.

Categories of data types


 Primary Data Type/Basic data types/Fundamental date types
(int, char, double and float.)
 Derived Data Types:
(Array, functions, and Pointers.)
 User Defined Data Types:
(Structure, Union, and Enumeration.)
 Void data types (void)

29 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Primary Data Types


The primary data types in C programming language are the basic data types. All the primary
data types are already defined in the system. Primary data types are also called as Built-In data types.
The following are the primary data types in c programming language...
1. Integer data type
2. Floating Point data type
3. Double data type
4. Character data type

Integer Data type


The integer data type is a set of whole numbers. Every integer value does not have the decimal
value. We use the keyword "int" to represent integer data type in C. We use the keyword int to
declare the variables and to specify the return type of a function. The integer data type is used with
different type modifiers like short, long, signed and unsigned. The following table provides complete
details about the integer data type.

Eg:- int a, b;

30 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Floating Point data types


Floating-point data types are a set of numbers with the decimal value. Every floating-point
value must contain the decimal value. The floating-point data type has two variants...

 Float
 Double

We use the keyword "float" to represent floating-point data type and "double" to represent
double data type in c. Both float and double are similar but they differ in the number of decimal
places. The float value contains 6 decimal places whereas double value contains 15 or 19 decimal
places. The following table provides complete details about floating-point data types.

Eg:- float b;

Character data type


The character data type is a set of characters enclosed in single quotations. The following
table provides complete details about the character data type

Eg:- char c;

Void data type


The void data type means nothing or no value. Generally, the void is used to specify the type
of functions which does not return any value. We also use the void data type to specify empty
parameters of a function.

31 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Eg: void sum(void); or void sum();

void fun1();

Derived Data Types in C


Derived data types are derived from the primitive or fundamental data types. There are mainly
3 types of derived data types in C that we are going to discuss in this section.
 Arrays
An array is a group of similar kinds of finite entities of the same type. These entities or
elements can be referred to by their indices respectively. The indexing starts from 0 to array_size
conventionally. An array can be one-dimensional, two-dimensional, or multidimensional.
Syntax
Data type arr_name[size];
Description of the syntax
 data_type: This is the data type that specifies the type of elements to be stored in the array.
It can be int, float, double, and char.
 array_name: This is the name of the array. To specify the name of an array, you must
follow the same rules which are applicable while declaring a usual variable in C.
 Size: The size specifies the number of elements held by the array. If the size is n then the
number of array elements will be n-1.

Eg: int a[10];

float b[15];

char c[10];

Functions
A function is a piece of code that performs some specific task when invoked in the program.
It can be called from anywhere and any number of times in the program. The return value i.e., what
type of value it will return depends upon the return type of the function. In C, a function can be called
by types: call by value and call by reference. When the function is called by value, a copy of the
variable is passed as the argument whereas when the function is called by the reference, the address
or reference of variable itself is passed to the function.
Syntax
Return type function_name(parameters);
Description of the Syntax

32 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

 return_type: This is the data type that specifies the type of value to be returned by the
function. If the return type is void, then it is not mandatory for the function to return a value.
 function_name: This is the name of the function. To specify the name of a function, you
must follow the same rules which are applicable while declaring a usual variable in C.
 parameters: The parameters are optional. They are passed according to the type of the
function call.
Eg: void sum();
int add(10,20);
Pointers
A pointer can be defined as a variable that stores the address of other variables. This address
signifies where that variable is located in the memory. If a is storing the address of b, then a is
pointing to b. The data type of a pointer must be the same as the variable whose address it is storing.
Syntax

Data type *pointer_name;


Description of the syntax
 Type: This is the data type that specifies the type of value to which the pointer is pointing.
 Pointer_name: This is the name of the pointer. To specify the name of a pointer, you must
follow the same rules which are applicable while declaring a usual variable in C. Apart from
these rules, a pointer must always be preceded by an asterisk(*).
Eg: int *p;
float *q;
User-Defined Data Types in C
Structure
A structure is a user-defined data type in C that allows you to combine members of different
types under a single name (or the struct type). The reason why it is called a user-defined data type is
that the variables of different types are clubbed together under a single structure, which can be
defined according to the user’s choice.
Syntax
struct structure_name
{
data_type var1;
data_type var2;
};

Description of the Syntax

33 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

 struct: The definition of a structure includes the keyword struct followed by its name. All
the items inside it are called its members and after being declared inside a structure.
 data_type: Each variable can have a different data type. Variables of any data type can be
declared inside a structure.
 The definition of a structure ends with a semicolon at the end.
Union
A union is also a user-defined data type. It also holds members of different data types under
a single name. A union sounds similar to a structure and they are similar in conceptual terms. But
there are some major differences between the two. While a structure allocates sufficient memory for
all its members, a union only allocates one memory equal to its largest member.
Syntax

// define a structure.

union structure_name

data_type var1;

data_type var2;

};

Description of the Syntax


 union: The union keyword is written at the beginning of the definition of a union in C. After
it the name of the union is specified.
 data_type: It is the data type of the member variable of the union. Members of different
types can be defined inside a union.

Enumeration
Enumeration or simply enum is one of the user-defined data types in C which provides a
special type of flexibility of defining variables. An enum consists of a set of integer constants that
can be replaced by user-defined names.
Syntax
enum identifier {value1, value2,…valuen};
enum day {mon. tue, wed, thu, fri, sat, sun};
Description of the Syntax
 enum: The keyword enum is written at the beginning of the definition.

34 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

 identifier: This is the default name of the enumeration set. It can be replaced by another
name or can be used as it is.
Example
enum color { red, blue, green };
After this definition new variables can be declared as
enum identifier v1, v2, v3…vn;
Eg:- enum day week-st,week-end;
enum color c1, c2:
The enumerated variables v1, v2…vn can have only one of the values value1, value2…valuen.
The compiler automatically assigns integer digits beginning with zero to all the enumeration
constants. That is the enumeration constant value1 is assigned 0, value2 assigned 1and so on.
However, the automatic assignments can be changed by assigning values explicitly to the
enumeration constants.
Eg:-enum color { red, blue, green }; // set is {0, 1, 2}.
enum fruit { mango = 10, apple, grapes }; // set is {10, 11, 12}.

Datatype Keyword Equivalent

Character char
Unsigned Character unsigned char
Signed Character signed char
Signed Integer signed int (or) int
Signed Short Integer signed short int (or) short int (or) short
Signed Long Integer signed long int (or) long int (or) long
UnSigned Integer unsigned int (or) unsigned
UnSigned Short Integer unsigned short int (or) unsigned short
UnSigned Long Integer unsigned long int (or) unsigned long
Floating Point float
Double Precision Floating Point double
Extended Double Precision Floating Point long double

Initialization of a variable is of two types:


 Static Initialization: Here, the variable is assigned a value in advance. This variable then acts
as a constant.

35 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

 Dynamic Initialization: Here, the variable is assigned a value at the run time. The value of
this variable can be altered every time the program is being run.
Type modifiers
In c language Data Type Modifiers are keywords used to change the properties of current
properties of data type. Data type modifiers are classified into following types.

 long
 short
 unsigned
 signed

Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount
of storage space allocated to a variable.

For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the range
by using long int which is 8 byte. We can decrease the range by using short int which is 2 byte.

 long:

This can be used to increased size of the current data type to 2 more bytes, which can be applied
on int or double data types. For example int occupy 2 byte of memory if we use long with integer
variable then it occupy 4 byte of memory.

Syntax

long a; --> by default which represent long int.

 short
In general int data type occupies different memory spaces for a different operating system;
to allocate fixed memory space short keyword can be used.

36 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Syntax

short int a; --> occupies 2 bytes of memory space in every operating system.

unsigned
This keyword can be used to make the accepting values of a data type is positive data type.

Syntax
unsigned int a =100; // right

unsigned int a=-100; // wrong

Signed
This keyword accepts both negative and positive value and this is default properties or data type
modifiers for every data type.

Example
int a=10; // right
int a=-10; // right
signed int a=10; // right
signed int a=-10; // right
Note: in real time no need to write signed keyword explicitly for any data type.
TYPE CONVERSIONS
In C programming, we can convert the value of one data type (int, float, double, etc.) to another.
This process is known as type conversion. Let's see an example,

#include <stdio.h>
int main()
{
int number = 34.78;
printf("%d", number);
return 0;
}
// Output: 34
Here, we are assigning the double value 34.78 to the integer variable number. In this case, the
double value is automatically converted to integer value 34.
This type of conversion is known as implicit type conversion. In C, there are two types of type
conversion:
 Implicit Conversion
 Explicit Conversion

37 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Implicit Type Conversion in C


As mentioned earlier, in implicit type conversion, the value of one type is automatically
converted to the value of another type. For example,
#include<stdio.h>
int main()
{
// create a double variable
double value = 4150.12;
printf("Double Value: %.2lf\n", value);
// convert double value to integer
int number = value;
printf("Integer Value: %d", number);
return 0;
}
Output
Double Value: 4150.12
Integer Value: 4150
The above example has a double variable with a value 4150.12. Notice that we have assigned the
double value to an integer variable.
int number = value;
Here, the C compiler automatically converts the double value 4150.12 to integer value 4150.
Since the conversion is happening automatically, this type of conversion is called implicit type
conversion.
Example: Implicit Type Conversion
#include<stdio.h>
int main()
{
// character variable
char alphabet = 'a';
printf("Character Value: %c\n", alphabet);
// assign character value to integer variable
int number = alphabet;
printf("Integer Value: %d", number);
return 0;
}

38 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Output
Character Value: a
Integer Value: 97
The code above has created a character variable alphabet with the value 'a'. Notice that we are
assigning alphabet to an integer variable.
int number = alphabet;
Here, the C compiler automatically converts the character 'a' to integer 97. This is because, in C
programming, characters are internally stored as integer values known as ASCII Values.
Explicit Type Conversion in C
In explicit type conversion, we manually convert values of one data type to another type.
For example,
#include<stdio.h>
int main()
{
// create an integer variable
int number = 35;
printf("Integer Value: %d\n", number);
// explicit type conversion
double value = (double) number;
printf("Double Value: %.2lf", value);
return 0;
}
Output
Integer Value: 35
Double Value: 35.00
We have created an integer variable named number with the value 35 in the above program. Notice
the code,
// explicit type conversion
double value = (double) number;
Here,
(double) - represents the data type to which number is to be converted
number - value that is to be converted to double type

39 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Example2
#include<stdio.h>
int main()
{
// create an integer variable
int number = 97;
printf("Integer Value: %d\n", number);
// (char) converts number to character
char alphabet = (char) number;
printf("Character Value: %c", alphabet);
return 0;
}
Output
Integer Value: 97
Character Value: a
We have created a variable number with the value 97 in the code above. Notice that we are
converting this integer to character.
char alphabet = (char) number;
Here,
(char) - explicitly converts number into character
number - value that is to be converted to char type
Data Loss in Type Conversion
In our earlier examples, when we converted a double type value to an integer type, the data after
decimal was lost.
#include<stdio.h>
int main()
{
// create a double variable
double value = 4150.12;
printf("Double Value: %.2lf\n", value);
// convert double value to integer
int number = value;
printf("Integer Value: %d", number);
return 0;}

40 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Output
Double Value: 4150.12
Integer Value: 4150
Here, the data 4150.12 is converted to 4150. In this conversion, data after the decimal, .12
is lost. This is because double is a larger data type (8 bytes) than int (4 bytes), and when we convert
data from larger type to smaller, there will be data loss. Similarly, there is a hierarchy of data types
in C programming. Based on the hierarchy, if a higher data type is converted to lower type, data is
lost, and if lower data type is converted to higher type, no data is lost.
OPERATORS AND EXPRESSIONS
OPERATORS
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. Operators are used in programs to manipulate data and variables. C operators can be
classified into a number of categories. They include
1. Arithmetic operators
2. Relational operators.
3. Logical operators.
4. Assignment operators.
5. Increment and decrement operators.
6. Conditional operators.
7. Bitwise operators.
8. Special operators.

ARITHMETIC OPERATORS
There are five arithmetic operators in C. They are

41 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Operators Meaning
+ Addition

- Subtraction

* Multiplication

/ Division
% Modulo division (Reminder after integer division)

Operator Example(int A=8,B=3) Result

+ A+B 11

- A-B 5

* A*B 24

/ A/B 2

% A%4 0

Relational Operators
Relational Operators are the operators used to create a relationship and compare the values of two
operands. The value of a relational expression is either one or zero. It is one if the specified relation
is true and zero if the relation is false.

Operators Example (int A=8, B=3) Result

< A<B False

<= A<=10 True

> A>B True

>= A<=B False

== A== B False

!= A!=(-4) True

42 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Logical Operators
Logical operators are used to determine the logic between variables or values:
The three logical operators are

Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

Operator Example (int A=8, B=3, C=-10) Result

&& (A<B) && (B>C) False

|| (B!=-C) || (A==B) True

! !(B<=-A) True

Assignment operators
It can be used to assign a value to a variable. Let’s suppose variable A hold 8 and B hold 3.

Operator Example (int A=8, B=3) Result

+= A+=B or A=A+B 11

-= A-=3 or A=A+3 5

*= A*=7 or A=A*7 56

/= A/=B or A=A/B 2

%= A%=5 or A=A%5 3

Increment and Decrement Operators (++, --)


C has two special unary operators called increment (++) and decrement (--) operators. These
operators’ increment and decrement value of a variable by 1.

43 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

a++ means a=a+1;


a- - means a=a-1;
Increment/Decrement operators are of two types:
 Prefix increment/decrement operator.
 Postfix increment/decrement operator.
Prefix increment/decrement operator.
The prefix increment/decrement operator immediately increases or decreases the current
value of the variable. This value is then used in the expression. Let's take an example:
y = ++x;
Here first, the current value of x is incremented by 1. The new value of x is then assigned
to y. Similarly, in the statement:
y = --x;
The current value of x is decremented by 1. The new value of x is then assigned to y
Example:

x = 12, y = 1;

y = ++x; // increment the value of x by 1 then assign this new value to y

y = --x; // decrement the value of x by 1 then assign this new value to y

Initial value of x = 12
Initial value of y = 1

After incrementing by 1: x = 13
y = 13

After decrementing by 1: x = 12
y = 12

Postfix increment/decrement operator.


The postfix increment/decrement operator causes the current value of the variable to be us
ed in the expression, and then the value is incremented or decremented. For example:
y = x++;
Here first, the current value of x is assigned to y then x is incremented.
Similarly, in the statement:
y = x--;
The current value of x is assigned to y then x is decremented.
x = 12, y = 1;
y = x++; // use the current value of x then increment it by 1

44 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

y = x--; // use the current value of x then decrement it by 1


Initial value of x = 12
Initial value of y = 1
After incrementing by 1: x = 13
y = 12
After decrementing by 1: x = 12
y = 13

Conditional Operator in C

The conditional operator is also known as a ternary operator. The conditional statements
are the decision-making statements which depend upon the output of the expression. It is represented
by two symbols, i.e., '?' and ':'.

As conditional operator works on three operands, so it is also known as the ternary operator.

The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else' statement is
also a decision-making statement.

Syntax
Expression1? expression2: expression3;
Eg:
a=10;
b=15;
X= (a>b)? a: b;
Here x will be assigned the value of b.

BITWISE OPERATORS
C provides six operators for bit manipulation; these may only be applied to integral operands,
that is, char, short, int and long whether signed or unsigned. These operators may not be applied to
float or double.
Operator Meaning
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< left shift
>> right shift
~ one‟s complement(unary)

45 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

SPECIAL OPERATORS
The special operators include the comma operator, sizeof operator, pointer operators (& and
*) and member selection operators (. and ->).
Operator Meaning
, comma operator

sizeof sizeof operator


pointer operator
& and *
. and -> member selection operator

Comma opereator
Comma (,) as Separator and Operator:
Comma (,) as separator
While declaration multiple variables and providing multiple arguments in a function, comma
works as a separator.
Example:
int a,b,c;
In this statement, comma is a separator and tells to the compiler that these (a, b, and c) are three
different variables.
Comma (,) as an operator
Sometimes we assign multiple values to a variable using comma, in that case comma is known as
operator.
Example:
a = 10, 20, 30;
b = (10, 20, 30);
In the first statement, value of a will be 10, because assignment operator (=) has more priority
more than comma (,), thus 10 will be assigned to the variable a.
In the second statement, value of b will be 30, because 10, 20, 30 are enclosed in braces, and braces
has more priority than assignment (=) operator.
When multiple values are given with comma operator within the braces, then right most value
is considered as result of the expression. Thus, 30 will be assigned to the variable b.
EXPRESSIONS
An expression is a sequence of operands and operators that reduces to a single value.
Let's see an example:
a-b;
In the above expression, minus character (-) is an operator, and a, and b are the two operands.

46 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

There are four types of expressions exist in C:


 Arithmetic expressions
 Relational expressions
 Logical expressions
 Conditional expressions

Priority of operators
The precedence is used to determine how an expression involving more than one operator is
evaluated. There are distinct levels of precedence and an operator may belong to one of these levels.
The operators at the higher level of precedence are evaluated first. The operators of the same
precedence are evaluated either from „left to right‟ or „right to left‟, depending on the level. This is
known as the associativity property of an operator.

47 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

P1. Write a program to print a message.

P2. Write a program to input a number and print the same.

P3. Write a program to input two numbers and print their sum.\

P4. Extend the above program to fine their difference, product and average.

P5. Write a program to input two numbers and interchange their values.

P6. Write a program to convert a given number of days into months and days.

void main()

{
int months, days;
printf(“enter the number of days”);

scanf(“%d”,&days) ;

months=days/30;

days=days%30;

printf(“ Months= %d Days=%d”,months,days);

getch();

48 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

MODULE 3

INPUT AND OUTPUT FUNCTIONS


C language includes a number of input/output functions. These functions permit the transfer
of information between the computer and the standard input/output devices. An input/output function
can be accessed from anywhere within a program by simply writing the function name, followed by
a list of arguments enclosed in parentheses. The arguments represent data items that are sent to the
function. Some input/output functions do not require arguments, though the parentheses must still
appear.
Most versions of C include a collection of header files that provide necessary information in
support of the various library functions. These files are entered into the program via a #include
statement at the beginning of the program. The header file required by the standard input/output
library functions is called stdio.h.
The six input/output functions are
 getchar
 getch()
 putchar
 scanf
 printf
 gets
 puts
Input output built-in functions in C falls into two categories, namely,
 Formatted input output (I/O) functions and
 Unformatted input output (I/O) functions.
printf() and scanf() are examples for formatted input and output functions and getch(),getchar(),
gets(), puts(), putchar() etc. are examples of unformatted input output functions.
Unformatted functions
SINGLE CHARACTER INPUT---THE getchar FUNCTION
Single characters can be entered into the computer using the C library function getchar. It
returns a single character from a standard input device (typically a keyboard). The function does not
require any arguments.
The getchar takes the following form:
Character_variable = getchar ( );
where character variable refers to some previously declared character variable.

49 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Example:
char c;
------------
c = getchar ( );
The first statement declares that c is a character-type variable. The second statement causes
a single character to be entered from the standard input device and then assigned to c.
Note: The getchar function can also be used to read multi character strings, by reading one
character at a time within a loop.
getch():-
The getch() in C is a non-standard function used to receive a character as input from the user.
It is defined in the header file conio.h. The character entered by the user is not visible on the output
screen but is stored in the assigned variable. We can also explain the getch() as a function call that
pauses the execution of the program until the user enters a character from the keyboard.

SINGLE CHARACTER OUTPUT---THE putchar FUNCTION

Single characters can be displayed using the C library function putchar. The putchar function
transmits a character to a standard output device. The character being transmitted will normally be
represented as a character-type variable. It must be expressed as an argument to the function,
enclosed in parentheses, following the word putchar.
The putchar takes the following form:
putchar ( character_variable ) ;
Where the character variable refers to some previously declared character variable.
Example:
char c;
------------
putchar (c ) ;
The first statement declares that c is a character-type variable. The second statement causes
the current value of c to be transmitted to the standard output device where it will be displayed.
Note: The putchar function can be used with loops to output a string.
THE gets AND puts FUNCTIONS
The gets and puts functions facilitates the transfer of strings between the computer and the
standard input/output devices. Each of these functions accepts a single argument. The argument must
be a string, (e.g., a character array). The string may include whitespace characters.

50 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

In the case of gets, the string will be entered from the keyboard, and will terminate with a
newline character (i.e., the string will end when the user presses the enter key). The gets and puts
functions offer simple alternatives to the use of scanf and printf for reading and displaying strings.
Example
main()
{
char a[40];
gets(a); /* reads a line of text into the computer */
puts(a); /* writes the text back out in its original form */
}
Formatted Functions
ENTERING INPUT DATA --- THE scanf FUNCTION
In C programming language, scanf() function is used to read character, string, numeric data
from keyboard
The general form of scanf is:
scanf (“control string”, arg 1,arg 2,……, arg n ) ;
The control string specifies the field format in which the data is to be entered and the arguments arg
1, arg 2, ….. ,arg n specify the address of locations where the data is stored. Control string and
arguments are separated by commas. Control string (also known as format string) contains field
specifications, which direct the interpretation of input data. It may include:
 Field (or format) specifications, consisting of the percentage sign %, a conversion character
(or type specifier), and an optional number, specifying the field width.
 Whitespace characters (Blanks, tabs, or newlines).

Example
main()
{
char a[20];
int b;
float c;
………
scanf (“ %s %d %f ”,a, &b, &c );
………….
}
Within the scanf function, the control string is “%s %d %f “. It contains three character groups.

51 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

The first character group %s represents a string.


The second character group %d represents a decimal integer value.
The third character group %f represents a floating-point value.
Numerical variables b and c are preceded by ampersands within the scanf function.

WRITING OUTPUT DATA--- THE printf FUNCTION

In C programming language, printf() function is used to print the (“character, string, float,
integer, octal and hexadecimal values”) onto the output screen.
 We use printf() function with %d format specifier to display the value of an integer variable.
 Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for
double and %x for hexadecimal variable.
 To generate a newline,we use “\n” in C printf() statement.
The general form of printf is:
printf ( "control string”, arg 1, arg 2, …..,arg n) ;
Control string consists of three types of items:
1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n,\t,\b.
The control string indicates how many arguments follow and what their types are. The arguments
arg1,arg2,….,argn are the variables whose values are formatted and printed according to the
specification of control string. The arguments should match in number, order and type with the
format specifications.
Some examples of formatted printf statements are:
printf(“Programming in C”);
printf(“ ”);
printf(“ \n ”);
printf(“ %d ”, x);
printf(“a=%f \n b= %f”,a,b);
printf(“sum= %d”, 1234);
printf(“\n \n”);

52 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Commonly Used Conversion Characters For Data Input/output

Conversion character Meaning


c dataitem is a single character
d dataitem is a decimal integer
e dataitem is a floating-point value
f dataitem is a floating-point value
h dataitem is a short integer
i dataitem is a decimal, hexadecimal or octal integer
o dataitem is a octal integer
dataitem is a string followed by a whitespace character (the
s
null character \0 will automatically be added at the end)
u dataitem is an unsigned decimal integer
x dataitem is a hexadecimal integer

COMMONLY USED LIBRARY FUNCTIONS

53 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

DECISION MAKING AND BRANCHING


Decision making helps us to change the order of execution of the statements based on certain
conditions. Decision making capabilities are supported by following statements
 if statement
 Switch statement
 Conditional operator statement
 goto statement
These statements ‘control’ the flow of execution, so they are also known as control statements.

DECISION MAKING WITH IF STATEMENT


The if statement is a powerful decision making statement and is used to control the flow of execution
of statements. It is a two way decision statement and is used in conjunction with an expression.
It takes the following form:
if (test expression)

Entry

test expression False


?

True

The if statement may be implemented in different forms depending on the complexity of


conditions to be tested. The different forms are:
 simple if statement

 if.....else statement

 Nested if…else statement

 Else if ladder

simple if statement
The general form of a simple if statement is
if ( expression )
statement;
or

54 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

if ( expression )
{
statement-block;
}
statement-x;

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

The if.....else statement


The if…else statement is an extension of the simple if statement. The general form is:
if (expression )
{
Statement-block 1;
}
else
{
Statement-block 2;
}
Statement-x;

55 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

If the expression is true, then the statement-block 1 will be executed. Otherwise (the
expression is false), statement-block 2 will be executed. In either case, either statement-block 1 or
statement-block 2 will be executed, not both. In both cases, the control is transferred subsequently to
the statement-x.

P7. Write a program to fine the largest of two numbers


P8. Write a program to check whether the number is even or odd.
P9. Write a program to input a number and check whether which is divisible by 7.
Nested if…else statement
When a series of decisions are involved, we may have to use more than one if..else statement
in nested form. The general form is:

If ( expression 1)
{
If ( expression 2 )
{
statement-1 ;
}
else
{
statement-2;
}
}
else

56 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

{
statement-3 ;
}
Statement-x;
One complete if-else statement will be executed if expression-1 is true, and another complete
if-else statement will be executed if expression-1 is false.

P10. Write program to print the largest of three numbers.

void main()
{
int a,b,c;
printf(“Enter three numbers”);
scanf(“%d%d%d”,&a,&b,&c);
printf(“The largest value is ”);
if(a>b)
{
if(a>c)
printf(“%d”,a);
else
printf(“%d”,c);
}

57 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Else
{
if(b>c)
printf(“%d”,b);
else
printf(“%d”,c);
}
getch();
}

P11. Write a program to input two numbers and check whether the first number is divisible by the
second number.
P12. Write a program to input two numbers and check the sum is even or odd.
P13. Write program to print the largest of three numbers using logical AND.
#include <stdio.h>
void main()
{
int a, b, c;
printf("Enter three numbers: \n ");
scanf("%d%d%d",&a,&b,&c);
if (a > b && a > c)
printf("Biggest number is %d", a);
if (b > a && b > c)
printf("Biggest number is %d", b);
if (c > a && c > b)
printf("Biggest number is %d", c);
getch();
}
P14. Write a program to input two numbers and find the largest among them using conditional
operator.
P15. Write a program to find he roots of the quadratic equation of the form ax2+bx+c=0.
Roots= -b+ b2-4ac
2a
#include <math.h>
#include <stdio.h>
void main()

58 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

{
float a, b, c, dis, root1, root2;
printf("Enter coefficients a, b and c: ");
scanf("%f %f %f", &a, &b, &c);
dis= b * b - 4 * a * c;
if (dis > 0)
{
root1 = (-b + sqrt(dis)) / (2 * a);
root2 = (-b - sqrt(dis)) / (2 * a);
printf("root1 = %.2f and root2 = %.2f", root1, root2);
}
else if (dis == 0) {
{
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
else
printf(“The roots are imaginary”);
getch();
}
else if ladder
else if ladder can be used to choose an option from more than two alternatives. else if
ladder is multiple branch decision statement.
General form/Syntax

59 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Working
1. The conditions are evaluated from the top to downwards, as soon as a true condition is found,
the statement associated with it is executed and the control is transferred to the statement x
skipping the rest of the ladder.
2. When all the n conditions become false then final else containing default statement will be
executed.

The switch Statement

Switch statement is multiple branch decision statement. The switch statement tests the value
of a given variable(expression) against a list of case values and when a match is found, a block of
statements associated with that case is executed.
General form/Syntax:
switch(expression)
{
case value-1:
block 1;
break;
case value-2:
block-2;
break;
…………
…………
default:

60 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

default-block;
break;
}
Statement-x;
Where expression can be an integer constant or characters. Value-1,value-2 are constants or
constant expressions and are known as case labels. switch statement is a multiple branch decision
statement.
Working:
1. Evaluates the expression.
2. The resulted integer value is compared with case constants.
3. If match is found, the statements associated with that particular case are executed.
4. If no match is found, statements under default are executed.
5. When break statement is encountered, the switch is terminated.
Note: Each case statement must have break statement.

P16. Write a program to print name of day based on a given number (1-7) using switch statement.
#include <stdio.h>
void main()
{
int day;
printf("Enter Day Number\n");
scanf("%d", &day);

switch(day)
{
case 1 : printf("Monday\n");
break;
case 2 : printf("Tuesday\n");
break;
case 3 : printf("Wednesday\n");
break;
case 4 : printf("Thursday\n");
break;
case 5 : printf("Friday\n");
break;

61 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

case 6 : printf("Saturday\n");
break;
case 7 : printf("Sunday\n");
break;
default: printf("Invalid Input !!!!\n");
}
getch();
}

Conditional operator statement


The conditional operator is a combination of ? and : ,and takes three operands.This operator
is popularly known as the conditional operator. The general form of conditional operator is:
Conditional expression? expression1: expression2;
The conditional expression is evaluated first. If the result is true, expression1 is evaluated
and is returned as the value of the conditional expression. Otherwise, expression2 is evaluated and
its value is returned.
Example:
a = (10>6) ? 10 : 6 ;
If (10>6) then return a=10 else return a= 6.
goto statement
C supports the goto statement to branch unconditionally from one point to another in the
program. The goto requires a label in order to identify the place where the branch is to make. A label

62 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

is any valid variable name, and must be followed by a colon. The label is placed immediately before
the statement where the control is to be transferred. The general forms of goto and label statements
are:

Forward jump Backward jump


The ‘label:’ can be anywhere in the program either before or after the ‘goto label;’ statement.
goto breaks the normal sequential execution of the program. If the label: is before the statement goto
label; a loop will be formed and some statements will be executed repeatedly.Such a jump is known
as a backward jump. On the other hand, if the label: is placed after the goto label; some statements
will be skipped and the jump is known as a forward jump.
Looping(control structures)
Looping statements are used to execute a statement or group of statements repeatedly for a
specified number of times or as long as the condition is true/ until the condition is false. A loop is a
particular area of a program where some executable statements are written which gets executed by
testing one or more conditions. So, in looping, a sequence of statements is executed until some
conditions for termination are satisfied.
A program loop therefore consists of two segments; the body of the loop and the control statement.
 “body of the loop”. Consists of set of statements.
 “Control statement” .The control statement tests certain conditions and then directs the
repeated execution of the statements contained in the body of the loop.
Depending on the position of the control statement in the loop, a control structure can be
classified into two types;
 entry controlled and
 exit controlled.
Entry-controlled loops:-
In Entry controlled loop the test condition is checked first and if that condition is true than
the block of statement in the loop body will be executed.
Example: while loop and for loop.

63 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Exit controlled loop: -


In exit controlled loop the body of loop will be executed first and at the end the test condition
is checked, if condition is satisfied then body of loop will be executed again.
Example: do-while loop.

C programming language provides three constructs for performing loop operations.


1. The while statement
2. The do statement
3. The for statement
THE while STATEMENT
The while is an entry-controlled loop statement. The test-condition is evaluated and
if the condition is true, then the body of the loop is executed. This process of repeated execution of
the body continues until the test-condition finally becomes false and the control is transferred out of
the loop. On exit, the program continues with the statement immediately after the body of the loop.
The basic format of the while statement is:

while(condition)
{
Body of the loop
}

64 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Example
P17. Write a program to find the sum first five natural numbers
void main()
{
int n, sum;
i=1; /*initialization*/
sum=0;
whie( i<=5) /* testing*/
{
sum=sum+i;
i=i+1; /*incrementing*/
}
printf(“sum =%d”, sum);
}
Output
sum =15
THE do STATEMENT
On some occasions it might be necessary to execute the body of the loop before the test is
performed. Such situations can be handled with the help of the do statement.
The general form is:
do
{
Body of the loop
} while(condition);

65 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

On reaching the do statement, the program first evaluates the body of the loop. At the end of the
loop, the test-condition in the while statement is evaluated. The process continues as long as the
condition is true. When the condition becomes false, the loop will be terminated and the control goes
to the statement that appears immediately after the while statement. Since the test-condition is
evaluated at the bottom of the loop, the do…while construct provides an exit-controlled loop and
therefore the body of the loop is always executed at least once.
Example
void main()
{
int n, sum;
i=1; /*initialization*/
sum=0;
do /* testing*/
{
sum=sum+i;
i=i+1; /*incrementing*/
} whie( i<=5);
printf(“sum =%d”, sum);
}
Output
sum =15
THE for STATEMENT
The for loop is another entry-controlled loop. The general form of the for loop is :
for ( initialization ; test-condition ; increment )
{
Body of the loop;
}
The execution of the for statement is as follows:
1. Initialization of the control variables is done first, using assignment statements.
2. The value of the control variable is tested using the test condition. If the condition is true, the body
of the loop is executed; otherwise the loop is terminated and the execution continues with the
statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back to the for statement after
evaluating the last statement in the loop. Now the control variable is incremented /decremented and
the new value of the control variable is again tested to see whether it satisfies the loop condition. If

66 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

the condition is satisfied, the body of the loop is again executed. This process continues till the value
of the control variable fails to satisfy the test-condition.
Example
for ( i=0 ;i<=9 ; i= i+1)
{
printf (“ %d”, i);
}
Output
for loop is executed 10 times and prints the digits 0 to 9 in one line.

Nested For Loop


One for statement within another for statement is known as nesting of for loop.
Syntax
for ( initialization ; test-condition ; increment )
{
…………….
for ( initialization ; test-condition ; increment )
{
……………………………….
}
}
Eg:
for(i=0;i<10;i++)
{
……………
for(j=0;J<5;j++)
{
………………
}
}
break AND continue
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. That is, the break will exit only a single loop.
General form of break is:

67 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

for(--------)
{
----------
-----------
if(error)
break;
-------
--------
}
---------
Example
for(i=0; i<50; i++)
{
if(i==10)
break;
printf("%d\n",i);
}
output
Only numbers 0 through 9 are printed.
The continue causes the loop to be continued with the next iteration after skipping any
statements in between. In while and do loops, continue causes the control to go directly to the test-
condition and then to continue the iteration process. In the case of for loop, the increment section of
the loop is executed before the test-condition is evaluated.
General form of continue is:

68 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Examples:
for (i=0;i<100;i++)
{
if (i==50)
continue;
printf ("%d\n",i);
}
The numbers 0 through 99 are printed except for 50.

69 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

MODULE 4

ARRAYS
An array is a fixed-size sequenced collection of elements of the same data type. It is simply
a grouping of like-type data. An array can be used to represent a list of numbers, or a list of names.
An array is a collective name given to a group of homogeneous elements (same data type).
These similar quantities could be percentage marks of 100 students, or salaries of 300 employees or
ages of 25 students.
Declaration of an Array
Arrays must be declared before they can be used in the program.
Standard array declaration is as
type variable_name [size];
The type specifies the type of the elements that will be contained in the array, such as int,
float or char and the size indicates the maximum number of elements that can be stored inside the
array. In C Language, an array starts at position 0.
1. C Programming Arrays is the Collection of Elements
2. C Programming Arrays is collection of the Elements of the same data type.
3. All Elements are stored in the Contiguous memory
4. All elements in the array are accessed using the subscript variable (index).
Pictorial representation of C Programming Arrays
eg: int Age[5];
Age[0]
Age[1]
Age[2]
Age[3]
Age[4]

The values to the array elements can be assigned as follows


Age[0] =35;
Age[1] =40;
Age[2] =20;
Age[3] =55;
Age[4] =25;
The value will be stored in array Age as shown below.

35
40
20

70 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

55 Age[0]
25 Age[1]
Age[2]
Age[3]
Age[4]

Character array declaration and initialization

char name[10];
Here we declare the name as a character array (string) variable that can hold a maximum of
10 characters. Suppose we read the following string constant into the string variable name.
“WELL DONE”
Array will be like this
‘W’
‘E’
‘L’
‘L’
‘’
‘D’
‘O’
‘N’
‘E’
‘\0’

When compiler sees the character string, it terminates with an additional null character, thus
the element name[10] holds the null character ‘\0’ . When declaring character arrays, we must allow
one extra element space for the null terminator.

What is Contiguous Memory?

1. When Big Block of memory is reserved or allocated then that memory block is called as
Contiguous Memory Block.

2. Alternate meaning of Contiguous Memory is continuous memory.

Array Terminologies:

Size: Number of elements or capacity to store elements in an array. It is always mentioned in square
brackets [ ].

Type: Refers to data type. It decides which type of element is stored in the array. It is also instructing
the compiler to reserve memory according to the data type.

71 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Base: The address of the first element is a base address. The array name itself stores address of the
first element.

Index: The array name is used to refer to the array element. For example num[x], num is array and
x is index. The value of x begins from 0.The index value is always an integer value.

Range: Value of index of an array varies from lower bound to upper bound. 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.
2. All the elements of an 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.
5. Any element of an array a[ ] can be assigned or equated to another ordinary variable or array
variable of its type.
6. Array elements are stored in contiguous memory locations.
Types of Array

1. Single Dimensional Array / One Dimensional Array

2. Multi-Dimensional Array

Single / One Dimensional Array:

 Single or One Dimensional array is used to represent and store data in a linear form.
 Array having only one subscript variable is called One-Dimensional array.
 It is also called as Single Dimensional Array or Linear Array.

Single Dimensional Array Declaration and initialization:

Syntax for declaration:

<data type> <array name> [size];

72 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Examples for declaration

int iarr[3];

char carr[20];

float farr[3];

Syntax for initialization:

<data type> <array name> [size] = {val1, val2, …, valn};

Examples for initialization:

int iarr[3] = {2, 3, 4};

char carr[20] = “program”;

float farr[3] = {12.5, 13.5, 14.5};

Different Methods of Initializing 1-D Array

Initializing 1-D Array is called as compiler time initialization if and only if we assign certain
set of values to array element before executing program. i.e. at compilation time.

Ways of Array Initializing 1-D Array:

1. Size is Specified Directly

2. Size is Specified Indirectly

Method 1: Array Size Specified Directly

In this method, we try to specify the Array Size directly.

73 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

int num [5] = {2,8,7,6,0};

In the above example we have specified the size of array as 5 directly in the initialization
statement. Compiler will assign the set of values to particular element of the array.

num[0] = 2; num[1] = 8; num[2] = 7; num[3] = 6; num[4] = 0;


Method 2: Size Specified Indirectly

int num[ ] = {2,8,7,6,0};

Explanation:

1. Compiler counts the number of elements written inside pair of braces and determines the size
of an array.
2. After counting the number of elements inside the braces, the size of array is considered as 5
during complete execution.
3. This type of Initialization Scheme is also called as “Compile Time Initialization”.

Example Program

#include <stdio.h>

void main()

int num[] = {2,8,7,6,0};

int i;

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

printf(“\n Array Element num [%d] = %d”,i, num[i]);

getch();

Output:
Array Element num[0] = 2

Array Element num[1] = 8

Array Element num[2] = 7

Array Element num[3] = 6

74 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Array Element num[4] = 0


Accessing Array
1. We all know that array elements are randomly accessed using the subscript variable.

2. Array can be accessed using array-name and subscript variable written inside pair of square
brackets [ ]. Consider the below example of an array

20 30 10 40 70
a[0] a[1] a[2] a[3] a[4]

In this example we will be accessing array like this

a[3] = Forth Element of Array

a[4] = Fifth Element of Array

Whereas elements are assigned to an array using below way

a [0] = 20; a[1] = 30; a[2] = 10; a[3] = 40; a[4] = 70;

READING AN AARAY USING scanf()

void main()
{
int a[5];
clrscr();
printf(“Enter a number\n”);
scanf(“%d”,&a[0]);
}
We can read number of elements in single statements by using for loop.
void main()
{

int i,a[5];
clrscr();
printf(“Enter five numbers\n”);
for(i=0;i<5;i++)
{

75 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

scanf(“%d”,&a[i]);
}
}

Operations with One Dimensional Array


1. Deletion – Involves deleting specified elements form an array.
2. Insertion – Used to insert an element at a specified position in an array.
3. Searching – An array element can be searched. The process of seeking specific elements in an
array is called searching.
4. Merging – The elements of two arrays are merged into a single one.
5. Sorting – Arranging elements in a specific order either in ascending or in descending order.
Example Programs:
Example Programs:
P18. C Program for deletion of an element from the specified location from an Array
#include<stdio.h>
void main()
{
int arr[30], num, i, loc;
printf("\nEnter no of elements:");
scanf("%d", &num);
//Read elements in an array

printf("\nEnter %d elements :", num);


for (i = 0; i < num; i++)
{
scanf("%d", &arr[i]);
}
//Read the location

printf("\nLocation of the element to be deleted :");


scanf("%d", &loc);
/* loop for the deletion */
while (loc < num)
{
arr[loc - 1] = arr[loc];
loc++;

76 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

num--; // No of elements reduced by 1


//Print Array
for (i = 0; i < num; i++)
printf("\n %d", arr[i]);

getch();
}
Output:
Enter no of elements: 5
Enter 5 elements: 3 4 1 7 8
Location of the element to be deleted: 3
3 478

P19. C Program to insert an element in an array

#include<stdio.h>
int main()
{
int arr[30], element, num, i, location;
printf("\nEnter no of elements:");
scanf("%d", &num);

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


{
scanf("%d", &arr[i]);
}
printf("\nEnter the element to be inserted:");
scanf("%d", &element);

printf("\nEnter the location");


scanf("%d", &location);
//Create space at the specified location
for (i = num; i >= location; i--)
{
arr[i] = arr[i - 1];

77 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

}
num++;
arr[location - 1] = element;
//Print out the result of insertion

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


printf("n %d", arr[i]);
return (0);
}
Output:
Enter no of elements: 5
12345

Enter the element to be inserted: 6


Enter the location: 2
1 62345

P20. C Program to search an element in an array


#include<stdio.h>
int main()
{
int a[30], ele, num, i;

printf("\nEnter no of elements:");
scanf("%d", &num);
printf("\nEnter the values :");
for (i = 0; i < num; i++)
{
scanf("%d", &a[i]);

}
//Read the element to be searched
printf("\nEnter the element to be searched :");
scanf("%d", &ele);
//Search starts from the zeroth location
i = 0;

78 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

while (i < num && ele != a[i])


{
i++;
}

//If i < num then Match found


if (i < num)
{
printf("Number found at the location = %d", i + 1);
}
else
{

printf("Number not found");


}
getch();
}
Output:
Enter no of elements: 5

11 22 33 44 55
Enter the elements to be searched: 44
Number found at the location = 4

P21. C program to merge two arrays in C Programming


#include<stdio.h>
int main()
{
int arr1[30], arr2[30], res[60];

int i, j, k, n1, n2;


printf("\nEnter no of elements in 1st array:");
scanf("%d", &n1);
for (i = 0; i < n1; i++)
{
scanf("%d", &arr1[i]);

79 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

}
printf("\nEnter no of elements in 2nd array:");
scanf("%d", &n2);
for (i = 0; i < n2; i++) {

scanf("%d", &arr2[i]); }
i = 0;
j = 0;
k = 0;
// Merging starts
while (i < n1 && j < n2)
{

if (arr1[i] <= arr2[j])


{
res[k] = arr1[i];
i++;
k++;
}

else
{
res[k] = arr2[j];
k++;
j++;
}

}
/*Some elements in array 'arr1' are still remaining where as the array 'arr2' is exhausted*/
while (i < n1)
{
res[k] = arr1[i];
i++;
k++;
}

80 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

/*Some elements in array 'arr2' are still remaining where as the array 'arr1' is exhausted */
while (j < n2)
{
res[k] = arr2[j];

k++;
j++;
}
//Displaying elements of array 'res'
printf("\nMerged array is:");
for (i = 0; i < n1 + n2; i++)
printf("%d ", res[i]);

return (0);
}
Enter no of elements in 1st array: 4
11 22 33 44
Enter no of elements in 2nd array: 3
10 40 80

Merged array is: 10 11 22 33 40 44 80

Multi Dimensional Array:

1. Array having more than one subscript variable is called Multi-Dimensional array.

2. Multi-Dimensional Array is also called as Matrix.

Syntax: <data type> <array name> [row subscript][column subscript];

Example:

Two Dimensional Arrays Declaration:

char name[50][20];
Initialization:
int a[3][3] = { {1, 2, 3}, { 4, 5, 6},{ 7,8, 9} };
Here a[0][0]=1; a[0][0]=1; a[0][1]=2; a[0][2]=3;

a[1][0]=4; a[1][1]=5; a[1][2]=6;

81 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

a[2][0]=7; a[2][1]=8; a[2][2]=9;

Two Dimensional Arrays:

 Two Dimensional Array requires Two Subscript Variables


 Two Dimensional Array stores the values in the form of matrix.
 One Subscript Variable denotes the “Row” of a matrix.
 Another Subscript Variable denotes the “Column” of a matrix.

Declaration and use of 2D Arrays:


int a[3][4];
for(i=0;i<row,i++)
for(j=0;j<col,j++)
{

printf("%d",a[i][j]);
}

Example Program:P22. Accept & Print 2×2 Matrix from user


#include<stdio.h>
void main()
{
int i, j, a[3][3];
for (i = 0; i < 3; i++)
{

for (j = 0; j < 3; j++)


{
printf("\nEnter the a[%d][%d] = ", i, j);
scanf("%d", &a[i][j]);
}

82 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

}
//Print array elements
for (i = 0; i < 3; i++)
{

for (j = 0; j < 3; j++)


{
printf("%d\t", a[i][j]);
}
printf("\n");
}
getch();

Example programs for practice:


P23. C Program for addition of two matrices

P24. C Program to find inverse of 3 X 3 Matrix

P25. C Program to multiply two 3 X 3 Matrices

P26. C Program to check whether matrix is magic square or not?

STRINGS
A string is a sequence of character enclosed with in double quotes (“ ”) but ends with \0. The
compiler puts \0 at the end of string to specify the end of the string. To get a value of string variable
we can use the two different types of formats.

 Using scanf() function as: scanf(“%s”, string variable);


 Using gets() function as : gets(string variable);

STRING HANDLING FUNCTIONS

C library supports a large number of string handling functions. Those functions are stored under
the header file string.h in the program.

Let us see about some of the string handling functions.

83 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

I. strlen() function
strlen() is used to return the length of the string , that means counts the number of
characters present in a string.
Syntax
integer variable = strlen (string variable);
Example:P27

void main()
{
char str[20];
int strlength;
clrscr();
printf(“Enter String:”);
gets(str);
strlength=strlen(str);
printf(“Given String Length Is: %d", strlength);
getch();
}

Output:
Enter String
Welcome
Given String Length is:7

II. strcat() function

The strcat() is used to concatenate two strings. The second string will be appended to the end of
the first string. This process is called concatenation.

Syntax

strcat (StringVariable1, StringVariable 2);

84 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Example:P28

void main()
{
char str1[20],str2[20];
clrscr();
printf(“Enter First String:”);
scanf(“%s”,str1);
printf(“Enter Second String:”);
scanf(“%s”,str2);
printf(“Concatenation String is:%s\n”, strcat(str1,str2));
getch();
}
Output:
Enter First String
Good
Enter Second String
Morning
Concatenation String is:

GoodMorning

III. strcmp() function

strcmp() function is used to compare two strings. strcmp() function does a case sensitive
comparison between two strings. The two strings are compared character by character until there is
a mismatch or end of one of the strings is reached (whichever occurs first). If the two strings are
identical, strcmp( ) returns a value zero. If they’re not, it returns the numeric difference between the
ASCII values of the first non-matching pairs of characters.
Syntax
strcmp(StringVariable1, StringVariable2);
Example: P29
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20], str2[20];

85 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

int res;
clrscr();
printf(“Enter First String:”);
scanf(“%s”,str1);
printf(“Enter Second String:”);
scanf(“%s”,str2);
res = strcmp(str1,str2);
if(res==0)
printf(“strings are equal”);
else
printf(“strings are not equal”);
getch();
}
Output:
Enter First String
Good
Enter Second String
Good
Strings are equal

Note:

strcmpi() function

strcmpi() function is used to compare two strings. strcmpi() function is not


case sensitive.

IV. strcpy() function:


strcpy() function is used to copy one string to another. strcpy() function copy the contents of
second string to first string.
Syntax
strcpy(StringVariable1, StringVariable2);
Example: P30
#include<stdio.h>
#include<conio.h>
void main()
{

86 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

char str1[20], str2[20];


int res;
clrscr();
printf(“Enter First String:\n”);
scanf(“%s”,str1);
printf(“Enter Second String:\n”);
scanf(“%s”,str2);
strcpy(str1,str2)
printf(“First String is:%s\n”,str1);
printf(“Second String is:%s”,str2);
getch();
}
Output:
Enter First String:
Hello
Enter Second String:
welcome
First String is: welcome
Second String is: welcome

V. strlwr () function:
This function converts all characters in a given string from uppercase to lowercase letter.
Syntax
strlwr(StringVariable);
Example:P31
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf(“Enter String:”);
gets(str);
printf(“Lowercase String : %s”, strlwr(str));
getch();

87 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

}
Output:
Enter String
WELCOME
Lowercase String : welcome
VI. strrev() function:
strrev() function is used to reverse characters in a given string.
Syntax
strrev(StringVariable);

Example:P32

#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf(“Enter String:”);
gets(str);
printf(“Reverse String : %s”, strrev(str));
getch();
}
Output:
Enter String
WELCOME
Reverse String : EMOCLEW

Note:
strupr() function:
strupr() function is used to convert all characters in a given string
from lower case to uppercase letter.
Syntax
strupr(Stringvariable);

Pointers

88 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

The pointer in C language is a variable which stores the address of another variable. An
integer variable holds (or you can say stores) an integer value, however an integer pointer holds the
address of an integer variable.
Consider the following example to define a pointer which stores the address of an integer.
int n = 10;
int *p = &n; // pointer declaration and initialization in single line.
n
10
5001

Here value of n=10 and value of p=5001.

Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.

int *a; //pointer to int

char *c; //pointer to char

By the help of * (indirection operator), we can print the value of pointer variable p

Eg P33:-
#include<stdio.h>
int main()
{
int number=50;
int *p;
p=&number; //stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number
printf("Value of p variable is %d \n",*p); // *p print the value of pointer variable
return 0;
}

Output

Address of p variable is fff4

Value of p variable is 50

Eg P34:-Write a program to display the value of variable and its location using pointer
Void main()

89 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

int *v, *p;

clrscr();

p=&v;

printf(“\n address of v=%u”,p);

printf(“\n value of v=%d”,*p);

printf(“\n address of p=%u”,&p);

Output

Address of v=4060

Value of v =10

Address of p=4062

Eg P35:-Write a program to print an element and its address using pointer.

void main ()

int i,*k;

clrscr ();

printf ("Enter a number : ") ;

scanf ("%d", &i) ;

k=&i;

printf (" \nAddress of i is %u", k) ;

printf (" \nValue of i is %d", *k) ;

Output

Enter a number: 15

Address of I is 4065

Value of I is 15

Eg P36:- write a program to add two numbers through variables and their pointers.

90 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

void main ( )

int a,b,c,d,*ap,*bp;

clrscr();

printf("Enter Two Numbers :");

scanf ("%d %d",&a,&b):

ap=&a;

bp=&b;

c=a+b;

d=*ap+*bp;

printf("\nSum of A & B Using Variable :%d",c);


printf("\nSum of A & B Using Pointers :%d",d);

OUTPUT:

Enter Two Numbers: 8 4


Sum of A & B Using Variable: 12

Sum of A & B Using Pointers: 12

Advantage of pointer
1) Pointer reduces the code and improves the performance; it is used to retrieving strings, trees, etc.
and used with arrays, structures, and functions.

2) We can return multiple values from a function using the pointer.

3) It makes you able to access any memory location in the computer's memory.

Usage of pointer

There are many applications of pointers in C language.

1) Dynamic memory allocation

In C language, we can dynamically allocate memory using malloc() and calloc() functions where the
pointer is used.

2) Arrays, Functions, and Structures

91 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Pointers in C language are widely used in arrays, functions, and structures. It reduces the code and
improves the performance.

NULL Pointer

A pointer that is not assigned any value but NULL is known as the NULL pointer. If you
don't have any address to be specified in the pointer at the time of declaration, you can assign NULL
value. It will provide a better approach.

int *p=NULL;

P37./*Swapping of two values using pointers*/

#include<stdio.h>
void main()
{
int a=10,b=20,*p1=&a,*p2=&b;
printf("Before swap: *p1=%d *p2=%d",*p1,*p2);
*p1=*p1+*p2;
*p2=*p1-*p2;
*p1=*p1-*p2;
printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);
getch();
}

Output

Before swap: *p1=10 *p2=20

After swap: *p1=20 *p2=10

THE void POINTERS


Pointers can also be declared as void types. void pointers cannot be dereferenced without
explicit type conversion. This is because being void the compiler cannot determine the size of the
object that the pointer points to. Though void pointer declaration is possible, void variable's
declaration is not allowed.

A void pointer can point any type of variable with proper type casting. The size of a void
pointer displayed will be two. When a pointer is declared as void two bytes are allocated to it. Later

92 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

using type casting, a number of bytes can be allocated or deallocated. Void variables cannot be
declared because memory is not allocated to them and there is no place to store the address.

WILD POINTERS

Pointers are used to store memory addresses. An improper use of pointer creates many errors
in the program. Hence, pointers should be handled cautiously. 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. That is uninitialized pointers are known as wild pointers. The wild pointer generates
garbage memory location and dependent reference. The pointer becomes wild due to the following
reasons:

 Pointer declared but not initialized


 Pointer alternation
 Accessing the destroyed data

Eg:-Write a program to show the wild pointer and its output.

void main()

int k,*x;

clrscr () ;

for(k=0;k<=3;k++)

printf("%u",x[k]);

OUTPUT:

7272 24 330 30 55 9 2 7 7 53

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.

Features of pointers

 Pointers provide direct access to memory.


 Reduce the storage space and complexity of the program.

93 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

 Reduces the execution time of the program.


 Provides an alternative way to access array elements.
 Address of objects can be extracted using pointers.
 Pointers help u8s to build complex data structures like linked list, stack, queues.

ARITHMETIC OPERATIONS WITH POINTERS

Arithmetic operations on pointer variables are also possible. Increment, decrement, prefix
and postfix operations can be performed with the pointers, The effects of these operations are shown
in Table.

Initial Address after Required


Dara Type Operation
Address Operation Bytes
int i=2 4046 ++ -- 4048 4044 25

char c= ‘x’ 4053 ++ -- 4054 4052 1

float f=2.2 4058 ++ -- 4062 4054 4

long l =2 4060 ++ -- 4064 4056 4

From the table we can observe that, on increment of the pointer variable for integers, the
address incremented by two. i.e. 4046 is the original address and on increment its value will be 4048
because integers require two bytes.

Similarly, characters, floating point numbers and long integers require 1, 4 and 4 bytes,
respectively.

Eg:-P38. Write a program to show the effect of increment and decrement operators used as
prefix and suffix with the pointer variable.

void main ()

int i, *ii;

puts ("Enter Value of i=") ;

scanf ("%d", &i) ;

ii=&i;

94 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

clrscr();

printf("Address of i = %u\n", ii);

printf("Address of I = %u\n", ++ii);

printf("Address of i = %u\n", ii++);

printf("Address of i = %u\n", --ii);

printf("Address of i =%u\n", ii--);

printf("Address of i = %u\n", ii);

OUTPUT:

Enter Value of i= 8
Address of i = 4060
Address of i = 4062
Address of i = 4062
Address of i = 4062
Address of i = 4062
Address of i = 4060

Eg:-P39. Write a program to perform different arithmetic operations using pointers.


void main()
{
int a=25,b=10,*Pi*j;
p=&a;
j=&b;
clrscr();
printf("\n Addition a+b = %d", *p+b);
printf("\n Subtraction a-b = %d", *p-b);
printf("\n Product a*b = %d", *p**j);
printf(“\n Division a/b = %d", *p / *j);
printf(“\n a Mod b = %d", *p % *j);
}
Output
Addition a+ b = 35
Subtraction a-b = 15
Product a*b = 250

95 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Division a/b = 2
a mod b = 5

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.

Eg:-P40write a program to display an array element with their addresses using array name
as a pointer

void main()

Int x[5]={2,4,6,8,10),k=0;

clrscr() ;

printf(" \ nElement No. Element Address");

while (k<5)

printf (\nx [%d] = \ t%8d %9u", k,* (x+k) ,x+k) ;

k++;

OUTPUT:

Element No. Element Address

x[0] = 2 4056

x[1]= 4 4058

x[2]= 6 4060

x[3]= 8 4062

96 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

x[4]= 10 4064

Eg: P41. Write a program to find the sum all the elements of an array. Use the array name
itself as pointer.

void main ( )

int sum=0,i=0,a[ ]={1,2,3,4,5};

clrscr ;

printf ("Elements Values Address \ n \ n") ;

while (i<5)

printf ("a [%d] \ t%5d \ t%8u \ n", * (a+i) , (a+i) ) ;

sum =sum+* (a+i++) ;

printf (" \ nSum of Array Elements = %d", sum) ;

OUTPUT:

Elements Values Address

A[0] = 1 4056

A[1] = 2 4058

A[2] = 3 4060

A[3] = 4 4062

A[4] = 5 4064

Sum of Array Elements = 15

POINTERS AND TWO-DIMENSIONAL ARRAYS

97 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

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 address of 1 st 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.

Eg:-P42. Write a program to display array elements and their addresses using pointers.

void main()

int i, j=1,*p;

int a[3][3]={(1,2,13),(4,5,61),(7,8,9)}:

clrscr();

printf("\t Elements of An Array with their addresses\n\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 an array with their addresses

1[4052] 2 [4054] 3 [4056]

4[4058] 5 [4060] 6 [4062]

7 [4064] 8 [4066] 9 [4068]

98 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

MODULE 5
FUNCTIONS
A function is a block of code that performs a specific task.
In C, we can divide a large program into the basic building blocks known as function. The function
contains the set of programming statements enclosed by {}. A function can be called multiple times
to provide reusability and modularity to the C program. In other words, we can say that the collection
of functions creates a program. The function is also known as procedure or subroutine in other
programming languages.
Advantage of functions in C

There are the following advantages of C functions.

 By using functions, we can avoid rewriting same logic/code again and again in a program.
 We can call C functions any number of times in a program and from any place in a program.
 We can track a large C program easily when it is divided into multiple functions
 Reusability is the main achievement of C functions.
 However, Function calling is always an overhead in a C program.

Function Aspects

There are three aspects of a C function.

Function declaration

All functions in a c program must be declared, before they are invoked. A function declaration (also
known as function prototype) consists of four parts.
 Function type (return type).
 Function name.
 Parameter list.
 Terminating semicolon.
The general format of function declaration is:

99 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Function-type function-name (parameter list) ;


In function declaration:
 The parameter list must be separated by commas.
 The parameter names do not need to be the same in the prototype declaration and the
function definition.
 Use of parameter names in the declaration is optional.
 If the function has no formal parameters, the list is written as (void)
 The return type is optional, when the function returns int type data.
 The return type must be void if no value is returned.

 Function definition

Function definition, also known as function implementation includes the following elements;

 Function name.
 Function type.
 List of parameters.
 Local variable declaration.
 Function statements; and
 A return statement.

The general format of function definition is:

function-type function-name (parameter list) /* function header*/


{
Local variable declaration; /*
Executable statement1;
………………………
function body
Executable statement n;
Return statement;
}

Function call

100 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

A function can be called by simply using the function name followed by a list of parameters (or
arguments), if any, enclosed in parentheses and separated by commas. If the function call does not
require any arguments, an empty pair of parentheses must follow the name of the function. The
function call may be a part of a simple expression (such as an assignment statement), or it may be
one of the operands within a more complex expression. The arguments appearing in the function call
are referred to as actual parameters.

The general format of function call is:


function name ( actual parameters );
variable = function name (actual parameters);

Function Aspects Syntax

Function Declaration Return_type function_name(argument list);

Function call Function_name(argument_list);

Return_type function_name(argument list)


{
Function Definition
Function body;
}

The syntax of creating function in c language is given below:

return_type function_name(data_type parameter...)


{
// Body of the function
}
Types of Functions

Functions

Library Functions User defined Functions

101 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

There are two types of functions in C programming:

1. Library Functions:

Library functions are built-in functions in Library functions are the functions which are
declared in the C header files (stdio.h) such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.

2. User-defined functions:

User defined functions are the functions which are created by the C programmer, so that
he/she can use it many times. It reduces the complexity of a big program and optimizes the code.

Return Value

C function may or may not return a value from the function. If you don't have to return any
value from the function, use void for the return type.

Let's see a simple example of C function that doesn't return any value from the

function.

Example without return value:

void hello()
{
printf("hello c");
}
If you want to return any value from the function, you need to use any data type such as int,
long, char, etc. The return type depends on the value to be returned from the function.

Let's see a simple example of C function that returns int value from the function.

Example with return value:

int get()
{
return 10;
}

102 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

In the above example, we have to return 10 as a value, so the return type is int. If you want
to return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type of
the method.

float get()
{
return 10.2;
}
Now, you need to call the function, to get the value of the function.

Different aspects of function calling

A function may or may not accept any argument. It may or may not return any value. Based
on these facts, there are four different aspects of function calls.

 function without arguments and without return value


 function without arguments and with return value
 function with arguments and without return value
 function with arguments and with return value

Example for Function without argument and without return value

Example P43.
#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf(" C programming");
}
Output
Hello C programming

103 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Example P44.

#include<stdio.h>
void sum();
void main()
{
printf("\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Output
Going to calculate the sum of two numbers:
Enter two numbers
10
20
The sum is 30
Example for Function without argument and with return value
Example P45
#include<stdio.h>
#include<conio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
getch();

104 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d%d",&a,&b);
return a+b;
}
Output
Going to calculate the sum of two numbers:
Enter two numbers
10
20
The sum is 30

Example P46:
program to calculate the area of the square

#include<stdio.h>
float square();
void main()
{
printf("Going to calculate the area of the square\n");
float area = square();
printf("The area of the square: %f\n",area);
getch();
}
float square()
{
float side;
printf("Enter the length of the side in meters: ");
scanf("%f”,&side);
return side * side;
}
Output

105 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Going to calculate the area of the square


Enter the length of the side in meters: 10
The area of the square: 100.000000
Example for Function with argument and without return value
Example P47
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}

Output
Going to calculate the sum of two numbers:
Enter two numbers
10
20
The sum is 30

Example P48:

program to calculate the average of five numbers.


#include<stdio.h>
void average(int, int, int, int, int);
void main()
{
int a,b,c,d,e;

106 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

printf("\nGoing to calculate the average of five numbers:");


printf("\nEnter five numbers:");
scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
average(a,b,c,d,e);
}
void average(int a, int b, int c, int d, int e)
{

float avg;
avg=(a+b+c+d+e)/5);
printf(“The average of five numbers=%f ”,avg);
}

Output
Going to calculate the average of five numbers
Enter five numbers
10
20
30
40
50
The average of five numbers= 30.000000

Example function with argument and with return value


Example P49
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);

107 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

}
int sum(int a, int b)
{
return a+b;
}
Output
Going to calculate the sum of two numbers:
Enter two numbers:
10
20
The sum is: 30
C Library functions
Library functions are the inbuilt function in C that are grouped and placed at a common place
called the library. Such functions are used to perform some specific operations. For example, printf
(Is a library function used to print on the console. The library functions are created by the designers
of compilers. All C standard library functions are defined inside the different header files saved
with the extension .h. We need to include these header files in our program to make use of the library
functions defined in such header files.

Header file Description


stdio.h This is a standard input/output header file. It contains all the library
functions regarding standard input/output.
conio.h This is a console input/output header file
string .h It contains all string related library functions like gets(), puts(),etc.
stdlib.h This header file contains all the general library functions like malloc(),
allot(), exit(), etc.
math.h This header file contains all the math operations related functions like
sqrt(), pow(), etc.

ctype.h This header file contains all character handling functions.


time.h This header file contains all the time-related functions
stdarg.h Variable argument functions are defined in this header file.
signal.h All the signal handling functions are defined in this header file.

108 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

CALL BY VALUE AND REFERENCE


There are two ways in which we can pass arguments to the function or we can call the functions.

 Call by value
 Call by reference

Call by Value
In this type, the value of actual arguments is passed to the formal arguments and operation is
done on the formal arguments. Any change in the formal arguments made does not affect the actual
arguments because formal arguments are the photocopy of the actual argument. Hence, when a
function is called by the call by value method, it does not affect the actual contents of the arguments.
Changes made in the formal arguments are local to the block of the called function.
P50. Write a program to exchange values of two variables by using 'call by value'
to the function.
#include<stdio.h>
void swap(int x,int y);
main()
{
int a,b;
printf(“Enter the values:”);
a=10;
b=20;
swap(a,b);
printf(“a=%d b=%d”,a,b);
}
void swap(int x,int y)
{
int t;
t=x;
x=y;
y=t;
printf(“x=%d y=%d”,x,y);
}
Output
x=20 y=10

109 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

a=10 b=20
Call by Reference
In this type, instead of passing values, addresses (reference) are passed. Function operates on
addresses rather than values. Here, the formal arguments are pointers to the actual argument. In this
type, formal arguments point to the actual argument. Hence, changes made in the argument are
permanent.

P51. Write a program to send a value by reference to the user-defined function.


#include<stdio.h>
void swap(int *x,int *y);
void main()
{
int a,b;
printf(“Enter the values:”);
a=10;
b=20;
swap(&a,&b);
printf(“a=%d b=%d”,a,b);
}
void swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
printf(“x=%d y=%d”,*x,*y);
}
Output
x=20 y=10
a=20 b=10

RECURSION

110 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

The C language supports recursive feature, i.e. a function is call repetitively by itself. The
recursion can be used directly or indirectly. The direct recursion function calls to itself till the
condition is true. In indirect recursion, a function calls to another function and then called function
calls to the calling function.
Example P52.
/* recursive function for factorial*/
int fact (int) ;
void main()
{
int num, f;
clrscr();
printf("\n Enter a number ;");
scanf ("%d", &num);
f=fact (num) ;
printf("\n Factorial of (%d) is (%d)",num,f);
}
int fact(int f)
{
if (f==1)
return f;
else
return f*fact(f-1);
}
OUTPUT:
Enter a number: 4
Factorial of (4) is (24)

P53. /*recursive function for fibonnaci series*/


int fibonnaci (int x)
{
if(x<=2) return 1;
return fibonnaci(x-1)+fibonnaci(x-2);
}
main()
{

111 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

printf("\n fact(10) : %d",fact(10));


printf("\n fibonnaci(10) : %d",fibonnaci(10));
}

Types of Recursion
int num()
{
…….
sum();
int num() }
{
……… Int sum()
num(); {
………
} num();
}

Direct recursion Indirect recursion

Following are the types of the recursion in C.

 Direct Recursion
 Indirect Recursion
 Tail Recursion
 No Tail/ Head Recursion

Direct Recursion
When a function calls itself within the same function repeatedly, it is called the direct
recursion.

Structure of the direct recursion


fun()
{
// write some code
fun();
// some code

112 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

}
In the above structure of the direct recursion, the outer fun() function recursively calls the
inner fun() function, and this type of recursion is called the direct recursion.
Indirect Recursion
When a function is mutually called by another function in a circular manner, the function is
called an indirect recursion function.

Structure of the indirect recursion


fun1()
{
// write some code
fun2()
}
fun2()
{
// write some code
fun3()
// write some code
}
fun3()
{
// write some code
fun1()
}

In this structure, there are three functions, fun1(), fun2(), fun3() and fun4(). When the fun1()
function is executed, it calls the fun2() for its execution. And then, the fun2() function starts its
execution calls the fun3() function. In this way, each function leads to another function to makes
their execution circularly. And this type of approach is called indirect recursion.
Tail Recursion
A recursive function is called the tail-recursive if the function makes recursive calling itself,
and that recursive call is the last statement executes by the function. After that, there is no function
or statement is left to call the recursive function.
void fun1( int num)
{
// if block check the condition
if (num == 0)
return;
else

113 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

printf ("\n Number is: %d", num); // print the number


return fun1(num - 1); // recursive call at the end in the fun() function
}
int main ()
{
fun1(7); // pass 7 as integer argument
return 0;
}

Non-Tail / Head Recursion


A function is called the non-tail or head recursive if a function makes a recursive call itself,
the recursive call will be the first statement in the function. It means there should be no statement or
operation is called before the recursive calls. Furthermore, the head recursive does not perform any
operation at the time of recursive calling. Instead, all operations are done at the return time.
Example
#include <stdio.h>
void head_fun (int num)
{
if ( num > 0 )
{
// Here the head_fun() is the first statement to be called
head_fun (num -1);
printf (" %d", num);
}
}
int main ()
{
int a = 5;
printf (" Use of Non-Tail/Head Recursive function \n");
head_fun (a); // function calling
return 0;
}

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 the recursion. Library function cannot be
involved in recursion because their source code cannot be viewed.

114 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

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.

int num()
{
if (condition)
…………..
num();
}

The user-defined function main ( ) can be invoked recursively. To implement such recursion, it is
necessary to mention prototype of function main ( ).
Recursion versus iterations
Recursion Iteration
Recursion uses selection structure. Iteration uses repetition structure
Recursion is the term given to the mechanism of The block of statement is executed
defining a set or procedure in terms of itself. repeatedly using loops.
A conditional statement is required in the body of The iteration control statements itself
the function for stopping the function execution. contain statements for stopping the
iteration.
At some places, the use of recursion generates extra Iteration does not create any overhead
overhead
Recursion always applied to functions Iteration is applied to statements or loops
Recursion is slow in execution Iteration is fast in execution
Recursion reduces the size of code Iteration makes the code longer

ADVANTAGES AND DISADVANTAGES OF RECURSION


Advantages
1. Although, 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.

115 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Disadvantages

1. It requires extra storage space. The recursive calls and automatic variables are stored on the
stack. 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. In such a situation user has to press Ctrl+ break to pause and s
the function.
3. The recursion function is not efficient in execution speed and time.
4. If possible, try to solve a problem with iteration instead of recursion.

STORAGE CLASSES

There are two different ways to characterize variables: by data type, and by storage class.

Data type refers to the type of information represented by a variable, e.g., integer number, floating-
point number, character, etc.

Storage class refers to the performance of a variable, and its scope within the program.

There are four different storage-class specifications in C:

 Automatic variables
 External variables
 Static variables
 Register variables
1. Automatic Variables

Automatic variables are declared inside a function in which they are to be utilized. They are
created when the function is called and destroyed automatically when the function is exited, hence
the name automatic. Automatic variables are therefore private (or local) to the function in which they
are declared. Because of this property, automatic variables are also referred to as local or internal
variables.

The general form of the variable declaration statement

< Storage class specifier > < data type > < variable name > ;

116 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Example:

auto char name ;

auto int number ;

A variable declared inside a function without storage class specification is, by default, an automatic
variable.
Example:-
main()
{
int i;
for(i=0; i<2; i++)
stat();
}
void stat()
{
int x=0;
x=x+1;
printf(“x=%d”,x);
}
Output
x=1
x=1
x=1
2. External variables

Variables that are both alive and active throughout the entire program are known as external
variables. They are also known as global variables. Unlike local variables, global variables can be
accessed by any function in the program. External variables are declared outside a function. The
‘extern’ keyword is used for declaring external variables.

Example:1
int number; /* global
int count=50; variables
float length =5.5; */
main()
{

117 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

count=10; /* take the value of count=10*/


---------
---------
}
Function1()
{
int count=0; /* take the value of count=0*/
--------
--------
}
Example:2
int no;
float length;
main()
{
---------
}
func1()
{
----------
}
Example:3
main()
{
y=5;
-------
------
}
int y;
func1()
{
y=y+1
}
In example 3, as far as main is concerned, y is not declared. So main function cannot access
the variable y. This problem can be overcome by declaring the variable with the storage class extern.

118 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

main()
{
extern int y;
--------------
}
func1()
{
extern int y;
--------------
}
int y;
Although the variable y has been defined after both the functions, the external declaration of
y inside the functions informs the compiler that y is an integer type defined somewhere else in the
program. The extern declaration does not allocate storage space for variables.

3. Static variables
The value of static variables persists until the end of the program. A variable can be declared static
using the keyword static.
static int x;
static float y;
A static variable may be either an internal type or an external type depending on the place of
declaration. Internal static variables are those which are declared inside a function. An external static
variable is declared outside of all functions and is available to all the functions in that program.
Example:
main ()
{
int i;
for (i=1; i<=3;i++)
Function1 ();
}
Function1 ()
{
static int x=0; /* take the value of x=0*/
x=x+1;
printf (“x=%d\n”, x);

119 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

}
Output
x=1
x=2
x=3
A static variable initialized only once, when the program is compiled. It is never initialized
again. During the first call to stat() x is incremented to stat(). Because x is static this value persists
and therefore the next call add another 1 to x giving it a value of 2. The value of x becomes 3 when
the third call is made.
4. Register variables
Registers are special storage areas within the computer’s central processing unit. In C, the
values of register variables are stored within the registers of the CPU. A variable can be assigned
this storage class by preceding the type declaration with the keyword register. Usually only integer
variables are assigned the register storage class.
Example:
register int a,b,c;

STRUCTURES
A structure is a collection of one or more variables of different data types, grouped together
under a single name. It is a user-defined data type because the user can decide the data types to be
included in the body of a structure. By using structures, we can make a group of variables, arrays,
pointers.
DEFINING A STRUCTURE
General syntax:
struct tag_name
{
data type member1;
data type member2;


};
Example:
struct books

120 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

{
char title[20];
char author[15];
int pages;
float price;
};
The keyword struct declares a structure to holds the details of four fields namely title, author, pages
and price. These are members of the structures. Each member may belong to different or same data
type.
DECLARING A STRUCTURE VARIABLES
A structure variable declaration is similar to the declaration of variables of any other data types. It
includes the following elements:
1. The keyword struct
2. The structure tag name.
3. List of variable names separated by commas.
4. Terminating semicolon.
For eg:
The statement
struct books book1, book2, book3;
Declares book1, book2 and book3 as variables of type struct books .
The complete declaration
struct books
{
char title[20];
char author[15];
int pages;
float price;
};
struct lib_books book1, book2, book3;
It is also allowed to combine both the structure definition and variable declaration in one statement.

struct books
{

121 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

char title[20];
char author[15];
int pages;
float price;
} book1, book2, book3;
Arrays vs Structures
Both arrays and structures are classified as structured data type. But they differ in a number of ways.
 An array is a collection of related data element of the type. Structure can have elements of
different types.
 An array is a derived data type whereas the structure is a programmer defined one.
 An array behaves like a built-in data type. All we have to do is to declare an array variable
and use it. But in the case of a structure, first we have to design and declare a data structure
before the variables of that type are declared and used.
ACCESSING STRUCTURE MEMBERS
The link between a member and a variable is established using the member operator ‘.’ which is
also known as ‘dot operator’ or ‘period operator’.
For example
Book1.price
P54. /* Example program for using a structure*/
#include< stdio.h >
void main()
{
struct student
{
int rollno;
char name[20];
char address[20];
int age;
}stud;
printf(“Enter the student information”);
printf(“Enter the student rollno”);
scanf(“%d”,&stud.rollno);

122 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

printf(“Enter the name of the student”);


scanf(“%s”, stud.name);
printf(“Enter the address of the student”);
scanf(“%s”, stud.address);
printf(“Enter the age of the student”);
scanf(“%d”, &stud.age);
printf(“Student information\n”);
printf(“student roll_number=%d\n”, stud.rollno);
printf(“student name=%s\n”, stud.name);
printf(“student Address=%s\n”, stud.address);
printf(“Age of student=%d\n”,stud.age);
}
STRUCTURE INITIALIZATION
A structure variable can also be initialized in the way as any other data type in C.
struct student_record
{
char name[50];
int rollno;
} student= {“abc”, 25};
This assigns value abc to student.name and25 to student.rollno .
The compile time initialization of structure variable must have the following elements:
1. The keyword struct
2. The structure tag name
3. The name of variable to be declared
4. The assignment operator=.
5. A set of values for the members of the structure variable, separated by commas and enclosed in
braces.
6. A terminating semicolon.
NESTED STRUCTURES
When a structure is declared as the member of another structure, it is called as a nested structure or
structure within a structure.
Syntax

123 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

struct structure-name
{
data-type member 1;
data-type member 2;
struct structure-name
{
data-type member 11;
data-type member 21;
};
};
ARRAYS OF STRUCTURES
We can declare arrays whose elements are structures. Such arrays are called arrays of structures or
structure arrays.
Syntax
struct structure-name arrayname[size];
For example, if we have a structure as shown below, we declare an array of structure as
struct student
{
char name[15];
int age;
float marks;
} student stud[3];
Here, the structure student contains 3 members such as a character variable name, an integer
variable age and a float variable mark. Then, we declare an array stud with size equal to 3. Now it
can store 3 structures, each of which having name, age and mark. The members of these structures
can be referenced as stud [0].name, stud [0].age etc.

POINTER TO STRUCTURE
We know that the pointer is a variable that holds the address of another data variable. The
variable may be of any data type, i.e. int, float or double. In the same way, we can also define pointer
to structure. Here, starting address of the member variables can be accessed. Thus, such pointers are
called structure pointers.

124 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

struct book
{
char name [20];
char author [25];
int pages;
};
struct book *ptr;
In the above example ptr is pointer to structure book. The pointer member can be accessed
as
ptr->name
ptr->author
ptr->pages
Structure and Functions
Like variables of standard data type structure variables can be passed to the function by values or
address.
The syntax of the same is as follows:
struct book
{
char name(35);
char author(35);
int pages;
} bl;
void main()
{
……………
…………….
show (&b1) ;
}
show (struct book *b2)
{
……………

125 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

……...
}
Whenever a structure element requires passing any other function, it is essential to declare the
structure outside the main () function i.e. global.
UNION
Union is the concept borrowed from structure and therefore follow the same syntax as
structure. But they differ in terms of storage. In structures, each member has its own storage location,
whereas all the members of a union use the same location. A union can store only one member at a
time. Syntax of union definition is shown below:
union union -name
{
data-type member 1;
data-type member 2;
-----------------
-----------------
};
Example
union item
{
int m;
float x;
char c;
}code;
typedef
We can create new data type by using typedef. The statement typedef is to be used while defining
the new data type.
The syntax is as follows:
typedef type dataname;
Here, type is the datatype and dataname is the user-defined name for that type.
typedef int hours;
Here, hours are another name for int and now we can use hours instead of int in the program as
follows:

126 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

hours hrs;

BIT FIELDS
In C, we can specify size (in bits) of structure and union members. The idea is to
use memory efficiently when we know that the value of a field or group of fields will never
exceed a limit or is within a small range.
For example, consider the following declaration of date without the use of bit fields.

#include <stdio.h>
// A simple representation of the date
struct date
{
unsigned int d;
unsigned int m;
unsigned int y;
};
int main()
{
printf("Size of date is %lu bytes\n", sizeof(struct date));
struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}

Output:
Size of date is 12 bytes
Date is 31/12/2014
The above representation of ‘date’ takes 12 bytes on a compiler where an unsigned int takes
4 bytes. Since we know that the value of d is always from 1 to 31, the value of m is from 1 to 12,
we can optimize the space using bit fields.
#include <stdio.h>
// Bit field representation

127 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

struct date
{
unsigned int d: 6;
unsigned int m : 5:
unsigned int y;
};
int main()
{
printf("Size of date is %lu bytes\n", sizeof(struct date));
struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}
enumerated data type(enum)
The enum in C is also known as the enumerated type. It is a user-defined data type that
consists of integer values, and it provides meaningful names to these values. The use of enum in
C makes the program easy to understand and maintain. The enum is defined by using the enum
keyword.

Syntax

enum enum_name{const1, const2, ....... };

enum week{sun,mon,tues,wed,thur,fri,sat};
This statement creates a user-defined data type. The keyword enum is followed by the tag
name week. The enumerators are the identifiers sun,mon,tues,wed,
thur,fri. Their values are constant unsigned integers and starts from 0. The identifier sun refers
to 0, mon to 1 and so on. The identifiers are not to be enclosed with quotation marks. Please also
note that integer constants are also not permitted.
void main()
{
enum month (Jan=1, Feb, Mar, Apr, May, June, July, Aug, Sep, Oct,
Nov, Dec); clrscr();
printf("\nJan = %d",Jan);
printf("\nFeb = $d",Feb);

128 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

printf("\nJune = %d",June);
printf("\nDec = %d",Dec );
}

OUTPUT :
Jan = 1
Feb = 2
June = 6
Dec - 12
Dynamic memory allocation in C
The concept of dynamic memory allocation in c language enables the C programmer to
allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions
of stdlib.h header file.

1. malloc()
2. calloc()
3. realloc()
4. free()

Before learning above functions, let's understand the difference between static memory
allocation and dynamic memory allocation.

static memory allocation dynamic memory allocation

Memory is allocated at compile time. Memory is allocated at run time.

Memory can't be increased while executing Memory can be increased while executing
program. program.

Used in array. Used in linked list.

malloc() Allocates single block of requested memory.

calloc() Allocates multiple block of requested memory.

129 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

realloc() Reallocates the memory occupied by malloc() or calloc() functions.

free() Frees the dynamically allocated memory.

malloc() function in C
The malloc() function allocates single block of requested memory.
A memory block is allocated with a function called malloc( ) . In other words, the malloc ( )
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 prototypes are declared in alloc . h and stdl b . h.
The format of the malloc( ) function is as follows:
pnt= (datatype*) malloc(given_size);
Here, from data type, compiler understands the pointer type and given size is the size to
reserve in the memory.
For example:
pnt=( int 4) malloc(20);
Here, in this declaration 20 bytes are allocated to pointer variable pnt of type int and base
address is returned to pointer pnt .
Let's see the example of malloc() function.
P55. #include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}

130 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

printf("Enter elements of array: ");


for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
calloc() function in C
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 the calloc ( ) function is as follows:
ptr=(datatype*)calloc(number, byte-size);
pnt= (int *) calloc (4/ 2) ;
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.
The calloc ( ) can be used in place of the malloc( ) function.
P56. #include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");

131 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
realloc() function in C
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc()
function. In short, it changes the memory size.
The syntax of realloc() function.
ptr=realloc(ptr, new-size)

free() function in C
The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.

132 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

The syntax of free() function.


free(ptr);

Memory Models
 TINY
 SMALL
 COMPACT
 MEDIUM
 LARGE
 HUGE.
TINY Model:
All segment registers are initialized with the identical value and all addressing is
accomplished using 16 bits. This means that the code, data and stack all must fit with in the same
64-KB segment. Programs are executed quickly in this case.
SMALL Model:
All codes should fit in a single 64-KB segment and all data should fit in a second 64-KB
segment. All pointers are 16 bits in length. Execution speed is same as tiny model. In the SMALL
model all code is placed in one physical segment and all data in another physical segment.
COMPACT Model:
All codes should fit in 64 KB segment, but the data can use multiple segments. However, no data
item can surpass 64 KB. All pointers to data are 32 bits, but jumps and calls can use 16 bit addresses.
There is slow access to data quick code execution.
MEDIUM Model:
All data should be fit in a single 64-KB segment; however, the code is allowed to use multiple
segments. All pointers to data are 16 bits, but all jumps and calls require 32-bit addresses. Fast access
to data is observed, but slower program execution is noticed with this model.
LARGE Model:
In the LARGE model both code elements (procedures) and data elements (variables) are
allowed to use multiple segments. All pointers are 32 bits in length. However, no single data item
can exceed 64 KB. There is slower code execution.

HUGE Model:

133 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Both code and data are allowed to use multiple segments. Every pointer is of 32 bit in length.
Single data item can exceed 64 KB. There is slower code execution.
********************************************************************
********************************************************************

B.Sc/BCA DEGREE(CBCS)REGULAR/IMPROVEMENT/REAPPEARANCE
EXAMINATIONS, FEBRUARY 2023
First Semester
CS1CRT02 - METHODOLOGY OF PROGRAMMING AND C LANGUAGE
Part A
Answer any ten questions.
Each question carries 2 marks.
1. What is an Assembler?
2. List out the characteristics of a good programming language.

3. What is a selection structure?


4. What are static variables?
5. What is the output of the following program
main()
{
int x=100,y=200;

printf("%d",(x>y)? x:y);
}
6. Explain the use of getch() statement.
7. What is the use of ‘default’ in switch statement?
8. How will you initialize an array?
9. Write short note on different arithmetic operations performed on a pointer.

10. Write the syntax of function definition.


11. What are the rules to be followed while using recursion?
12. Define
a) malloc b)calloc (10×2=20)

134 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Part B
Answer any six questions.
Each question carries 5 marks.
13. What are the different classifications of programming languages?
14. What do you mean by Testing and Debugging? Explain.
15. Why do you mean by type modifier? What are the different type conversions possible in C?
Explain with example
16. Write a C program to check whether the given number is Armstrong number or not.
17. Write a C program to print the series 1, 3, 9, 27, 81 ……up to a given 'n'.
18. Write a C Program to find the transpose a matrix.
19. What is the relationship between array and pointer?

20. How an array is passed to a function explain it with example


21. Explain the difference between structure and union with example (6×5=30)
Part C
Answer any two questions.
Each question carries 15 marks.
22. a) What is a flowchart ? Explain the different symbols used in flow chart.
b) Draw a flowchart to check whether a number is prime or not.
23. Explain different tokens in C language.

24. Write a C program to check whether two strings are equal or not without using string
handling functions.
25. a) Explain storage classes in C with example
b) What is recursion? What are its different types? Write a recursive function to find the
factorial of a given integer. (2×15=30)
B.Sc/BCA DEGREE(CBCS)EXAMINATIONS, OCTOBER 2021
First Semester
METHODOLOGY OF PROGRAMMING AND C LANGUAGE
Part A
Answer any ten questions.
Each question carries 2 marks.
1. List out any three factors for selecting a programming language.
2. Draw a flow chart to find the average of three numbers.
3. List the three control structures with atleast one example for each.
4. Differentiate between keywords and identifiers.
5. What are different storage class specifiers in C?

135 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

6. Explain the use of printf() statement.


7. Draw the flow chart showing the execution of while loop in C.
8. How a matrix can be declared in C?
9. Differentiate between array of pointers and pointers to array.
10. Write the commonly used library functions in C.
11. What is external variable?
12. What is dynamic memory allocation? (10×2=20)
Part B
Answer any six questions.
Each question carries 5 marks.
13. Discuss about various programming languages with its advantages and limitations.
14. What do you mean by Testing and Debugging? Explain.
15. Discuss the precedence of arithmetic, logical and relational operators in C.
16. Discuss the various unconditional branching statements in C.
17. Write a C program to print the first n prime numbers.
18. What is array? Write a program to sort a set of numbers in ascending order.
19. Write a C program to find the number of vowels in a string.
20. What is the difference between function prototype and function definition? Explain with an
example.
21. What is recursion? Write a program to find the factorial of a number using recursion?
(6×5=30)

Part C
Answer any two questions.
Each question carries 15 marks.
22. Explain about a) Linker b) Subprogram c) Differences between compiler and interpreter.
23. Explain in detail various data types used in C with example.
24. a) Write a C program using pointer to swap the values of two integer number.
b) Explain the relation between an array and a pointer. What is wild pointer in C?
25. Explain a) structure with sample program.
b) Explain Pointers to Structure. (2×15=30)
B.Sc.DEGREE (CBCS) EXAMINATION, NOVEMBER 2019
First Semester

Core Course - CS1CRT02 - METHODOLOGY OF PROGRAMMING AND C LANGUAGE


Part A
Answer any ten questions.
Each question carries 2 marks.

136 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

1. List out the characteristics of a good programming language.


2. Create an algorithm to find the reverse of a number.
3. What is Debugging?
4. What are static variables?

5. Define the term 'type casting'.


6. Explain the use of getche() statement
7. What is a loop?
8. How a matrix can be declared in C?
9. What is meant by wild pointer?
10. What is user defined function?
11. Compare Union and Structure in C

12. Define a) malloc b) calloc. (10×2=20)


Part B
Answer any six questions.
Each question carries 5 marks.
13. Compare compiler and interpreter.
14. Explain the various control structures used in a programming language.
15. Explain various bitwise operators in C.
16. Distinguish break and continue statements with the help of examples.

17. Given are the marks of three subjects. Write a C program to display the student's grade (A -
above
90%, B - above 60%, C - above 40%) using else if ladder.
18. Write a C program to find the number of vowels in a string.

19. Explain how to pass array as argument to function with example.


20. Differentiate between call by value and call by reference with the help of an example.
21. Write a program to find the sum of n numbers using recursion. (6×5=30)
Part C
Answer any two questions.
Each question carries 15 marks.
22. Write an essay about the various types of programming languages with its advantages and
disadvantages.
23. Explain different tokens in C language.

137 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

24. a) What is an array? Explain single dimensional array b) Write a C program to insert an item
into a

given position in an array.


25. Explain different storage classes in C with example. (2×15=30)
B.Sc. DEGREE (CBCS) EXAMINATION, NOVEMBER 2019
First Semester
Core Course - CS1CRT02 - METHODOLOGY OF PROGRAMMING AND C LANGUAGE
Part A
Answer any ten questions.
Each question carries 2 marks.
1) What is an algorithm?
2) What is a pointer?
3) What are keywords?
4) What is pseudo code?
5) Define Linker?
6) What is mean by testing and debugging?
7) Briefly explain the characteristics of a good program.
8) Discuss the purpose of program planning.
9) What are enumerated data types?
10) What is a variable? What are naming rules?
11) List any three unconditional branching statements.
12) What are header files? Give examples.

Part B
Answer any six questions.
Each question carries 5 marks.
13) Discuss various bitwise operators in C.
14) What are strings? Explain 5 string handling functions.
15) What are structures in C? How is it different from Union? Give examples.
16) Discuss various arithmetic operations with pointers.
17) Explain the difference between entry controlled and exit controlled loops. Explain with the
help of example.
18) What are Language translators?
19) What is meant by dynamic memory allocation? Explain.
20) What is recursion? Explain direct and indirect recursion.
21) With the help of flowchart, explain any two decision statements in C. Give examples.

Part C
Answer any two questions.

138 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

Each question carries 15 marks.


22) Write a C program to add two square matrices.
23) Write notes on various operators in C.
24) What is a function? Discuss different types of functions. Give examples.
25) Explain in detail the various data types in C.

List of Programs

1. Write a program to find the largest among three numbers


2. Find the sum of digits of a number
3. Reverse of a number
4. Check whether an input number is Armstrong or not
5. Find the sum of first n natural numbers
6. Find ‘n’ number of Fibonacci Series.
7. Print Floyd’s Triangle.
8. Program using switch statement for displaying the day corresponding to a number.
9. Generate ‘n’ Prime number series.
10. Find the value of nPr and nCr.
11. Input five numbers into an array and find the largest and second largest among them.
12. Input ‘n’ numbers into an array and sort them in ascending order.
13. Write a program to search for a given number from an array and if it is found find its
position in the array.
14. Input five names into an array and arrange them in alphabetical order.
15. Check whether a matrix is symmetric or not
16. Find the value of trace and norm of a matrix.
17. Multiplication of two matrices.
18. Check whether a given matrix is upper triangular or not
19. Find the factorial of a number using function.
20. Input a string and check whether it is palindrome or not
21. Program using call by reference
22. Define a structure with fields Rollno, Name, Mark of three subjects and also calculate the
total mark of each student.
23. Write a program to illustrate the method of sending an entire structure as a parameter to a
function.

139 Dept. of CS, IGCAS


Methodology of Programming & C Language BCA/BSc CS

24. Write a program using pointers to find the sum of all the elements of an array.
25. Write a program to create a structure book with members bookname, author and noofpages
and enter the details of five books and print the same.

140 Dept. of CS, IGCAS

You might also like