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

EC22303 UNIT 1 notes

notes

Uploaded by

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

EC22303 UNIT 1 notes

notes

Uploaded by

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

EC22303 C PROGRAMMING AND DATA STRUCTURES LTPC

3 0 0 3

UNIT I C PROGRAMMING FUNDAMENTALS 9


Introduction to programming paradigms – Storage classes - Operations Precedence and
Associativity – Compilation process - Functions – Recursive Functions – Array –
String processing.

UNIT II C PROGRAMMING - ADVANCED FEATURES 9


Structures – Union – Enumerated Data Types – Pointers: Pointers to Variables, Arrays and
Functions – File Handling – Pre-processor Directives.

UNIT III LINEAR DATA STRUCTURES 9


Abstract Data Types (ADTs) – List ADT – Array-Based Implementation – Linked List –
Doubly Linked Lists – Circular Linked List – Stack ADT – Implementation of Stack –
Applications – Queue ADT – Priority Queues – Queue Implementation – Applications.

UNIT IV NON-LINEAR DATA STRUCTURES 9


Trees – Binary Trees – Tree Traversals – Expression Trees – Binary Search Tree –
Hashing – Hash Functions – Separate Chaining – Open Addressing – Linear Probing–
Quadratic Probing – Double Hashing – Rehashing.

UNIT V SORTING AND SEARCHING TECHNIQUES 9


Sorting - Insertion Sort – Quick Sort – Heap Sort – Merge Sort – Searching - Linear
Search – Binary Search.
Total Period: 45 Periods
References
Text Books (T):
T1. Mark Allen Weiss, “Data Structures and Algorithm Analysis in C”, Second Edition,
Pearson Education, 1997.
T2. Reema Thareja, “Programming in C”, Second Edition, Oxford University Press, 2016.
Reference Books (R):

R1. Anita Goel and Ajay Mittal, “Computer Fundamentals and Programming in C”, First
Edition, Pearson Education, 2013.
R2. Paul J. Deitel, Harvey Deitel, “C How to Program”, Seventh Edition, Pearson Education,
2013.
R3. Alfred V. Aho, John E. Hopcroft, Jeffrey D. Ullman, “Data Structures and Algorithms”,
Pearson Education, 2016.
R4. Ellis Horowitz, Sartaj Sahni and Susan Anderson, “Fundamentals of Data Structures”,
Galgotia, 2018.
R5. Kernighan, B.W and Ritchie, D.M, “The C Programming language”, Second Edition,
Pearson Education, 2015.

Additional References
Books (AR):
AR1. Reema Thareja, “Data structures using C”, Second Edition, 2014.
Journals/Magazines (J):
J1.https://www.routledge.com/Data-Structures-using-C-A-Practical-Approach-for-Beginners/
Jagtap-Mali/p/book/9780367616311
J2.
https://www.researchgate.net/publication/259058750_Programming_and_Data_Structure_usin
g_C

Web References (W):


W1. https://onlinecourses.nptel.ac.in/noc23_cs93/preview - C Programming and Assembly
Language
W2. https://onlinecourses.nptel.ac.in/noc23_cs95/preview - Programming, Data Structures
and Algorithms Using Python.
Others (O) (Pls. Specify):
O1 https://www.coursera.org/specializations/data-structures-algorithms.
O2. https://www.goclasses.in/courses/Data-Structures-62655aaa0cf21b4eea415dbb.
O3. https://www.codecademy.com/learn/learn-data-structures-and-algorithms-with-python.
I
C PROGRAMMING
FUNDAMENTALS
Introduction to programming paradigms – Storage classes - Operations Precedence and
Associativity – Compilation process - Functions – Recursive Functions – Array – String
processing.

1.1 INTRODUCTION TO PROGRAMMING PARADIGMS


 Paradigm can also be termed as method to solve some problem or do some task.
 Programming paradigm is an approach to solve problem using some
programming language or also we can say it is a method to solve a problem using
tools and techniques that are available to us following some approach.
 There are lots for programming language that are known but all of them need to
follow some strategy when they are implemented and this methodology/strategy
is paradigms. Apart from varieties of programming language there are lots of
paradigms to fulfil each and every demand. The programming paradigm is
divided into two broad categories.
 Imperative programming paradigm
 Declarative programming paradigm

1.1.1 Imperative programming paradigm


 It is one of the oldest programming paradigm. It features close relation to
machine architecture. It is based on Von Neumann architecture. It works by
changing the program state through assignment statements. It performs step by
step task by changing state. The main focus is on how to achieve the goal. The
paradigm consist of several statements and after execution of all the result is
stored.
Advantage
1. Very simple to implement
2. It contains loops, variables etc.
DisadvantageComplex problem cannot be solved
1. Less efficient and less productive
2. Parallel programming is not possible
Examples of Imperative programming paradigm: C, FORTAN, Basic

Figure 1.1 Types Programming Paradigms


 Imperative programming is divided into three broad categories: Procedural,
OOP and parallel processing. These paradigms are as follows:
1.1.1.1 Procedural programming paradigm
 This programming has a single program that is divided into small piece called
procedure (also known as functions, routines, subroutines). These procedures are
combined into one single location with the help of return statements.
 From the main controlling procedure, a procedure call is used to invoke the
required procedure. After the sequence is processed, the flow of control
continues from where the call was made.
 The main program coordinates calls to procedures and hands over appropriate
data as parameters. The data is processed by the procedures and once the
program has finished, the resulting data is displayed.
 Example: C, C++, JAVA, Pascal.

1.1.1.2 Object Oriented Programming


 It is a type of programming in which programmers define not only the data type
of a data structure, but also the types of operations (functions) that can be
applied to the data structure.
 In this way, the data structure becomes an object that includes both data and
functions. In addition, programmers can create relationships between one object
and another. For example, objects can inherit characteristics from other objects.
 One of the principal advantages of object-oriented programming techniques over
procedural programming techniques is that they enable programmers to create
modules that do not need to be changed when a new type of object is added. A
programmer can simply create a new object that inherits many of its features
from existing objects. This makes object-oriented programs easier to modify.
The basic concepts of OOP are as follows:
1. Objects 2. Classes
3. Data abstraction and encapsulation 4. Inheritance
5. Polymorphism 6. Dynamic binding
7. Message passing.
Objects:
Objects are the basic run-time entities in an object oriented system. They may
represent a person, place or a bank a/c or a table of data that the program has to handle.
When a program is executed the objects interact by sending messages to one another.
They can interact without knowing the details of each other’s data or code. Thus an
object is considered to be a partitioned area of computer memory that stores data and set
of functions that can access the data.
Classes:
The entire set of data and code of an object can be made a user-defined data type
with the help of a class. Objects are variables of the type class. Each object is associated
with the data of type class with which they are created. A class is thus a collection of
objects of similar type.

Fig. 1.2 Class and Objects


Data abstraction and encapsulation
Encapsulation:
The wrapping up of data and functions in to a single unit (that unit is called a
class) is known as encapsulation. The data is not accessible to the outside world (other
functions which are not the members of that class) and only those functions which are
wrapped in the class can access it. This insulation of data from the direct access by the
program is called data hiding or information hiding.
Abstraction:
Abstraction refers to the act of representing essential features without including
the background details or explanations. Classes use the concept of abstraction and are
defined as a list of abstract attributes such as size, weight and cost and functions to
operate on these attributes. The attributes are sometimes called data members because
they hold information. The functions that operate on these data are called member
functions.
Inheritance:
Inheritance is the process by which objects of one class acquire the properties of
objects of another class. It supports the concept of hierarchical classification. In OOP, the
concept of inheritance provides the idea of reusability. This means that we can include
additional features to an existing class without modifying it. It is important because it
supports the concept of classification. C++ supports different types of inheritance such
as single inheritance, multiple inheritance, multilevel inheritance and hierarchical
inheritance.
To understand the concept of inheritance, let us consider an example of vehicles
as shown in Fig.1.3. Here the class car is a subclass of automatic vehicle, which is again
a subclass of the class vehicle. This implies that the class car has all the characteristics
of automatic vehicles which in turn has all the properties of vehicles. However, car has
some unique features which differentiate it from other subclasses. For example, it has
four wheels and five gears, while scooter has two wheels and four gears.

Fig. 1.3 Inheritance


Polymorphism:
Polymorphism, a Greek term means the ability to take more than one form. An
operation may exhibit different behaviour in different instances. The behaviour depends
up on the types of data used in the operation. The concepts of polymorphism are
Operator overloading and Function overloading. For two numbers, the operator + will
give the sum. If the operands are strings, then the operation would produce a third string
by concatenation. Thus the process of making an operator to exhibit different
behaviours in different instances is known as operator overloading. Similarly, we can
use a single function to perform different tasks which is known as function overloading.
A single function can be used to handle different number and types of arguments.
Binding:
Dynamic Binding:
Dynamic binding means that the code associated with a given procedure call is
not known until the time of the call at run-time. It is associated with polymorphism
concept.
Message Passing:
OOP consists of a set of objects that communicate with each other by sending
and receiving information. A message for an object is a request for execution of a
procedure (function) and therefore will invoke a function in the receiving object that
generates the desired result.
Benefits of OOP
 Through inheritance we can eliminate redundant code and extend the use of
existing classes.
 We can build secure programs by the principle of data hiding.
 It is easy to partition the work in a project based on objects.
 Object oriented systems can be easily upgraded from small to large systems.
 Communication with external systems are much simpler by means of message
passing techniques.
 Software complexity can be easily managed.
Applications of OOP
OOP can be applied in the following areas:
 Real time systems
 Simulation and modeling
 Object oriented data bases
 Hypertext, hypermedia and expertext
 Artificial Intelligence and expert systems.
 Neural networks and parallel programming
 Office automation systems
 CIM / CAM / CAD systems
Example: Simula, JAVA, Python, VB.NET, Ruby.
1.1.1.3 Parallel processing approach
 Parallel processing is the processing of program instructions by dividing them
among multiple processors. A parallel processing system possess many numbers
of processor with the objective of running a program in less time by dividing
them. This approach seems to be like divide and conquer.
 Examples are NESL (one of the oldest one) and C/C++ also supports because of
some library function.

1.1.2 Declarative programming paradigm


 It is divided as Logic, Functional, and Database. In computer science
the declarative programming is a style of building programs that expresses logic
of computation without talking about its control flow.
 It often considers programs as theories of some logic. It may simplify writing
parallel programs. The focus is on what needs to be done rather how it should
be done basically emphasize on what code is actually doing.
 It just declare the result we want rather how it has be produced. This is the only
difference between imperative (how to do) and declarative (what to do)
programming paradigms.

1.1.2.1 Logic programming paradigms


 It can be termed as abstract model of computation. It would solve logical
problems like puzzles, series etc.
 In logic programming we have a knowledge base which we know before and
along with the question and knowledge base which is given to machine, it
produces result. In normal programming languages, such concept of knowledge
base is not available but while using the concept of artificial intelligence,
machine learning.
 In logical programming the main emphasize is on knowledge base and the
problem. The execution of the program is very much like proof of mathematical
statement, e.g., Prolog

1.1.2.2 Functional programming paradigms


 The functional programming paradigms has its roots in mathematics and it is
language independent. The key principal of this paradigms is the execution of
 The central model for the abstraction is the function which are meant for some
specific computation and not the data structure. Data are loosely coupled to
functions.
 The function hide their implementation. Function can be replaced with their
values without changing the meaning of the program. Some of the languages
like Perl, java script mostly uses this paradigm.

1.1.2.3 Database/Data driven programming approach


 This programming methodology is based on data and its movement. Program
statements are defined by data rather than hard-coding a series of steps.
 A database program is the heart of a business information system and provides
file creation, data entry, update, query and reporting functions. There are several
programming languages that are developed mostly for database application.
 For example SQL. It is applied to streams of structured data, for filtering,
transforming, aggregating (such as computing statistics), or calling other
programs. So it has its own wide application.

1.1.3 Characteristics of a Good Programming Language


 A programming language must be simple, easy to learn and use, have good
readability and human recognizable.
 Abstraction is a must-have Characteristics for a programming language in which
ability to define the complex structure and then its degree of usability comes.
 A portable programming language is always preferred.
 Programming language’s efficiency must be high so that it can be easily
converted into a machine code and executed consumes little space in memory.
 A programming language should be well structured and documented so that it is
suitable for application development.
 Necessary tools for development, debugging, testing, and maintenance of a
program must be provided by a programming language.
 A programming language should provide single environment known as
Integrated Development Environment (IDE).
 A programming language must be consistent in terms of syntax and semantics.
1.2 HISTORY OF C PROGRAMMING
 C is a general purpose structured programming language. C was developed by
Dennis Ritchie at AT & T Bell laboratories in 1972. It is an outgrowth of an
earlier language called BCPL & B. It was named as C to present it as the
successor of B language which was developed earlier by Ken Thompson in 1970
at AT & T Bell laboratories. The various stages in evolution of C language is

CPL (Combined Programming Language)


Developed by Cambridge and University of London in 1963
given in Fig 1.4.

BCPL (Basic Combined Programming Language)


Developed by Martin Richards in 1967

B Language Developed by Ken Thompson at AT and T Bell


Laboratory in 1970

C Language Developed by Dennis Ritchie at AT and T


Bell Laboratory in 1972

Fig. 1.4 Various Stages in Evaluation of C Languages


 C is a highly portable, which means that C program written for one computer
can be run on another with little or no modification. C is well suited for
structured programming; thus user has to think of a problem in terms of function
modules and blocks.
 The proper collection of these modules would makes a complete program. This
modular structures makes program debugging, testing and maintenance easier.
 Another important feature of C is its ability to extend itself. A C program is
basically a collection of functions that are supported by the C library. We can
add our own functions to the C library. With the availability of a large number of
functions, the programming task becomes simple.
 Its flexibility allows C to be used for system programming (For example: the
UNIX operating system, the C compiler and all UNIX application software are
1.2.1 Features of C Programming
 C is the widely used language. It provides many features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible

1.3 APPLICATIONS OF C LANGUAGE


 The applications of C are not only limited to the development of operating
systems, like Windows or Linux, but also in the development of GUIs
(Graphical User Interfaces) and, IDEs (Integrated Development Environments).
 Here are some striking applications offered by the C programming language:
1. Operating Systems
The first operating system to be developed using a high-level programming
language was UNIX, which was designed in the C programming language. Later on,
Microsoft Windows and various Android applications were scripted in C.
2. Embedded Systems
The C programming language is considered an optimum choice when it comes
to scripting applications and drivers of embedded systems, as it is closely related to
machine hardware.
3. GUI
GUI stands for Graphical User Interface. Adobe Photoshop, one of the most
popularly used photo editors since olden times, was created with the help of C. Later on,
Adobe Premiere and Illustrator were also created using C.
4. New Programming Platforms
Not only has C given birth to C++, a programming language including all
the features of C in addition to the concept of object-oriented programming but, various
other programming languages that are extensively used in today’s world like MATLAB
and Mathematica. It facilitates the faster computation of programs.
5. Google
Google file system and Google chromium browser were developed using C/C++.
Not only this, the Google Open Source community has a large number of projects being
handled using C/C++.
6. Mozilla Firefox and Thunderbird
Since Mozilla Firefox and Thunderbird were open-source email client projects,
they were written in C/C++.
7. MySQL
MySQL, again being an open-source project, used in Database Management
Systems was written in C/C++.
8. Compiler Design
One of the most popular uses of the C language was the creation of
compilers. Compilers for several other programming languages were designed keeping
in mind the association of C with low-level languages, making it easier to be
comprehensible by the machine.
Several popular compilers were designed using C such as Bloodshed Dev-C,
Clang C, MINGW, and Apple C.
9. Gaming and Animation
Since the C programming language is relatively faster than Java or Python, as it is
compiler-based, it finds several applications in the gaming sector. Some of the simplest
games are coded in C such as Tic-Tac-Toe, The Dino game, The Snake game and many
more. Increasing advanced versions of graphics and functions, Doom3 a first-person
horror shooter game was designed by id Software for Microsoft Windows using C in
2004.

1.4 STRUCTURE OF C PROGRAM


 As C is a programming language, let us go into the concepts of programming in
C and it is a structured programming language. Every C program contains a
 These building blocks should be written in the correct order and procedure, for
the C program to execute without any errors. The structure of C is given below.
documentation section
preprocessor section
definition section
global declaration section
main( )
{
declaration part;
executable part;
}
sub program
{
body of the subprogram;
}

Program 1.1
/* Program to find the area of a circle */ /* Documentation Section
*/ # include<stdio.h> /* Preprocessor Section */
# include<conio.h>
# define PI 3.14 /* Definition Section */
void main() /* main( ) function */
{
float area,r; /* Local variable declaration */
clrscr(); // Executable part of the program
printf("\n Enter the radius:\
n"); scanf("%f",&r);
area= PI*(r*r);
printf("\n Area of the Circle = %8.2f", area);
getch();
}
Output
Enter the radius: 4.5
Area of the Circle = 63.58

Program 1.2
/* Program to find the sum of two numbers using function */
/*Documentation Section */
# include<stdio.h> /* Preprocessor Section
*/ # include<conio.h>
int a,b; /* Global Variable declaration */
int add(int,int); /* Function declaration */
void main() /* main( ) function */
{
int c; /* Local Variable declaration */
clrscr(); // Executable part of the main()
program printf("\n Enter the values for a and b:\n");
scanf("%d
%d",&a,&b); c =
add(a,b);
printf("\n Sum of %d + %d = %d",
a,b,c); getch();
}
int add(int a,int b) /* Subprogram of add() function definition */
{
int c; /* Local Variable declaration */
c=a+b; // Executable part of the
function return(c);
}
Output
Enter the values for a and b: 5 3
Sum of 5 + 3 = 8
Documentation section
The documentation section is included in the comments, which contains the author
name, the date of development and the program details.
Preprocessor section
The preprocessor section provides preprocessor statements which direct the
compiler to link functions from the system library.
Definition section
The definition section defines all symbolic constants refer to assigning a macro
of a name to a constant. The general syntax of a symbolic constant is
#define constant_name constant_value
Global declaration section
The global declaration section contains variable declarations which can be
accessed anywhere within the program.
Main section
Main section is divided into two portions, the declaration part and the executable
part. The declaration part used to declare any variables in the main block of the
program. The executable part contains set of statements within the open and close
braces. Execution of the program begins at the opening braces and ends at the closing
braces.
User defined function section
The user defined function section (or) the Sub program section contains user
defined functions which are called by the main function. Each user defined function
contains the function name, the argument and the return value.

1.5 LEXICAL ELEMENTS OF C


 Data’s can be of any kind, it may be numbers, characters and strings. These data
should be processed in order to produce the information output. Programming
languages are used for this processing of data into information.
 Every program consists of a sequence of steps or instruction for processing data.
Each instruction must abide to certain syntax rules of grammar of the particular
language. Likewise C has its own grammar. Data may be either a constant or a
variable.
 In ‘C’ language each and every individual unit is called as Token or Lexical
element. The various ‘C’ Tokens are
i) Character set
ii) Delimiters
iii) Keywords
iv) Identifiers
v) Data types
vi) Constants
vii) Variables

1.5.1 Character Set


 The set of characters used to write the program words, expressions and
statements. It is the basic building block to form program elements. The set of
characters used in a language is known as its character set. These characters can
be represented in the computer.
 The C character set consists of upper and lower case alphabets, digits, special
characters and white spaces. The alphabets and digits are together called the
alphanumeric characters.
i) Alphabets
A, B, C,…..Z
a, b, c,….z
ii) Digits
0123456789
iii) Special Characters
Table 1.1 List of Special Characters

www.poriyaa
n.in

Table 1.1 List of Special Characters


iv) White space characters
Blank space, newline, form feed, horizontal tab, vertical tab
v) Trigraph characters
The trigraph characters are used to type certain characters that are not
available on some keyboards. It consists of three characters. Two
question marks followed by character.
1.5.2 Delimiters
 The language pattern of C uses a special kind of symbols, which are called
delimiters. They are given in Table. 1.3.

Table 1.3 Delimiters


1.5.3 Keywords
 These are certain reserved words called keywords, which are standard,
predefined meanings in C. They must be written in lower case. There are 32
keywords available in C. The standard keywords are shown in Table 1.4.

Table 1.4 Keywords in C


1.5.4 Identifiers
 Identifiers are the names defined by the programmer for various program
elements such as variables, constant and functions. An identifier consists of a
sequence of letters and digits.
 The following rules are to be followed to declare an identifier.
i) The first character must be a letter followed by a letter or a digit.
ii) Special characters are not allowed except underscore.
iii) The length of the variable varies from one compiler to another. Generally,
most of the compilers support eight characters excluding extension.
However, the ANSI standard recognizes the maximum length of a variable
up to 31 characters.
iv) The variable should not be a C keyword.
v) The variable names may be a combination of upper and lower characters. For
example, suM and sum are not the same variable.
vi) The variable name should not start with a digit.
Examples
 The following names are valid identifier

1.5.5 Data Types


 The C language supports different types of data. Each data may be represented
differently within the computer memory. Typical memory requirements for each
data will determine the possible range of values for that data type.
 The varieties of data types available allow the programmer to select the type
appropriate to the needs of the application as well as the machine.
C supports three categories of data types:
1. Primary data type 2. Derived data type 3. User defined data type.

Fig. 1.5 Classification of ‘C’ Data types


Primary Data Types
 C compiler supports the following four Fundamental/ Primary/ Primitive/ Basic/
Built-in data types:
o Character: Character data type is used to store a character. A variable of
character data type allocated only one byte of memory and can store only one
character. Keyword char is used to declare variables of type character. The
range of character (char) data type is -128 to 127. For Example: char ch =
‘A’;
o Integer: Integer data type is used to store a value of numeric type. Keyword
int is used to declare variables of integer type. The memory size of a variable
of integer data type is dependent on the operating system. For example the
size of integer data type in a 32 bit computer is 4 bytes whereas size of integer
data type in 16 bit computer is 2 bytes. For Example: int count = 10;
o Float: Floating point data type is used to store a value of decimal values.
The memory size of a variable of floating point data type is dependent on the
Operating System. Keyword float is used to declare variables of floating data
type. For example the size of a floating point data type in a 16 bit computer is
4 bytes. For Example: float rate = 5.6;
o Double: Double data type is similar to floating data type except that it
provides up to ten digits of precision and occupies eight bytes of memory. For
Example: double d = 11676.2435676542;
o Void Data Type: Void is an empty data type that has no value. This can be
used in functions and pointers.
Type modifiers in C
 In c language Data Type Modifiers are keywords used to change the current
properties of data type. Data type modifiers are classified into the following
types.
o Long
o Short
o Unsigned
o 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 bytes for a 32 bit processor. We can increase
the range by using long int which is 8 bytes. We can decrease the range by using
short int which is 2 bytes.
long
 This can be used to increase the size of the current data type by 2 more bytes,
which can be applied on int or double data types. For example int occupy 2 bytes
of memory; if we use long with integer variable, then it occupies 4 bytes 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 systems; to allocated fixed memory space a short keyword can be
used.
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 of positive
data type.
Syntax
unsigned int a = 100; // right
unsigned int a = -100; // wrong
Signed
 This keyword accepts both negative and positive values and this is the default
property or data type modifier for every data type.
int a = 10; // right
int a = -10; // right
signed int a = 10; // right
signed int a = -10; // right
Table 1.5 Size and range of Integer type on 16-bit machine

Table 1.6 Size and range of Float type on 16-bit machine

Table 1.7 Size and range of Character type on 16-bit machine


Derived data types
 Derived data types are derived from the collection of primary data types. C
supports the following derived data types.
 Arrays
o Array is a collection of variables of same data type that are referenced by a
common name.
Syntax: <datatype> <variable name> [Index];
 Functions
o A function is a self-contained program segment (block of statements) that
carries out some specific, well defined task.
Syntax for function prototype
<return datatype> function name (forma) arg, formal arg2 ... formal arg
n);
Syntax for function definition
<return type> function name (parameter
list) parameter declarations
{
body of the
function; return
(expression);
}
Example
void swap (int x, int y)
{
int z;
z = x;
x=
y; y
= z;
}
 Pointers
o Pointer is a variable which stores the address of another variable.
Example
int *p; // declaration of
pointer int x; // declaration of
variable
p=&x; // pointer variable stores the address of x
variable. x=5 ; // x variable assigned with value 5.
User defined data types
 The user defined data types enable a program to invent his own data types and
define what values it can taken on. Thus these data types can help a programmer
to reducing programming errors.
 C supports the following user defined data types.
o Structures
A structure is a single entity representing a collection of data items of
different data types.
Example
struct student
{
int roll_no;
char
fname[25];
char
branch[15]; int
marks;
}s1;
o Unions
A union is a data type in ‘c’ which allows overlay of more than one variable
in the same memory area.
Example
union emp
{
char
name[20];
char eno[10];
}
union emp e1;
o Enumerated data type
A enumerated data type is a set of values represented by identifiers called
enumeration constants. It is a user-defined data type and the general format of
enum name {number 1, number 2, ... number n};
In above format enum is a keyword, name is given by the programmer by the
identifier rules. number 1, number 2, ... number n are the member of
enumerated datatype.
o Type definition
“type definition” that allows user to define an identifier that would represent
a data type using an existing data type.
Syntax:
typedef type identifier;
typedef <existing_data_type> <new_user_define_data_type>;
Example
typedef int number;
typedef long big_ number;
typedef float decimal;
number visitors = 25;
big_number population = 12500000;
decimal radius = 3.5;

1.5.6 Constants
 Constants are fixed values and they remain unchanged during the execution of
the program. The constants are classified as follows:
Integer constants
 It consist of a sequence of digits without any decimal point. Integer constant can
be written in three different number systems: decimal, octal and hexadecimal. A
decimal integer constant can consist of any combination of digits taken from the
set 0 through 9.
1. Decimal number – 0 to 9
2. Octal number – 0 to 7
3. Hexadecimal number – 0 to 9, A, B, C, D, E, F
 Examples
Decimal number – 10, 145,-89, 067 etc.
Octal number – 037, 0, 057, 0456 etc.
Hexadecimal number – 0x4, 0x9C, 0xAFE etc.
 Rules for an integer constant
o It must have at least one digit.
o Decimal point is not allowed.
o It can be either positive or negative.
o If it is negative the sign must be preceded. For positive the sign is not
necessary.
o No commas or blank spaces are allowed.
o The allowable range for integer constant is –32,768 to +32,767
Real Constant
 It is made up of a sequence of numeric digits with presence of a decimal point.
 It is to represent quantities that vary continuously such as distance, height,
temperature etc.
 Example:
Distance=134.9;
Height=88.10;
 Rules for a real constant
o It must have one digit.
o It must have decimal point.
o It can be either positive or negative.
o If it is negative the sign must be preceded. For positive the sign is not
necessary.
o No commas or blank spaces are allowed.
Character constants
Single Character Constant
 It contains a single character enclosed within a pair of single quote marks.
Example
‘d’, ‘r’, ‘6’, ‘_’
String Constant
 It is a sequence of characters enclosed in double quotes.
 The characters may be letters, numbers, special characters and blank spaces
 At the end of string ‘\0’ is automatically placed.
 Example
“hai”
“4565”

1.5.7 Variables and Declaration


 Variables are identifiers whose value changes during the execution of the
program. Variables specify the name and type information. The compiler
allocates memory for a particular variable based on the type.
 Variables can be modified using the variable name or address of the variable.
The variable name must be chosen in a meaningful way. The declaration of the
variable must be done before it can be used in the program.
 The general syntax of the variable declaration is given below.
datatype : var1, var2, ….,varn;
where datatype : may be any data type
Examples
1. int sum, count;
2. int rollno;
3. float int_rate;
4. double avg, netsal;
5. char char;
Variable declaration with qualifiers
Examples
1. short int number;
2. unsigned int total;
3. long int ser_no;
4. long double volume;
Variable Initialization
 Assigning a relevant value to a variable for the first time in a program is known
as initialization. Sometimes a variable may be initialized on its declaration itself.
Variables can be initialized with a constant value or expression.
Syntax:
datatype variablename = expression;
(or)
datatype variablename = constant;
Example
1. int c = 10, d = c + 5;
2. float rate = 12.5;
3. char ch = ‘Y’;
4. int count = 0 , sum = 0;
5. float pi = 3.14;
CONSTANT AND VOLATILE VARIABLE
Constant variable
 If we want that the value of a certain variable remain the same or remain
unchanged during the execution of a program, then it can be done only by
 The keyword constant is then added before the declaration. It tells the compiler
that the variable is a constant. Thus, constant declared variables are protected
from modification.
Example
const int a = 20;
where, const is a keyword, a is a variable name and 20 is a constant value. The
compiler protects the value of ‘a’ from modification. The user cannot assign any
value to a; by scanf ( ) statement the value can be replaced.
Volatile variable
 The volatile variables are those variables that are changed at any time by any
other external program or the same program. The syntax is as follows.
Example
volatile int b;
where volatile is a keyword and b is a variable If the value of a variable in the
current program is to be maintained constant and desired not to be changed by
any other external operation, then the declaration of the variable will be as
follows;
volatile const b = 20;

1.6 OPERATORS IN C
Operator: An operator is a symbol that specifies an operation to be performed on
operands. Eg: x= a+b; where + is an operator.
Operands: An operand is an entity on which an operation is to be performed. An
operand can be a variable name, a constant, a function call or a macro name.
Eg. x= a+b; where x, a, b are the operands.
Expression: An expression is a sequence of operands and operators that specifies the
computations of a value. An expression is made up of one or more operands. Eg. x= a+b.

1.6.1 Types of Operators


1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators (Ternary Operators)
7. Bitwise Operators
8. Special Operators

1.6.1.1 Arithmetic Operators


 Addition, subtraction, multiplication, division and modulo are the arithmetic
operations.
 The arithmetic operators are used for numerical calculations between two
Constants
Operators Explanations Examples
+ Addition 2+2=4
- Subtraction 3-2=1
* Multiplication 5 * 4 =20
/ Division 10 / 2 = 5
% Modular Division 11 % 2 = 1

Example:
void main()
{
int a=5, b=4, c;
c=a-b;
printf(“%d”,
c);
}
 The following table show the division operator on various data types.
Operation Result Example
int/int int 2/5=0
real/int real 5.0/2=2.5
int/real real 5/2.0=2.5
real/real real 5.0/2.0=2.5
 Arithmetic operators can be classified as
o Unary arithmetic – it requires only one operand.
Example: +a, -b
o Binary arithmetic – it requires two operands.
Example: a+b, a-b, a/b, a%b
o Integer arithmetic – it requires both operands to be integer type for
arithmetic operation.
Example:
a=4, b=3
a+b =4+3 =7
a-b =4-3=1
o Floating Point arithmetic – It requires both operands to be float type for
arithmetic operation.
Example:
a=6.5, b=3.5
a+b =6.5+3.5 =10.0
a-b =6.5-3.5=3.0
Program 1.3
#include<stdio.h>
#include<conio.h
> void main()
{
int b,c;
int sum, sub,
mul; float div;
clrscr();
printf(“enter the value of
b,c:”); scanf(“%d%d”, &b,
&c);
sub=b-c;
mul=b*c
;
div=b/c;
printf(“\n sum=%d,sub=%d,mul=%d,div=
%f”,sum,sub,mul,div); getch();
}
Output:
Enter the value of b,c: 8 4
sum=12,sub=4,mul=32,div=
2

1.6.1.2 Relational Operators


 Relational operators are used to compare two or more operands.
 Operands may be variable, constant or expression
Operators Descriptions Example Return Value
> Greater than 5>4 1
< Less than 10<9 0
<= Less than or equal to 10<=10 1
>= Greater than or equal to 11>=5 1
== Equal to 2==3 0
!= Not equal to 3!=3 0

Syntax
AE1 operator AE2
where, AE- Arithmetic Expression or Variable or Value.
 These operators provide the relationship between two expressions.
 If the condition is true it returns a value 1, otherwise it returns 0.
 These operators are used in decision making process. They are generally used in
conditional or control statement.
1.6.1.3 Logical Operators
 Logical Operators are used to combine the result of two or more conditions.
 The logical relationship between the two expressions is checked with logical
operators.
 After checking the condition, it provides logical true (1) or false (0).
Operators Descriptions Example Return Value
&& Logical AND 5>3 && 1
5<10
|| Logical OR 8>5 || 8<2 1
!= Logical NOT 8!=8 0

 && - This operator is usually used in situation where two or more expressions
must be true.
Syntax:
(exp1) && (exp2)
 || – This is used in situation, where at least one expression is true.
Syntax:
(exp1) || (exp2)
 ! – This operator reverses the value of the expression it operates on. (i.e.,) it
makes a true expression false and false expression true.
Syntax:
!(exp1)

Program 1.4
/* Program using Logical operators */
#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
printf("\n Condition : Return values ");
printf("\n 5<=8 && 4>2: %5d",5<=8 && 4>2);
printf("\n !(7==7): %5d",!(7==7));
getch( );
}
Output
Condition : Return values
5<=8 && 4>2 : 1
5>=3 || 6<8 : 1
!(7==7) : 0

1.6.1.4 Assignment Operator


 Assignment Operator are used to assign constant or a value of a variable or an
expression to another variable.
Syntax
variable =expression (or) value;
Example
x=10;
x=a+b
; x=y;

Program 1.5
/* Program using Assignment and Short-hand Assignment operators */
#include<stdio.h>
#include<conio.h
> void main( )
{
int a=20,b=10,c=15,d=25,e=34,x=5;
clrscr( );
printf("\n Value of a=%d",a);
printf("\n Value of b=
%d",b); a+=x;
b- =x;
c*=x;
d/=x;
e
%=x;
printf("\n Value of a=
%d",a); printf("\n Value of
b=%d",b); printf("\n Value
of c=%d",c); printf("\n Value
of d=%d",d); printf("\n
Value of e=%d",e); getch();
Outpu }
t
Value of a = 20
Value of b = 10
Value of a = 25
Value of b = 5
Value of c = 75
Value of d = 5
Value of e = 4

1.6.1.5 Increment and Decrement Operators (Unary Operators)


 The ‘++’ adds one to the variable and ‘--‘subtracts one from the variable. These
operators are called unary operators.
Operator Meaning
++X Pre increment
--X Pre decrement
X++ Post increment
X-- Post decrement

Pre-increment operator
 This operator increment the value of a variable first and then perform other
Program 1.6
#include
<stdio.h> void
main()
{
int
a,b;
a=10;
b=++a;
printf(“a=
%d”,a);
printf(“b=%d”,b);
}
output: a=11
b=11 #include
<stdio.h> void
main()
{
int
a,b;
a=10;
b=—a; printf(“a=
%d”,a);
printf(“b=%d”,b);
}
Output:
a=9 b=9
Post-increment operator
 This operator perform other actions first and then increment the value of a
variable.
Program 1.7
#include
<stdio.h> void
main()
int
a,b;
a=10;
b=a++;
printf(“a=
%d”,a);
printf(“b=%d”,b);
}
Output:
a=11 b=10
Program 1.8
#include
<stdio.h> void
main()
{
int
a,b;
a=10;
b=a--; printf(“a=
%d”,a);
printf(“b=%d”,b);
}
Output:
a=9 b=10

1.6.1.6 Conditional Operator (or) Ternary Operator


 Conditional operator checks the condition itself and executes the statement
depending on the condition.
Syntax
condition?exp1:exp2;
Example
void main()
{
big=a>b?a:b;
printf(“big is…
%d”,big);
}
Output
big is…5

1.6.1.7 Bitwise Operators


 Bitwise operators are used to manipulate the data at bit level.
 It operates on integers only.
 It may not be applied to float or real.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift left
>> Shift right
~ One’s complement

Bitwise AND (&):


 This operator is represented as ‘&’ and operates on two operands of integer type.
If both the operands bit is ‘1’ then the result is ‘1’.
Bitwise OR (|):
 Bitwise OR (|) operator gives the value ‘1’ if either of the operands bit is ‘1’
Bitwise Exclusive OR (^)
 Bitwise Exclusive OR(^) gives the value ‘1’ if both operands bit are same.
Program 1.9
/* Program using One's complement operator */
#include<stdio.h>
#include<conio.h
> void main( )
{
int a;
clrscr( );
printf("\n Enter the value for a :
"); scanf("%d",&a);
printf("\n The One's complement value for a is : %d",
~a); getch( );
}
Output
Enter the value for a: 3
The One's complement value for a is: -4

1.6.1.8 The Special Operator


 C language supports some of the special operators given below.
Operator Meaning
, Comma operators
Sizeof Size of operators
& and * Pointer operators
. and — > Member selection operators

a) Comma operator(,):
 The comma operator is used to separate the statement elements such as
variables, constants or expression etc.,
 This operator is used to link the related expression together.
 Such expression can be evaluated from left to right and the value of right most
Example:
val=(a=3,b=9,c=77,a+c);
Where,
First assigns the value 3 to a
Second assigns the value 9 to b
Third assigns the value 77 to c
Last assigns the value 80.
b) The sizeof() operator:
 The sizeof() is a unary operator that returns the length in bytes of the specified
variable and it is very useful to find the bytes occupied by the specified variable
in memory.
Syntax:
sizeof(var);
Example:
void main()
{
int a;
printf(“size of variable a is…%d”, sizeof(a));
}
Output:
size of variable a is…….2
c) Pointer operator:
 & : This symbol specifies the address of the variable.
 * : This symbol specifies the value of the variable.
d) Member selection operator:
 . and — >: These symbols are used to access the elements from a structure.
1.7 EXPRESSIONS AND STATEMENTS
1.7.1 Expressions
 An expression represents data item such as variables, constants and are
interconnected with operators as per the syntax of the language.
 An expression is evaluated using assignment operators.
Syntax
Variable = expression;
Example: 1
x=a*b-c;
 In example 1, the expression evaluated from left to right. After the evaluation of
the expression the final value is assigned to the variable from right to left.
Example: 2
a++;
 In example 2, the value of variable a is incremented by 1, i.e, this expression is
equivalent to a = a + 1.

1.7.2 Statements
 A statement is an instruction given to the computer to perform an action. There
are three different types of statements in C:
1. Expression Statements
2. Compound Statements
3. Control Statements
Expression Statement
 An expression statement or simple statement consists of an expression followed
by a semicolon (;).
Example
a=100;
b=20;
c=a/b;
Compound Statement
 A compound statement also called a block, consists of several individual
statements enclosed within a pair of braces { }.
Example
{
a=3;
b=10;
c=a+b;
}
Control Statement
 A single statement or a block of statements can be executed depending upon a
condition using control statements like if, if-else, etc.
Example
a=10;
if (a>5)
{
b= a+10;
}

1.8 CONDITIONAL STATEMENTS


 The conditional statement requires the programmer to specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and
optionally, other statements to be executed if the condition is determined to be
false.
 In a conditional statement, the flow of execution may be transferred from one
part to another part based on the output of the conditional test carried out. It has
been further classified into selective and loop constructs. In a selective
constructs, the statements are selected for execution based on the output of the
conditional test given by an expression. It supports the following constructs such
as if-else, if- else-if, nested-if and switch case statement. In loop constructs, the
block of statements will be executed repeatedly until the condition is true else
the loop will
be terminated. It supports the following constructs such as For, While and Do-
while loops.

1.8.1 Conditional Branching Statement


1.8.1.1 Selection Statement
 Simple If statement
 The syntax for a simple if statement is
if (expression)
{
block of statements;
}
 In this statement, if the expression is true, the block of statements are executed
otherwise false and it comes out of the if condition.

Fig. 1.7 Flowchart for an If statement


Program 1.10
/*Program to find the given number is divisible by 2 */
#include<stdio.h
> void main()
{
int n;
printf(“\n Enter the
number”); scanf(“%d”,&n);
if(n%2==0)
{
printf(“\n The given number%d is divisible by 2", n);
}
getch();
}
Output
Enter the number : 10
The given number 10 is divisible by 2
Program 1.11
/* Program to check the given numbers are equal or not */
#include<stdio.h>
#include<conio.h
> void main()
{
int m,n;
clrscr()
;
printf(“\n Enter two
numbers:”); scanf(“%d %d”,
&m,&n);
if (m==n)
printf(“\n Two numbers are
equal”); getch();
}
Output
Two numbers are equal.
 If –else statement
 The syntax for the if-else statement is
if(expression)
{
block of statements1;
}
else
{
block of statements2;
}

Fig. 1.8 Flowchart for the If-else statement


 In this statement, if the expression is true the block of statements1 will be
executed, otherwise the block of statements2 will be executed.
Program 1.12
/* Program to find the given number is positive or negative */
#include<stdio.h
> void main()
{
int n;
printf(“\n Enter the
number:”); scanf(“%d”,&n);
if(n>0)
{
printf(“\n The given number %d is positive”, n);
}
else
{
printf(“\n The given number %d is negative”, n);
}
}
Output
Enter the number : 5
The given number 5 is positive.
Program 1.13
/* Program to find the given number is even or odd */
#include<stdio.h>
#include<conio.h
> void main()
{
int a;
clrscr()
;
printf(“\n Enter the
number:”); scanf(“%d”,&a);
if (a%2==0)
printf(“\n %d is an even
number”,a); else
printf(“%d is an odd
number”,a); getch();
}
Output
Enter the number: 10
10 is an even number.
 Conditional Expression
 The ternary operator is used to form a conditional expression. It uses three
operands and hence it is called as a ternary operator. The syntax for a
conditional expression is:
<expression-1> ? <expression-2> : <expression-3>;
 In this method if expression-1 is true then expression-2 is evaluated, otherwise
expression-3 is evaluated.
Program 1.14
/* Program to find biggest of two given numbers */
#include<stdio.h
> void main()
{
int x,y,z;
printf(“\n Enter the value of x and
y:”); scanf(“%d%d”,&x,&y);
z = ((x>y)?x:y);
printf(“The biggest value is
%d”,z); getch();
}
Output
Enter the value of x and y: 5 10
The biggest value is 10
 If-else-if statement
 The syntax for the if-else-if statement is
if(expression1)
{
statements1;
}
else if(expression2)
{
statements2;
}
else if(expression3)
{
statements3;
else
{
statements4;
}
 In this statement, if the expression1 is true, statements1 will be executed,
otherwise the expression2 is evaluated, if it is true then statements2 is executed,
otherwise the expression3 is evaluated, if it is true then statements3 is executed,
otherwise statements4 is executed.

Fig. 1.10 Flowchart for the If-else-if statement


Program 1.15
/* Program to find the student’s class for the given average marks using if-elseif*/
#include<stdio.h
> void main()
{
printf (“Enter the Average
mark:”)
scanf(“%d”,&Avg_Mark);
if(Avg_Mark>=75)
{
printf(“Distinction”);
}
elseif((Avg_Mark>=60) && (Avg_Mark<75))
{
printf(“First Class”);
}
elseif((Avg_Mark>=50) && (Avg_Mark<60))
{
printf(“Second Class”);
}
elseif((Avg_Mark>=45) && (Avg_Mark<50))
{
printf(“Third Class”);
}
else
{
printf(“Fail”);
}
}
Output
Enter the Average Mark : 65
First Class
Program 1.16
Write a program to calculate the gross salary for the conditions given below:
/* Program to Calculate the gross salary */
#include<stdio.h>
#include<conio.h
> void main()
{
float bs, hra, da, cv,
ts; clrscr();
printf(“\n Enter Basic
salary:”); scanf(“%f”,&bs);
if(bs>=5000)
{
hra = bs*20/100;
da =
bs*110/100; cv =
500;
else if(bs>=3000 && bs<5000)
{
hra = bs*15/100;
da =
bs*100/100; cv =
400;
}
else if(bs<3000)
hra =
bs*10/100; da =
bs*90/100; cv =
300;
}
ts = bs+hra+da+cv; printf(“\
nBasic salary: %5.2f”,bs);
printf(“\nHRA: %5.2f”,hra);
printf(“\nDA: %5.2f”,da);
printf(“\nConveyance: %5.2f”,cv);
printf(“\nGross Salary:
%5.2f”,ts); getch();
}
Output
Enter basic salary: 5400
Basic salary: 5400
HRA: 1080
DA: 5940
Conveyance: 500
Gross salary: 12920
 Nested if statement
 The syntax for the nested if statement is
if(expression1)
{
statements1;
}
else
{
if(expression2)
statements2;
}
else
{
statements3;
}
}

Fig. 1.11 Flowchart for Nested if statement


 In this statement, if expression1 is true, then statement1 is evaluated, otherwise
the inner if expression2 is true then statements2 will be executed otherwise inner
else statements3 will be executed.
Program 1.17
/* Program to find the biggest of given three numbers */
#include<stdio.h
> void main()
int x,y,z;
printf(“\n Enter the three
numbers”); scanf(“%d%d
%d”,&x,&y,&z);
if ((x>y) && (x>z))
{
printf(“The Biggest number = %d”,x);
}
else
{
if(y>z)
{
printf(“The Biggest number =%d”,y);
}
else
{
printf(“The Biggest number =%d”,z);
}
}
getch();
}
Output
Enter the three numbers: 5 2 8
The Biggest number = 8
 Switch () Case Statement
 The switch ( ) case statement is like if statement that allows us to make a
decision from a number of choices. The switch statement requires only one
argument of any data type, which is checked with a number of case options.
 The switch statement evaluates the expression and then looks for its value
among the case constants.
 If the value matches with a case constant, this particular case statement is
executed. If not, the default is executed. The general syntax for the switch - case
statement is:
switch<exprn>
{
case constant_1:
{
statements1;
break;
}
case constant_2:
{
statements2;
break;
}
case constant_3:
{
statements3;
break;
}
case constant_n:
{
statementsn
; break;
}
default:
{
default statements;
}
Fig. 1.12 Flowchart for Switch - Case statement
Program 1.18
/* Program to provide multiple functions such as 1. Addition 2. Subtraction
3. Multiplication 4. Division by using switch statements. */
#include<stdio.h>
#include<conio.h
> void main()
{
float c;
int a,b,n;
printf(“\n MENU”);
printf(“\n 1.Addition”);
printf(“\n 2.Subtraction”);
printf(“\n
3.Multiplication”); printf(“\
n 4.Division”);
printf(“\n 0.Exit”);
printf(“\n Enter your
choice:”); scanf(“%d”,&n);
printf(“Enter two
numbers:”); scanf(“%d
%d”,&a,&b); switch(n)
{
case 1:
c = a + b;
printf(“\n Addition:
%d”,c); break;
case 2:
c = a - b;
printf(“\n Subtraction:
%d”,c); break;
case 3:
c = a * b;
printf(“\n Multiplication:
%d”,c); break;
case 4:
c = a / b;
printf(“\n Division: %d”,c);
break;
case
0:
exit();
break;
default
:
printf(“Invalid
choice”); break;
getch();
}
Output
Menu
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice: 2
Enter two numbers: 40 20
Subtraction: 20

1.8.1.2 Looping Statements


 A loop is defined as a block of statements which are repeatedly executed for
certain number of times. The `C’ language supports three types of loop
statements.
1. for statement
2. while statement
3. do-while statement
 For Loop Statement
 The for loop allows to execute a set of instructions until a certain condition is
satisfied. Condition may be predefined or open-ended.
 The syntax for loop this is follows:
for<initial value>;<condition>;<incrementation/decrementation>)
{
block of statements;
}
Fig. 1.13 Flowchart of the For loop statement
 Here the initial value means the starting value assigned to the variable and
condition in the loop counter to determine whether the loop should continue or
not. Incremention / decrementation is to increment/decrement the loop counter
value each time the program segment has been executed.
Program 1.19
/* Program to Generate numbers from 1 to 10 */
#include<stdio.h
> void main()
{
int i,n;
printf(“\n Enter the
limit”); scanf(“%d”,&n);
for(i=1;i <=n;i++)
{
printf(“%d\n”,i);
}
getch( );
}
Output
Enter the limit: 10
1
2
3
4
5
6
7
8
9
10
 While Loop Statement
 The syntax for the while loop statement is
while(condition)
{
block of
statements;
incr/decr;
}
 The while loop is often used when the number of times the loop is to be
executed is not known in advance. A sequence of statements are executed until
some condition is satisfied.
 When the condition specified inside the parenthesis the while loop is satisfied,
the control is transferred to the statements inside the loop and executes the body
of the loop. The loop continues until the condition is violated. The while tests
the
 If the condition initially fails the loop is skipped entirely even in the first
iteration itself. It is otherwise called as entry controlled loop.

Fig. 1.14 Flowchart of the While loop

Program 1.20
/* Program to Generate the Even numbers to a given limit*/
#include<stdio.h>
#include<conio.h
> void main()
{
int n,i;
printf(“\n Enter the
limit:”); scanf(“%d”,&n);
i=1;
while(i<=n)
{ if(i
%2==0)
printf(“%d\
t”,i); i++;
}
getch( );
}
Output
Enter the limit: 10
2 4 6 8 10
 Do While Statement
 The do while loop varies from the while loop in the checking condition. The
condition of the loop is not tested until the body of the loop has been executed
once. If the condition is false, after the first loop iteration the loop terminates.
The statements are executed atleast once even if the condition fails for the first
time itself. It is otherwise called as exit control loop.

Fig. 1.15 Flowchart of the Do while loop


 The syntax for the do while loop is
do
{
statements;
}
while(condition);
Program
1.21
/* Program to check the given number is palindrome or not */
#include<stdio.h>
#include<conio.h
> void main()
{
int n,t,s,r;
clrscr();
printf(“\n Enter the
number”); scanf(“%d”,&n);
t=n;
s=0
;
do
{ r=n
%10;
s=(s*10)+r
; n=n/10;
} while(n>0);
printf(“%d is a
palindrome”,t); else
printf (“%d is not a palindrome”,
t); getch( );
}
Output
Enter the number 242
STORAGE CLASSES:
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program.
They precede the type that they modify. We have four different storage classes in a C program −

 auto
 register
 static
 extern

The auto Storage Class

The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}

The example above defines two variables with in the same storage class. 'auto' can only be used within functions,
i.e., local variables.

The register Storage Class


The register storage class is used to define local variables that should be stored in a register instead of RAM.
This means that the variable has a maximum size equal to the register size (usually one word) and can't have the
unary '&' operator applied to it (as it does not have a memory location).
{
register int miles;
}

The register should only be used for variables that require quick access such as counters. It should also be noted
that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be
stored in a register depending on hardware and implementation restrictions.

The static Storage Class

The static storage class instructs the compiler to keep a local variable in existence during the life-time of the
program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making
local variables static allows them to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to
be restricted to the file in which it is declared.
In C programming, when static is used on a global variable, it causes only one copy of that member to be shared
by all the objects of its class.
#include <stdio.h>

/* function declaration */
void func(void);

static int count = 5; /* global variable */

main() {

while(count--) {
func();
}

return 0;
}

/* function definition */
void func( void ) {

static int i = 5; /* local static variable */ i+


+;

printf("i is %d and count is %d\n", i, count);


}

When the above code is compiled and executed, it produces the following result −
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0

The extern Storage Class

The extern storage class is used to give a reference of a global variable that is visible to ALL the program
files. When you use 'extern', the variable cannot be initialized however, it points the variable name at a storage
location that has been previously defined.
When you have multiple files and you define a global variable or function, which will also be used in other files,
then extern will be used in another file to provide the reference of defined variable or function. Just for
understanding, extern is used to declare a global variable or function in another file.
The extern modifier is most commonly used when there are two or more files sharing the same global variables
or functions as explained below.
First File: main.c
#include <stdio.h>

int count ;
extern void write_extern();

main() {
count = 5;
write_extern();
}
Second File: support.c

#include <stdio.h> extern int count;

void
write_extern(
void) {
printf("count
is %d\n",
count);
}

Here, extern is being used to declare count in the second file, where as it has its definition in the first file, main.c.
Now, compile these two files
it produces the following result −
count is 5

PRECEDENCE AND ASSOCIATIVITY OF OPERATOR


Operators Precedence and Associativity are two characteristics of operators that determine the evaluation
order of sub-expressions in absence of brackets.
Precedence of operators
 The precedence rule is used to determine the order of application of operators inevaluating
sub expressions.
 Each operator in C has a precedence associated with it.
 The operator with the highest precedence is operated first.
Associativity of operators
 The associativity rule is applied when two or more operators are having same
precedence in the sub expression.
 An operator can be left-to-right associative or right-to-left associative.

Rules for evaluation of expression


• First parenthesized sub expressions are evaluated first.
• If parentheses are nested, the evaluation begins with the innermost sub expression.
• The precedence rule is applied to determine the order of application of operators inevaluating
sub expressions.
• The associability rule is applied when two or more operators are having same precedence in the
sub expressions.
Example:

Compilation process:
Once a C program is written, it should run through a compiler to create an executable
file
i.e. a machine readable file. The compiler translates the source code into an
object code i.e. machine instructions for CPU, call to OS API etc.
The compilation process composed of the following steps:
1. The pre-processor programs read the source file as the text to produce another
output text file.
2. The linker combines the object file with the library routine to produce the final
executable file.
Steps in executing the C program:
1. Save the program with .c extension.
2. Compile the C program using a compiler.
3. Execute or run the program.
4. The output is generated on giving the required input to the
program which can be stored if needed.
FUNCTIONS
Introduction
 A function is a sub program which contains a set of instructions that are used to
perform specified tasks
 A function is used to provide modularity to the software. By using function can
divide complex task into manageable tasks. The function can also help to avoid
duplication of work.
Advantages of Functions
 Code reusability
 Better readability
 Reduction in code redundancy
 Easy to debug & test.
How Does Function Work?
 Once a function is called, it takes some data from the calling function and
returns back some value to the called function.
 Whenever function is called control passes to the called function and working of
the calling function is temporarily stopped, when the execution of the called
function is completed then a control return back to the calling function and
executes the next statement.
 The function operates on formal and actual arguments and send back the result
to the calling function using return() statement.
Types of Functions
Functions are classified into two types
a) User defined functions
b) Predefined functions or Library functions or Built-in functions
a) User-defined functions
 User-defined functions are defined by the user at the time of writing a program.
Example: sum( ), square( )
b) Library functions [Built-in functions]
 Library functions are predefined functions. These functions are already developed
Example: printf( ), scanf( )
Terminologies used in functions
 A function f that uses another function g is known as the calling function, and g
is known as the called function.
 The inputs that a function takes are known as arguments.
 When a called function returns some result back to the calling function, it is said
to return that result.
 The calling function may or may not pass parameters to the called function. If
the called function accepts arguments, the calling function will pass parameters,
else not.
 Function declaration is a declaration statement that identifies a function’s
name, a list of arguments that it accepts, and the type of data it returns.
 Function definition consists of a function header that identifies the function,
followed by the body of the function containing the executable code for that
function.

Function prototype
User Defined Function
 The function defined by the users according to their requirements is called user
defined functions. The users can modify the function according to their
requirement.
Need For user Defined Functions
 While it is possible to write any complex program under the main () function
and it leads to a number of problems, such as
 The program becomes too large and complex
 The users cannot go through at a glance.
 The task of debugging, testing and maintenance becomes difficult.
Advantages of user Defined Functions
 The length of the source program can be reduced by dividing it into the smaller
functions.
 By using functions it is very easy to locate and debug an error.
 The user defined function can be used in many other source programs whenever
necessary.
 Functions avoid coding of repeated programming of the similar instructions.
 Functions enable a programmer to build a customized library of repeatedly used
routines.
 Functions facilitate top-down programming approach.
1.9.1.2 Elements of user Defined Functions
 In order to write an efficient user defined function, the programmer must be
familiar with the following three elements.
 Function declaration
 Function definition
 Function call
Function Declaration
 A function declaration is defined as a prototype of a function which consists of
the functions return type, function name and arguments list
 It is always terminated with semicolon (;)
 Function prototypes can be classified into four types
a) Function with no arguments and no return values
b) Function with arguments and no return values
c) Function with arguments and with return values
d) Function with no arguments and with return values
Syntax
return_type function_name (parameter_list);
Where,
return_type can be primitive or non-primitive data type
function_name can be any user specified name
parameter_list can consist of any number of parameter of any type
Example
void add(void);
void
add(int,int); int
add(int,int); int
add(void);
a) Function with No Arguments and No Return Values
 In this prototype, no data transfer takes place between the calling function and
the called function. (i.e) the called program does not receive any data from the
calling program and does not send back any value to the calling program.
Syntax:
void
function_name(void);
void main()
{
…….
function_name()
;
…..
}
void function_name(void)
{
…..
……
}
Program 1.22
/*Implementation of function with no return type and no argument list*/
#include<stdio.h>
#include<conio.h
>
void add(void); //function declaration with no return type and
no arguments list
void main()
{

}
void add()
{

}
Output:
int a,b,c;
printf(“Enter the two numbers . . .
“); scanf(“ %d %d”,&a,&b);
c=a+b;
printf(“sum is . . . %d”,c);
Enter the two numbers . . . 10 20
Sum is . . . 30
b) Function with Arguments and No Return Values
 In this prototype, data is transferred from calling function to called function. i.e
the called program receives some data from the calling program and does not
send back any values to calling program.
Syntax:
void
function_name(arguments_list);
void main()
{
…….
function_name(argument_list)
;
…..
}
void function_name(arguments_list)
{
//function body
}
Program 1.23
/*Implementation of function with no return type and with argument list*/
#include<stdio.h>
#include<conio.h
>
int add(int,int); ); //function declaration with no return type and with
arguments list
void main()
{
int a,b,;
clrscr();
printf(“enter the two values:
“); scanf(“ %d %d”,&a,&b);
add(a,b); /*calling a function with arguments
*/ getch();
}
void add(int x,int y)
{
int z;
z=x+y
;
printf(“Sum is........%d”,z);
Output:
Enter two values: 10 20
Sum is.........30
c) Function with arguments and With Return Values
 In this prototype, data is transferred between calling function and called
function.( i.e) the called program receives some data from the calling program
and send back a return value to the calling program.
 Value received from a function can be further used in rest of the program.
Syntax:
return_type
function_name(arguments_list); void main()
{
…….
variable_name=function_name(argument_list)
;
…..
}
return_type function_name(arguments_list)
{
//function body
}
Program 1.24
#include<stdio.h>
#include<conio.h
>
int add(int,int); //function declaration with return type and with arguments
list void main()
{
int a,b,c;
clrscr();
printf(“enter the two numbers:
“); scanf(“ %d %d”,&a,&b);
c=add(a,b); /*calling function with
arguments*/ printf(“sum is . . . %d “, c);
getch();
}
int add(int x,int y)
{
int z;
z=x+y
;
} return(z); /*returning result to calling function*/
Output:
Enter the two numbers: 10 20
sum is. . 30
d) Function with No Arguments and with Return Values
 In this prototype, the calling program cannot pass any arguments to the called
program. i.e) program may send some return values to the calling program.
Syntax:
return_type
function_name(void); void main()
{
…….
variable_name=function_name()
;
…..
}
return_type function_name(void)
{
//function body
}
Program 1.25
/*Implementation of function with return type and no argument
list*/ #include<stdio.h>
#include<conio.h>
int add(void); //function declaration with no return type and no arguments
list void main()
int c;
c=add(); //function call
printf(“sum is . . . %d”,c);
}
int add(void)
{
int a,b,c;
printf(“Enter the two numbers . . .
“); scanf(“ %d %d”,&a,&b);
c=a+b;
return(c)
;
}
Function Definition
 It is the process of specifying and establishing the user defined function by
specifying all of its elements and characteristics.
 When a function is defined, space is allocated for that function in the memory.
 A function definition comprises of two parts:
 Function header
 Function Body
Syntax

return_type function_name(argument_list)
{
//function body
}
Example
int add(int x, int y)
{
int z;
return(z);
}
Program 1.26
#include<stdio.h>
// function prototype, also called function
declaration float square ( float x );
// main function, program starts from here
int main( )
{
float m, n ;
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
// function call
n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
}
float square ( float x ) // function definition
{
float p ;
p=x*x;
return ( p )
} ;
Output
Enter some number for finding square
2
Square of the given number 2.000000 is 4.00000
Function Call
 The function can be called by simply specifying the name of the function, return
 The function call statement invokes the function. When a function is invoked,
the compiler jumps to the called function to execute the statements that are a part
of that function. Once the called function is executed, the program control passes
back to the calling function.
Syntax
function_name();
function_name(parameter);
variable_name=function_name(parameter)
; variable_name=function_name();
Example
add();
add(a,b);
c=add(a,b)
; c=add;
 There are two ways that a C function can be called from a program. They are,
a) Call by value
b) Call by reference
a) Function-Call by value
 In the call by value method the actual arguments are copied to the formal
arguments, hence any operation performed by function on arguments doesn’t
affect actual parameters.
b) Function-Call by Reference
 Unlike call by value, in this method, address of actual arguments (or parameters)
is passed to the formal parameters, which means any operation performed on
formal parameters affects the value of actual parameters.
Actual parameters: The parameters that appear in function calls.
Formal parameters: The parameters that appear in function declarations.
Program 1.27
//Example program for Actual Parameter and Formal Parameters
int sum(int a, int b)
{
int
c=a+b;
return c;
}
int main(
{
int var1 =10;
int var2 = 20;
int var3 = sum(var1,
var2); printf("%d", var3);
return 0;
}
In the above example variable a and b are the formal parameters (or formal
arguments). Variable var1 and var2 are the actual arguments (or actual parameters). The
actual parameters can also be the values. Like sum(10, 20), here 10 and 20 are actual
parameters.
Program 1.28
//Example of Function call by Value
#include <stdio.h>
int increment(int var)
{
var =
var+1;
return var;
}
int main()
{
int num1=20;
int num2 = increment(num1);
printf("num1 value is: %d", num1);
printf("\nnum2 value is: %d",
num2); return 0;
}
Output

num1 value is: 20


num2 value is: 21
Program 1.29
//Example 2: Swapping numbers using Function Call by Value
#include <stdio.h>
void swapnum( int var1, int var2 )
{
int tempnum ;
/*Copying var1 value into temporary variable
*/ tempnum = var1;
/* Copying var2 value into
var1*/ var1 = var2;
/*Copying temporary variable value into var2
*/ var2 = tempnum;
}
int main( )
{
int num1 = 35, num2 = 45;
printf("Before swapping: %d, %d", num1, num2);
/*calling swap
function*/
swapnum(num1, num2);
printf("\nAfter swapping: %d, %d", num1, num2);
}
Output
Before swapping: 35, 45
After swapping: 45, 35
Program 1.30
Example 2: Function Call by Reference – Swapping numbers
#include
void swapnum ( int *var1, int *var2 )
{
int tempnum ;
tempnum =
*var1;
*var1 = *var2;
*var2 = tempnum;
}
int main( )
{
int num1 = 35, num2 = 45;
printf("Before swapping:"); printf("\
nnum1 value is %d", num1);
printf("\nnum2 value is %d",
num2);
printf("\nAfter swapping:");
printf("\nnum1 value is %d",
num1); printf("\nnum2 value is
%d", num2); return 0;
}
Output

Before swapping:
num1 value is 35
num2 value is 45
After swapping:
num1 value is 45
num2 value is 35

1.9 RECURSIVE FUNCTIONS


 Recursion is the process of calling the same function again and again until some
condition is satisfied.
 This process is used for repetitive computation.
Syntax:
function_name()
{
function_name();
}
Types of Recursion
a) Direct Recursion
b) Indirect Recursion
a) Direct Recursion
 A function is directly recursive if it calls itself.
Functionname1( )
{
….
Functionname1 ( ); // call to itself
….
}
Example
 A function is said to be directly recursive if it explicitly calls itself. Here, the
function Func() calls itself for all positive values of n, so it is said to be a
directly recursive function.
{
if (n ==
0) return
n; else
return (Func (n–1));
}
b) Indirect Recursion
 Function calls another function, which in turn calls the original function.
Functionname1 ( )
{

Functionname2 ( );

}
Functionname1 ( )
{

Functionname1 ( );// function (Functionname2) calls (Functionname1)

}
Example
 A function is said to be indirectly recursive if it contains a call to another
function which ultimately calls it. These two functions are indirectly recursive as
they both call each other.
int Funcl (int n)
{
if (n ==
0) return
n; else
}
int Func2(int x)
{
return Func1(x–1);
}
Program
1.31
/*C program to find factorial of a given number using recursion*/

#include<
stdio.h>
#include<conio.h
> void main()
{
int
fact(int);
int num,f;
clrscr();
printf(“enter the
number”);
scanf(“%d”,&num);
f=fact(num);
printf(“ the factorial of %d= %d”, num, f);

int f;
if(x==1)
return(1)
; else
f=x*fact(x-1); //recursive function
call return (f);
}
Output:
Enter the number 5
The factorial of 5=120

ARRAYS
Introduction to Arrays
 An Array is a collection of similar data elements
 These data elements have the same data type
 The elements of the array are stored in consecutive memory locations and are
referenced by an index
Definition
 An array is a data structure that is used to store data of the same type. The
position of an element is specified with an integer value known as index or
subscript.
Example

Fig. 1.16 Array Structure


Characteristics
 All the elements of an array share a common name called as array name
 The individual elements of an array are referred based on their position
 The array index in c starts with 0
Advantages of C array
 Code Optimization : Less code to access the data
 Easy to traverse data : By using the for loop, we can retrieve the elements of
can array easily
 Easy to sort data: To sort the elements of array, we need a few lines of code only
 Random Access : We can access any element randomly using the array
Disadvantages of array
 Fixed Size: Whatever size, we define at the time of declaration of array, we
can’t exceed the limit. So it doesn’t grow the size dynamically like Linked List
Classifications
 In general arrays are classified as:
 One-Dimensional Array
 Two-Dimensional Array
 Multi-Dimensional Array

Declaration of an Array
Array has to be declared before using it in C program. Declaring array means
specifying three things.
Data_type Data Type of Each Element of the array
Array_name Valid variable name
Size Dimensions of the Array
Arrays are declared using the following syntax:

type name[size]

Here the type can be either int, float, double, char or any other valid data type. The
number within the brackets indicates the size of the array, i.e., the maximum number of
elements that can be stored in the array.
Example: i) int marks[10]
ii) int a[5]={10,20,5,56,100}
The declaration of an array tells the compiler that, the data type, name of the
array, size of the array and for each element it occupies memory space. Like for int data
type occupies 2 bytes for each element and for float occupies 4 bytes for each element
etc. The
size of the array operates the number of elements that can be stored in an array.
Initialization of arrays
Elements of the array can also be initialized at the time of declaration as in the
case of every other variable. When an array is initialized, we need to provide a value for
every element in the array. Arrays are initialized using the following syntax:
type array_name [size] = { list of values};

The values are written with curly brackets and every value is separated by a comma.
It is a compiler error to specify more number of values than the number of elements in
the array.
Example: int marks [5] = {90, 92, 78, 82, 58};

ONE DIMENSIONAL ARRAY


 It is also known as single-dimensional arrays or linear array or vectors
 It consists of fixed number of elements of same type
 Elements can be accessed by using a single subscript
Example

Declaration of Single Dimensional Array


 An array must be declared before being used. Declaring an array means
specifying three things.
1. Data type
2. Name
3. Size
Syntax

datatype arrayname [array size];

Example
int a[4]; // a is an array of 4 integers
Initialization of single dimensional array
 Elements of an array can also be initialized. After declaration, the array elements
must be initialized otherwise they hold garbage value. An array can be initialized
at compile time or at run time.
 Elements of an array can be initialized by using an initialization list. An
initialization list is a comma separated list of initializers enclosed within braces.
Example
1. int a[3]={1,3,4};
2. int i[5] ={1, 2, 3, 4, 5};
3. float a[5]={1.1, 2.3, 5.5, 6.7, 7.0};
4. int b[ ]={1,1,2,2};
 In the fourth example the size has been omitted (it can be) and have been
declared as an array with 4 elements having 1, 1, 2 and 2 as initial values.
 Character arrays that hold strings allow a shortcut initialization of the form:
char array_name[size]=”string”
For example,
char mess[ ]={‘w’,‘e’,‘l’,‘c’,‘o’,‘m’,‘e’};
 If the number of initializers in the list is less than array size, the leading array
locations gets initialized with the given values. The rest of the array locations
gets initialized to
0 - for int array
0.0 - for float array
\0 - for character array
Example
int a[2]={1}; a
1 0
char b[5]={‘A’.’r’,’r’}; b

‘A’ ‘r’ ‘r’ ‘\0’ ‘\0’


Example Programs
Program 1.32
/*Program to find the maximum number in an array * /
#include<stdio.h
> void main( )
{
int a[5], i, max;
printf(“Enter 5 numbers one by one \n”);
for(i=0;i<5;i++)
{
scanf(“%d”, & a[i]);
}
max=a[0];
for(i=1;i<5;i+
+)
{
if (max<a[i])
max =a[i];
}
printf(“\n The maximum number in the array is
%d”,max); getch( ) ;

Output:
Enter 5 numbers one by one
57364
The maximum number in the array is 7

Program 1.33
/*Program for reversing an array*/
#include<stdio.h>
{
int a[10],
i; int n;
printf(“Enter the maximum number of elements\
n”); scanf(“%d”, &n);
for(i=0; i<n; i++)
{
scanf(“%d”,&a[i]);
}
printf(“Array in the reverse order\
n”); for(i=n–1; i>=0; i--)
{
printf(“%d\t”, a[i]);
}
getch( );
}
Output
Enter the maximum number of elements
5 11 12 13 14 15
Array in the reverse order
15 14 13 12 11
Program 1.34
/* Program to calculate sum of array content */
#
include<stdio.h>
void main( )
{
int a[20], n, i, sum = 0;
print f(“\n Enter the size of the array:”);
scanf(“%d”, &n)
printf (“\n Enter the %d numbers one by
one:”); for (i=0; i<n; i++)
{
scanf(“%d”,
&a[i]); sum = sum
+ a[i];
}
printf (“The sum of array content = %d”,
sum); getch( );
}
Output

Enter the size of the array: 5


Enter the 5 number one by one:
10 20 30 40 50
The sum oif the array content = 150

MULTI-DIMENSIONAL ARRAY
 A multi-dimensional array is an array that has more than one dimension. It is an
array of arrays; an array that has multiple levels. The simplest multi-dimensional
array is the 2D array, or two-dimensional array and 3D or three-dimensional
array.

1.13.1 Two Dimensional Array


 A two dimensional array is an array of one dimensional arrays and can be
visualized as a plane that has rows and columns.
 The elements can be accessed by using two subscripts, row subscript (row
number), column subscript (column number).
 It is also known as matrix.
 A single dimensional array can store a list of values, whereas two dimensional
array can store a table of values.
Example
1 2 3 6 7
9 10 5 0 4
a[3][5] 3 1 2 1 6

Declaration
datatype arrayname [row size][column size]

Example: int a [2][3]; //a is an integer array of 2 rows and 3 columns


Number of elements=2*3=6
Initialization
1. By using an initialization list, 2D array can be initialized.
e.g. int a[2][3] = {1,4,6,2}

a 1 4 6
2 0 0

2. The initializers in the list can be braced row wise.


e.g int a[2][3] = {{1,4,6} , {2}};
Program 1.35
/ * Example for two dimensional array handling * /
#include
<stdio.h> void
main( )
{
int a[10]
[10],i,j,sum,d,n1,n,rowsum,colsum,diasum;
printf(“Enter order[row][col] of the matrix\n”);
scanf(“%d %d”,&n,&n1);
printf(“Enter %d elements\n”,n1*n);
for(i=0;i<n;i++)
for(j=0;j<n1;j++)
scanf(“%d”,&a[i]
[j]);
/ * Program module to sum all elements * /
sum=0;
for(i=0;i<n;i++)
for(j=0;j<n1;j+
+) sum+=a[i][j];
printf(“Sum of all elements%d\n”,sum);
/ * Program to module to sum row wise */
for(i=0;i<n;i++)
{
rowsum=0;
for(j=0;j<n1;j+
+)
{
rowsum+=a[i][j];

}
}
/* Program module to sum colwise
*/
for(i=0;i<n;i++)
{
colsum=0;
for(j=0;j<n1;j+
+) colsum+=a[j]
[i];
printf(“col no=%d sum=%d\n “,i,colsum);
}
diasum=0;
for(i=0;i<n;i++)
for(j=0;j<n1;j++)
if(i==j) diasum+=a[i]
[j];
printf(“Principle diagonal sum %d\n”,diasum);
/ * Program module to sum off diagonal */
diasum=0;
for(i=0;i<n;i+
+)
{
j= -n1;
diasum +=a[i][j];
} }
Output printf(“Off diagonal sum%d\n”,diasum);
Enter order [row][col] of the matrix
33
Enter 9 elements
123456789
Sum of all elements 45
row no = 0 sum = 6
row no = 1 sum = 15
row no = 2 sum = 24
col no = 0 sum = 12
col no = 1 sum = 15
col no = 2 sum = 18
Principle diagonal sum 15
Off diagonal sum 15
1.13.2 Three-Dimensional Arrays
Initialization of a 3d array
Initialize a three-dimensional array in a similar way to a two-dimensional array.
Example
int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
Program 1.36
Write a C Program to store and print 12 values entered by the user
#include <stdio.h>
int main()
{
int test[2][3][2];
printf("Enter 12 values: \n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
scanf("%d", &test[i][j][k]);
}
}
}
// Printing values with the proper index.
printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}
return 0;
}
Output
Enter 12 values:
1
2
3
4
5
6
7
8
9
10
11
12
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
String Functions:
C Programming allows us to perform different string processing operations through the
functions defined in <string.h> header file. The <string.h> header file contains various methods for
performing mathematical operations such as

No. Function Syntax Description


1. strlen size_t strlen(const char *str); Finds out the length of the string
strlen(string1);
2. strcpy char *strcpy( char *str1, char *str2); Copy one string to another string
strcpy(source, destination);
3. strncpy char *strncpy( char *str1, char Copies first ‘n’ characters from one
*str2, size_t n); string to another string
strcpy(source, destination,n);
4. strcat char *strcat(char *str1, char *str2); Appends one string to the end of another
strcat(source, destination); string
5. strncat char *strncat(char *str1, char *str2, Apppends first ‘n’ character of a string
int n); to another string
strncat(source, destination,n);
6. strcmp int strcmp(const char *str1, const compares two string
char *str2);
strcmp(str1,str2);
7. strncmp int strncmp(const char *str1, const compares first n character of twe strings
char *str2, size_t n);
strncmp(str1,str2,n);
8. strcmpi int strcmpi (const char * str1, const compares two strings without regard to
stricmp char * str2 ); case
strcmpi(string1, string2);
9. strnicmp Compares first ‘n’ characters without
case sensitivity
10. strlwr char *strlwr(char *str); Converts a string to its lower case
strlwr(string);
11. strupr char *strupr(char *str); Converts a string to its uppercase
strupr(string);
12. strstr char *strstr(const char *string, Finds the first occurrence of a string in
const char *match); the given string
strstr(string, sub-string);
13. strchr char *strchr(char *str, int ch); Finds the first occurrence of a character
strchr(string, character); in the given string
14. strset char *strset(char *string, int c); Sets all character of a string to a given
strset(string, character); string
15. strnset char *strnset(char *string, int c, Sets first ‘n’ characters of a string to the
size_t n); given character
strnset(string, character, size);
16. strrev char *strrev(char *str); It reverses a string
strrev(string);
17. strtok char *strtok(char *str, const char Tokenizing given string using delimiters
*delim);
strtok(string,token);
18. strstr char *strstr(char *str, char It is similar to strchr, except that it
*srch_term); searches for string srch_term instead of
strstr(string, substring); a single char.

Illustrations
Program: Output:
strstr()
#include <stdio.h> Output string is: Programming
#include <string.h>
int main()
{
char inputstr[70] = "String Function in C
Programming";
printf ("Output string is: %s", strstr(inputstr,
"Pro"));
}
strchr( )
#include <stdio.h> String after '.' is ".google.com"
#include <string.h>
int main () {
const char str[] =
"http://www.google.com"; const char ch =
'.';
char *ret;
ret = strchr(str, ch);
printf("String after \'%c\' is \"%s\"\n", ch, ret);
}
strrev( )
#include<stdio.h> The given string is =C Programming
#include<string.h> After reversing string is =gnimmargorP
int main() C
{
char str[50] = "C Programming";
printf("The given string is =%s\n",str);
printf("After reversing string is
=%s",strrev(str));
return 0;
}
strupr( )
#include<stdio.h> PROGRAMMING IN C
#include<string.h>
int main()
{
char str[ ] = "programming in C";
//converting the given string into uppercase.
printf("%s\n", strupr (str));
return 0;
}
strlwr( )
#include<stdio.h> Programming in C
#include<string.h>
int main()
{
char str[ ] = " PROGRAMMING IN C";
// converting the given string into lowercase.
printf("%s\n",strlwr (str));
return 0;
}
strstr( )
#include<stdio.h> Substring is: C Programming
#include <string.h>
int main(){
char str[100]="this is C
Programming"; char *sub;
sub=strstr(str,"C Pro");
printf("\nSubstring is: %s",sub);
return 0;
}
strset( ), strnset( )
#include <stdio.h> This is the string: abcdefghi
#include <string.h> This is the string after strnset:
int main(void) xxxxefghi This is the string after strset:
kkkkkkkkk
{
char str[] = "abcdefghi";
printf("This is the string: %s\n", str);
printf("This is the string after strnset: %s\n",
strnset((char*)str, 'x', 4));
printf("This is the string after strset: %s\n",
strset((char*)str, 'k'));
return 0;
}
strtok( )
#include <string.h> /* Splits str[] according to given delimiters
#include <stdio.h> returns next token. It needs to be called i
int main () { loop to get all tokens. It returns NULL w
char str[80] = "This is - www.google.com - there are no more tokens.*/
website";
const char s[2] =
"-"; char *token; This is
/* get the first token */ www.google.com
token = strtok(str, s); website
/* walk through other tokens */
while( token != NULL ) {
printf( " %s\n", token );
token = strtok(NULL, s);
}
return(0);
}
REVIEW QUESTIONS
PART-A
1. List down the Primary Data Types in C
 Integer – We use these for storing various whole numbers, such as 5, 8, 67,
2390, etc.
 Character – It refers to all ASCII character sets as well as the single alphabets,
such as ‘x’, ‘Y’, etc.
 Double – These include all large types of numeric values that do not come
under either floating-point data type or integer data type.
 Floating-point – These refer to all the real number values or decimal points,
such as 40.1, 820.673, 5.9, etc.
 Void – This term refers to no values at all. We mostly use this data type when
defining the functions in a program.
2. What is Variable?
 Variables are containers for storing data values.
 Its value can be changed, and it can be reused many times.
 Syntax for creating variables
 type variableName = value;
 Example: int a = 5;
3. What is Operator?
 An operator is a special symbol that tells the compiler to perform specific
mathematical or logical operations.
 Operators in programming languages are taken from mathematics.
 C language supports a rich set of built-in operators.
4. List the types of operators supported in C
 Arithmetic operators
 Relational operators
 Logical operators
 Bitwise operators
 Assignment operators
 Type Information Operators(Special operators)
5. What is Ternary operators or Conditional operators?
 Ternary operators is a conditional operator with symbols? and :
 Syntax: variable = exp1 ? exp2 : exp3
 If the exp1 is true variable takes value of exp2. If the exp2 is false, variable
takes the value of exp3.
6. What is an Operator and Operand?
 An operator is a symbol that specifies an operation to be performed on
operands.
 Example: *, +, -, / are called arithmetic operators.
 The data items that operators act upon are called operands.
7. What is type casting?
 Type casting is the process of converting the value of an expression to a
particular data type.
 Example: int x,y.
c = (float) x/y; where a and y are defined as integers. Then the result of x/y is
converted into float.
8. What is the difference between while loop and do while loop?
while do while
In the while loop the condition is first In the do…while loop first the
executed. statement is executed and then the
condition is checked.
If the condition is true, then it executes The do…while loop will execute at
the body of the loop. When the least one time even though the
condition is false it comes of the loop. condition is false at the very first time.

9. What is the difference between ++a and a++?


 ++a means do the increment before the operation (pre increment) a++ means
do the increment after the operation (post increment)
10. What is a Function?
 A function is a block of code which only runs when it is called.
 It performs a specific task.
11. What is meant by Recursive function?
 If a function calls itself again and again, then that function is called Recursive
function.
 The syntax for recursive function is:
function recurse() {
// function code
recurse();
// function code
}
recurse();
12. Write short notes about main() function in ’C’ program.
Every C program must have main () function.
 All functions in C, has to end with ‘( )’ parenthesis.
 It is a starting point of all ‘C’ programs.
 The program execution starts from the opening brace ‘{‘ and ends with
closing brace ‘}’, within which executable part of the program exists.
13. Give the syntax for the ‘for’ loop statement
for (Initialize counter; Test condition; Increment / Decrement)
{
statements;
}
14. What is an Array?
 An array is defined as finite ordered collection of homogenous data, stored in
contiguous memory locations.
 finite means data range must be defined.
 ordered means data must be stored in continuous memory addresses.
 homogenous means data must be of similar data type.
 For example: if you want to store marks of 50 students, you can create an array
for it.
 int marks[50];
15. What are the different types of arrays available in C.
 One-dimensional arrays
 Multidimensional arrays
16. Write short notes on One-dimensional arrays.
 A One-Dimensional Array in C programming is a special type of variable that
can store multiple values of only a single data type such as int, float, double,
char etc.
 The syntax of declaring Two-dimensional arrays is:
 datatype array name [size]
 Example
For example, int a[5]
17. Write short notes on Two-dimensional arrays.
 A multi-dimensional array can be termed as an array of arrays that stores
homogeneous data in tabular form.
 The general form of declaring Two-dimensional arrays is:
 data_type array_name[x][y];
 Example
int x[10][20];
18. What are the key features in the C programming language?
 Portability: It is a platform-independent language.
 Modularity: Possibility to break down large programs into small modules.
 Flexibility: The possibility of a programmer to control the language.
 Speed: C comes with support for system programming and hence it compiles
and executes with high speed when compared with other high-level languages.
 Extensibility: Possibility to add new features by the programmer.
19. What is a nested loop?
 A loop that runs within another loop is referred to as a nested loop. The first
loop is called the Outer Loop and the inside loop is called the Inner Loop. The
inner loop executes the number of times defined in an outer loop.
20. What are the modifiers available in C programming language?
 Short
 Long
 Signed
 Unsigned
 long long
21. What is the explanation for prototype function in C?
 Prototype function is a declaration of a function with the following information
to the compiler.
 Name of the function.
 The return type of the function.
 Parameters list of the function.
 Example
 int sum(int,int);
22. What do you mean by the Scope of the variable?
 Scope of the variable can be defined as the part of the code area where the
variables declared in the program can be accessed directly. In C, all identifiers
are lexically (or statically) scoped.
23. Can a C program be compiled or executed in the absence of a main()?
 The program will be compiled but will not be executed. To execute any C
program, main() is required.
24. What is the main difference between the Compiler and the Interpreter?
Interpreter Compiler
Translates program one statement at a Scans the entire program and translates
time. it as a whole into machine code.
Interpreters usually take less amount of Compilers usually take a large amount
time to analyze the source code. of time to analyze the source code.
However, the overall execution time is However, the overall execution time is
comparatively slower than compilers. comparatively faster than interpreters.
No Object Code is generated, hence are Generates Object Code which
memory efficient. further requires linking, hence
requires more memory.
Programming languages like Programming languages like C, C++,
JavaScript, Python, Ruby use Java use compilers.
interpreters.

PART-B
1. Explain the different types of operators with neat examples.
2. Illustrate the different conditional statements available in C with syntax and
examples
3. Explain the looping statements with neat examples.
4. What is an Array? Explain Single and Multi-Dimensional arrays with neat examples.
5. Write a C program for Matrix Multiplication with a 3*3 matrix.
6. Create a C program for Matrix Addition.
7. Write a C program to calculate the total, average and grade for 50 Students.
8. Write a C program to calculate the factorial of a given number.
9. Write a C program to check whether a given number is odd or even.
10. Write a C program to check whether a given number is prime or not.
11. Write a C program to check whether a given number is a palindrome or not.
12. Write a C program to check whether a given number is a Armstrong number or not.

You might also like