You are on page 1of 52

UNIT-I

Introduction to Programming

A program is a set of instructions that tell the computer to do various things; sometimes
the instruction it has to perform depends on what happened when it performed a previous
instruction. This section gives an overview of the two main ways in which you can give these
instructions or “commands” as they are usually called. One way uses an interpreter, the other
a compiler
Programming Language
A programming language is a mathematical calculus, or formal language. Its goal is to
express algorithms in a manner that is unambiguous to people and machines. Like any calculus,
a language‟s notation contains both syntax and semantics. Since syntax can be easily translated,
the semantics are more fundamental.
Or
It is a computer language programmers use to develop applications, scripts, or other set
of instructions for a computer to execute.
Linker
Linking is the final stage of compilation. It takes one or more object files or libraries as
input and combines them to produce a single (usually executable) file. In doing so, it resolves
references to external symbols, assigns final addresses to procedures/functions and variables,
and revises code and data to reflect new addresses (a process called relocation).
Loader
Loader is a program that loads machine codes of a program into the system memory.
In computing, a loader is the part of an operating system that is responsible for loading
programs. It is one of the essential stages in the process of starting a program, as it places
programs into memory and prepares them for execution. Loading a program involves reading
the contents of the executable file containing the program instructions into memory, and then
carrying out other required preparatory tasks to prepare the executable for running. Once
loading is complete, the operating system starts the program by passing control to the loaded
program code.

1
Execution of C Program:
C program executes in following 4 (four steps).

1. Creating a program :
An editor like notepad or WordPad is used to create a C program. This file contains a
source code which consists of executable code. The file should be saved as '*.c' extension
only.
2. Compiling the program :
The next step is to compile the program. The code is compiled by using compiler.
Compiler converts executable code to binary code i.e. object code.
3. Linking a program to library :
The object code of a program is linked with libraries that are needed for execution of a
program. The linker is used to link the program with libraries. It creates a file
with '*.exe' extension.
4. Execution of program :
The final executable file is then run by dos command prompt or by any other software.
Algorithm
An algorithm is procedure consisting of a finite set of unambiguous rules (instructions)
which specify a finite sequence of operations that provides the solution to a problem, or to a
specific class of problems for any allowable set of input quantities (if there are inputs).
Or
An algorithm is a step-by-step procedure to solve a given problem.
Flowchart
A Flowchart is a type of diagram that represents an algorithm, workflow or process,
showing the steps as boxes of various kinds, and their order by connecting them with arrows.
This diagrammatic representation illustrates a solution model to a given problem. Flowcharts
are used in analyzing, designing, documenting or managing a process or program in various
fields.
Or

2
A graphical representation of an algorithm, often used in the design phase of
programming to work out the logical flow of a program.
Symbol Name Function

Process Indicates any type of internal operation inside the


Processor or Memory

Input/output Used for any Input / Output (I/O) operation.


Indicates that the computer is to obtain data or
output results

Decision Used to ask a question that can be answered in a


binary format (Yes/No, True/False)

Connector Allows the flowchart to be drawn without


intersecting lines or without a reverse flow.

Predefined Process Used to invoke a subroutine or an interrupt


program.

Terminal Indicates the starting or ending of the program,


process, or interrupt program.

Flow Lines Shows direction of flow.

3
OVERVIEW OF ‘C’

C is a programming language developed by AT & T‟s Bell Laboratories of USA in


1972. It was designed and written by Dennis Ritchie. C is reliable, simple and easy to use. C has
survived for more than 3 decades. C language is a base to learn different programming
language.
In the late seventies „C‟ began to replace the more familiar languages of that time like
PL/I, ALGOL etc. without any advertisement „C‟ reputation spread and its pool of user grew.
Historical development of ‘C’
 By 1960 a hoarde of computer languages had come into existence, almost each for a
specific purpose. For example: COBOL was being used for commercial applications,
FORTON for engineering and scientific application and so on.
 At this stage people started thinking that instead of learning and using so many
languages each for a different purpose, why not use only one language which can
program all possible applications.
 Therefore, an international committee was setup to develop such a languages.
 This committee came out with a language called ALGOL60. ALGOL 60 never really
became popular because it seemed to abstract, too general.
 To reduce this abstractness and generality, a new language called combined
programming language (CPL) was developed at Cambridge University. CPL was an
attempt to bring ALGOL60 down to earth. However CPL turned out to be so big having
so many features, that it was hard to learn and difficult to implement.
 Basic combined programming language (BCPL), developed by martin Richards at
Cambridge University, and aimed to solve this problem by bringing CPL down to its
basic good feature. But unfortunately it turned out to be too less powerful and too
specific.
 Around some time a language called „B‟ was written by Ken Thompson at AT&T‟s Bell
Labs, as a further simplification of CPL. But like BCPL, B too turned out to be very
specific.
 Ritchie inherited the features of B and BCPL, added some of his own and developed
„C‟. Ritchie‟s main achievement is the restoration of the lost generality in BCPL and B
and still keeping it powerful.
4
Year Language Developed By Remarks
1960 ALGOL International Committee Too General, Too abstract
1963 CPL Cambridge University Hard to learn, difficult to
implement
1967 BCPL Martin Richards at Could deal with only specific
Cambridge University Problem
1970 B Ken Thopson at AT&T Could deal with only specific
Bell
1972 C Dennis Ritchie at AT & T Lost generality of BCPL & B
restored

Characteristics/Features
1. General Purpose Programming Language: it is general purpose programming
language. It is usually called “system programming language” but equally suited to
writing a variety of applications.
2. Middle Level: As a middle level language it bridges elements of high level language
with the functionality of assembly language.
3. Structured Programming: C is very suited for structured programming. The
programmers can easily divide a problem into a number of modules or functions.
4. Simplicity: C is simple to use because of its structured approach. It has a wide
collection of inbuilt functions, keywords, operators and data types.
5. Portability: This refers to the ability of a program to run in different environments.
With the availability of compilers for almost all operating systems and hardware
platforms, it is easy to write code on one system which can be easily ported to another.
6. Wide Acceptability: C is widely popular in the software industry. Its importance is not
entirely derived from its use as primary development language but also because of its
use as an interface language to some of the visual languages.
7. Flexibility: C Language combines the convenience and portable nature of a high level
language with the flexibility of a low level language. It can be interfaced readily to other
programming languages.

5
8. Efficient Compilation and Execution: The process of compilation and execution of
programs is quite fast in C Language as compared to other languages like BASIC
(Beginner‟s All purpose Symbolic Instruction Code) and FORTRAN
(FORmula TRANslator).
9. Modularity: C Language programs can be divided into small modules with the help of
functions which help in increasing understanding of the programs.
10. Clarity: The features like keywords, in-built functions and structures help to improve
the clarity and hence understanding of the program.
11. High Availability: The software of C Language is readily available in market and can
be easily installed on the computer.
12. Easy Debugging: The syntax errors can be easily detected by the C compiler. The error
is displayed with line number of the code and the error message.
13. Memory Management: Various memory management in-built functions are available
in C language which helps to save memory and hence improve efficiency of the
program. E.g. malloc(),alloc() and calloc().
14. Recursion: Recursion is a technique in which the function calls itself again and again
until a condition is achieved.
15. Rich set of Library Functions: C has a rich set of library functions. These are the
functions that provide readymade functionality to the users. It also supports graphic
programming.
Why to use C:
C was initially used for system development work, in particular the programs that make-up
the operating system. C was adopted as a system development language because it produces
code that runs nearly as fast as code written in assembly language. Some examples of the use of
C might be:
 Operating Systems
 Language Compilers
 Assemblers
 Text Editors
 Print Spoolers
 Network Drivers
 Modern Programs
6
 Data Bases
 Language Interpreters
 Utilities
Where ‘C’ Stands
All the programming languages can be divided into two categories.
1) Problem oriented languages (or) High level language :
These languages have been designed to give a better programming efficiency i.e. faster
program development examples of languages falling in this category are FORTRAN,
BASIC, PASCAL etc.
2) Machine oriented languages (or) Low level Languages:
These languages have been designed to give a better machine efficiency i.e. faster program
execution
Ex: Assembly languages and Machine language
„C‟ stands in between these two categories. That‟s why it is often called a Middle level
language. Sine it was designed to have both relatively good programming efficiency and
relatively good machine efficiency.
CHARACTER SET OF ' C ' Language
Alphabets : A, B, ----------- Z
a, b, ----------- z
Digits : 0, 1, 2, --------- 9
Special Symbols : ~ @ # $ % ^ & * ( ) _ - + = | \ { } [ ] : ; " ' < > , . ? /
Programming Languages: There are three types of programming languages.
1. High Level Languages (HLL).
2. Machine Languages.
3. Assembly Languages.
High Level Languages: These are referred as problem oriented languages (POL). These are
referred as third generation languages. The advantages of these languages are
 The high level languages are convenient for writing programs as they can be written
without any codes. These languages follow rules like ―English‖ language.
 Because of their English like nature, less time is required to write a program.
 They are machine independent. A program written in any HLL can be run on computers
of different types without any modifications.
7
Advantages of High Level Language
Following are the advantages of a high level language:
 User-friendly
 Similar to English with vocabulary of words and symbols
 Therefore it is easier to learn.
 They require less time to write.
 They are easier to maintain.
 Problem oriented rather than 'machine' based.
 Program written in a high-level language can be translated into many machine language
and therefore can run on any computer for which there exists an appropriate translator.
 It is independent of the machine on which it is used i.e. Programs developed in high
level language can be run on any Computer
Disadvantages of High Level Language
1. A high-level language has to be translated into the machine language by a translator and
thus a price in computer time is paid.
2. The object code generated by a translator might be inefficient Compared to an
equivalent assembly language program
Machine Languages: Computers respond only to machine language. This language is in terms of
binary codes (0,1). i.e. all programs should be written with these codes, which is difficult, time
consuming and leading to errors while writing the programs. There is no unique standard
machine language. Rather there are many machine languages. These are machine dependent.
Assembly Languages: It uses mnemonic codes rather than numeric codes (as in machine
languages). Ex. Add or A is used as a symbol for addition. It requires translators to convert into
machine language. Like machine language, writing program in assembly language is also time
consuming. These are also machine dependent.
Translators: Computers can understand instructions only when they are written in their own
language – the machine language. Therefore, a program written in any other language should be
translated into machine language. The software that translates the instructions of different
languages is known as translators.
There are two types of translators. They are
1. Compilers
2. Interpreters
8
Compilers
A Compiler checks the entire user – written program (known as the source program) and
if it is error free, produces a complete program in machine language (known as object program).
The source program is retained for possible modifications and corrections and the object
program is loaded into the computer for execution. If the source program contains errors, the
compilers produce a list of errors at the end of the execution of the program. i.e a compiler
translates the whole program before execution.
Interpreters
An interpreter does a similar job but in a different style. The interpreter translates one
statement at a time and if it is error – free, executes. This continues till the last statement. Thus
an interpreter translates or executes the first instruction before it goes to the second, while a
compiler translates the whole program before execution.
The major difference between compiler and interpreter is
1. Error correction is very much simpler in the case of interpreter as it translates the statements
in stages. The compiler produces an error list of the entire program at the end.
2. Interpreter takes more time for the execution of the program compared to compilers as it
translates one statement at a time
Structure of a „C‟ Program

A C program basically has the following form:


 Preprocessor Commands

9
 Global declaration
 Functions
 Variables
 Statements & Expressions
 Comments
Preprocessor Commands: These commands tell the compiler to do preprocessing before doing
actual compilation. Like #include <stdio.h> is a preprocessor command which tells a C
compiler to include stdio.h file before going to actual compilation.
Global declaration: This section declares some that are used in more than on function variable
are known as global variables. This section must be declared outside of all the functions.
Functions: Functions are main building blocks of any C Program. Every C Program will have
one or more functions and there is one mandatory function which is called main() function. This
function is prefixed with keyword int which means this function returns an integer value when it
exits. This integer value is returned using return statement.
The C Programming language provides a set of built-in functions. In the above
example printf () is a C built-in function which is used to print anything on the screen.
Check Built-in function section for more detail.
Variables: are used to hold numbers, strings and complex data for manipulation. You
will learn in detail about variables in C Variable Types.
Statements & Expressions: Expressions combine variables and constants to create new
values. Statements are expressions, assignments, function calls, or control flow statements
which make up C programs.
Comments: are used to give additional useful information inside a C Program. All the
comments will be put inside /*...*/ as given in the example above. A comment can span through
multiple lines.
Note the followings
C is a case sensitive programming language. It means in C printf and Printf will have
different meanings.
 C has a free-form line structure. End of each C statement must be marked with a
semicolon.
 Multiple statements can be one the same line.
 White Spaces (i.e. tab space and space bar) are ignored.
10
 Statements can continue over multiple lines.

C tokens
C tokens, Identifiers and Keywords are the basics in a C program. All are explained in
this page with definition and simple example programs.
C tokens:
o C tokens are the basic buildings blocks in C language which are constructed
together to write a C program.
o Each and every smallest individual unit in a C program is known as C tokens.
C tokens are of six types. They are,

C tokens example program:


int main()
{
int x, y, total;
x = 10, y = 20;
total = x + y;
Printf (“Total = %d \n”, total);
}
where,
 main – identifier
 {,}, (,) – delimiter
 int – keyword

11
 x, y, total – identifier
 main, {, }, (, ), int, x, y, total – tokens
Keywords in C language:
C programs are constructed from a set of reserved words which provide control and
from libraries which perform special functions. The basic instructions are built up using a
reserved set of words, such as main, for, if, while, default, double, extern, for, and int, etc., C
demands that they are used only for giving commands or making statements. You cannot
use default, for example, as the name of a variable. An attempt to do so will result in a
compilation error.
Keywords have standard, predefined meanings in C. These keywords can be used only
for their intended purpose; they cannot be used as programmer-defined identifiers. Keywords
are an essential part of a language definition. They implement specific features of the language.
Every C word is classified as either a keyword or an identifier. A keyword is a sequence of
characters that the C compiler readily accepts and recognizes while being used in a program.
Note that the keywords are all lowercase. Since uppercase and lowercase characters are not
equivalent, it is possible to utilize an uppercase keyword as an identifier.
The keywords are also called „Reserved words‟.
 Keywords are the words whose meaning has already been explained to the C compiler
and their meanings cannot be changed.
 Keywords serve as basic building blocks for program statements.
 Keywords can be used only for their intended purpose.
 Keywords cannot be used as user-defined variables.
 All keywords must be written in lowercase.
 32 keywords available in C.

Auto Else Long Switch

Break Enum Register Typedef

Case Extern Return Union

Char Float Short Unsigned

12
Const For Signed Void

Continue Goto Sizeof Double

Default If Static While

Do Int Struct Packed

Identifiers in C language:
o Each program elements in a C program are given a name called identifiers.
o Names given to identify Variables, functions and arrays are examples for
identifiers. E.g. x is a name given to integer variable in above program.
Rules for constructing identifier name in C:
1. First character should be an alphabet or underscore.
Succeeding characters might be digits or letter.
2. Punctuation and special characters aren‟t allowed except underscore.
3. Identifiers should not be keywords.
Characteristic of identifier:
1. The first character must be an alphabet or an underscore.
2. It must consist of only letters, digits or underscore.
3. Only first 31 characters are significant, i.e. if the user enters an identifier of more than
31 characters, the compiler considers only first 31 characters & deletes the others.
4. A keyword cannot be used as an identifier name.
5. It cannot contain any spaces
3. Constants:
Constants are the fixed values that do not change during the execution of program.

13
Integer constants: An integer constant refers to a sequence of digits. There are three types of
integer constants, namely, decimal integer, octal integer and hexadecimal integer.
Decimal integer consists of a set of digits from 0 to 9, preceded by an optional + or – sign.
Examples, 123 -321 0 64932
Octal integer consists of a set of digits from 0 to 7, with a leading 0. Examples, 037 0
0437 0551
A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer. They
may also includes letters from A to F or from a to f. The letters represents the numbers from 10
to 15.Examples, 0X2 0x9F 0Xbcd 0x
Real constants: Real constants are used to represent quantities that are very continuously, such
as distances, temperature etc. These quantities are represented by numbers containing fractional
parts. Examples, 0.00832 -0.75 33.337
Single character constants: A single character constants contains a single character enclosed
within a pair of single quote marks. Example, „5‟ „X‟ „;‟
String constants: A string constant contains a string of characters enclosed within a pair of
double quote marks. Examples, “Hello!” “1987” “?....!”
Backslash character constants: C supports some special backslash character constants that are
used in output functions. For example
Constants Meaning
„\a‟ audible alert (bell)
„\n‟ new line

14
„\?‟ question mark
Variable: A variable is just a named area of storage that can hold a single value (numeric or
character). The C language demands that you declare the name of each variable that you are
going to use and its type, or class, before you actually try to do anything with it.
E.g. int a, b, c;
where a, b, c are the variables.
The Programming language C has two main variable types
 Local Variable
 Global Variable
Local Variable
Local variables scope is confined within the block or function where it is defined. Local
variables must always be defined at the top of a block.
When a local variable is defined - it is not initialized by the system, you must initialize it
yourself.
When execution of the block starts the variable is available, and when the block ends the
variable 'dies'.
Global Variable
 Global variable is defined at the top of the program file and it can be visible and
modified by any function that may reference it.
 Global variables are initialized automatically by the system when you define them.
Data Type:
A data type is a classification of the type of data that a variable or object can hold in
computer programming. The amount of storage allocated to variables, the values that they can
accept, and the operation that can be performed on those variables.

15
Primitive Data Type (Primary):

Integer Data Types:

Integers are whole numbers with a range of values, range of values are machine
dependent. Generally an integer occupies 2 bytes memory space and its value range limited to -
32768 to +32767 (that is, -215 to +215-1). A signed integer use one bit for storing sign and rest 15
bits for number.
To control the range of numbers and storage space, C has three classes of integer storage
namely short int, int and long int. All three data types have signed and unsigned
forms. A short int requires half the amount of storage than normal integer. Unlike signed
integer, unsigned integers are always positive and use all the bits for the magnitude of the
number. Therefore, the range of an unsigned integer will be from 0 to 65535. The long
integers are used to declare a longer range of values and it occupies 4 bytes of storage space.
Syntax:
int <variable name>;
int num1;
short int num2;
long int num3;
Example: 5, 6, 100, 2500.
Integer Data Type Memory:
16
Floating Point Data Types:
The float data type is used to store fractional numbers (real numbers) with 6 digits of
precision. Floating point numbers are denoted by the keyword float. When the accuracy of the
floating point number is insufficient, we can use the double to define the number. The double is
same as float but with longer precision and takes double space (8 bytes) than float. To extend
the precision further we can use long double which occupies 10 bytes of memory space.
Syntax:
float <variable name>;
float num1;
double num2;
long double num3;
Example: 9.125, 3.1254.
Floating Point Data Type Memory Allocation:

Character Data Type:


Character type variable can hold a single character and are declared by using the keyword char.
As there are singed and unsigned int (either short or long), in the same way there are signed and
unsigned chars; both occupy 1 byte each, but having different ranges. Unsigned characters have
values between 0 and 255, signed characters have values from –128 to 127.
Syntax:
char <variable name>;
char ch = „a‟;
Example: a, b, g, S, j.
Derived data type:
Arrays, functions, structures and pointers, are derived data types.

17
Array: an array is nothing but a collection of similar data types stored in a consecutive memory
location.
Function: it is a self contained block or code, which performs a particular task.
Structure: it is a collection of dissimilar data types stored in consecutive memory location.
Pointers: pointer is a variable that stores the address of memory location.

User Defined Data Type: There are 2 types of user defined data types.
 Enumerated data type
 Type def data type

Enumerated Data Type: enumerated data type can be defined as enum identifier
{v1,v2,v3,…….vn}; here “enum” is the reserve word and “identifier” is a user defined
enumerated data type. This can be used to declare variable that have values enclosed with in the
braces. These values are called “enumeration constants”.
Eg: Enum month {Jan, Feb, ….. Dec};

Enum year {2000, 2001, ………. 2003};


Enum day {Monday, Tuesday, …….. Sunday}
Type def data type: “C” supports a feature known as type definition. That allows users to
define a user defined data type .its syntax is type def data type identifier,
here data type refers to an existing data type identifiers refers to the new name given to
the data type.
Eg: typedef int pay; typedef float salary;
Instead of int are can use pay to declare variables; instead of float we can use
salary to declare the variables.
pay p1, p2;
salary s1, s2, s3;
Keyword Format Specifier Size Date Range
Char %c 1 byte -128 to +127
Int %d 2 bytes 0 to 255
Float %f 4 bytes -3.4e38 to +3.4e38
Double %lf 8 bytes -1.7e38 to +1.7e38
long int %ld 4 bytes -231 to +231
unsigned int %u 2 bytes 0 to 65535
long double %Lf 16 bytes -3.4e38 to +3.4e38

18
Unsigned char %c 1 byte 0 to 255

Operators in C:
Definition: An operator is a symbol that tells the computer to perform certain mathematical or
logical operations.
Operators are used to operate 2 or more than two operands depending upon their
processing and given conditions.
The relationship of the operator with the operands as operand as operand 1
operator, operand 2 operator, operand 3…..
Here operand 1, operand 2 and operand 3 many be a variable constant or an expression etc.
There are mainly “8” operators used in C-language.
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment or decrement operators
6. Conditional operators
7. Bit wise operators
8. Special operators
Arithmetic operators: “C” provides all the basic arithmetic operators such as +,-,*,/. These are used for
addition, subtraction, multiplication and division respectively.
Arithmetic operators meaning
+ - addition
* - multiplication
- - subtraction
/ - division
% - modular division
Expressions: an expression is a combination of operand and operators or expression is a
formula. There are mainly “3”- types of arithmetic expression.
 Integer arithmetic expression
 Float / real arithmetic expression
 Mixed mode arithmetic expression

19
Integer arithmetic expression: when both “a” and “b” operands are of integer type, then such
type of expression by using arithmetic operators is called an integer arithmetic expression the
result is always an integer value.
Eg: a=5 Result: a+b=7 a*b=10
b=2 a-b=3 a/b=2 a%b=1
Float / real arithmetic expression: when both “a” and “b” operands are of real type, then such
type of expression using arithmetic is called real arithmetic expression.
Eg: a = 2.5 Result: a+b = 3.75 a*b = 3.125
b=1.25 a-b = 1.25 a/b = 2
The result is always an real value [float value] .
Mixed mode arithmetic expression: when one operand is of integer type and of expression is
called as mixed mode arithmetic expression.
Eg: a = 15.0 Result: a+b = 25.0 a-b = 5.0
b= 10 a*b = 150.0 a/b = 1.5
The result is real type. Modulus cannot be used in mixed mode expression.
Relational operators: relational operators are used for comparison purpose these operators are
used to create logical relationship between two operands.
The expression having two operands and one relational operator is called relational
expression there are 6 relational operators, they are Relational operators
meaning
< - less than
<= - less than or equal to
> - greater than
>= - greater than or equal to
== - equal to
!= - not equal to
These operators give the results in 2-branches one is of true and other is of false. The
value of relational expression is “one” if the specified relation is true and the value of relation
expression is “Zero” is the specified relation is false.
Eg: 10<20 true, 10>20 false, 10==10 true
Logical operators: there are three types of logical operators.
Meaning logical operator
20
&& - logical AND
!! - logical OR
! - logical NOT
The logical operators are used to test more than one condition and make decision. An
expression which combines two or more relational expression is termed as logical expression or
a compound relational expression this logical express contains values of Zero or one according
to the truth table.
Logical AND Logical OR Logical NOT
A B A&&B A B A&&B A B
T T T T T T 1 0
T F F T F T 0 1
F T F F T T
F F F F F F

Assignment operator: assignment operators are used assign the result of an expression to a
variable. Assignment operators are divided into “2” types.
1) Simple assignment operator
2) Short hand assignment operator
Simple assignment operator is = (equal to):
Syn: v = constant or variable or expression where “V” is a variable.
Eg: sum = 0; I = 1 or a=b or Si = (p*+*r)/100;
Short hand assignment operator: it has equal to (=) sign with all the arithmetic operators.
Syn: vop = constant or expression
Eg: I=i+1 => i+ = 1 a = a*a => a* = a
a = a*(n+1) => a*= n +1 a = a % b => a % = b
Increment or decrement operators: “C” has very useful increment and decrement operators
they are
++(increment operator)
--(decrement operator)
The operator ++ are used for incrementing the value one by one, -- are used for
decrementing value one by one. We use these operators in for and while loops. These are further
divided into “2”-types.
21
 Prefix increment / decrement operator (++v/--v)
 Postfix increment / decrement operator (v++/v--)
Conditional operator: „?‟and „:‟ is a conditional operator block or if-else block.
Syn: exp1?exp2:exp 3;
Here exp1 is evaluates, if it is true then the exp2 is evaluated and becomes the value of
the expression. If the exp1 is false,exp3 is evaluated and its value becomes the value of
expression.
Eg: a=10; b=15
Big=(a>b)? a:b;
Bitwise operator: these operators are used for manipulation of binary data (bits); these are six
types of bitwise operators.
Bitwise operator meaning
& - bitwise AND
! - bitwise OR
^ - bitwise exclusivor
<< - bitwise left
>> - bitwise right
~ - bitwise NOT
Special operators: these are used for special purpose in C-language. These operators are used
in pointers, structures and union etc some special operators are.
i. Unary operator
ii. Comma operator
iii. Sizeof operator
iv. Type operator
v. Pointer operator
vi. Member selection operator
 Unary operators are used for identification of a number whether it is signed or unsigned
and increment/decrement operator.
 Comma operators are used to link the related expression together.
Eg: a=12, b=10, c=a+b
These three statements can be written by comma operator as C=(a=12, b=10,
c=a+b);
22
 Size of operator is a compile time operator. It returns the no.of bytes occupied by the
operand. The operand may be a variable, a constant or a data type.
Eg: int a=100 x=size of (a);
 Pointer operators are “&” and “*” these operator are used in pointers.
 Member selection operators are used in structure and unions. These are “.” and→.
Operator precedence: There are distinct levels of precedence and an operator may belong to
one of the levels. The operators at high level of precedence are evaluated first. The operator of
the same precedence are evaluated either from left to right or from right to left depending on the
levels this is called associativity property.
Precedence order Operator Associativity
1 ( ),[ ],-> left to right
2 ++,--,&, sizeof right to left
3 *,/,% left to right
4 +,- left to right
5 << >> left to right
6 <,<=,>,>= left to right
7 ==,!= left to right
8 &(bit wise AND) left to right
9 ^(bit wise XOR) left to right
10 |(bit wise OR) left to right
11 &&(logical AND) left to right
12 ||(logical OR) left to right
13 ?,: right to left
14 +=,-=,*=(assignment) right to left
15 comma operator left to right
Example:
i)z=a*b/c;
Here (*) and slash have the same priority but a*b would be performed first because *
operator has associativity property the result obtained would then be divided by c.
ii) (a+b+c) / (d+e)

23
Here there are more than one set of parenthesis. The operations with in the inner most
parentheses would be performed first following by the operations with in the second inner most
pair and so on.
Implicit & Explicit Type Conversions
Normally in mixed type expressions all operands are converted temporarily up to the
type of the largest operand in the expression.

Normally this automatic or implicit casting of operands follows the following guidelines
in ascending order.
long double
Double
Float
unsigned
long
Long
unsigned int
signed int
For Example :-
int i ;
float f1, f2 ;
f1 = f2 + i ;
Since f2 is a floating point variable the value contained in the integer variable is
temporarily converted or cast to a floating point variable also to standardize the addition
operation in this case. However it is important to realize that no permanent modification is made
to the integer variable.
Explicit: casting coerces the expression to be of specific type and is carried out by means of the
cast operator which has the following syntax.
Syntax: (type) expression
For Example if we have an integer x, and we wish to use floating point division in the
expression x/2 we might do the following
(float) x / 2

24
Which causes x to be temporarily cast to a floating point value and then implicit casting
causes the whole operation to be floating point division.
The same results could be achieved by stating the operation as
x / 2.0
Which essentially does the same thing but the former is more obvious and descriptive of
what is happening.
Input and Output Functions:
1. printf():It prints that strings on the output window what are written within its
parenthesis‟s quotation like (“ ”).
The printf() function is used for formatted output and uses a control string which is
made up of a series of format specifiers to govern how it prints out the values of the
variables or constants required.
For Example :-
int i ;
printf( "%d", i ) ;
The printf() function takes a variable number of arguments. In the above example
two arguments are required, the format string and the variable i. The value of i is
substituted for the format specifier %d which simply specifies how the value is to be
displayed, in this case as a signed integer.
2. scanf():The scanf () function scans and formats input from stdin. It scans a series of input
fields (all characters up to the next white-space character) one character at a time. The format

of scanf() function is scanf (“Formatted _specifier”, & variable_ name). If you

don’t use the & (Address Operator), you might get undesired result. So you should be careful
put it before variable name. A list of formatted Specifier is given below→

Formatted specifier Meaning


%d For taking integer value
%c For taking a character
%s For taking string
%f For taking float and double value

3. getChar( ): getchar( ) is used to read one character at a time from the standard input
device. It has the following form.
a. Ch=getchar();
25
Where ch is a char variable.
eg: char c; C=getchar();
4. putchar( ): putchar( ) is used to read to display one character at a time on the monitor
screen it has the following form
a. putchar(ch);
where ch is a char variable
eg: char c=”M”; putchar(c);
5. getch( ): getch( ) is used to read a character from the keyboard and it does not express
enter key press its format is
a. ch=getchar( );
where ch is a char variable
eg: char c;
b. c=getch( );
6. getChe( ) : getche( ) is used to read a character from the keyword without expecting
enter key.
a. Ch=getche( );
Where ch is a char variable
b. getch( ) is similar to getch( ) except that getch( ) displays the key pressed from
the keyboard onto the monitor screen.
7. gets( ): gets( )is used to read a string of character including white spaces it has following
format.
i. gets(st);
ii. Where st is a character string variable
iii. Eg: char st(20); gets(st);
The statement is executed the computer waits for string value, string of characters are
entered when enter key is pressed. A null character “\0” is added to the end of the string.
8. puts():- It is used to display a character string on the monitor screen it has the following
format.
puts(str);
Where str is a string (array of character).
Eg; char st[20]=”computer world”;
puts(st);
26
9. clrscr( )(Clear screen):-clrscr( ) is used to clear the monitor screen it has the following
format.
clrscr();

Control statements
Control statements enable us to specify the flow of program control, i.e. the order in
which the instructions in a program must be executed. They make it possible to make decisions,
to perform tasks repeatedly or to jump from one section of code to another.
There are four types of control statements in C:
1. Decision making statements
2. Selection statements
3. Iteration statements
4. Jumping statements
Decision Making Statements:
Decision Making statements are used when we wants to execute the statements as
according to the user needs. A User can Change the Sequence of the Statements for Execution.
Many Times the user wants to execute the set of instructions to be executed in one
Situation and other Statements in other Situations for Executing the Statements in Specific
Situation there are Some Decision Making Statements or Decision Control Statements those are
provided by the C Language. In The Decision First a Condition is checked it is true then it
Executes the next Instruction otherwise it Executes other Statements.
The different forms are:
Simple if statement
if …..else statement.
Nested if …..else statement.
else if ladder.
Simple if statement:
1. if statement:- It is a powerful decision making statement and is used to control the flow of
execution of statements. The general form of a simple if statement is The „statement-block‟ may
be a single statement or a group of statement. If the test expression is true, the statement-block
will be executed; otherwise the statement-block will be skipped and the execution will jump to
the statement-x. It takes the following form:
27
if (Text expression)
{
Statements;
}
The if statement may be implemented in different forms depending on the complexity of
conditions to be tested.

if else statement:
This feature permits the programmer to write a single comparison, and then execute
one of the two statements depending upon whether the test expression is true or false. The
general form of the if-else statement is
if(expression)
statement1
else
statement2
Here also expression in parentheses must evaluate to (a boolean) true or false.
Typically you're testing something to see if it's true, and then running a code block (one or more
statements) if it is true, and another block of code if it isn't. The statement1 or statement2 can be
either simple or compound statement.
Here, if the test expression is true, then the true-block statements will be executed,
otherwise the false-block statements will be executed. In either case, either true block or false
block statements will be executed, not both. The general form can be shown by the following
flowchart.

28
Nested if...else Statement: When a series of decisions are involved, we may have to use more
than one if....else statement in nested.
If condition 1 is false, then condition 2 is checked and statements are executed if it is
true. If condition 2 also gets failure, then else part is executed.

Here, if the condition 1 is false then it skipped to statement 3. But if the condition 1 is
true, then it tests condition 2. If condition 2 is true then it executes statement 1 and if false then
it executes statement 2. Then the control is transferred to the statement x. This can also be
shown by the following flowchart.

29
The else if ladder:
When a multipath decision is involved then we use else if ladder. A multipath decision
is a chain of ifs in which the statement associated with each else is an if. It takes the following
general form

This construct is known as the else if ladder. The conditions are evaluated from the top,
downwards. This can be shown by the f++++++++++++++++++++++ollowing flowchart.

30
Selection Statements:
Switch statement
The switch statement is almost the same as an “if statement”. The switch statement can
have many conditions.
C provides multiway decision statement known as a switch.
Switch statement is used for complex programs when the number of alternatives
increases. The switch statement tests the value of a given variable (or expression) against a list
of case values and when a match is found, a block of statements associated with case is
executed. The general form of the switch statement is as shown below:
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;

31
break;
……
……
default:
default- block-;
break;
}
Statement-x;
The expression is an integer expression or characters. Value-1,value-2….. are constants
or constant expressions and are known as case labels. Block-1,block-2 ….. are statement lists
and mat contain zero or more statements. Note that case labels end with a colon(:).
The default is an optional case. When present, it will be executed if the value of the
expression does not match with any of case values. if not present, no action takes place if all
matches fail and the control goes to the statement-x.
This can be shown by the following flowchart.

The Conditional Operator: The C language has an unusual operator, useful for making two
way decisions. This operator is a combination of ? and : ,and takes three operands. This operator
is known as the conditional operator. Syntax:-

32
Conditional expression ? expression1 : expression2
The conditional expression is evaluated first. If the result is nonzero, expression1 is evaluated
and is returned as the value of the conditional expression. Otherwise, expression2 is evaluated
and its value is returned.
Iteration statements:
Loop: A loop is a particular area of a program where some executable statements are written
which gets execution by testing one or more conditions. So, in looping, a sequence of
statements is executed until some conditions for termination are satisfied.
Or
Loops cause program to execute the certain block of code repeatedly until test condition
is false. Loops are used in performing repetitive task in programming. Consider these scenarios:
 You want to execute some code/s „n‟ times.
 You want to execute some code/s certain number of times depending upon input from
user.
These types of task can be solved in programming using loops.
There are 3 types of loops in C programming:
1. for loop
2. while loop
3. do...while loop
A program loop therefore consists of two segments; the body of the loop and the
control statement.
Steps of looping process: A looping process, in general, would include the following four
steps.
1. Setting and initialization of a condition variable.
2. Execution of the statements of the loop.
3. Test for a specified value of the condition variable for execution of the loop.
4. Incrementing or updating the condition variable.
The above given steps may come at any order depending on the type of the loop.
For Loop:
The initialization statement is executed only once at the beginning of the for loop.
Then the test expression is checked by the program. If the test expression is false, for loop is
terminated. But if test expression is true then the code/s inside body of for loop is executed and
33
then update expression is updated. This process repeats until test expression is false.
Syntax is:
for(initialization statement; test expression; update statement)
{
Body of the loop to be executed;
}
The execution of the for statement is as follows:
 Initialization of the control variables is done first.
 The value of the control variable is tested using the test-condition. If the condition is
true, the body of the loop is executed; otherwise the loop is terminated and the execution
continues with the statement that immediately follows the loop.
 When the body of the loop is executed, the control is transferred back to the for
statement after evaluating the last statement in the loop. Now, the control variable is
either incremented or decremented as per the condition.
The flowchart describes the working of for loop is

While loop (Entry controlled loop):


The types of loop where the test condition is stated before the body of the loop are
known as the entry controlled loop. So in the case of an entry controlled loop, the condition is
tested before the execution of the loop. If the test condition is true, then the loop gets the
execution, otherwise not.

34
The while loop checks whether the test expression is true or not. If it is true, code/s
inside the body of while loop is executed, that is, code/s inside the braces { } are executed. Then
again the test expression is checked whether test expression is true or not. This process
continues until the test expression becomes false.
Syntax is
While(Test condition)
{
Body of the loop;
}
The structure of an entry controlled loop is

Do while (Exit controlled loop):


These types of loop where the test condition is stated at the end of the body of the loop
are known as the exit controlled loops. So, in the case of the exit controlled loops, the body of
the loop gets execution without testing the given condition for the first time. Then the condition
is tested. If it comes true, then the loop gets another execution and continues till the result of the
test condition is not false. For example, the do statement or the do....while loop is an exit
controlled loop.
Syntax is:
do
{
Body of the loop;
}while(Test condition);
The structure of an exit controlled loop is:

35
Jumping Statements:
The goto statement
C supports the goto statement to branch unconditionally from one point of the program
to another. The goto requires a label in order to identify the place where the branch is to be
made. A label is any valid variable name and must be followed by a colon.
A goto statement in C programming language provides an unconditional jump from the goto to
a labeled statement in the same function.
NOTE: Use of goto statement is highly discouraged in any programming language because it
makes difficult to trace the control flow of a program, making the program hard to understand
and hard to modify. Any program that uses a goto can be rewritten so that it doesn't need the
goto.
Syntax:
The syntax for a goto statement in C is as follows:
goto label;
..
.
label: statement;
The general from is

36
Break and Continue Statements:
There are two statements built in C programming, break; and continue; to alter the
normal flow of a program. Loops perform a set of repetitive task until text expression becomes
false but it is sometimes desirable to skip some statement/s inside loop or terminate the loop
immediately without checking the test expression. In such cases, break and continue statements
are used. The break; statement is also used in switch statement to exit switch statement.
break Statement
In C programming, break is used in terminating the loop immediately after it is
encountered. The break statement is used with conditional if statement.
Syntax of break statement
break;
The break statement can be used in terminating all three loops for, while and do...while loops.

The figure below explains the working of break statement in all three types of loops.

37
Continue Statement
It is sometimes desirable to skip some statements inside the loop. In such cases, continue
statements are used.
Syntax of continue Statement
continue;
Just like break, continue is also used with conditional if statement.

For better understanding of how continue statements works in C programming. Analyze


the figure below which bypasses some code/s inside loops using continue statement.

38
Nested Loops:
A Nested loop is one loop inside another loop. A common use for nested loops is to
display data in rows and columns. One loop can handle, say, all the columns in a row, and the
second loop handles the rows.
The syntax for a nested for loop statement is as follows:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement is as follows:
while(condition)
{
while(condition)
{ statement(s); }
statement(s);

39
}
The syntax for a nested do...while loop statement is as follows:
do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );
A final note on loop nesting is that you can put any type of loop inside of any other type
of loop. For example, a for loop can be inside a while loop or vice versa.
Functions:
Function is a self contained block of statements that carries out a specific, well-defined
task or operation.
Identification of Function & Purpose:
The identification of a function is set of parentheses “( )” i.e. after a name, if there is a set of
parentheses then it is said to be a function.
e.g. add(), mul() are functions.
Functions break large computing tasks into smaller ones, and enable people to build on
what others have done instead of starting over from scratch. Appropriate functions hide details
of operation from parts of the program that don‟t need to know them, thus clarifying the whole,
and easing the pain of making changes
Defining a Function:
The general form of a function definition in C programming language is as follows:
return_type function_name( parameter list )
{
body of the function
}
A function consists of a function header and a function body. Here are all the parts of a
function:

40
 Return Type: A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
 Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters: A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
 Function Body: The function body contains a collection of statements that define what
the function does.
Function Declarations:
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration has the following parts:
return_type function_name( parameter list );
For the above defined function max(), following is the function declaration:
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so
following is also valid declaration:
int max(int, int);
Function declaration is required when you define a function in one source file and you
call that function in another file. In such case you should declare the function at the top of the
file calling the function.

41
Benefits of Functions:
Writing programs as a collection of functions has manifold benefits, including the following.
 Functions allow a program to be split into a set of subproblems which, in turn, may be
further split into smaller subproblems. This divide-and-conquer approach means that
small parts of the program can be written, tested, and debugged in isolation without
interfering with other parts of the program.
 Functions can wrap-up difficult algorithms in a simple and intuitive interface, hiding the
implementation details, and enabling a higher-level view of the algorithm‟s purpose and
use.
 Functions avoid code duplication. If a particular segment of code is required in several
places, a function provides a tidy means for writing the code only once. This is of
considerable benefit if the code segment is later altered.
Types of functions:
The functions can be divided into two types. They are
 System defined functions.
 User defined functions.
System defined functions:
The functions that are already defined in the system are called as System defined
functions. These functions should be used or written in the same manner in which they are
given. These functions ate also called as library functions
E.g. main(), printf(), scanf(), sqrt() etc…
User defined functions:
The functions that are created or defined by the user to perform his own operations are called as
User defined functions.
E.g. sum(), display() etc…
Components of Functions:
Any type of function should contain three main elements. They are
1. Prototype of function
2. Definition of function or called function
3. Function call.
Prototype of function:

42
 When the compiler processes a call to a function, it will check to see that the correct
number and types of data items are being passed to the function, and will automatically
generate type conversions as necessary. This is known as type checking.
 Type checking is only possible if the compiler already knows about the function,
including what kind of data the function is expecting to receive. Otherwise, the
compiler has to make assumptions, which can lead to incorrect and erratic behavior if
those assumptions are not correct.
 One way of dealing with this situation is to make certain that all functions appear earlier
in a file than any calls to them. This works for simple cases, but can make large
complex programs hard to follow, and does not work in the cases of ( mutually )
recursive functions and functions located in separate files or libraries.
 A better approach is to use function prototypes. This is a way of declaring to the
compiler what data a function will require, without actually providing the function itself.
Examples:
int add( int a, int b );
int add( int, int );
 Note that the function prototypes end with semicolons, indicating that this is not a
function, but merely a prototype of a function to be provided elsewhere.
 Note also that the variable names are not required in the function prototype.
Calling a Function:
 A function is called by using the function name, followed by a set of parentheses
containing the data to be passed to the function.
 The data passed to the function are referred to as the "actual" parameters. The variables
within the function which receive the passed data are referred to as the "formal"
parameters.
 The formal parameters are local variables, which exist during the execution of the
function only, and are only known by the called function. They are initialized when the
function starts by copies of the data passed as actual parameters. This mechanism,
known as "pass by value", ensures that the called function can not directly change the
values of the calling functions variables. ( Exceptions to this will be discussed later. )
 To call a function which takes no arguments, use an empty pair of parentheses.
Example: total = add( 5, 3 );
43
 VERY IMPORTANT: It is crucial that the number and types of actual parameters
passed match with the number and types of parameters expected by the functions formal
parameter list. ( If the number of arguments matches but the data types do not, then the
compiler MAY insert some type conversion code if the correct data types are known, but
it is safer not to rely on this. )
 NOTE CAREFULLY: The actual parameters passed by the calling program and the
formal parameters used to receive the values in the called function will often have the
same variable names. However it is very important to recognize that they are totally
different independent variables ( because they exist in different scopes, see below ),
whether they happen to have the same name or not.
Example: In the code below, the variables x, y, z, and x again in main are used to initialize the
variables x, z, b, and c in the function. The fact that x and z appear in both main and the
function is irrelevant - They are independent variables with independent values.
void func( double x, double z, double b, double c );
int main( void ) {
double x( 1.0 ), y( 2.0 ), z( 3.0 );
func( x, y, z, x );
The call to the function above initializes the function parameters equivalently to the following
assignment statements:
 x in func = x in main
 z in func = y in main
 b in func = z in main
 c in func = x in main
Calling a Function:
While creating a C function, you give a definition of what the function has to do. To use
a function, you will have to call that function to perform the defined task.
When a program calls a function, program control is transferred to the called function. A called
function performs defined task and when its return statement is executed or when its function-
ending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name,
and if function returns a value, then you can store returned value.

44
Function call
Control of the program cannot be transferred to user-defined function unless it is called
invoked.
Syntax of function call
function_name(argument(1),....argument(n));
In the above example, function call is made using statement add(num1,num2); from
main(). This makes the control of program jump from that statement to function definition and
executes the codes inside that function.
Function definition
Function definition contains programming codes to perform specific task.
Syntax of function definition
return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
//body of function
}
Function definition has two major components:
1. Function declarator
Function declarator is the first line of function definition. When a function is called, control of
the program is transferred to function declarator.
Syntax of function declarator
return_type function_name(type(1) argument(1),....,type(n) argument(n))
Syntax of function declaration and declarator are almost same except, there is no
semicolon at the end of declarator and function declarator is followed by function body.
In above example, int add(int a,int b) in line 12 is a function declarator.
2. Function body
Function declarator is followed by body of function inside braces.
Passing arguments to functions
In programming, argument(parameter) refers to data this is passed to function(function
definition) while calling function.
In above example two variable, num1 and num2 are passed to function during function
call and these arguments are accepted by arguments a and b in function definition.

45
Arguments that are passed in function call and arguments that are accepted in function
definition should have same data type. For example:
If argument num1 was of int type and num2 was of float type then, argument variable a should
be of type int and b should be of type float,i.e., type of argument during function call and
function definition should be same.
A function can be called with or without an argument.
Return Statement
Return statement is used for returning a value from function definition to calling function.
Syntax of return statement
return (expression);
For example:
return a;
return (a+b);
In above example, value of variable add in add() function is returned and that value is
stored in variable sum in main() function. The data type of expression in return statement should
also match the return type of function.

46
Parameter Passing
 Parameter passing is a technique used to pass data to a function
 There are two ways in which we can pass arguments to the function
1. call by value
2. call by reference
Call By Value:
 In this type value of actual arguments are pass to the formal arguments and the operation
is done one the formal arguments
 Any change made in the formal arguments does not effect the actual arguments because
form arguments are photo copy of actual arguments
 Hence when function is called by the call (or) by val method, it does not affect the actual
contents of the actual arguments
 Changes made in the formal arguments are local to the block of the called function.
 Once control returns back to the calling function the changes made vanish
Call By Reference:
 In this type instead of passing values address (reference) are passed.
 Function operates on address rather than values.
 Here the formal arguments are pointers to he actual arguments
 In this type formal arguments point to the actual arguments
 Hence changes made in the arguments are permanent
Variable:
A variable is just a named area of storage that can hold a single value (numeric or
character). The C language demands that you declare the name of each variable that you are
going to use and its type, or class, before you actually try to do anything with it.
47
The Programming language C has two main variable types
1. Local Variables
2. Global Variables
Local Variables
 Local variables scope is confined within the block or function where it is defined. Local
variables must always be defined at the top of a block.
 When a local variable is defined - it is not initalised by the system, you must initalise it
yourself.
 When execution of the block starts the variable is available, and when the block ends the
variable 'dies'.
Syntax:
main()
{
int i=4;
int j=10;
Statements;
}
Global Variables
Global variable is defined at the top of the program file and it can be visible and
modified by any function that may reference it.
Global variables are initialized automatically by the system when you define them!

Data Type Initialser


int 0
char '\0'
float 0
pointer NULL

If same variable name is being used for global and local variable then local variable
takes preference in its scope. But it is not a good practice to use global variables and local
variables with the same name.
int i=4; /* Global definition */
main()

48
{
i++; /* Global variable */
statements;
}
Standard Library Functions - Header File
In the C Programming Language, the Standard Library Functions are divided into
several header files.
Below is the list of header files that we will cover:
Header Files
<assert.h> Diagnostics Functions
<ctype.h> Character Handling Functions
<locale.h> Localization Functions
<math.h> Mathematics Functions
<setjmp.h> Nonlocal Jump Functions
<signal.h> Signal Handling Functions
<stdarg.h> Variable Argument List Functions
<stdio.h> Input/Output Functions
<stdlib.h> General Utility Functions
<string.h> String Functions
<time.h> Date and Time Functions
Recursion
A function that calls itself is known as recursive function and this technique is known as
recursion.
A useful way to think of recursive functions is to imagine them as a process being
performed where one of the instructions is to "repeat the process". This makes it sound very
similar to a loop because it repeats the same code, and in some ways it is similar to looping. On
the other hand, recursion makes it easier to express ideas in which the result of the recursive call
is necessary to complete the task.
Every recursive function must be provided with a way to end the recursion.
void recursion()

49
{
recursion(); /* function calls itself */
}

int main()
{
recursion();
}
But while using recursion, programmers need to be careful to define an exit condition
from the function; otherwise it will go in infinite loop.
Recursive function is very useful to solve many mathematical problems like to calculate
factorial of a number, generating Fibonacci series, etc.
Advantages and Disadvantages of Recursion
Recursion is more elegant and requires few variables which make program clean.
Recursion can be used to replace complex nesting code by dividing the problem into same
problem of its sub-type.
In other hand, it is hard to think the logic of a recursive function. It is also difficult to
debug the code containing recursion.
Arrays:
 An array is a collection of data items, all of the same type, accessed using a common
name.
Arrays are of two types:
1. One-dimensional arrays
2. Multidimensional arrays
 A one-dimensional array is like a list; A two dimensional array is like a table; The C
language places no limits on the number of dimensions in an array, though specific
implementations may.
 Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as
matrices, and use the general term arrays when the number of dimensions is unspecified
or unimportant.
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by an
index.
50
All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.

Declaration of Array:
To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array as follows:
<type-of-array> <name-of-array> [<number of elements in array>];
type-of-array: It is the type of elements that an array stores. If array stores character elements
then type of array is „char‟. If array stores integer elements then type of array is „int‟. Besides
these native types, if type of elements in array is structure objects then type of array becomes
the structure.
name-of-array: This is the name that is given to array. It can be any string but it is usually
suggested that some can of standard should be followed while naming arrays. At least the name
should be in context with what is being stored in the array.
[number of elements]: This value in subscripts [] indicates the number of elements the array
stores.
Initializing Arrays
You can initialize array in C either one by one or using a single statement as follows:
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces { } can not be larger than the number of elements that we
declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write:
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
You will create exactly the same array as you did in the previous example. Following is an
example to assign a single element of the array:
balance[4] = 50.0;
The above statement assigns element number 5th in the array with a value of 50.0. All arrays
have 0 as the index of their first element which is also called base index and last index of an
51
array will be total size of the array minus 1. Following is the pictorial representation of the same
array we discussed above:

Accessing Array Elements


An element is accessed by indexing the array name. This is done by placing the index of
the element within square brackets after the name of the array. For example:
double salary = balance[9];
The above statement will take 10th element from the array and assign the value to salary
variable

52

You might also like