0% found this document useful (0 votes)
7 views99 pages

C Programming Unit 1-14-112

C PROGRAMMINGFUNDAMENTALS

Uploaded by

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

C Programming Unit 1-14-112

C PROGRAMMINGFUNDAMENTALS

Uploaded by

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

[Link] [Link]

in/

in
C PROGRAMMING

n.
FUNDAMENTALS

aa
Data Types – Variables – Operations – Expressions and Statements – Conditional

iy
Statements – Functions – Recursive Functions – Arrays – Single and Multi-Dimensional
Arrays.
or
.p
1.1 INTRODUCTION TO PROGRAMMING PARADIGMS
w

➢ 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
w

programming language or also we can say it is a method to solve a problem using


w

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
1.2 C Programming Fundamentals
[Link] [Link]
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.

in
Disadvantage

n.
1. Complex problem cannot be solved
2. Less efficient and less productive

aa
3. Parallel programming is not possible

iy
Examples of Imperative programming paradigm: C, FORTAN, Basic

or
.p
w
w
w

Figure 1.1 Types Programming Paradigms


➢ Imperative programming is divided into three broad categories: Procedural,
OOP and parallel processing. These paradigms are as follows:
[Link] 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
C Programming and Data Structures 1.3
[Link] [Link]
➢ 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.

in
➢ Example: C, C++, JAVA, Pascal.

n.
[Link] Object Oriented Programming

aa
➢ 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

iy
to the data structure.
➢ In this way, the data structure becomes an object that includes both data and
or
functions. In addition, programmers can create relationships between one object
.p
and another. For example, objects can inherit characteristics from other objects.
➢ One of the principal advantages of object-oriented programming techniques over
w

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
w

programmer can simply create a new object that inherits many of its features from
w

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.
1.4 C Programming Fundamentals
[Link] [Link]
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.

in
n.
aa
iy
or
.p
w

Fig. 1.2 Class and Objects


w

Data abstraction and encapsulation


w

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
C Programming and Data Structures 1.5
[Link] [Link]
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

in
as shown in Fig.1.3. Here the class car is a subclass of automatic vehicle, which is again

n.
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

aa
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.

iy
or
.p
w
w
w

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:
1.6 C Programming Fundamentals
[Link] [Link]
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:

in
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

n.
(function) and therefore will invoke a function in the receiving object that generates the

aa
desired result.
Benefits of OOP

iy
➢ Through inheritance we can eliminate redundant code and extend the use of
existing classes.
or
➢ We can build secure programs by the principle of data hiding.
.p
➢ 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.
w

➢ Communication with external systems are much simpler by means of message


w

passing techniques.
➢ Software complexity can be easily managed.
w

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, [Link], Ruby.
C Programming and Data Structures 1.7
[Link] [Link]
[Link] 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.

in
➢ Examples are NESL (one of the oldest one) and C/C++ also supports because of
some library function.

n.
1.1.2 Declarative programming paradigm

aa
➢ It is divided as Logic, Functional, and Database. In computer science
the declarative programming is a style of building programs that expresses logic

iy
of computation without talking about its control flow.
➢ It often considers programs as theories of some logic. It may simplify writing
or
parallel programs. The focus is on what needs to be done rather how it should
.p
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
w

difference between imperative (how to do) and declarative (what to do)


w

programming paradigms.
w

[Link] 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

[Link] 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
1.8 C Programming Fundamentals
[Link] [Link]
➢ 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.

in
[Link] Database/Data driven programming approach

n.
➢ This programming methodology is based on data and its movement. Program

aa
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

iy
file creation, data entry, update, query and reporting functions. There are several
programming languages that are developed mostly for database application.
or
➢ For example SQL. It is applied to streams of structured data, for filtering,
.p
transforming, aggregating (such as computing statistics), or calling other
programs. So it has its own wide application.
w

1.1.3 Characteristics of a Good Programming Language


w

➢ A programming language must be simple, easy to learn and use, have good
w

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.
C Programming and Data Structures 1.9
[Link] [Link]
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

in
laboratories. The various stages in evolution of C language is given in Fig 1.4.

n.
CPL (Combined Programming Language)
Developed by Cambridge and University of London in 1963

aa
iy
BCPL (Basic Combined Programming Language)
Developed by Martin Richards in 1967
or
.p
B Language Developed by Ken Thompson at AT and T Bell
Laboratory in 1970
w
w

C Language Developed by Dennis Ritchie at AT and T


w

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.10 C Programming Fundamentals
[Link] [Link]
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

in
4. structured programming language

n.
5. Rich Library

aa
6. Memory Management
7. Fast Speed

iy
8. Pointers
9. Recursion or
10. Extensible
.p
1.3 APPLICATIONS OF C LANGUAGE
w

➢ The applications of C are not only limited to the development of operating


w

systems, like Windows or Linux, but also in the development of GUIs (Graphical
User Interfaces) and, IDEs (Integrated Development Environments).
w

➢ 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.
C Programming and Data Structures 1.11
[Link] [Link]
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.

in
5. Google
Google file system and Google chromium browser were developed using C/C++.

n.
Not only this, the Google Open Source community has a large number of projects being
handled using C/C++.

aa
6. Mozilla Firefox and Thunderbird
Since Mozilla Firefox and Thunderbird were open-source email client projects,

iy
they were written in C/C++.
7. MySQL or
MySQL, again being an open-source project, used in Database Management
.p
Systems was written in C/C++.
w

8. Compiler Design
One of the most popular uses of the C language was the creation of
w

compilers. Compilers for several other programming languages were designed keeping in
w

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
1.12 C Programming Fundamentals
[Link] [Link]
➢ 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

in
global declaration section

n.
main( )
{

aa
declaration part;
executable part;

iy
}
or
sub program
{
.p
body of the subprogram;
w

}
w

Program 1.1
w

/* 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);
C Programming and Data Structures 1.13
[Link] [Link]
getch();
}
Output
Enter the radius: 4.5
Area of the Circle = 63.58

in
Program 1.2

n.
/* Program to find the sum of two numbers using function */

aa
/*Documentation Section */
# include<stdio.h> /* Preprocessor Section */

iy
# include<conio.h>
int a,b;
int add(int,int);
or
/* Global Variable declaration */
/* Function declaration */
.p
void main() /* main( ) function */
w

{
w

int c; /* Local Variable declaration */


clrscr(); // Executable part of the main() program
w

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);
}
1.14 C Programming Fundamentals
[Link] [Link]
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

in
name, the date of development and the program details.

n.
Preprocessor section

aa
The preprocessor section provides preprocessor statements which direct the
compiler to link functions from the system library.

iy
Definition section
The definition section defines all symbolic constants refer to assigning a macro of
or
a name to a constant. The general syntax of a symbolic constant is
.p
#define constant_name constant_value
Global declaration section
w

The global declaration section contains variable declarations which can be


w

accessed anywhere within the program.


w

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.
C Programming and Data Structures 1.15
[Link] [Link]
➢ 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

in
i) Character set

n.
ii) Delimiters

aa
iii) Keywords
iv) Identifiers

iy
v) Data types
vi) Constants
vii) Variables
or
.p
1.5.1 Character Set
w

➢ The set of characters used to write the program words, expressions and statements.
w

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
w

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
1.16 C Programming Fundamentals
[Link] [Link]
iii) Special Characters
Table 1.1 List of Special Characters

in
n.
aa
iy
or
.p
w

Table 1.1 List of Special Characters


iv) White space characters
w

Blank space, newline, form feed, horizontal tab, vertical tab


w

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.
C Programming and Data Structures 1.17
[Link] [Link]
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.

in
n.
aa
iy
or
.p
Table 1.3 Delimiters
1.5.3 Keywords
w

➢ These are certain reserved words called keywords, which are standard, predefined
w

meanings in C. They must be written in lower case. There are 32 keywords


w

available in C. The standard keywords are shown in Table 1.4.

Table 1.4 Keywords in C


1.18 C Programming Fundamentals
[Link] [Link]
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.

in
i) The first character must be a letter followed by a letter or a digit.

n.
ii) Special characters are not allowed except underscore.
iii) The length of the variable varies from one compiler to another. Generally,

aa
most of the compilers support eight characters excluding extension. However,
the ANSI standard recognizes the maximum length of a variable up to 31

iy
characters.
iv) The variable should not be a C keyword.
or
v) The variable names may be a combination of upper and lower characters. For
.p
example, suM and sum are not the same variable.
vi) The variable name should not start with a digit.
w

Examples
w

➢ The following names are valid identifier


w

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 Programming and Data Structures 1.19
[Link] [Link]
C supports three categories of data types:
1. Primary data type 2. Derived data type 3. User defined data type.

in
n.
aa
iy
or
.p
w
w
w

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
1.20 C Programming Fundamentals
[Link] [Link]
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

in
type. For example the size of a floating point data type in a 16 bit computer is

n.
4 bytes. For Example: float rate = 5.6;
o Double: Double data type is similar to floating data type except that it

aa
provides up to ten digits of precision and occupies eight bytes of memory. For
Example: double d = 11676.2435676542;

iy
o Void Data Type: Void is an empty data type that has no value. This can be
or
used in functions and pointers.
Type modifiers in C
.p
➢ In c language Data Type Modifiers are keywords used to change the current
w

properties of data type. Data type modifiers are classified into the following types.
o Long
w

o Short
w

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.
C Programming and Data Structures 1.21
[Link] [Link]

in
n.
aa
Syntax

iy
long a; —> by default which represent long int
short or
➢ In general int data type occupies different memory spaces for a different operating
.p
systems; to allocated fixed memory space a short keyword can be used.
w

Syntax
short int a; —> occupies 2 bytes of memory space in every operating system
w

unsigned
w

➢ 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
1.22 C Programming Fundamentals
[Link] [Link]

in
n.
aa
Table 1.5 Size and range of Integer type on 16-bit machine

iy
or
.p
w
w

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


w

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];
C Programming and Data Structures 1.23
[Link] [Link]
➢ 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

in
n);

n.
Syntax for function definition
<return type> function name (parameter list)

aa
parameter declarations
{

iy
body of the function;
or
return (expression);
}
.p
Example
w

void swap (int x, int y)


w

{
w

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.
1.24 C Programming Fundamentals
[Link] [Link]
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.

in
o Structures

n.
A structure is a single entity representing a collection of data items of
different data types.

aa
Example
struct student

iy
{
int roll_no;
char fname[25];
or
.p
char branch[15];
w

int marks;
w

}s1;
o Unions
w

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
C Programming and Data Structures 1.25
[Link] [Link]
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

in
“type definition” that allows user to define an identifier that would represent
a data type using an existing data type.

n.
Syntax:

aa
typedef type identifier;
typedef <existing_data_type> <new_user_define_data_type>;

iy
Example
typedef int number; or
typedef long big_ number;
.p
typedef float decimal;
w

number visitors = 25;


w

big_number population = 12500000;


decimal radius = 3.5;
w

1.5.6 Constants
1.26 C Programming Fundamentals
[Link] [Link]
➢ 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

in
decimal integer constant can consist of any combination of digits taken from the
set 0 through 9.

n.
1. Decimal number – 0 to 9

aa
2. Octal number – 0 to 7
3. Hexadecimal number – 0 to 9, A, B, C, D, E, F

iy
➢ Examples
or
Decimal number – 10, 145,-89, 067 etc.
Octal number – 037, 0, 057, 0456 etc.
.p
Hexadecimal number – 0x4, 0x9C, 0xAFE etc.
w

➢ Rules for an integer constant


w

o It must have at least one digit.


o Decimal point is not allowed.
w

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;
C Programming and Data Structures 1.27
[Link] [Link]
➢ 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

in
necessary.
o No commas or blank spaces are allowed.

n.
Character constants

aa
Single Character Constant
➢ It contains a single character enclosed within a pair of single quote marks.

iy
Example
‘d’, ‘r’, ‘6’, ‘_’ or
String Constant
.p
➢ It is a sequence of characters enclosed in double quotes.
w

➢ The characters may be letters, numbers, special characters and blank spaces
w

➢ At the end of string ‘\0’ is automatically placed.


➢ Example
w

“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
1.28 C Programming Fundamentals
[Link] [Link]
Examples
1. int sum, count;
2. int rollno;
3. float int_rate;
4. double avg, netsal;

in
5. char char;
Variable declaration with qualifiers

n.
Examples

aa
1. short int number;
2. unsigned int total;

iy
3. long int ser_no;
4. long double volume;
Variable Initialization
or
.p
➢ 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.
w

Variables can be initialized with a constant value or expression.


w

Syntax:
w

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
C Programming and Data Structures 1.29
[Link] [Link]
➢ 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;

in
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

n.
value to a; by scanf ( ) statement the value can be replaced.

aa
Volatile variable
➢ The volatile variables are those variables that are changed at any time by any other

iy
external program or the same program. The syntax is as follows.
Example
volatile int b;
or
.p
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
w

other external operation, then the declaration of the variable will be as follows;
w

volatile const b = 20;


w

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
1.30 C Programming Fundamentals
[Link] [Link]
5. Increment and Decrement Operators
6. Conditional Operators (Ternary Operators)
7. Bitwise Operators
8. Special Operators

in
[Link] Arithmetic Operators
➢ Addition, subtraction, multiplication, division and modulo are the arithmetic

n.
operations.
➢ The arithmetic operators are used for numerical calculations between two

aa
Constants

iy
Operators Explanations Examples
+ Addition 2+2=4
-
or
Subtraction 3-2=1
.p
* Multiplication 5 * 4 =20
/ Division 10 / 2 = 5
w

% Modular Division 11 % 2 = 1
w

Example:
w

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
C Programming and Data Structures 1.31
[Link] [Link]
➢ 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

in
o Integer arithmetic – it requires both operands to be integer type for

n.
arithmetic operation.
Example:

aa
a=4, b=3
a+b =4+3 =7

iy
a-b =4-3=1
or
o Floating Point arithmetic – It requires both operands to be float type for
arithmetic operation.
.p
Example:
w

a=6.5, b=3.5
w

a+b =6.5+3.5 =10.0


w

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);
1.32 C Programming Fundamentals
[Link] [Link]
sub=b-c;
mul=b*c;
div=b/c;
printf(“\n sum=%d,sub=%d,mul=%d,div=%f”,sum,sub,mul,div);
getch();

in
}

n.
Output:

aa
Enter the value of b,c: 8 4
sum=12,sub=4,mul=32,div=2

iy
[Link] Relational Operators
or
➢ Relational operators are used to compare two or more operands.
➢ Operands may be variable, constant or expression
.p
Operators Descriptions Example Return Value
w

> Greater than 5>4 1


w

< Less than 10<9 0


<= Less than or equal to 10<=10 1
w

>= 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.
[Link] Logical Operators
C Programming and Data Structures 1.33
[Link] [Link]
➢ 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

in
5<10

n.
|| Logical OR 8>5 || 8<2 1
!= Logical NOT 8!=8 0

aa
➢ && - This operator is usually used in situation where two or more expressions
must be true.

iy
Syntax:
(exp1) && (exp2)
or
.p
➢ || – This is used in situation, where at least one expression is true.
Syntax:
w

(exp1) || (exp2)
w

➢ ! – This operator reverses the value of the expression it operates on. (i.e.,) it makes
w

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);
1.34 C Programming Fundamentals
[Link] [Link]
printf("\n !(7==7): %5d",!(7==7));
getch( );
}
Output
Condition : Return values

in
5<=8 && 4>2 : 1

n.
5>=3 || 6<8 : 1

aa
!(7==7) : 0

[Link] Assignment Operator

iy
➢ Assignment Operator are used to assign constant or a value of a variable or an
expression to another variable.
or
Syntax
.p
variable =expression (or) value;
w

Example
x=10;
w

x=a+b;
w

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;
C Programming and Data Structures 1.35
[Link] [Link]
b-=x;
c*=x;
d/=x;
e%=x;
printf("\n Value of a=%d",a);

in
printf("\n Value of b=%d",b);

n.
printf("\n Value of c=%d",c);
printf("\n Value of d=%d",d);

aa
printf("\n Value of e=%d",e);
getch();

iy
}
Output
Value of a = 20
or
.p
Value of b = 10
w

Value of a = 25
w

Value of b = 5
Value of c = 75
w

Value of d = 5
Value of e = 4

[Link] 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
1.36 C Programming Fundamentals
[Link] [Link]
Program 1.6
#include <stdio.h>
void main()
{
int a,b;

in
a=10;

n.
b=++a;
printf(“a=%d”,a);

aa
printf(“b=%d”,b);

iy
}
output: a=11 b=11 or
#include <stdio.h>
.p
void main()
{
w

int a,b;
w

a=10;
w

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()
C Programming and Data Structures 1.37
[Link] [Link]
int a,b;
a=10;
b=a++;
printf(“a=%d”,a);
printf(“b=%d”,b);

in
}

n.
Output:
a=11 b=10

aa
Program 1.8
#include <stdio.h>

iy
void main()
{
or
.p
int a,b;
a=10;
w

b=a--;
w

printf(“a=%d”,a);
w

printf(“b=%d”,b);
}
Output:
a=9 b=10

[Link] 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()
{
1.38 C Programming Fundamentals
[Link] [Link]
big=a>b?a:b;
printf(“big is…%d”,big);
}
Output
big is…5

in
[Link] Bitwise Operators

n.
➢ Bitwise operators are used to manipulate the data at bit level.

aa
➢ It operates on integers only.
➢ It may not be applied to float or real.

iy
Operator Meaning
&
|
or Bitwise AND
Bitwise OR
.p
^ Bitwise XOR
w

<< Shift left


>> Shift right
w

~ One’s complement
w

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.
C Programming and Data Structures 1.39
[Link] [Link]
Program 1.9
/* Program using One's complement operator */
#include<stdio.h>
#include<conio.h>
void main( )

in
{

n.
int a;

aa
clrscr( );
printf("\n Enter the value for a : ");

iy
scanf("%d",&a);
printf("\n The One's complement value for a is : %d", ~a);
or
getch( );
.p
}
Output
w

Enter the value for a: 3


w

The One's complement value for a is: -4


w

[Link] 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
1.40 C Programming Fundamentals
[Link] [Link]
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

in
Third assigns the value 77 to c

n.
Last assigns the value 80.

aa
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

iy
in memory.
Syntax: or
sizeof(var);
.p
Example:
w

void main()
w

{
w

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.
C Programming and Data Structures 1.41
[Link] [Link]
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.

in
Syntax

n.
Variable = expression;

aa
Example: 1
x=a*b-c;

iy
➢ 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
or
.p
a++;
➢ In example 2, the value of variable a is incremented by 1, i.e, this expression is
w

equivalent to a = a + 1.
w

1.7.2 Statements
w

➢ 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;
1.42 C Programming Fundamentals
[Link] [Link]
Compound Statement
➢ A compound statement also called a block, consists of several individual
statements enclosed within a pair of braces { }.
Example
{

in
a=3;

n.
b=10;
c=a+b;

aa
}
Control Statement

iy
➢ A single statement or a block of statements can be executed depending upon a
or
condition using control statements like if, if-else, etc.
Example
.p
a=10;
w

if (a>5)
w

{
w

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
C Programming and Data Structures 1.43
[Link] [Link]
be terminated. It supports the following constructs such as For, While and Do-
while loops.

1.8.1 Conditional Branching Statement


[Link] Selection Statement
❖ Simple If statement

in
➢ The syntax for a simple if statement is

n.
if (expression)

aa
{
block of statements;

iy
}
➢ In this statement, if the expression is true, the block of statements are executed
or
otherwise false and it comes out of the if condition.
.p
w
w
w

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()
1.44 C Programming Fundamentals
[Link] [Link]
{
int n;
printf(“\n Enter the number”);
scanf(“%d”,&n);
if(n%2==0)

in
{

n.
printf(“\n The given number%d is divisible by 2", n);

aa
}
getch();

iy
}
Output or
Enter the number : 10
.p
The given number 10 is divisible by 2
w

Program 1.11
/* Program to check the given numbers are equal or not */
w

#include<stdio.h>
w

#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
C Programming and Data Structures 1.45
[Link] [Link]
Two numbers are equal.
❖ If –else statement
➢ The syntax for the if-else statement is
if(expression)
{

in
block of statements1;

n.
}

aa
else
{

iy
block of statements2;
} or
.p
w
w
w

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.
1.46 C Programming Fundamentals
[Link] [Link]
Program 1.12
/* Program to find the given number is positive or negative */
#include<stdio.h>
void main()
{

in
int n;

n.
printf(“\n Enter the number:”);
scanf(“%d”,&n);

aa
if(n>0)

iy
{
printf(“\n The given number %d is positive”, n);
or
}
.p
else
{
w

printf(“\n The given number %d is negative”, n);


w

}
w

}
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();
C Programming and Data Structures 1.47
[Link] [Link]
printf(“\n Enter the number:”);
scanf(“%d”,&a);
if (a%2==0)
printf(“\n %d is an even number”,a);
else

in
printf(“%d is an odd number”,a);

n.
getch();

aa
}
Output

iy
Enter the number: 10
10 is an even number. or
❖ Conditional Expression
.p
➢ 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
w

expression is:
w

<expression-1> ? <expression-2> : <expression-3>;


➢ In this method if expression-1 is true then expression-2 is evaluated, otherwise
w

expression-3 is evaluated.
1.48 C Programming Fundamentals
[Link] [Link]
Program 1.14
/* Program to find biggest of two given numbers */
#include<stdio.h>
void main()
{

in
int x,y,z;

n.
printf(“\n Enter the value of x and y:”);
scanf(“%d%d”,&x,&y);

aa
z = ((x>y)?x:y);

iy
printf(“The biggest value is %d”,z);
getch(); or
}
.p
Output
Enter the value of x and y: 5 10
w

The biggest value is 10


w

❖ If-else-if statement
w

➢ The syntax for the if-else-if statement is


if(expression1)
{
statements1;
}
else if(expression2)
{
statements2;
}
else if(expression3)
{
statements3;
C Programming and Data Structures 1.49
[Link] [Link]
else
{
statements4;
}
➢ In this statement, if the expression1 is true, statements1 will be executed,

in
otherwise the expression2 is evaluated, if it is true then statements2 is executed,

n.
otherwise the expression3 is evaluated, if it is true then statements3 is executed,
otherwise statements4 is executed.

aa
iy
or
.p
w
w
w

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()
{
1.50 C Programming Fundamentals
[Link] [Link]
printf (“Enter the Average mark:”)
scanf(“%d”,&Avg_Mark);
if(Avg_Mark>=75)
{
printf(“Distinction”);

in
}

n.
elseif((Avg_Mark>=60) && (Avg_Mark<75))

aa
{
printf(“First Class”);

iy
}
elseif((Avg_Mark>=50) && (Avg_Mark<60))
or
{
.p
printf(“Second Class”);
}
w

elseif((Avg_Mark>=45) && (Avg_Mark<50))


w

{
w

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:
C Programming and Data Structures 1.51
[Link] [Link]

in
n.
/* Program to Calculate the gross salary */
#include<stdio.h>

aa
#include<conio.h>
void main()

iy
{
float bs, hra, da, cv, ts;
or
.p
clrscr();
printf(“\n Enter Basic salary:”);
w

scanf(“%f”,&bs);
w

if(bs>=5000)
w

{
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)
1.52 C Programming Fundamentals
[Link] [Link]
hra = bs*10/100;
da = bs*90/100;
cv = 300;
}
ts = bs+hra+da+cv;

in
printf(“\nBasic salary: %5.2f”,bs);

n.
printf(“\nHRA: %5.2f”,hra);
printf(“\nDA: %5.2f”,da);

aa
printf(“\nConveyance: %5.2f”,cv);

iy
printf(“\nGross Salary: %5.2f”,ts);
getch(); or
}
.p
Output
Enter basic salary: 5400
w

Basic salary: 5400


w

HRA: 1080
w

DA: 5940
Conveyance: 500
Gross salary: 12920
❖ Nested if statement
➢ The syntax for the nested if statement is
if(expression1)
{
statements1;
}
else
{
if(expression2)
C Programming and Data Structures 1.53
[Link] [Link]
statements2;
}
else
{
statements3;

in
}

n.
}

aa
iy
or
.p
w
w
w

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()
1.54 C Programming Fundamentals
[Link] [Link]
int x,y,z;
printf(“\n Enter the three numbers”);
scanf(“%d%d%d”,&x,&y,&z);
if ((x>y) && (x>z))
{

in
printf(“The Biggest number = %d”,x);

n.
}

aa
else
{

iy
if(y>z)
{ or
printf(“The Biggest number =%d”,y);
.p
}
else
w

{
w

printf(“The Biggest number =%d”,z);


w

}
}
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.
C Programming and Data Structures 1.55
[Link] [Link]
➢ 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>
{

in
case constant_1:
{

n.
statements1;

aa
break;
}

iy
case constant_2:
{
statements2;
or
.p
break;
w

}
w

case constant_3:
{
w

statements3;
break;
}
case constant_n:
{
statementsn;
break;
}
default:
{
default statements;
}
1.56 C Programming Fundamentals
[Link] [Link]

in
n.
aa
iy
or
.p
Fig. 1.12 Flowchart for Switch - Case statement
w

Program 1.18
w

/* Program to provide multiple functions such as 1. Addition 2. Subtraction


w

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 [Link]”);
printf(“\n [Link]”);
printf(“\n [Link]”);
printf(“\n [Link]”);
C Programming and Data Structures 1.57
[Link] [Link]
printf(“\n Enter your choice:”);
scanf(“%d”,&n);
printf(“Enter two numbers:”);
scanf(“%d%d”,&a,&b);
switch(n)

in
{

n.
case 1:

aa
c = a + b;
printf(“\n Addition: %d”,c);

iy
break;
case 2: or
c = a - b;
.p
printf(“\n Subtraction: %d”,c);
break;
w

case 3:
w

c = a * b;
w

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;
1.58 C Programming Fundamentals
[Link] [Link]
getch();
}
Output
Menu
1. Addition

in
2. Subtraction

n.
3. Multiplication

aa
4. Division
5. Exit

iy
Enter your choice: 2
Enter two numbers: 40 20 or
Subtraction: 20
.p
[Link] Looping Statements
w

➢ 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.
w

1. for statement
w

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;
}
C Programming and Data Structures 1.59
[Link] [Link]

in
n.
aa
iy
or
.p
w

Fig. 1.13 Flowchart of the For loop statement


w

➢ 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
w

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++)
{
1.60 C Programming Fundamentals
[Link] [Link]
printf(“%d\n”,i);
}
getch( );
}
Output

in
Enter the limit: 10

n.
1

aa
2
3

iy
4
5 or
6
.p
7
8
w

9
w

10
w

❖ 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
C Programming and Data Structures 1.61
[Link] [Link]
➢ If the condition initially fails the loop is skipped entirely even in the first iteration
itself. It is otherwise called as entry controlled loop.

in
n.
aa
iy
or
.p
w

Fig. 1.14 Flowchart of the While loop


w
w

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)
{
1.62 C Programming Fundamentals
[Link] [Link]
printf(“%d\t”,i);
i++;
}
getch( );
}

in
Output

n.
Enter the limit: 10

aa
2 4 6 8 10
❖ Do While Statement

iy
➢ 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
or
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
.p
itself. It is otherwise called as exit control loop.
w
w
w

Fig. 1.15 Flowchart of the Do while loop


➢ The syntax for the do while loop is
do
{
C Programming and Data Structures 1.63
[Link] [Link]
}
while(condition);
Program 1.21
/* Program to check the given number is palindrome or not */
#include<stdio.h>

in
#include<conio.h>

n.
void main()

aa
{
int n,t,s,r;

iy
clrscr();
printf(“\n Enter the number”);
or
scanf(“%d”,&n);
.p
t=n;
s=0;
w

do
w

{
w

r=n%10;
s=(s*10)+r;
n=n/10;
} while(n>0);
if(t==s)
printf(“%d is a palindrome”,t);
else
printf (“%d is not a palindrome”, t);
getch( );
}
Output
Enter the number 242
1.64 C Programming Fundamentals
[Link] [Link]
1.9 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

in
divide complex task into manageable tasks. The function can also help to avoid
duplication of work.

n.
Advantages of Functions

aa
✓ Code reusability
✓ Better readability

iy
✓ Reduction in code redundancy
✓ Easy to debug & test.
How Does Function Work?
or
.p
➢ Once a function is called, it takes some data from the calling function and returns
w

back some value to the called function.


➢ Whenever function is called control passes to the called function and working of
w

the calling function is temporarily stopped, when the execution of the called
w

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
C Programming and Data Structures 1.65
[Link] [Link]
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.

in
➢ When a called function returns some result back to the calling function, it is said

n.
to return that result.
➢ The calling function may or may not pass parameters to the called function. If

aa
the called function accepts arguments, the calling function will pass parameters,
else not.

iy
➢ Function declaration is a declaration statement that identifies a function’s name,
or
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,
.p
followed by the body of the function containing the executable code for that
function.
w

1.9.1 Function prototype


w

[Link] User Defined Function


w

➢ 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.
1.66 C Programming Fundamentals
[Link] [Link]
➢ 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.

in
➢ Functions facilitate top-down programming approach.

n.
[Link] Elements of user Defined Functions
➢ In order to write an efficient user defined function, the programmer must be

aa
familiar with the following three elements.
− Function declaration

iy
− Function definition
− Function call
or
.p
Function Declaration
➢ A function declaration is defined as a prototype of a function which consists of
w

the functions return type, function name and arguments list


w

➢ It is always terminated with semicolon (;)


➢ Function prototypes can be classified into four types
w

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);
C Programming and Data Structures 1.67
[Link] [Link]
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

in
the called function. (i.e) the called program does not receive any data from the

n.
calling program and does not send back any value to the calling program.
Syntax:

aa
void function_name(void);
void main()

iy
{
……. or
function_name();
.p
…..
w

}
w

void function_name(void)
w

{
…..
……
}
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()
{
1.68 C Programming Fundamentals
[Link] [Link]
}
void add()
{
int a,b,c;
printf(“Enter the two numbers . . . “);

in
scanf(“ %d %d”,&a,&b);

n.
c=a+b;
printf(“sum is . . . %d”,c);

aa
}

iy
Output:
Enter the two numbers . . . 10 20
or
Sum is . . . 30
.p
b) Function with Arguments and No Return Values
➢ In this prototype, data is transferred from calling function to called function. i.e
w

the called program receives some data from the calling program and does not
w

send back any values to calling program.


w

Syntax:
void function_name(arguments_list);
void main()
{
…….
function_name(argument_list);
…..
}
void function_name(arguments_list)
{
//function body
}
C Programming and Data Structures 1.69
[Link] [Link]
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

in
list

n.
void main()
{

aa
int a,b,;
clrscr();

iy
printf(“enter the two values: “);
or
scanf(“ %d %d”,&a,&b);
.p
add(a,b); /*calling a function with arguments */
getch();
w

}
w

void add(int x,int y)


w

{
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.
1.70 C Programming Fundamentals
[Link] [Link]
Syntax:
return_type function_name(arguments_list);
void main()
{
…….

in
variable_name=function_name(argument_list);

n.
…..

aa
}
return_type function_name(arguments_list)

iy
{
//function body or
}
.p
Program 1.24
w

#include<stdio.h>
#include<conio.h>
w

int add(int,int); //function declaration with return type and with arguments list
w

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)
{
C Programming and Data Structures 1.71
[Link] [Link]
int z;
z=x+y;
return(z); /*returning result to calling function*/
}
Output:

in
Enter the two numbers: 10 20

n.
sum is. . 30

aa
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.

iy
Syntax:
or
return_type function_name(void);
.p
void main()
{
w

…….
w

variable_name=function_name();
w

…..
}
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()
1.72 C Programming Fundamentals
[Link] [Link]
int c;
c=add(); //function call
printf(“sum is . . . %d”,c);
}
int add(void)

in
{

n.
int a,b,c;
printf(“Enter the two numbers . . . “);

aa
scanf(“ %d %d”,&a,&b);

iy
c=a+b;
return(c); or
}
.p
Function Definition
➢ It is the process of specifying and establishing the user defined function by
w

specifying all of its elements and characteristics.


w

➢ When a function is defined, space is allocated for that function in the memory.
w

➢ 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;
C Programming and Data Structures 1.73
[Link] [Link]
return(z);
}
Program 1.26
#include<stdio.h>
// function prototype, also called function declaration

in
float square ( float x );

n.
// main function, program starts from here

aa
int main( )
{

iy
float m, n ;
or
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
.p
// function call
w

n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
w

}
w

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
1.74 C Programming Fundamentals
[Link] [Link]
➢ 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

in
function_name();
function_name(parameter);

n.
variable_name=function_name(parameter);

aa
variable_name=function_name();
Example

iy
add();
add(a,b);
c=add(a,b);
or
.p
c=add;
w

➢ There are two ways that a C function can be called from a program. They are,
w

a) Call by value
b) Call by reference
w

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
C Programming and Data Structures 1.75
[Link] [Link]
int sum(int a, int b)
{
int c=a+b;
return c;
}

in
int main(

n.
{

aa
int var1 =10;
int var2 = 20;

iy
int var3 = sum(var1, var2);
printf("%d", var3); or
return 0;
.p
}
In the above example variable a and b are the formal parameters (or formal
w

arguments). Variable var1 and var2 are the actual arguments (or actual parameters). The
w

actual parameters can also be the values. Like sum(10, 20), here 10 and 20 are actual
parameters.
w

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;
1.76 C Programming Fundamentals
[Link] [Link]
printf("num1 value is: %d", num1);
printf("\nnum2 value is: %d", num2);
return 0;
}
Output

in
num1 value is: 20

n.
num2 value is: 21

aa
Program 1.29
//Example 2: Swapping numbers using Function Call by Value

iy
#include <stdio.h>
or
void swapnum( int var1, int var2 )
{
.p
int tempnum ;
w

/*Copying var1 value into temporary variable */


tempnum = var1;
w

/* Copying var2 value into var1*/


w

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);
}
C Programming and Data Structures 1.77
[Link] [Link]
Output
Before swapping: 35, 45
After swapping: 45, 35
Program 1.30
Example 2: Function Call by Reference – Swapping numbers

in
#include

n.
void swapnum ( int *var1, int *var2 )

aa
{
int tempnum ;

iy
tempnum = *var1;
*var1 = *var2; or
*var2 = tempnum;
.p
}
int main( )
w

{
w

int num1 = 35, num2 = 45;


w

printf("Before swapping:");
printf("\nnum1 value is %d", num1);
printf("\nnum2 value is %d", num2);
/*calling swap function*/
swapnum( &num1, &num2 );
printf("\nAfter swapping:");
printf("\nnum1 value is %d", num1);
printf("\nnum2 value is %d", num2);
return 0;
}
Output
Before swapping:
1.78 C Programming Fundamentals
[Link] [Link]
num2 value is 45
After swapping:
num1 value is 45
num2 value is 35

in
1.10 RECURSIVE FUNCTIONS
➢ Recursion is the process of calling the same function again and again until some

n.
condition is satisfied.

aa
➢ This process is used for repetitive computation.
Syntax:

iy
function_name()
{
function_name();
or
.p
}
w

Types of Recursion
a) Direct Recursion
w

b) Indirect Recursion
w

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.
C Programming and Data Structures 1.79
[Link] [Link]
{
if (n == 0)
return n;
else
return (Func (n–1));

in
}

n.
b) Indirect Recursion
➢ Function calls another function, which in turn calls the original function.

aa
Functionname1 ( )

iy
{

Functionname2 ( );
or
.p

}
w

Functionname1 ( )
w

{

w

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
1.80 C Programming Fundamentals
[Link] [Link]
}
int Func2(int x)
{
return Func1(x–1);
}

in
Program 1.31

n.
/*C program to find factorial of a given number using recursion*/

aa
#include< stdio.h>
#include<conio.h>

iy
void main()
{
int fact(int);
or
.p
int num,f;
w

clrscr();
printf(“enter the number”);
w

scanf(“%d”,&num);
w

f=fact(num);
printf(“ the factorial of %d= %d”, num, f);
}
int fact(int x)
{
int f;
if(x==1)
return(1);
else
f=x*fact(x-1); //recursive function call
return (f);
}
C Programming and Data Structures 1.81
[Link] [Link]
Output:
Enter the number 5
The factorial of 5=120

1.11 ARRAYS

in
Introduction to Arrays
➢ An Array is a collection of similar data elements

n.
➢ These data elements have the same data type

aa
➢ The elements of the array are stored in consecutive memory locations and are
referenced by an index

iy
Definition
or
➢ 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.
.p
Example
w
w
w

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
1.82 C Programming Fundamentals
[Link] [Link]
➢ 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

in
➢ 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

n.
Classifications

aa
➢ In general arrays are classified as:
➢ One-Dimensional Array

iy
➢ Two-Dimensional Array
➢ Multi-Dimensional Array or
.p
1.11.1 Declaration of an Array
Array has to be declared before using it in C program. Declaring array means
w

specifying three things.


w

Data_type Data Type of Each Element of the array


w

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
C Programming and Data Structures 1.83
[Link] [Link]
1.11.2 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};

in
The values are written with curly brackets and every value is separated by a comma.

n.
It is a compiler error to specify more number of values than the number of elements in
the array.

aa
Example: int marks [5] = {90, 92, 78, 82, 58};

iy
1.12 ONE DIMENSIONAL ARRAY
➢ It is also known as single-dimensional arrays or linear array or vectors
or
➢ It consists of fixed number of elements of same type
.p
➢ Elements can be accessed by using a single subscript
w

Example
w
w

1.12.1 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
1.84 C Programming Fundamentals
[Link] [Link]
1.12.2 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

in
initialization list is a comma separated list of initializers enclosed within braces.
Example

n.
1. int a[3]={1,3,4};

aa
2. int i[5] ={1, 2, 3, 4, 5};
3. float a[5]={1.1, 2.3, 5.5, 6.7, 7.0};

iy
4. int b[ ]={1,1,2,2};
➢ In the fourth example the size has been omitted (it can be) and have been declared
or
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:
.p
char array_name[size]=”string”
w

For example,
w

char mess[ ]={‘w’,‘e’,‘l’,‘c’,‘o’,‘m’,‘e’};


w

➢ 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’


C Programming and Data Structures 1.85
[Link] [Link]
Example Programs
Program 1.32
/*Program to find the maximum number in an array * /
#include<stdio.h>
void main( )

in
{

n.
int a[5], i, max;
printf(“Enter 5 numbers one by one \n”);

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

iy
{
scanf(“%d”, & a[i]);
or
}
.p
max=a[0];
for(i=1;i<5;i++)
w

{
w

if (max<a[i])
w

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>
1.86 C Programming Fundamentals
[Link] [Link]
{
int a[10], i;
int n;
printf(“Enter the maximum number of elements\n”);
scanf(“%d”, &n);

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

n.
{
scanf(“%d”,&a[i]);

aa
}

iy
printf(“Array in the reverse order\n”);
for(i=n–1; i>=0; i--)or
{
.p
printf(“%d\t”, a[i]);
}
w

getch( );
w

}
w

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:”);
C Programming and Data Structures 1.87
[Link] [Link]
scanf(“%d”, &n)
printf (“\n Enter the %d numbers one by one:”);
for (i=0; i<n; i++)
{

in
scanf(“%d”, &a[i]);
sum = sum + a[i];

n.
}

aa
printf (“The sum of array content = %d”, sum);
getch( );

iy
}
Output
or
.p
Enter the size of the array: 5
Enter the 5 number one by one:
w

10 20 30 40 50
w

The sum oif the array content = 150


w

1.13 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.
1.88 C Programming Fundamentals
[Link] [Link]
Example
1 2 3 6 7
9 10 5 0 4
a[3][5] 3 1 2 1 6

in
Declaration

n.
datatype arrayname [row size][column size]

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

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

a 1 4 6
w

2 0 0
w

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);
C Programming and Data Structures 1.89
[Link] [Link]
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;

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

n.
for(j=0;j<n1;j++)

aa
sum+=a[i][j];
printf(“Sum of all elements%d\n”,sum);

iy
/ * Program to module to sum row wise */
for(i=0;i<n;i++) or
{
.p
rowsum=0;
for(j=0;j<n1;j++)
w

{
w

rowsum+=a[i][j];
w

printf(“row no = %d sum = %d\n”,i,rowsum);

}
}
/* 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);
}
1.90 C Programming Fundamentals
[Link] [Link]
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);

in
/ * Program module to sum off diagonal */

n.
diasum=0;

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

iy
j= -n1;
diasum +=a[i][j];
or
}
.p
printf(“Off diagonal sum%d\n”,diasum);
}
w

Output
w

Enter order [row][col] of the matrix


w

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
C Programming and Data Structures 1.91
[Link] [Link]
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] = {

in
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},

n.
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};

aa
Program 1.36
Write a C Program to store and print 12 values entered by the user

iy
#include <stdio.h>
int main()
{
or
.p
int test[2][3][2];
w

printf("Enter 12 values: \n");


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

{
w

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)
{
1.92 C Programming Fundamentals
[Link] [Link]
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]);

in
}

n.
}

aa
}
return 0;

iy
}
Output or
Enter 12 values:
.p
1
2
w

3
w

4
w

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
C Programming and Data Structures 1.93
[Link] [Link]
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

in
test[1][1][1] = 10

n.
test[1][2][0] = 11

aa
test[1][2][1] = 12

iy
or
.p
w
w
w
1.94 C Programming Fundamentals
[Link] [Link]
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.

in
• Character – It refers to all ASCII character sets as well as the single alphabets,

n.
such as ‘x’, ‘Y’, etc.
• Double – These include all large types of numeric values that do not come under

aa
either floating-point data type or integer data type.
• Floating-point – These refer to all the real number values or decimal points,

iy
such as 40.1, 820.673, 5.9, etc.

or
Void – This term refers to no values at all. We mostly use this data type when
defining the functions in a program.
.p
2. What is Variable?
w

✓ Variables are containers for storing data values.


w

✓ Its value can be changed, and it can be reused many times.


✓ Syntax for creating variables
w

• 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
C Programming and Data Structures 1.95
[Link] [Link]
✓ 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

in
✓ If the exp1 is true variable takes value of exp2. If the exp2 is false, variable

n.
takes the value of exp3.
6. What is an Operator and Operand?

aa
✓ An operator is a symbol that specifies an operation to be performed on
operands.

iy
✓ Example: *, +, -, / are called arithmetic operators.
or
✓ The data items that operators act upon are called operands.
7. What is type casting?
.p
✓ Type casting is the process of converting the value of an expression to a
w

particular data type.


w

✓ Example: int x,y.


c = (float) x/y; where a and y are defined as integers. Then the result of x/y is
w

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 statement
executed. is executed and then the condition is
checked.
If the condition is true, then it executes The do…while loop will execute at least
the body of the loop. When the one time even though the condition is
condition is false it comes of the loop. 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
1.96 C Programming Fundamentals
[Link] [Link]
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

in
function.

n.
✓ The syntax for recursive function is:
function recurse() {

aa
// function code
recurse();

iy
// function code
}
or
.p
recurse();
12. Write short notes about main() function in ’C’ program.
w

Every C program must have main () function.


w

✓ All functions in C, has to end with ‘( )’ parenthesis.


w

✓ 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.
C Programming and Data Structures 1.97
[Link] [Link]
➢ 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.

in
✓ One-dimensional arrays

n.
✓ Multidimensional arrays
16. Write short notes on One-dimensional arrays.

aa
✓ 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

iy
etc.
or
✓ The syntax of declaring Two-dimensional arrays is:
➢ datatype array name [size]
.p
✓ Example
w

For example, int a[5]


w

17. Write short notes on Two-dimensional arrays.


✓ A multi-dimensional array can be termed as an array of arrays that stores
w

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.
1.98 C Programming Fundamentals
[Link] [Link]
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?

in
✓ Short
✓ Long

n.
✓ Signed

aa
✓ Unsigned
✓ long long

iy
21. What is the explanation for prototype function in C?
or
✓ Prototype function is a declaration of a function with the following information
to the compiler.
.p
• Name of the function.
w

• The return type of the function.


w

• Parameters list of the function.


✓ Example
w

• 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.
C Programming and Data Structures 1.99
[Link] [Link]
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 further

in
memory efficient. requires linking, hence requires more
memory.

n.
Programming languages like Programming languages like C, C++,
JavaScript, Python, Ruby use Java use compilers.

aa
interpreters.

iy
or PART-B
.p
1. Explain the different types of operators with neat examples.
2. Illustrate the different conditional statements available in C with syntax and
w

examples
w

3. Explain the looping statements with neat examples.


w

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