0% found this document useful (0 votes)
40 views204 pages

Pps Notes

Uploaded by

5377696raghav10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
40 views204 pages

Pps Notes

Uploaded by

5377696raghav10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 204

Preface

The main objective of the course entitled “Programming for Problem Solving” is to make first year
B.Tech students familiar with the Computer Programming concepts and language fundamentals in a
more systematic manner. This material is written according to GRIET GR-22(Autonomous)
syllabus. This book has been prepared to meet the requirements of Programming for Problem
Solving

This work is Contributed and verified by the faculty of CPDS/CSE

1. S T G Y.Sandhya

2. D. SugunaKumari

3. P. Rajesh

4. R.S.Shalini

5. M.Suresh Babu

6. G.Vandana

7. V.Ramyamanaswi

8. Arunkumar

9. K.B.Anusha
COURSE: PROGRAMMING FOR PROBLEMSOLVING (T) CODE: GR22A1007
COURSESYLLABUS
Prerequisite: Knowledge of Mathematics required.
Course Objectives:
1. To interpret the various steps in problem solving and program development.
2. To recall and reuse the fundamentals, syntax and semantics of C programming language.
3. To illustrate problem solving using arrays, strings, structures and pointers.
4. To demonstrate structured and modular programming approach in solving problems.
5. To interpret code and debug the given problems using files.
Course Outcomes:
1. To design algorithms and flowcharts for problem solving and illustrate the fundamentals of C language.
2. To identify and apply control structures and arrays to solve problems.
3. To discover the need for strings and functions in problem solving and apply it.
4. To analyze the need for pointers and structures in C and implement for solutions.
5. To interpret working with files, preprocessor directives and command line arguments in C.
UNIT I
Introduction to Programming:
Introduction to Algorithms: Representation of Algorithm, Flowchart, Pseudo code with examples, compiling and
executing programs, syntax and logical errors.
Introduction to C Programming Language: Structure of C program, keywords, variables, constants, datatypes,
operators, precedence and associativity, expression evaluation, implicit and explicit type conversion, formatted and
unformatted I/O.
UNIT II
Decision Making and Arrays:
Branching and Loops: Conditional branching with simple if, if-else, nested if else, else if ladder, switch-case, loops: for,
while, do-while, jumping statements: goto, break, continue, exit.
Arrays: One and two dimensional arrays, creating, accessing and manipulating elements of arrays. Searching:
Introduction to searching, Linear search and Binary search.
UNIT III
Strings and Functions:
Functions: Introduction to structured programming, function declaration, signature of a function, parameters and return
type of a function, categories of functions, parameter passing techniques, passing arrays and strings to functions,
recursion, merits and demerits of recursive functions, storage classes.
Strings: Introduction to strings, operations on characters, basic string functions available in C - strlen, strcat, strcpy,
strrev, strcmp, String operations without string handling functions, arrays of strings.
UNIT IV
Pointers and Structures:
Pointers: Idea of pointers, declaration and initialization of pointers, pointer to pointer, void pointer, null pointer, pointers
to arrays and structures, function pointer.
Structures and Unions: Defining structures, declaring and initializing structures, arrays within structures, array of
structures, nested structures, passing structures to functions, unions, typedef.
UNIT V
File handling and Preprocessor in C:
Files: Text and binary files, creating, reading and writing text and binary files, random access to files, error handling in
files. Preprocessor: Commonly used preprocessor commands like include, define, undef, if, ifdef, ifndef, elif, command
line arguments, enumeration data type.
TEXT BOOKS:
1. Byron Gottfried, Schaum’s Outline of Programming with C, McGraw-Hill
2. B.A. Forouzan and R.F. Gilberg C Programming and Data Structures, Cengage Learning, (3rd Edition)
REFERENCE BOOKS:
1. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice Hall of India
2. R.G. Dromey, How to solve it by Computer, Pearson (16th Impression)
3. Programming in C, Stephen G. Kochan, Fourth Edition, Pearson Education
4. Herbert Schildt, C: The Complete Reference, Mc Graw Hill, 4th Edition
UNIT-I
Unit-1: Introduction to Programming
Introduction to Algorithms: Representation of Algorithm, Flowchart , Pseudo code with examples, compiling &
executing program, syntax and logical errors.
Introduction to C Programming Language: Structure of c program, variables, data types, constants, Operators,
expressions and precedence, Expression evaluation, type conversion.

I/O: Simple input and output with formatted I/O and unformatted I/O.

Representation of Algorithm Flowchart and Pseudo code with Examples:

Algorithm:
Algorithm is a finite set of instructions that , if followed accomplishes a particular task. The same
problem can be solved with different methods. So, to solve a problem different algorithms, may
be accomplished. Algorithm may vary in time.User writes algorithm in his / her own
language. So,it cannotbe executed on computer. Algorithm should be in sufficient detail that it
can be easily translated into anylanguage.

Characteristics or properties of Algorithm:


1. Input:Zero or more quantities are externallysupplied.
2. Output: At least one quantity isproduced.
3. Definiteness: Each instruction is clear and unambiguous. Ex:Add B or C toA.
4. Finiteness : Algorithm should terminate after finite number ofsteps.
5. Effectivenes : Every Instruction must bebasic.i.e.,
it can be carried out,by a person using Pencil and paper.

Advantages of Algorithms:
• It provides the core solution to a given problem. the solution can beimplemented on a
computer system using any programming language of user‘schoice.
• It facilitates program development by acting as a design document or a blue print of a
given problemsolution.
• Itensureseasycomprehensionofaproblemsolutionascomparedtoanequivalent
computerprogram.
• It eases identification and removal of logical errors in a program.
• It facilitates algorithm analysis to find out the most efficient solution to a given problem.

Disadvantages of Algorithms:
• In large algorithms the flow of program control becomes difficult totrack.
• Algorithms lack visual representation of programming constructs like flowcharts.
• Understanding the logic becomes relativelydifficult.

Examples:

Example1 :Add two numbers.


Step 1: Start
Step 2: Read 2 numbers as A and B
Step 3: Add numbers A and B andstoreresult in C
Step 4 :DisplayC
Step 5: Stop
Example2: Average of 3 numbers.
Step 1.Start
Step 2.Read the numbers a , b , c
Step 3.Compute the sum and divide by 3 Step 4.Store the result in variabled
Step 5.Print value of d
Step 6.End

Example3: Average of n inputtednumbers.


Step 1.Start
Step 2.Read the number n Step 3.Initialize i to Zero
Step 4.Initialize sum to zero Step 5.If i is greater than n Step 6.Read a
Step 7.Add a to sum and goto step 5.
Step 9.Dividesum by n and store the result in avg
Step 10.Print value ofAvg
Step 11.End

Flowchart:

A flowchart is a Visual representation of the sequence of steps for solving a problem.


Aflowchartisasetofsymbolsthatindicatevariousoperationsintheprogram.Forevery process, there is
a corresponding symbol in the flowchart. A pictorial representationof a textual algorithm is done
using a flowchart.A flowchart gives a pictorial representation of analgorithm.

o •The first flowchart is made by John Von Neumann in 1945.

o It is a symbolic diagram of operations sequence,dataflow,controlflowandprocessing


logic in information processing.

o •The symbols used are simple and easy to learn.

It is a very helpful tool for programmers andbeginners.

Purpose of a Flowchart :
•Providescommunication.
•Provides anoverview.
•Shows all elements and their relationships.
•Quick method of showing programflow.
•Checks program logic.
•Facilitates coding.
•Provides programrevision.
•Provides programdocumentation.
Advantages of a Flowchart :
•Flowchart is an important aid in the development of an algorithm itself.
•Easier to understand than a programitself.
• Independent of any particular programminglanguage.
•Proper documentation.
•Proper debugging.
•Easy and clear presentation.

Limitations of a Flowchart :
•Complex logic.
•Drawing is time consuming.
•Difficult to draw and remember.
•Technical detail.

Symbols : Symbols are divided in to the following twoparts.


I. AuxiliarySymbols.
II. PrimarySymbols.

Prepare an algorithm and flow chart for swapping two numbers


To Swap two integer numbers:
Algorithm :
Using third variable
Step 1 : Start
Step 2 : Input num1 , num2
Step 3 : Temp = num1
Step 4 : num1 = num2
Step 5 : num2 = Temp
Step 6 : Output num1 , num2
Step 7 : Stop
Flowcharts
Develop an algorithm and flowchart to find the largest among two numbers.

Ans:Algorithm:

Step 1: Start
Step 2: Input A ,B
Step 3: if A > B then output A else outputB
Step 4: Stop

Flowchart :

Develop an algorithm and flowchart to find the largest among three numbers. Algorithm:
Step 1 : Start
Step 2 :Input A, B, C
Step 3 :If A > B goto step 4 ,otherwise goto step 5.
Step 4 :if A > C goto step 6,otherwise goto step 8
Step 5 :if B > C go to step 7,otherwise goto step 8
Step 6 : print A is largest and goto step9
Step 7 : print B is largest and goto step9
Step 8 : print C is largest and goto step9
Step 9 :Stop
Flowchart:
Simulate an algorithm and flowchart to find factorial of a number Flowchart:

Algorithm:

Step 1:Start Step 2:Input n


Step 3:Initialize counter variable, i , to 1 and factors = 1
Step 4:if i<= n go to step 5 otherwise goto step 7
Step 5:Calculate factors = factors * i
Step 6:Increment counter variable, i, and goto step 4 Step 7:output factors.
Step 8:stop

Pseudocode:

Pseudocode is an informal way of programming description that does not require any strict
programming language syntax or underlying technology considerations. It is used for creating an
outline or a rough draft of a program. Pseudocode summarizes a program’s flow, but excludes
underlying details. System designers write pseudocode to ensure that programmers understand a
software project's requirements and align code accordingly.
Advantages of pseudocode –
• Pseudocode is understood by the programmers of alltypes.
• it enables the programmer to concentrate only on the algorithm part of the code development.
• It cannot be compiled into an executableprogram.
Example of Pseudocode:
Bigger of 2 numbers:
Read a,b.
If (a >b)
Then print a “is bigger”;
Else print b “is bigger”;
endif

Example Sum of numbers from 1 to 5:


Program : Print sum 1 to 5 Sum=0;
A=1;
While(A!=6)
Do sum=sum+A; Endwhile.

Print sum;

End

Creating compiling and executing a program:


Creating and running programs:
It is the job of programmer to write and test the program. The following are four steps for
creating and running programs:

A. Writing and Editing theProgram.


B. Compiling theProgram.
C. Linking the Program with the required librarymodules.
D. Executing theProgram.
A. Writing and Editing Program: The Software to write programs is known as text editor. A
text editor helps us enter, change and store character data. Depending on the editor on our
system, it could be used to write letters, create reports or writeprograms.

Example : word processor. The text editor could be generalized word processor, but every
compiler comes with associated text editor.
Some of the features of editors are Search : To locate and replacestatements.
Copy , Paste : To copy and move statements. Format : To set tabs to align text.

After the program is completed the program is saved in a file to disk. This file will be input to
the compiler, it is known as source file. The following figure shows the various steps in building
a C – program
Fig: Steps followed to Build a C – program

A. Compiling Programs: The code in a source file on the disk must be translated into machine
language. This is the job of compiler which translates code in source file stored on disk into
machine language. The C compiler is actually two separate programs: the preprocessor and the
translator. The preprocessor reads the source code and prepares it for the compiler. It scans
special instructions known as preprocessor commands. These commands tell the preprocessor to
take for special code libraries make substitutions in the code.The result of
preprocessing is called translation unit.The translator reads the translation unit and writes
resulting object module to a file that can be combined with other precompiled units to form
the final program. An object module is the code in machine language. This module is not readyf
or execution because it does not have the required C and other functions included.

B. Linking Programs: C programs are made up of manyfunctions.

Example: printf( ) , cos( )… etc Their codes exists elsewhere , they must be attached to our
program. The linker assembles all these functions, ours and the system‘s, into a final executable
program.

C.Executing Programs : Once our program has been linked, it is ready for execution. To
execute a program, we use operating system command, such as run to load the program in to
main memory and execute it. Getting program into memory is the function of an Operating
System programs called loader. Loader locates the executable program and reads it into memory.
In a typical program execution, the program reads data for processing, either from user or from
file.After the program processes the data,it prepares output.Data output can be to user‘s monitor
or to a file. When program has executed, Operating System removes the program from memory.
Syntax And Logical Errors In Compilation:

In a logic error is a program that causes it to operate incorrectly, but not to terminate abnormally.
A logic error produces unintended or undesired output or other behavior, although it may not immediately
be recognized as such.

Logic errors occur in both and languages. Unlike a program with a a program with a logic error is
a valid program in the language, though it does not behave as intended. Often the only clue to the
existence of logic errors istheproductionof wrong solutions, though may sometimes spotthem.

Object and Executable Codes:

Object Code :

Object code is produced when an interpreter or a compiler translates source code into recognizable and
executable machine code. Object code is a set of instruction codes that is understood by a computer at the
lowest hardware level. Object code is usually produced by a compiler that reads some higher level
computer
language source instructions and translates them into equivalent machine language instructions.

Executable Code :

Executable code is a file or a program that indicates tasks according to encoded instructions. The CPU
can directly execute an executable file to defined tasks. In other words, it is machine code instructions for
a physical CPU. As a CPU can directly execute an object code, we can also consider the object code as an
executable code. Furthermore, it is sometimes possible to consider or scripting language instructions as
an executable code.
Structure of C Program:

Documentation section :
This section consists of a set of comment lines giving the name of the program, and other details. which the programmer
would like to user later.
Ex:- /*Addition of two numbers */
Link section:Link section provides instructions to the compiler to link functions from thesystem library.
Ex:- # include<stdio.h>
# include<conio.h>
Definition section:Definition section defines all symbolic constants.
Ex:- # define A 10.
Global declaration section:Some of the variables that are used in more than one functionthroughout the program are called
global variables and declared outside of all the functions. This section declares all the user-defined functions.

Main() function section:


Every C program must have one main ( ) function section. This contains two parts.
i) Declaration part:This part declares all the variables used in the executable part.
Ex:-inta,b;
ii) Executable part:This part contains at least one statement .These two parts must appearbetween the opening and closing
braces. The program execution begins at the opening brace and ends at the closing brace. All the statements in the declaration
and executable parts end with a semicolon (;).
Sub program section:This section contains all the user-defined functions, that are called in themain () function. User-
defined functions are generally placed immediately after the main() function, although they may appear in any order.
Ex:
VARIABLES
It is a data name that may be used to store a data value. It cannot be changed during the
execution of a program. A variable may take different values at different times during
execution. A variable name can be chosen by the programmer in a meaningful way so as to
reflect its function or nature in the program.
Rules:
 Variable names may consist of letters, digits and under score( _ ) character.
 First char must be an alphabet or an ‗-‘
 Length of the variable cannot exceed upto 8 characters, some C compilers can
 recognized upto 31 characters.
 White space is not allowed.
 Variables name should not be a keyword.
 Uppercase and lower case are significant.
Ex:- mark,sum1,tot_value,delhi (valid)
Prics$, group one, char (invalid)
Declaration and initialization of variables with examples:
Declaration does two things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.

The declaration of variables must be done before they are used in the program.
The syntax for declaring a variable is as follows:
data-type v1,v2,…….,vn;
v1,v2,…,vn are the names of variables. Variables are separated by commas. A declaration statement must end
with a semicolon. For example , valid declarations are:
int count;
int number, total;
double ratio;
The simplest declaration of a variable is shown in the following code fragment:
Example:
/*…………….ProgramName……….*/
int main()
{
//Declarations
float x,y;
int code;
short int count;
long int amount;
double deviation;
unsigned n;
char c;
/*…………………………Computation…………………………*/
}
/*…………………………Program ends…………………..*/

Initialization of variable :
Initialize a variable in c is to assign it a starting value. Without this we can't get
whatever happened to memory at that moment.
C does not initialize variables automatically. So if you do not initialize them properly,
you can get unexpected results. Fortunately, C makes it easy to initialize variables
when you declare them.
For Example :
int x=45;
intmonth_lengths[] ={23,34,43,56,32,12,24};
struct role = { "Hamlet", 7, FALSE, "Prince of Denmark ", "Kenneth Branagh"};
*Note : The initialization of variable is a good process in programming.

Data types :
A data type is a classification of the type of data that a variable can hold in computer programming.
Data type is the type of the data that are going to access within the program. C supports different data
types. Each data type may have pre-defined memory requirement and storage representation.

C supports 4 classes of data types.

1. Primary or (fundamental) data type(int, char, float, double)


2. User-defined data type(typedef,structures, unions)
3. Derived data type(arrays, pointers,)
4. Empty data type (void).

1. Primary or (fundamental) data type

All C compilers support 4 fundamentals data types, they are

i) Integer (int)
ii) Character(char)
iii) Floating (float)

iv) Double – precision floating point(double)


i)Integer types:

Integers are whole numbers with a range of values supported by a particular machine. Integers
occupy one word of storage and since the word size of the machine vary. If we use 16 bit word
length the size of an integer value is -32768 to +32767. In order to control over the range of
numbers and storage space, C has 3 classes of integer storage, namely short, long, and unsigned.

FORMAT
DATA TYPE RANGE SIZE
SPECIFIER

-215 to 215 -1 4 bytes (on 32 bit


Int processors ) %d or %i
-32768 to +32767

Signed short int or 4 bytes


-128 to +127 %d or %i
Short int

4 bytes
Unsigned short int 0 to 255 %d or %i

0 to 65,535 4 bytes
Unsigned int %u

4 bytes
Unsigned long int 0 to 4,294,967,295 %lu

Long int or -2147483648 to


4 bytes %lu
signed long int +2147483647

Character type:-

Single character can be defined as a character (char) type data. Characters are usually stored in 8bits
of internal storage. Two classes of char types are there.

signed char, unsigned char.

signed char(or) char 1 byte- -128 to +127%c

unsigned char 1 byte0 to 255%c


iii) Floating point types:
Floating point (real) numbers are stored in 32 bits, with 6 digits of precision when
accuracy provided by a float number is not sufficient.

float 4 bytes3.4e-38 to 3.4e+38%f

iv). Double precision type:


double datatype number uses 64 bits giving a precision of 14 digits. These are known as double precision
numbers. Double type represents the same data type that float represents, but with a greater precision.
To extend the precision further, we may use long double which uses 80 bits.

Double8 bytes 1.7e-308 to 1.7e+308%lf

long double10 bytes 3.4e-4932 to 1.1e+4932%lf

2. User defined data types:


C –supports a feature known as ―type definition‖ that allows users define an identifier that would
represents an existing type.

Syntax: typedef data-type identifier; where data-type indicates the existing datatype identifier
indicates the new name that is given to the data type.

Ex:-typedef int marks;

marks m1, m2, m3;


typedef cannot create a new data type ,it can rename the existing datatype. The main advantage of typedef
is that we can create meaningful datatype names for increasing the readability of the program.Another
user-defined datatype is ―enumerated data type(enum)
Syntax: enumidentifier{value1, value2,… ............... valuen};

Where identifier is user-defined datatype which is used to declare variables that can have one of the
values enclosed within the braces. value1 ,value2,……valuen all these are known as enumeration
constants.

Ex:-enum identifier v1, v2,……vn

v1=value3;
v2=value1;…
……
Ex:-enum day {Monday,Tuesday………….
sunday}; enum day week-f,week-end
Week-f = Monday

enum day{Monday…Sunday}week-f, week-end;

CONSTANTS IN C
Constants is the most fundamental and essential part of the C programming language.
Constants in C are the fixed values that are used in a program, and its value remains the
same during the entire execution of the program.
 Constants are also called literals.
 Constants can be any of the data types.
 It is considered best practice to define constants using only upper-case names.

Types of C constants:
1.Integerconstants
2.Real constants
3.Character constants
4. String constants

1. Integer constants: An integer constant refers to a sequence of digits. There are three
types ofintegers, namely, decimal integer, octal integer and hexadecimal integer.
Examples of Integer Constants:
426 ,+786 , -34(decimal integers)
037, 0345, 0661(octal integers)
0X2, 0X9F, 0X (hexadecimal integers)

2. Real constants:These quantities are represented by numbers containing fractional


parts like18.234. Such numbers are called real (or floating point) constants.
Examples of Real
Constants: +325.34426.0
-32.67 etc.
The exponential form of representation of real constants is usually used if the value of the
constant is either too small or too large. In exponential form of representation the real
constant is
represented in two parts. The first part present before 'e' is called Mantissa and
the part following 'e'is called Exponent.
For ex. .000342 can be written in Exponential form as 3.42e-4.

3. Single Character constants:Single character constant contains a single character


enclosedwithin a pair of single quote marks.
For ex. 'A',‘5‘,‘;‘,‘ ‗
Note that the character constant‘5‘ is not same as the number 5. The last constant is a
blank space.Character constant has integer values known as ASCII values. For example,
the statement
printf(“%d”,a); would print the number 97,the ASCII value of the letter a. Similarly,
thestatement printf(“%c”,97); would output the letter ‗a‘

Backslash Character Constants: C supports some special backslash character constants


that areused in output functions. Some of the back slash character constants are as follows:

CONSTANT MEANING
‘\0’ NULL
‘\t’ Horizontal tab
‘\b’ Backspace
‘\a’ Audible bell
‘\n’ New line
‘\v’ Vertical tab
‘\?’ Question mark
‘\’’ Single Quote
‘\”’ Double Quote
‘\\’ Backslash
These character combinations are called escape sequences.

String constants: A string constant is a sequence of character enclosed in double


quotes. Thecharacters may be letters, numbers, special characters and blank space.
Examples are: “HELLO!”
“1979”
“welcome”
“.......!”
“5+3”
“A”

Rules for constructing integer constants:


a. An integer constant must have at least one digit.
b. It must not have a decimal point.
c. It can be either positive or negative.
d. The allowable range for constants is -32768 to 32767
In fact the range of integer constants depends upon
compiler. For ex. 435

Rules for constructing real constants:


a. A real constant must have at least one digit
b. It must have a decimal point.
c. It could be either positive or negative.
d. Default sign is positive.
For ex.
+325.34
426.0
In exponential form of representation, the real constants is represented in two parts.
The part appearing before ‗e‘ is called mantissa where as the part following ‗e‘ is
called exponent.
Range of real constants expressed in exponential form is -3.4e38 to
3.4e38. Ex. +3.2e-5

Rules for constructing character constants:


a. A character constant is a single alphabet, a single digit or a single special symbol
enclosed within single inverted commas.
b. The maximum length of character constant can be one character.
Ex `A`

Operators :
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. Operators are used in programs to manipulate data and variables.

C operators can be classified into a number of categories, they are

1. Arithmetic Operators 2. Relational Operators 3.Logical Operators 4.Assignment


Operators
5.Increment and decrement operators 6.Conditional operators 7.Bitwise Operators
8.Special operators

1. Arithmetic Operators: C provides all the basic arithmetic operators. These can operate onany
built –in data type allowed in C.

The arithmetic operators are listed as follows:


Operator Meaning Examples

+ Addition c=a+5;a=b+c;h=9+6;

- Subtraction d=e-f;

* Multiplication k=3*g;

/ Division (quotient) m=u/v;

% Modulo division (remainder) I=j%k

NOTE:

1. Integer division truncates any fractional part.


2. The modulodivision operation produces the remainder of an integer division.
3. Modulus operator is not valid for real and mixed mode arithmetic.

Integer Arithmetic:

If both the operands in an arithmetic expression are integers then it is known as integer
arithmetic and the result is an integer.

Real Arithmetic:

If both the operands in an arithmetic expression are real operands then it is known as real
arithmetic and the result is real.

Mixed mode Arithmetic:

If the operands in an arithmetic expression are of different types then it is known as mixed mode
arithmetic and the result is a bigger type.

2. Relational Operators:
Relational operators are used for comparing two quantities, and used for decision making.
For example we may compare the age of two persons or the price of two items which can be
done with the help of relational operators.
An expression containing a relational operator is termed as a relational expression. The

value of a relational expression is either one or zero. It is one if the specified relation is true and
zero if the relation is false. Ex:- 13<34 (true) 23>35(false)

C supports 6 relational operators


Operator Meaning Example Result

< is less than a<6 (a=7) 0

<= is less than or equal to x<=y (x=4,y=7) 1

> is greater than t 9>8 1

>= is greater than or equal to x+10 >=y (x=4,y=7) 1

== is equal to 8==8 1

!= is not equal to 6!=5 1

When arithmetic expression are used on either side of a relational operator, the arithmetic
expression will be evaluated first and then the results compared, that means arithmetic
operators have a higher priority over relational operators.

3. Logical Operator:
C has 3 logical operators. The logical operators are used when we want to test more than one
condition and make decisions. The operators are as follows:

Operator Meaning Example Result

&& Logical AND 4>3 && 5!=6 1

|| Logical OR 5<=7 || 5==5 1

! Logical NOT !(5==4) 1

The logical operators && and || are used when we test more than one condition and make decisions.
Logical expressions combines two or more relational expressions, is also known as compound
relational expression. The truth table for Logical AND and Logical OR is as below

OP1 OP2 OP1&&OP2 OP1||OP2

0 0 0 0

0 1 0 1

1 0 0 1

1 1 1 1
4. Assignment operator:
These operators are used to assign the result of an expression to a variable. The usual assignment
operator is “=‟. In addition ,C has a set of shorthand assignment operators of the form:

v op = exp;

Where v is a variable, exp is an expression and op is a C binary arithmetic operator. The


operator op=is known as the shorthand assignment operator.

Operator Meaning Example

= Assignment a=5; x=y; r=s*t;

+= Sum equal to b+=5 implies b=b+5

-= Subtract and assign c-=55 implies c=c-55

*= Multiply equal to b*=5 implies b=b*5

/= Divide equal to a/=10 implies a=a/10

%= Remainder equal to d%=7 implies d=d%7

The assignment statement v op=exp; is equivalent tov =v op (exp);

The use of short hand assignment operators has the following advantages:

i. What appears on the left- hand side need not be repeated and therefore it becomes easier to
write
ii. The statement is more concise and easier to read
iii. The statement is more efficient

5. Increment and Decrement operators:

++ and - - are increment and decrement operators in C. The operator ++ adds 1 to the operand,
while - - subtracts 1.Both are unary operators. They exist in postfix and prefix forms.

Operator Form Meaning Examples

++ a++ Post increment i++

++a Pre increment ++sum

-- b-- Post decrement j--

--b Pre decrement --count


++m; or m++; is equal to m=m+1(m+=1;)

--m; or m- - is equal to m=m-1(m- = 1;)

We use the increment and decrement statements in for and while loops extensively

Consider the following example when m=5,then

y=++m; the value of y=6 and m =6. Suppose if we write the above statement as m=5;

y= m++; the value of y=5 and m=6.

A prefix operator first adds 1 to the operand and then the result is assigned to the variable on left. On
the other hand, a postfix operator first assigns the value to the variable on left and then increments the
operand. Likewise for decrement operator.

6. Conditional operator:

A ternary operator pair “? :” is available in C to construct conditional expressions of the form

exp1 ?exp2 : exp3 where exp1,exp2 and exp3 are expressions.

The operator?: works as follows: exp1 is evaluated first. If it is non-zero (true), then
theexpression exp 2 is evaluated and becomes the value of the expression. If exp1 is false, exp3 is
evaluated and it becomes the value of the expression.

Ex:- a=10; b=45;

Big= (a>b) ?a:b;

o/p:- Big will be assigned the value of b (45) since a>b is false.

7. Bitwise Operators:

C supports a special operator knows as bitwise operators for manipulation of data at bit
level.These operators are used for testing the bits, or shifting them right to left.
Note: Bitwise operators may not be applied to float or double.

Operator Meaning Example

& Bitwise AND X&y

| Bitwise OR x|y

^ Bitwise exclusive OR X^y

<< Shift left X<<y

>> Shift right X>>y

~ Bitwise ones complement ~y


8. Special operators:

C supports some special operators such as comma operator, size of operator, pointer operators(&
and *) and member selection operators (. and -> ).
comma operator: The comma operator is used to link the related expressions together. Acomma-
linked list of expressions is evaluated left to right and the value of right- most expression is the value
of the combined expression. For example, the statement

value = (x=10, y=5, x+y);

This statement first assigns the value 10 to x, then assigns 5 to y and finally assigns 15. In for loops: for

(n=1 , m=10; n<=m; n++, m++);

sizeof operator: The sizeof is a compile time operator and when used with an operand, itreturns the
number of bytes the operand occupies. The operand may be variable, a constant or a data type qualifier.

m = sizeof (sum);

n = sizeof (long int);

The sizeof operator is normally used to determine the lengths of arrays and structures when their sizes are not known to
the programmer. It is also used to allocate memory space dynamically to variables during execution of a program

Expressions:
An expression in C is some combination of constants, variables, operators and function calls.
Examples:C= a + b;
tan (angle)
•Most expressions have a value based on their contents.
•A statement in C is just an expression terminated with a semicolon. For
Example:
sum = x + y + z;
The rules given below are used to evaluate an expression,
1. If an expression has parenthesis, sub expression within the parenthesis is evaluated first and
arithmetic expression without parenthesis is evaluated first.
2. The operators of high level precedence are evaluated first.
3. The operators at the same precedence are evaluated from left to right or right to left depending on
the associativity of operators.
Expressions are evaluated using an assignment statement of the form:

variable = expression;
Expression evaluation:
variable is any valid C variable name. When the statement is encountered, the expression is evaluated
first and the result then replaces the previous value of the variable on the left-hand side. All variables
used in the expression must be assigned values before evaluation is attempted

Ex:- x = a*b-c;

y = b/c*a;
z = a-b / c+d;

Ex:- x= a-b/3+c*2-1 when a=9, b=12, and c=3 the expression becomes. x = 9-

12/3 +3*2-1
Step1: x = 9-4+3*2-1
Step2: x = 9-4+6-1
Step3: x = 5+6-1
Step4: x = 11-1
Step5: x = 10

Precedence and Associativity of operators:


Operator precedence:

Various relational operators have different priorities or precedence. If an arithmetic expression


contains more operators then the execution will be performed according to their properties. The
precedence is set for different operators in C.

Type of operator Operators Associativity

Unary operators +,-,!,++,--,type, ͂,size of Right to left

Arithmetic operators *, /,%,+,- Left to right

Bit – manipulation operators <<,>> Left to right

Relational operators >,<,>=,<=,==,!= Left to right

Logical operators &&,|| Left to right

Conditional operators ?,: Left to right

Assignment operators =,+=,-=,*=,/=,%= Right to left

Note:

1. Precedence rules decide the order in which different operators are applied

2. Associativity rule decides the order in which multiple occurrences of the same level
operators are applied.
Hierarchy of operators in C :

The higher the position of an operator is, higher is its priority.When an expression
contains two operators of equal priority the tie between them is settled using the
associativity of the operators.

Associativity can be of two types—Left to Right or Right to Left

Left to Right means, as you go from left to right in an expression which operator among the two is
found, execute it first.Right to left means, as you go from right to left in an expression which operator
among the two is found, execute it first.
Consider expression a=3/2*5 Here there is a tie between operators of same priority, that is between /
and *. This tie is settled using the associativity of / and *. But both enjoy Left to Right associativity,
which means as you go from left to right / is found so execute it first.
The table clearly shows the associativity and precedence of operators in c.

RANK OPERATORS MEANING ASSOCIATIVIT


Y
1 ++ POSTFIX INCREMENT
-- POSTFIX DECREMENT
() FUNCTION CALL
[] ARRAY SUBSCRIPTING LEFT TO
. STRUCTURE AND UNION MEMBER ACCESS RIGHT
STRUCTUTRE AND UNION MEMBER ACESS
THROUGH POINTER
2 ++ PREFIX INC REMENT
-- PREFIX DECREMENT
+ UNARY PLUS
- UNARY MINUS
RIGHT TO
! LOGICAL NOT
~ BITWISE NOT LEFT
(TYPE) TYPE CAST
* INDIRECTION
& ADDRESS OF
sizeof() SIZE OF
3 * MULTIPLICATION
/ DIVISION LEFT TO
% MODULO DIVISION RIGHT
4 + ADDITION LEFT TO
- SUBTRACTION RIGHT
5 << BITWISE SHIFT LEFT LEFT TO
>> BITWISE SHIFT RIGHT RIGHT
6 < RELATIONAL OPERATORS LESSER
<= LESSER THAN OR EQUAL TO LEFT TO
> GREATER THAN RIGHT
>= GREATER THAN OR EQUAL TO
7 == IS EQUAL TO LEFT TO
!= IS NOT EQUAL TO RIGHT
8 & BITWISE AND LEFT TO
RIGHT
9 ^ BITWISE XOR LEFT TO
RIGHT
10 | BITWISE OR LEFT TO
RIGHT
11 && LOGICAL AND LEFT TO
RIGHT
12 || LOGICAL OR LEFT TO
RIGHT
13 ?: TERANARY LEFT TO
RIGHT
14 = ASSIGNMENT OPERATOR SIMPLE
+= ASSIGNMENT BY SUM
-= ASSIGNMENT BY DIFFERENCE
*= ASSIGNMENT BY PRODUCT RIGHT TO
/= ASSIGNMENT BY QUOTIENT LEFT
%= ASSIGNMENT BY REMAINDER
<< = ASSIGNMENT BY BITWISE LEFT SHIFT
>>= ASSIGNMENT BY BITWISE RIGHT SHIFT
&= ASSIGNMENT BY BITWISE AND
^= ASSIGNMENT BY BITWISE XOR
|= ASSIGNMENT BY BITWISE OR
15 , COMMA LEFT TO
RIGHT

For Example:
i= 2*3/4+4/4+8-2+5/8
i=6/4+4+8-2+5/8
i=1+4/4+8-2+5/8
i=1+1+8-2+5/8
i=1+1+8-2+0
i=2+8-2+0
i=10-2+0
i=8+0
i=8

Type conversion:
It is a process of converting a variable value or a constant value temporarily from one data type to
other data type for the purpose of calculation is known as type conversion.

There are two types of conversions

i.. Automatic type conversion (or) Implicit conversion.

ii . Type Casting (or) explicit conversion (or) manual conversion.

Implicit: In this lower data type can be converted into higher data type automatically. The figure
below shows the C conversion hierarchy for implicit –type conversion in an expression:

The sequence of rules that are applied while implicit type conversion is as follows: All

short and char are automatically converted into int then

1. if one of the operands is long double the other will be converted to long double and the result
will be long double.

2. else, if one of the operand is double, the other will be converted to double and the result will be
double.

3. else, if one of the operand is float ,the other will be converted to float and the result will be float.

4. else, if one of the operand is unsigned long int, the other will be converted to unsigned long int and
the result will be unsigned long int.

5. else, if one of the operand is long int, the other is unsigned int then

a) if unsigned int can be converted into long int, the unsigned int operand will be converted as such
and the result will be long int.

b) else both operands will be converted to unsigned long int and the result will be unsigned long
int.

6. else if one of the operand is long int ,the other will be converted into long int and the result will be
long int.

7. else if one of the operand unsigned int ,the other will be converted into unsigned int and the result
will be unsigned int.

The final result of an expression is converted to the type of the variable on the left of the assignment
sign before assigning the value to it. The following changes are introduced during the final
assignment.

i. float to int causes truncation of the fractional part


ii. double to float causes rounding of digits

iii. long int to int causes dropping of the excess higher order bits

Example : Consider the following variables along with their datatypes: int

i,x; float f; double d; longint l;

Explicit:

In this type of conversion, the programmer can convert one data type to other
datatype explicitly .Such conversions are also known as forced conversions
or manual conversions or type casting.
Syntax: (datatype) (expression) Expression can be a constant or a variable

Ex:y = (int) (a+b) y= cos(double(x)) double a = 6.5; double b = 6.5;

int result = (int) (a) + (int) (b); result = 12 instead of 13.

int a=10;

float(a)> 10.00000

Example:

//converting fahrenheit to celsius by type casting #include<stdio.h>

#include<conio.h> void main()

float c,f;

clrscr();

printf("\n enter fahrenheit:");

scanf("%f",&f);

c=(float)5/9*(f-32);
printf("\n c=%f",c);

getch();

Managing Input and Output:


Managing input and output operations:

Reading, processing and writing of data are the three essential functions of a computer program. Most
programs take some data as input and display the processed data. We have two methods of providing
data to the program variables. One method is to assign values to variables through the assignment
statements like x=5, a=0 and so on. Another method is to use the input function scanf, which can read
data from a keyboard. We have used both the methods in programs. For outputting results, we have
used extensively the function printf, which sends results out to a terminal.

Input – Output functions:

The program takes some I/P- data, process it and gives the O/P.We have two methods for providing
data to the program

(i) Assigning the data to the variables in a program.

(ii)By using I/P-O/P statements.

C language has 2 types of I/O statements. All these operations are carried out through function calls.

1. Unformatted I/O statements 2.Formatted I/O statements

Unformatted I/O statements:

i/p function o/p function


1)getchar() putchar()
2) gets() puts()
3)getc() putc()
4)getw() putw()
5)getch() putch()
6)getche()

getchar ( ):- It reads single character from standard input device. This function don‘t require
anyarguments.

Syntax : - char variable _name = getchar( );

Ex:- char x;

x = getchar( );

putchar ( ):- This function is used to display one character at a time on the standard
outputdevice.
Syntax:-putchar(variable_name);

Ex:- char x;

putchar(x);

program:

void main( )

char ch;

printf("enter a character:");

ch=getchar( );

printf("\ncharacter is:");

putchar(ch);

Output:

enter a character: a

character is a

gets( ):- This function is used to read group of characters(string) from the standard I/P device.

Syntax:-gets(string name);

Ex:- gets(s);

puts( ):- This function is used to display string to the standard O/P device.

Syntax:-puts(string name);

Ex:- puts(s);

program:

void main()
{
char s[10];
puts(“enter name”);
gets(s);
puts(“print name:”);
puts(s);
}
Output:

enter name ramu

print name : ramu

getch():- This function reads a single character directly from the keyboard without displaying
onthe screen. This function is used at the end of the program for displaying the output (without
pressing (Alt-F5).

Syntax: char variable_name = getch();

Ex:- char c;

c = getch();

getche():- This function reads a single character from the keyboard and echoes(displays) it tothe
current text window.

Syntax:-char variable_name = getche();

Ex:- char c;

c = getche();

Program:

void main()
{
char ch, c;
printf("enter char");
ch = getch();
printf("%c", ch);
printf("enter char");
c = getche();
printf("%c",c);
}
Output :-
enter character a
enter character b b

Character test functions:

ctype.h

Function Test

isalnum(c) Is c an alphanumeric character?

isalpha(c) Is c an alphabetic character

isdigit(c) Is c a digit?

islower(c) Is c alower case letter?

isprint(c) Is c a character?

ispunct(c) Is c a punctuation mark?

isspace(c) Is c a white space character?

isupper(c) Is c an upper case letter?

tolower(c) Convert c to lower case

toupper(c) Convert c to upper case

program:

void main()
{
char a,x;
printf(“enter char”);
a = getchar();
if (isupper(a))
{
x= tolower(a);
putchar(x);
}
else
putchar(toupper(a));
}
Output:-
enter char A
a

Formatted I/O Functions:

Formatted I/O refers to input and output that has been arranged ina particular format.

Formatted I/P functions---------- scanf( ) ,fscanf()

Formatted O/P functions -------- printf( ) ,fprintf()

scanf( ) :-scanf() function is used to read information from the standard I/P device.

Syntax:-scanf(“controlstring”, &variable_names);

Control string (also known as format string) represents the type of data that the user is going
to accept and gives the address of variable.

(char-%c , int-%d , float - %f , double-%lf).

Control string and variables are separated by commas. Control string and the variables going
to I/P should match with each other.

Ex:-int n;

scanf(“%d”,&n);

Inputting Integer Numbers:

The field specification for reading an integer number is: %w d

The percentage sign(%) indicates that a conversion specification follows. w is an integer number
that specifies the field width of the number to be read and d known as data type character
indicates that the number to be read is in integer mode.

Ex:-scanf(“%2d,%5d”,&a,&b);

The following data are entered at the console: 50

31426

Here the value 50 is assigned to a and 31426 to b


Inputting Real Numbers:

The field width of real numbers is not to be specified unlike integers. Therefore scanf reads
real numbers using the simple specification %f.

Ex: scanf(“%f %f”,&x,&y);

Suppose the following data are entered as input: 23.45 34.5 The

value 23.45 is assigned to x and 34.5 is assigned to y.

Inputting character strings:

The field specification for reading character strings is %ws or %wc

%c may be used to read a single character.

Ex:scanf(“%s”,name1);

Suppose the following data is entered as input:Griet

Griet is assigned to name1.

Formatted Output:

printf( ): This function is used to output any combination of data. The outputs are produced insuch a
way that they are understandable and are in an easy to use form. It is necessary for the programmer to
give clarity of the output produced by his program.

Syntax:- printf(“control string”, var1,var2……);

Control string consists of 3 types of items

1. Characters that will be printed on the screen as they appear.

2. Format specifications that define the O/P format for display of each item.

3.Escape sequence chars such as \n , \t and \b…..

The control string indicates how many arguments follow and what their types are.

The var1, var2 etc..are variables whose values are formatted and printed according to the
specifications of the control string.

The arguments should match in number, order and type with the format specifications
Example Program:

#include<stdio.h>
int main()
{
printf("%s\n","program");
printf("%3s\n","program");
printf("%12s\n","program");
printf("%-12s\n","program");
printf("%12.3s\n","program");
return 0;
}
Output:-
program
program
program
program
pro
UNIT-II
Conditional Branching and Loops: Conditional branching with if, if-else, nested if else, else if ladder, switch-case,
loops : for, while, do-while, jumping statements: goto, break, continue.
Arrays: one and two dimensional arrays, creating, accessing and manipulating elements of arrays.
Searching: Basic searching in an array of elements, linear and binary search.

Conditional Branching and Loops:

Writing and Evaluation of conditional statements (examples).


In C, when a logical operation is being evaluated, if the result is known before all sub expressions
have been evaluated, then the evaluation stops, or short circuits. The two situations where this can
occur is when the first expression of a logical AND operation is FALSE (zero) or the first expression
of a logical OR operation is TRUE (non-zero). In both of these cases, the result is already known. For
AND, if either of the two expressions is FALSE, the result will be FALSE. For OR, if either of the
two expressions is TRUE, then the result will be TRUE.
Example :
If we have two expressions being tested in a logical AND operation:
expr1 && expr2
The expressions are evaluated from left to right. If expr1is 0 (FALSE), then expr2would not be
evaluated at all since the overall result is already known to be false.
Truth table for AND (&&)
FALSE=0
TRUE=1

expr1 expr2 Result

0 X (0) 0

0 X (1) 0

1 0 0

1 1 1

Expr2is not evaluated in the first two cases since its value is not relevant to the result.

Examples:

1.if (5 || ++x)
{
printf("%d\n",x);
}

1
2.int x=0;
if(5||2&&++x)
printf("%d", x);

3.(a >= 0) && (b < 10)

4.(a > b) || (b++ / 3)

5. (13 * a) * (b/13 –1)

6 if((a || b || c || d || e || f || g || h ||i|| j || k)==1)

7.while((x &&y)==1)

8. if ((x < 10) && (y > 3))

What are control structures:

Control Structures / Statements In C Language

A program is nothing but the execution of sequence of one or more instructions. Quite often, it is
desirable to alter the sequence of the statements in the program depending upon certain circumstances.
(i.e., we have a number of situations where we may have to change the order of execution of statements
based on certain conditions) (Or)Repeat a group of statements until certain specified conditions are
met.This involves a kind of decision making to see whether a particular condition has occurred or not
and direct the computer to execute certain statements accordingly.

Based on application, it is necessary / essential


(i) To alter the flow of a program
(ii) Test the logical conditions
(iii) Control the flow of execution as per the selection these conditions can be placed in the program
using decision-making statements.

“C” SUPPORTS MAINLY THREE TYPES OF CONTROL STATEMENTS.

1.Decision making statements


a) Simple if Statement
b) if – else Statement
c) Nested if-else statement
d) else – if Ladder
e) switch statement

2.Loop control statements


a) for Loop
b) while Loop
c) do-while Loop

3.Unconditional control statements


a) goto Statement
b) break Statement
c) continue Statement
d) return statement
2
Conditional Branching:

Conditional statements help you to make decision based on certain conditions. These conditions are
specified by a set of conditional statements having boolean expressions whichare evaluated to a
boolean value true or false.
When we need to execute a block of statements only when a given condition is true and skip some
statements when the condition is false ,we then use branching or selection control structures in c.
There are the following types of conditional statements in C.
1. Simple ifstatement.
2. if…else statement.
3. Nested if…else statement.
4. else if ladder
5. switch case

if statement
if statement is used for branching when a single condition is to be checked. The condition enclosed in if statement
decides the sequence of execution of instruction. If the condition is true, the statements inside if statement are
executed, otherwise they are skipped. In C programming language, any non zero value is considered as true and zero
or null is considered false.

Syntax of if statement
if (condition)
{
statements;
... ... ...
}
Stmt x;

 if is the keyword.<condition>is a relational expression or logical expression or any expression that


returns either true or false. It is important to note that the condition should be enclosed within
parentheses ‘(‘ and ’)’.
 The stmt block can be a simple statement or a compound statement or a null statement.
 stmt-x is any valid C statement.
The flow of control using simple if statement is determined as follows:
Whenever simple if statement is encountered, first the condition is tested. It returns either true or
false.If the condition is false,the control transfers directly to stmt-x without considering the stmt
block.If the condition is true,the control enters into the stmtblock.Once,the endof stmt block is
reached, the control transfers to stmt-x.

3
Flowchart of if statement

Example of if statement
Example 1: C program to print the square of a number if it is less than 10.

#include<stdio.h>
void main()
{
int age;
printf("enter age\n");
scanf("%d",&age);
if(age>=55)
printf("person is retired\n");
printf(“END”);
}
Output:

enter age 57
person is retired
END
Example 2: C program to print the square of a number if it is less than 10.
#include<stdio.h>
int main()
{
int n;
printf("Enter a number:");
scanf("%d",&n);
if(n<10)
{
printf("%d is less than 10\n",n);
printf("Square = %d\n",n*n);
}
printf(“END”);
return 0;
}
4
Output
Enter a number:6
6 is less than 10
Square = 36
END

if else statement:
if…else statement is used to make a decision based on two choices. It has the following form:

Whenever if...else statement is encountered, first the condition is tested. It returns either true or false. If
the condition is true, the control enters into the true stmt block. Once, the end of true stmt block is
reached, the control transfers to stmt-x without considering else-body.

If the condition is false, the control enters into the false stmt block by skipping true stmt block. Once,
the end of false stmt block is reached, the control transfers to stmt-x.

Syntax:
if(condition)
{
truestmt block;
}
else
{
falsestmt block;
}
stmt-x;

FLOWCHART:

5
In this syntax,

 if and else are thekeywords.


 <condition>is a relational expression or logical expression or any expression that returns either true or
false. It is important to note that the condition should be enclosed within parentheses ( and ).
 The truestmtblock and false stmt block are simple statements or compound statements or null
statements.
 stmt-x is any valid Cstatement.

Program for if else statement:

Example1:c program to find a person is retired or not


#include<stdio.h>
int main()
{
int age;
printf("enter age\n");
scanf("%d",&age);
if(age>=55)
printf("person is retired\n");
else
printf("person is not retired\n");
return 0;
}

Output:
enter age 47 person is not retired

Example2:C program to find if a number is odd or even.

#include<stdio.h>
int main()
{
int n;
printf("Enter a number:");
scanf("%d",&n);
if(n%2 == 0)
printf("%d is even",n);
else
printf("%d is odd",n);
return 0;
}
Output:
Enter a number:5
5 is odd

6
Nested if Statements:

When a if statement is kept inside another if statement, it is called nested if statement. Nested if statements are
used if there is a sub condition to be tested. The depth of nested if statements depends upon the number of
conditions to be checked.

Syntax of nested if statement


if (condition 1)
{
statements;
if (sub condition 1)
{
statements;
}
statements;
}
else if (condition 2)
{
statements;
if (sub condition 2)
{
statements;
}
statements;
}
... ... ...
... ... ...
else
{
statements;
if (sub condition n)
{
statements;
}
statements;
}

7
Flow chart:

Example

Write a c program to print largest of three numbers:

#include<stdio.h>
int main ( )
{
int a, b,c;
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
printf("%d is big\n", a);
else
printf("%d is big\n", b);
}
else
{
if(c>b)
printf("%d is big\n" , c);
else
printf("%d is big\n" , b);
}
return 0;
}
8
Output:
10
20
30
30 is big

Example:

Write a c program if the number is even or odd, and then if it is even, whether it is divisible by 4 or not,
and if it is odd, whether it is divisible by 3 or not.

#include<stdio.h>
int main() {
int n;
scanf("%d",&n);
if (n % 2 == 0){
printf("Even ");
if (n % 4 == 0) {
printf("and divisible by 4");
} else {
printf("and not divisible by 4");
}
} else {
printf("Odd ");
if(n % 3 == 0) {
printf("and divisible by 3");
} else {
printf("and not divisible by 3");
}
}
return 0;
}

Output:
4
Even and divisible by 4

else if ladder statement


It is used when more than one condition is to be checked. A block of statement is enclosed inside if, else if and
else part. Conditions are checked in each if and else if part. If the condition is true, the statements inside that
block are executed. If none of the conditions are true, the statements inside else block are executed. A if … else
if … else statement must have only one if block but can have as many else if block as required. Else part is
optional and may be present or absent.

9
Syntax of else if ladder statement
if (condition 1)
{
statements;
... ... ...
}
else if (condition 2)
{
statements;
... ... ...
}
... ... ...
... ... ...
else if (condition n)
{
statements;
... ... ...
}else
{
statements;
... ... ...
}
Flow chart:

10
Example:
#include<stdio.h>
int main()
{
int day;
printf("Enter day number: ");
scanf("%d", &day);
if(day==1)
{
printf("SUNDAY.");
}
else if(day==2)
{
printf("MONDAY.");
}
else if(day==3)
{
printf("TUESDAY.");
}
else if(day==4)
{
printf("WEDNESDAY.");
}
else if(day==5)
{
printf("THURSDAY.");
}
else if(day==6)
{
printf("FRIDAY.");
}
else if(day==7)
{
printf("SATURDAY.");
}
else
{
printf("INVALID DAY.");
}
return(0);
}

OUTPUT:
Enter day number: 4
WEDNESDAY

11
Example Program:
void main()

int m1,m2,m3,avg,tot;

printf("enter three subject marks ");

scanf("%d%d%d", &m1,&m2,&m3);

tot=m1+m2+m3;

avg=tot/3;

if(avg>=75) {

printf("distinction"); }

else if(avg>=60 && avg<75) {

printf("first class"); }

else if(avg>=50 && avg<60) {

printf("second class"); }

else if (avg<50) {

printf("fail");

Output:
enter three subject marks 5 6 7
fail

12
Switch Statement:
switch statement is one of decision-making control-flow statements. Just like else if ladder, it is also
used to make a decision among multiple choices. switch statement has the following form:

Syntax:

switch(<exp>)
{
case<exp-val-1>: statements block-1;
break;
case<exp-val-2>: statements block-2;
break;
case<exp-val-3>: statements block-3;
break;
case<exp-val-N>: statements block-N;
break; default: default statements
block;
}
Next-statement;

In this syntax,

 switch, case, default and break arekeywords.


 <exp>is any expression that should give an integer value or character value. In other words,it
should never return any floating-point value. It should always be enclosed with in parentheses
( and ). It should also be placed after the keyword switch.
 <exp-val-1>, <exp-val-2>, <exp-val-3>…. <exp-val-N>should always be integer constants
or character constants or constant expressions.In otherwords,variables can never be used as
<exp-val>. There should be a space between the keyword case and <exp-val>. The keyword
case along with its<exp-val> is called as a case label.<exp-val>should always be unique;no
duplications are allowed.
 statements block-1, statements block-2, statements block-3… statements block-N and default
statementsblock are simple statements,compound statements or null statements.It is important
to note that the statements blocks along with their own case labels should be separated with a
colon ( :)
 The break statement at the end of each statements block is an optional one. It is recommended
that break statement always be placed at the end of each statements block.With its absence,all
the statements blocks below the matched case label along with statements block of matched
case get executed. Usually, the result isunwanted.

 The statement block and break statement can be enclosed with in a pair of curly braces{and}.
 The default along with its statements block is an optional one. The break statement can be
placed at the end of default statements block. The default statements block can be placed at
anywhere in the switch statement. If they are placed at any other place other than at end, it is
compulsory to include a break statement at the end of default statements block.
13
 Next-statement is a valid Cstatement.

Whenever, switch statement is encountered, first the value of <exp>gets matched with case values. If
suitable match is found, the statements block related to that matched case gets executed. The break
statement at the end transfers the control to the Next-statement.

If suitable match is not found, the default statements block gets executed and then the control gets
transferred to Next-statement.

Example:
#include <stdio.h>
int main()
{
char gender;
printf("Enter gender (M/m or F/f): ");
scanf("%c",&gender);

switch(gender)
{
case 'M':
case 'm':
printf("Male.");
break;
case 'F':
case 'f':
printf("Female.");
break;
default:
printf("Unspecified Gender.");
}
printf("\n");
return 0;
}
14
OUTPUT:
Enter gender (M/m or F/f): f
Female.

Example Program:

#include<stdio.h>
void main()
{
int a,b,c,ch;
printf("\nEnter two numbers :");

scanf("%d%d",&a,&b);
printf("\nEnter the choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: c=a+b;
break; case 2: c=a-b;
break; case 3: c=a*b;
break; case 4: c=a/b;
break;
default: printf(“ enter a valid choice \n”);
}
printf("\nThe result is: %d",c);
}
Output: enter the choice 1

Enter two numbers 4 2

Use of switch statement:

 We can use switch statements alternative for an if...elseladder.


 The switch statement is often faster than nested if...elseLadder.
 Switch statement syntax is well structured and easy to understand.

Iteration and Loops: while, do-while, for loops.

It is the process where a set of instructions or statements is executed repeatedly for a specified
number of time or until a condition is satisfied.These statements also alter the control flow of
the program. It can also be classified as control statements in C Programming Language.

Iteration statements are most commonly known as loops.

15
There are three types of looping statements:

1. while Loop
2. do while loop

3. forloop

1. while Loop:
The simplest of all the looping structures in c is the
while statement. A WHILE loop has one control Flow chart for while loop
expression, andexecutes as long as that expression
is true.
The basic format of the while statement is:

Syntax:

while(condition)

statements;

The while is an entry–controlled loop statement.Thecondition is evaluated and if the condition is true
then the statements will be executed. After execution of the statements the condition will be evaluated
and if it is true the statements will be executed once again.
This process is repeated until the condition becomes false and the control is transferred out of the
loop.On exit the program continues with the statement immediately after the body of theloop.

Program to print n natural numbers using using while

#include<stdio.h>
void main()
{
int i,n;
printf("enter the range\n");
scanf("%d",&n);
i=1;
while(i<=n)
{
printf("%d ",i);
i=i+1;
}
}

Output: enter the range 10

1 2 3 4 5 6 7 8 9 10
16
2. do while statement:
It is one of the looping control statements. It is also called as exit-controlled looping control
statement. i.e., it tests the condition after executing the do-while loop body.
The main difference between “while” and “do-while” is that in “do-while” statement, theloop body
gets executed at least once, though the condition returns the value false for the firsttime, which is not
possible with while statement. In “while” statement, the control enters into the loop body only when
the condition returnstrue.
Flow chart for do while
Syntax:

Initialization statement;

do

statement(s);

} while(<condition>);

next statement;

In this syntax:

While and do are the keywords.<condition>is a relational expression or a compound relational


expression or any expression that returns either true or false. initialization statement, statement(s) and
next_statement are valid ‘c’statements.

The statements within the curly braces are called as do-while loop body. The updating statement
should be included within the do-while loop body.There should be a semi-colon(;) at the end of
while(<condition>).

Whenever “do-while” statement is encountered, the initialization statement gets executed first. After
then, the control enters into do-while loop body and all the statements in that body will be executed.
When the end of the body is reached, the condition is tested again with the updated loop counter
value.

If the condition returns the value false, the control transfers to next statement without executing do-
while loop body. Hence, it states that, the do-while loop body gets executed for the first time, though
the condition returns the value false.

17
Program to print n natural numbers using using do while

#include<stdio.h>
void main()
{
int i,n;
printf("enter the range\n");
scanf("%d",&n);
i=1;
do{
printf("%d ",i);
i=i+1;
}
while(i<=n);}
Output: enter the range 8
12345678

Difference Between while and do-while loop


Parameters while do-while
Checking of Condition It first needs to check the The execution of statement(s) occurs
condition, and only then can at least once. After that, the checking
we execute the statement(s). of the condition occurs.
Semicolon while(condition) while(condition);
No semicolon is present at the A semicolon is present at the end of
end of the while loop. the do-while loop.
Requirement of Brackets We don’t require any brackets We would always require brackets in
if there is only a single this case.
statement.
Initialization of Variables We always need to initialize a The initialization of the variable may
variable in a condition before occur within or before the execution
the execution of this loop. of the loop.
Controlling The while loop is an entry- The do-while loop is an exit-
controlled type of loop. controlled type of loop.

3. for statement:
It is one of the looping control statements. It is also called as entry-controlled looping control
statement. i.e., it tests the condition before entering into the loop body. The syntax for “for” statement
is as follows:
Syntax:

for(exp1;exp2;exp3)

for-body;

}next_statement;

18
In this syntax,

for is a keyword. exp1 is the initialization statement. If there is more than one statement, then
the statements must be separated with commas. exp2 is the condition. It is a relational expression or a
compound relational expression or any expression that returns either true or false.The exp3 is the
updating statement.If there ismore than one statement then,they must be separated with commas.
exp1, exp2 and exp3 should be separated with two semi-colons. exp1, exp2, exp3, for-body and
next_statement are valid ‘c’ statements. for-body is a simple statement or compound statement or a
nullstatement.

Whenever “for” statement is encountered,first exp1 gets executed.After then,exp2 is tested.If exp2 is
true then the body of the loop will be executed otherwise loop will beterminated.

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 exp3 will be evaluated and the new value is again tested
.if it satisfies body of the loop is executed .This process continues till condition isfalse.

Program to print n natural numbers using for loop

#include<stdio.h>
void main()
int i,n;
printf("enter the value");
scanf("%d",&n);
for(i=1;i<=n;i++)
printf("%d\n",i);
}

Output: enter the value 5

1
2
3
4
5

Nested for Loop:

Nested for loop refers to the process of having one loop inside another loop. We can have
multiple loops inside one another. The body of one ‘for’ loop contains the other and so on. The
syntax of a nested for loop is as follows(using two for loops):

19
Syntax:

for(initialization ; condition; update)


{
for(initialization ;condition;update) //using anothervariable
{
body of the inner loop
}
body ofouterloop //(might or might not be present)

Example Program :

#include<stdio.h>
void main()
{
inti,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",j);
}
printf("\n");
}
}

Output:
1
12
123
1234
12345

The syntax for a nested while loop statement in C programming language is as follows -

Syntax:

while(outer condition)

{
outer while statements;

while(inner condition)

{
inner while statements;
}

outer while statements;


}
20
WAP to print the following format.
Example1:

1
12
123
1234
12345

Program1:
#include <stdio.h>
int main ()
{
int i, n, in;
printf ("ENTER A NUMBER ");
scanf ("%d", &n);
i = 1;
while (i <= n)
{
printf ("\n");
in = 1;
while (in <= i)
{
printf ("%d ", in);
in = in + 1;
}
i = i + 1;
}
return 0;
}
21
Output:
1
12
123
1234
12345

The syntax for a nested do...while loop statement in C programming language is as follows −
Syntax:
Statements;

do
{
Statements;
do
{
Statements;

}while( condition );

Statements;
}
while( condition );

FLOWCHART:

22
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j;
i=1;
printf("Triangle number pattern\n");
printf("Here your pattern\n");
do{
j=1;
do{
printf("%d",j);
j++;
}while(j<=i);
printf("\n");
i++;
}while(i<=9);
getch();
return 0;
}
OUTPUT:

Triangle number pattern


Here your pattern
1
12
123
1234
12345
123456
1234567
12345678
123456789

Types of Jump Statements in C


There are 4 types of Jump statements in C language.

1. Break Statement
2. Continue Statement
3. Goto Statement
4. Return Stateme

1.Break Statement :
Break Statement in C is a loop control statement that is used to terminate the loop. There are two usages and the
given statement is explained below.
Inside a Loop: If the break statement is using inside a loop along with the if statement then if the condition
becomes true the loop is immediately terminated and the next statement after the loop starts executing by the
program control.
Inside a Switch Case: If Break Statement in C is using inside a switch case after each switch case then the
break statement terminates a case after executing the case.

23
In general the break statements we used in the situations where we need to stop the loop execution based on the
condition or not sure how many times the loop is to be iterate. If the break statements using inside the nested
loop, then the break statement breaks the inner loop and starts executing the statement after the inner loop of the
program control continue to the outer loop.

Syntax of Break Statement

break;

Any loop
{
statement_1;
statement_2;
break;
:
}
next_statement;

Flowchart of Break Statement

Flowchart of the break statement in the loop:

The break statement is written inside the loop.


First, the execution of the loop starts.
If the condition for the loop is true, then the body of the loop executes; otherwise, the loop terminates.
If the body of the loop executes, the break condition written inside the body is checked.
If it is true, it immediately terminates the loop; otherwise, the loop keeps executing until it meets the break
condition or the loop condition becomes false.

24
Example:
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 15; i++) {
printf("%d\n", i);
if (i == 10)
break;
}
return 0;
}

OUTPUT:
1
2
3
4
5
6
7
8
9
10

2. continue Jump Statement


The continue jump statement like any other jump statement interrupts or changes the flow of control
during the execution of a program. Continue is mostly used in loops.
Rather than terminating the loop it stops the execution of the statements underneath and takes control
to the next iteration.
Similar to a break statement, in the case of a nested loop, the continue passes the control to the next
iteration of the inner loop where it is present and not to any of the outer loops.
Let’s implement an example to understand how continue statement works in C language.

Syntax for continue statement is:

Any loop
{
statement_1;
statement_2;
.....
continue;
......
}
next_statement;

25
Flowchart:

Example:
#include <stdio.h>
int main() {
int i, j;
for (i = 1; i < 3; i++) {
for (j = 1; j < 5; j++) {
if (j == 2)
continue;
printf("%d\n", j);
}
}
return 0;
}
Output:
1
3
4
1
3
4

In this program, we see that the printf() instruction for the condition j=2 is skipped each time during the
execution because of continue. We also see that only the condition j=2 gets affected by the continue. The outer
loop runs without any disruption in its iteration.

3.'goto' Statement in C language


goto is a jumping statement in c language, which transfer the program’s control from one statement to another
statement (where label is defined).
goto can transfer the program’s within the same block and there must a label, where you want to transfer
program’s control.

Defining a label
Label is defined following by the given syntax
26
label_name:

• label_name should be a valid identifier name.


• : (colon) should be used after the label_name.

Transferring the control using ‘goto’

Program’s control can be transfer following by the given syntax


goto label_name
Syntax1:
label-name:
statement1;
statement2;
..
if(any-test-condition)
goto label-name;

Flowchart:

Example1:
/*To print numbers from 1 to 10 using goto statement*/
#include <stdio.h>
int main()
{
int number;
number=1;
repeat:
printf("%d\n",number);
number++;
if(number<=10)
goto repeat;
return 0;
}

27
OUTPUT:

1
2
3
4
5
6
7
8
9
10

Syntax2:

statements;
if(any-test-condition)
goto label-name;
statement1;
statement2;
label-name:
Other statements;

Example2:
#include <stdio.h>
int main()
{
int number;

printf("Enter an integer number: ");


scanf("%d",&number);

if(number<=0)
goto end;
printf("Number is : %d\n", number);

end:
printf("Bye Bye !!!");
return 0;
}
OUTPUT:
Enter an integer number: 0
Bye Bye !!!

28
Difference Between the break and continue statement:

Break Statement Continue Statement

The Break statement is used to exit from the loop The continue statement is not used to exit from the
constructs. loop constructs.

The break statement is usually used with the switch The continue statement is not used with the switch
statement, and it can also use it within the while loop, statement, but it can be used within the while loop,
do-while loop, or the for-loop. do-while loop, or for-loop.

When the continue statement is encountered then


When a break statement is encountered then the the control automatically passed from the beginning
control is exited from the loop construct immediately. of the loop statement.

Syntax: Syntax:
break; continue;

4. Return Jump Statement


Return jump statement is usually used at the end of a function to end or terminate it with or without a
value. It takes the control from the calling function back to the main function(main function itself can
also have a return).
An important point to be taken into consideration is that return can only be used in functions that is
declared with a return type such as int, float, double, char, etc.
The functions declared with void type does not return any value. Also, the function returns the value
that belongs to the same data type as it is declared. Here is a simple example to show you how
the return statement works.
Let’s implement an example to understand return statement in C language.
Example:
#include <stdio.h>
char func(int ascii)
{
return ((char) ascii);
}
int main() {
int ascii;
char ch;
printf("Enter any ascii value in decimal: \n");
scanf("%d", & ascii);
ch = func(ascii);
printf("The character is : %c", ch);
return 0;
}
OUTPUT:
Enter any ascii value in decimal:
110
The character is : n

29
In this program, we have two functions that have a return type but only one function is returning a value[func()]
and the other is just used to terminate the function[main()].
The function func() is returning the character value of the given number(here 110). We also see that the return
type of func() is char because it is returning a character value.
The return in main() function returns zero because it is necessary to have a return value here because main has
been given the return type int.

Exit :
The C library function void exit(int status) terminates the calling process immediately.This function does not
return any value.

void exit(int status)

//Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Start oftheprogram. \n");
printf("Exitingtheprogram. \n");
exit(0);
printf("End oftheprogram. \n");
return(0);
}

Output:
Start of the program....
Exitingtheprogram....

30
ARRAYS
Contents

Arrays: One and Two Dimensional arrays, creating, accessing and manipulating elements of
arrays.
Searching: Introduction to Searching, Linear Search and Binary Search.

ARRAYS
Introduction:
So far we have used only single variable name for storing one data item. If we need to store
multiple copies of the same data then it is very difficult for the user. To overcome the difficulty a
new data structure is used called arrays.
An array is a linear and homogeneous data structure
An array permits homogeneous data. It means that similar types of elements are stored
contiguously in the memory under one variable name.
An array can be declared of any standard or custom data type.
Example of an Array:
Suppose we have to store the roll numbers of the 100 students the we have to declare 100
variables named as roll1, roll2, roll3, ……. roll100 which is very difficult job. Concept of C
programming arrays is introduced in C which gives the capability to store the 100 roll numbers
in the contiguous memory which has 100 blocks and which can be accessed by single variable
name.
1. C Programming Arrays is the Collection of Elements
2. C Programming Arrays is collection of the Elements of the same data type.
3. All Elements are stored in the Contiguous memory
4. All elements in the array are accessed using the subscript variable (index).
Pictorial representation of C Programming Arrays

The above array is declared as int a [5];


a[0] = 4; a[1] = 5; a[2] = 33; a[3] = 13; a[4] = 1;
In the above figure 4, 5, 33, 13, 1 are actual data items. 0, 1, 2, 3, 4 are index variables.
Index or Subscript Variable:
1. Individual data items can be accessed by the name of the array and an integer enclosed
in square bracket called subscript variable / index
2. Subscript Variables helps us to identify the item number to be accessed in the contiguousmemory.
What is Contiguous Memory?
1. When Big Block of memory is reserved or allocated then that memory block is called as
Contiguous Memory Block.
2. Alternate meaning of Contiguous Memory is continuous memory.
3. Suppose inside memory we have reserved 1000-1200 memory addresses for special purposes
then we can say that these 200 blocks are going to reserve contiguous memory.
Contiguous Memory Allocation
1. Two registers are used while implementing the contiguous memory scheme. These registers are
base register and limit register.
2. When OS is executing a process inside the main memory then content of each registerare as

Register Content of register

Base register Starting address of the memory location where


process execution is happening

Limit register Total amount of memory in bytes consumed by


process

Here diagram 1 represents the contiguous allocation of memory and diagram 2 represents non-
contiguous allocation of memory.
3. When process try to refer a part of the memory then it will firstly refer the base address from base
register and then it will refer relative address of memory location with respect tobase address.

Examples where the concept of an array can be used are:


 List of employees in an organization
 List of products and their cost
 Test scores of a class of students.
 List of customers and their telephone numbers. Etc..

Since an array provides a convenient structure for representing data, it is classified as one of
the data structures in C.
Types of Arrays :

1. One-dimensional arrays
2. Two-dimensional arrays
3. Multi-dimensional arrays.
ONE-DIMENSIONAL ARRAYS:

A list of items can be given one variable name using only one subscript and such a
variable is called a single-subscripted variable or a one-dimensional array.

DECLARATION OF ONE-DIMENSIONAL ARRAYS:

Like any other variable, arrays must be declared before they are used so that the
compiler can allocate space for them in memory.

Syntax:
Type variable-name [size];

 The type specifies the type of element that will be contained in the array, such
as int, float or char.
 The size indicates the maximum number of elements that can be stored inside the array

For e.g.-

int number[5];

Declares the number to be an array containing 5 elements. Any subscripts 0 to 4 are


valid and the computer reserves five storage locations as shown below

number[0]
number[1]
number[2]
number[3]
number[4]

Note :

1. Any reference to the arrays outside the declared limits would not
necessarily cause an error. Rather, it might result in unpredictable program
results.
2. The size should be either a numeric constant or a symbolic constant.

INITIALIZATION OF ONE-DIMENSIONAL ARRAYS:

After an array is declared, its elements must be initialized. Otherwise, they will contain “garbage”. An
array can be initialized at either of the following stages:

 At Compile time

 At run time
COMPILE TIME INITIALIZATION :

We can initialize the elements of arrays in the same way as the ordinary variables when they are declared.

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

The values in the list are separated by commas. For example, the statement
int number [5] = { 35, 40, 50, 20, 25 };

Will declare the variable number as an array of size 5 and will assign the value to each
element as follows

number [0] 35
number[1] 40

number[2] 50

number[3] 20

number[4] 25

If the number of values in the list is less than the number of elements, then only that many elements will
be initialized. The remaining elements will be set to zero automatically if the array type is numeric and
NULL if the type is char.

For e.g:- float total[5]={0.0,5.2,-10};


Will initialize the first three elements to 0.0, 5.2 and -10.0 and the remaining two elements to zero.

If we have more initializes than the declared size, the compiler will produce an error.
int number[3]={10,20,30,40}; is illegal in C.
The size may be omitted in the declaration statement. In such cases, the compiler allocates
enough space for all initialized elements.

For e.g.-int count[ ]={1,1,1,1};

Will declare the count array to contain four elements with initial values 1. This approach works fine
as long as we initialize every element in the array.
Character arrays may be initialized in a similar manner. Thus the statement
char name[]={‘h’,’e’,’l’,’l’,’o’,’\0’};

Declares the name to be array of five characters, initialized with the string “hello” ending
with the null character. Alternatively we can assign the string literal directly as

char name[]=”hello”;

RUN TIME INITIALIZATION

An array can be explicitly initialized at run time. This approach is usually applied for initializing
large arrays. For example, consider the following segment of C program
for(i=0;i<100;i=i+1)
{
if(i<50)
sum[i]=0.0;
else sum[i]=1.0;
}
The first 50 elements of the array sum are initialized to 0 while the remaining 50 are
initialize to 1.0 at run time.
We can also use a read function such as scanf to initialize an array. For example, the
statements
int x[3];
scanf(“%d%d%d”,&x[0],&x[1],&x[2]);
will initialize array elements with the values entered through the key board.
EXAMPLE PROGRAMS :

1. C Program for deletion of an element from the specified locationfrom an Array


#include<stdio.h>
int main() {
int arr[30], num, i, loc;
printf("\nEnter no of elements:");
scanf("%d", &num);
//Read elements in an array
printf("\nEnter %d elements :", num);
for (i = 0; i < num; i++)
{
scanf("%d", &arr[i]);
}
//Read the location
printf("\nLocation of the element to be deleted :");

scanf("%d", &loc);
/* loop for the deletion */
while (loc < num)
{
arr[loc - 1] = arr[loc];
loc++;
}
num--;
// No of elements reduced by 1
//Print Array
for (i = 0; i < num; i++)
printf("\n %d", arr[i]);

return (0);
}
Output:
Enter no of elements: 5 Enter 5 elements: 3
4178
Location of the element to be deleted: 33 4 7 8
2.C Program to delete duplicate elements from an array
int main()
{
int arr[20], i, j, k, size;

printf("\nEnter array size: ");

scanf("%d", &size);

printf("\nAccept Numbers: ");

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

scanf("%d", &arr[i]);
printf("\nArray with Unique list: ");
for (i = 0; i < size; i++)
{
for (j = i + 1; j < size;)
{
if (arr[j] == arr[i])
{
for (k = j; k < size; k++)
{
arr[k] = arr[k + 1];
}
size--;
}
else
j++; }
}
for (i = 0; i < size; i++)
{

printf("%d ", arr[i]);

return (0);
}
Output:
Enter array size: 5 Accept Numbers: 1 3
453
Array with Unique list: 1 3 4 5
3.C Program to insert an element in an array
#include<stdio.h>

int main() {
int arr[30], element, num, i, location;
printf("\nEnter no of elements:");
scanf("%d", &num);
for (i = 0; i < num; i++)
{
scanf("%d", &arr[i]);
}
printf("\nEnter the element to be inserted:");
scanf("%d", &element);
printf("\nEnter the location");
scanf("%d", &location);
//Create space at the specified location
for (i = num; i >= location; i--)
{
arr[i] = arr[i - 1];
}
num++;
arr[location - 1] = element;
//Print out the result of insertion

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


printf("n %d", arr[i]);
return (0);
}
Output:
Enter no of elements: 51 2 3 4 5
Enter the element to be inserted: 6 Enter the location:
2
1 62345
4.C Program to search an element in an array
#include<stdio.h>

int main() {
int a[30], ele, num, i; printf("\nEnter no of
elements:");
scanf("%d", &num);
printf("\nEnter the values :");
for (i = 0; i < num; i++)
{
scanf("%d", &a[i]);
}
//Read the element to be searched
printf("\nEnter the elements to be searched :");
scanf("%d", &ele);
//Search starts from the zeroth location
i = 0;
while (i < num && ele != a[i])
{
i++;
}
//If i < num then Match found
if (i < num) {
printf("Number found at the location = %d", i + 1);
}
else {
printf("Number not found");

}return (0);
}
Output:
Enter no of elements: 511 22 33 44 55
Enter the elements to be searched: 44 Number found at
the location = 4
5.C Program to copy all elements of an array into another array
#include<stdio.h>

int main() {
int arr1[30], arr2[30], i, num;
printf("\nEnter no of elements:");
scanf("%d", &num);
//Accepting values into Array
printf("\n Enter the values:");
for (i = 0; i < num; i++)
{
scanf("%d", &arr1[i]); }
/* Copying data from array 'a' to array 'b */
for (i = 0; i < num; i++)
{
arr2[i] = arr1[i]; }
//Printing of all elements of array

printf("The copied array is:");

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


printf("\narr2[%d] = %d", i, arr2[i]);
return (0);
}
Output:
Enter no of elements: 5
Enter the values: 11 22 33 44 55
The copied array is: 11 22 33 44 55

Programs for Practice


1 C Program to display array elements with addresses
2 C Program for Reading and printing Array Elements
3 C Program to calculate Addition of All Elements in Array
4 C Program to find Smallest Element in Array
5 C Program to find Largest Element in Array
6 C Program to reversing an Array Elements

TWO- DIMENSIONAL ARRAYS:


1D array variables stores a list of values only but there could be a situations where
a table of values have to be stored which need 2D arrays. For examples
 Periodic table
 Sales information of a company
 Data in spread sheets etc.

The two dimensional (2D) array in C programming is also known as matrix. A


matrix can be represented as a table of rows and columns. A particular value in a
matrix can be accessed by using two subscripts such as Vij . here V denotes the
entire matrix and Vij refers to the value in the ith row and jth column. An array of
arrays is known as 2D array.

Syntax:

type array-name[row_size][column_size];

2D arrays are stored in memory as shown below :

[0][0] [0][1] [0][2]


Row 0 ---- 310 275 365

[1][0] [1][1] [1][2]

→ 10 190 325
Row 1 ----
INITIALIZING 2D ARRAYS:
Like the 1D arrays, 2D arrays can be initialized by following their declaration with
a list of initial values enclosed in braces. For example

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

Initializes the elements of the first row to zero and the second row to one. The initialization
is done row by row. The above statement is equivalently written as int
table[2][3]={{0,0,0},{1,1,1}};

by surrounding the elements of each row by braces.

We can also initialize a two-dimensional array in the form of a matrix as shown below:
int table[2][3]={
{0,0,0},
{1,1,1}
};
When the array is completely initialized with all values, explicitly, we need not specify
the size of the first dimension. That is, the below statement is permitted.

int table[][3]= ]={


{0,0,0},
{1,1,1}
};
If the values are missing in an initialize, they are automaticaaly set to zero.
For example int table[2][3]={ {1,1},{2}};

Will initialize the first two elements of the first row to one, the first element of the
second row to two, and all other elements to zero.When all the elements are to
be initialized to zero, the following short-cut method may be used.
int m[3][5]={{0},{0},{0}};
the first element of each row is explicitly initialized to zero while other
elements are automatically initialized to zero.

Example program:

#include<stdio.
> void main()
{
int
disp[2][3];
int i, j;
for(i=0; i<2; i++)
{
for(j=0;j<3;j++)
{
printf("Enter value fordisp[%d][%d]:",i,j);
scanf("%d", &disp[i][j]);
}
}
//Displaying array elements
printf("Two Dimensional array elements:\n");
for(i=0; i<2; i++)
{
for(j=0;j<3;j++)
{
printf("%d ",
disp[i][j]);
if(j==2)
{
printf("\n");
}
}
}

}
Multidimensional arrays :
C allows arrays of three or more dimensions. The exact limit is determined by the compiler.
Syntax:
type array-name[s1][s2][s3] ------------------------ [sm];

Where si is the size of the ith dimension.

e.g.- int a[3][3][3];


int b[5][4][5][3];
A 3D array is essentially an array of arrays of arrays: it's an array or collection of 2D arrays,
and a 2D array is an array of 1D
array.
Initializing 3d array:
int arr[3][3][3]= { {
{11, 12, 13},
{14, 15, 16},
{17, 18, 19}
},

{
{21, 22, 23},
{24, 25, 26},
{27, 28, 29}
},
{
{31, 32, 33},
{34, 35, 36},
{37, 38, 39}
}
};
Example Programs:
1.Develop a program to Find the Largest Two Numbers in a given Array and also
Calculate their average

include <stdio.h>

#define MAX 4

void main()

int array[MAX], i, largest1, largest2, temp;

printf("Enter %d integer numbers \n", MAX); for

(i = 0; i < MAX; i++)

printf("Input interger are \n");

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

printf("%5d", array[i]);

printf("\n");

/* assume first element of array is the first


larges t*/ largest1 = array[0];

/* assume first element of array is the second


largest */ largest2 = array[1];

if (largest1 < largest2)

{
temp = largest1;
largest1 =
largest2; largest2
= temp;
}
for (i = 2; i < 4;i++)
{
if (array[i] >= largest1)
{
largest2 =
largest1; largest1
= array[i];
}

else if (array[i] > largest2)


{
largest2 = array[i];
}
}

printf("n%d is the first largest \n", largest1);


printf("%d is the second largest \n", largest2);
printf("nAverage of %d and %d = %d \n", largest1, largest2,(largest1 + largest2) / 2);
}

Output:
Enter 4 integer numbers
80
23
79
58
Input integer are
80 23 79 58
80 is the first largest
79 is the second
largest
Average of 80 and 79 = 79

Implement a program to insert an elements of an Array in the required position


#include <stdio.h>
int main()
{
int array[100], position, c, n, value;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d elements\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the location where you
wish to insert an element\n");
scanf("%d", &position);
printf("Enter the value to
insert\n"); scanf("%d",
&value);
for (c = n - 1; c >= position - 1; c--)
array[c+1] = array[c];
array[position-1] =
value;
printf("Resultant
array is\n"); for (c =
0; c <= n; c++)
printf("%3d",
array[c]); return
0;
}

Output:
Enter the value of the n = 4
Enter the numbers 3
40
100
68
Enter the location where you wish to insert an element 2
Enter the value to insert 35
3 35 40 100 80
3. Develop a program to reverse an array
#include <stdio.h> void main()
{
int n, c, d, a[100], b[100];
printf("Enter the number of elements in array\n"); scanf("%d", &n);
printf("Enter the array elements\n"); for (c = 0; c < n ; c++)
scanf("%d", &a[c]);
for (c = n - 1, d = 0; c >= 0; c--, d++) b[d] = a[c];
for (c = 0; c < n; c++)
a[c] = b[c];
printf("Reverse array is\n");
for (c = 0; c < n; c++)
printf("%d\n", a[c]);
}

4.Program to add two matrices


#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],r1,r2,c1,c2,i,j;
clrscr();
printf("\n enter r1,c1,r2,c2");
scanf("%d %d %d %d",&r1,&c1,&r2,&c2); if(r1==r2&&c1==c2)
{
printf("\n matrix addition possible"); for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("\n enter a[%d][%d]:",i,j);
scanf("%d",&a[i][j]);
}
}
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("\n enter b[%d][%d]:",i,j);
scanf("%d",&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf("\n sum of matrix c:");
for(i=0;i<r1;i++)
{
printf("\n"); for(j=0;j<c1;j++)
{
printf("\t%d",c[i][j]);
}
}
else
{
printf("\n matrix multiplication is not possible");
}
getch();
}
3. Program to multiply two matrices

#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],r1,r2,c1,c2,i,j,k;
clrscr();
printf("\n enter r1,c1,r2,c2");
scanf("%d %d %d %d",&r1,&c1,&r2,&c2); if(r1==r2&&c1==c2)
{
printf("\n matrix mutliplication possible"); for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("\n enter a[%d][%d]:",i,j);
scanf("%d",&a[i][j]);
}
}
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("\n enter b[%d][%d]:",i,j);
scanf("%d",&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
c[i][j]=0;
for(k=0;k<c1;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("\n product of matrix c:"); for(i=0;i<r1;i++)
{
printf("\n"); for(j=0;j<c2;j++)
{
printf("\t%d",c[i][j]);
}
}
}
else
{
printf("\n matrix multiplication is not possible");
}
getch();
}
4.Program to display the transpose of a matrix

#include<stdio.h>
#include<conio.h>
void main()
{
int row,col,a[5][5],i,j,b[5][5];
clrscr();
printf("\n enter order of matrix r,c:");
scanf("%d %d",&row,&col);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("\n enter a[%d][%d]:",i,j);
scanf("%d",&a[i][j]);
}
}
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
b[j][i]=a[i][j];
}
}
printf("\n transpose matrix b");
for(i=0;i<col;i++)
{
printf("\n");
for(j=0;j<row;j++)
{
printf("\t %d",b[i][j]);
}
}
getch();
}
SEARCHING:

Searching is a technique of finding an element from the given data


list or set of the elements like an array, list, or trees. It is a technique to find
out an element in a sorted or unsorted list. For example, consider an array
of 10 elements. These data elements are stored in successive memory
locations. We need to search an element from the array. In the searching
operation, assume a particular element n is to be searched. The element n
is compared with all the elements in a list starting from the first element of
an array till the last element. In other words, the process of searching is
continued till the element is found or list is completely exhausted. When
the exact match is found then the search process is terminated. In case, no
such element exists in the array, the process of searching should be
abandoned.

LINEAR SEARCH:
Linear search technique is also known as sequential search
technique. The linear search is a method of searching an element in a list
in sequence. In this method, the array is searched for the required
element from the beginning of the list/array or from the last element to
first element of array and continues until the item is found or the entire
list/array has been searched.

Algorithm:
Step 1: set-up a flag to indicate
“element not found”
Step 2: Take the first element
in the list
Step 3: If the element in the list is equal to the desired element
 Set flag to “element found”
 Display the message “element found in the list”
 Go to step 6
Step 4: If it is not the end of list,
 Take the next element in the list
 Go to step 3
Step 5: If the flag is “element not found”
Display the message “element not found”
Step 6: End of the Algorithm
Advantages:
1. It is simple and conventional method of searching data. The linear or
sequential name implies that the items are stored in a systematic
manner.
2. The elements in the list can be in any order. i.e. The linear search
can be applied on sorted or unsorted linear data structure.
Disadvantage:
1. This method is insufficient when large number of elements is present in list.
2. It consumes more time and reduces the retrieval rate of the system.
Time complexity: O(n)
BINARY

SEARCH:

Binary search is quicker than the linear search. However, it cannot be


applied on unsorted data structure. The binary search is based on the
approach divide-and-conquer.The binary search starts by testing the data in
the middle element of the array. This determines target is whether in the first
half or second half. If target is in first half, we do not need to check the
second half and if it is in second half no need to check in first half. Similarly
we repeat this process until we find target in the list or not found from the
list. Here we need 3 variables to identify first, last and middle elements.
To implement binary search method, the elements must be in sorted order.
Search is performed as follows:
1. The key is compared with item in the middle position of an array
2. If the key matches with item, return it and stop
3. If the key is less than mid positioned item, then the item to be found
must be in first half of array, otherwise it must be in second half of
array.
4.Repeat the procedure for lower (or upper half) of array until the element is
found.

Recursive Algorithm:
Binary Search (a,key,lb,ub) begin
Step 1:[initialization] lb=0,ub=n-1;
Step 2:[search for the item] Repeat through step 4 while lower bound(lb) is less than
upper bound.
Step 3:[obtain the index of middle value] mid = (lb+ub)/2
Step 4:[compare to search for item] if(key < a[mid]) then ub=mid-1
otherwise if( key > a[mid]) then lb=mid+1;
otherwise if(key==a[mid]) Write “match found” return (mid)
returnBinary_Search(a,key,lb,ub)
Step 5:[unsuccessful search] Write “match not found”
Step 6:[end of algorithm]
/* C program that searches a value in a stored array using linear search.*/

#include<stdio.h>
int linear(int [ ],int,int);
void main( )
{
int a[20], pos = -1, n, k, i;
clrscr( );
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:");
for(i=0; i<n ;i++)
scanf("%d",&a[i]);
printf("\nEnter the element to be searched:");
scanf("%d",&k);
pos=linear(a,n,k);
if(pos != -1)
printf("\n Search successful element found at position %d",pos);
else
printf("\n Search unsuccessful, element not found");
getch( );
}
int linear(int a[ ],intn,int k)
{
int i; for(i=0;i<n;i++)
{
if(a[i]==k)
return(i);
}
return -1;
}
Output:-
Enter the n value : 5
Enter elements for an array : 11 2 23 14 55
Enter the element to be searched: 14
Search successful element found at position : 3

/* C program for recursive binary search to find the given element within array. */

#include<stdio.h>
intbsearch(int [ ],int, int, int);
void main( )
{
int a[20],pos,n,k,i,lb,ub;
clrscr( );
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the key value:");
scanf("%d",&k);
lb=0;
ub=n-1;
pos=bsearch(a,k,lb,ub);
if(pos!=-1)
printf("Search successful, element found at position %d",pos);
else
printf("Search unsuccessful, element not found");
getch( );
}
int bsearch(int a[ ], int k, intlb, intub)
{
int mid; while(ub>=lb)
{
mid=(lb+ub)/2; if(k<a[mid])
ub=mid-1; else if(k>a[mid])
lb=mid+1; else if(k==a[mid])
return(mid);
return(bsearch(a,k,lb,ub));
}
return -1;
}

OUTPUT:
Enter ‘n’ value : 6
Enter elements for an array : 10 32 25 84 55 78
Enter the element to be searched : 78
Search successful, Element found at Position : 5

/*Recursive program for Linear Search*/

#include<stdio.h>
int linear(int [ ],int,int ,int); void main( )
{
int a[20],pos=-1,n,k,i; clrscr();
printf("\nEnter n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n Enter the element to be searched:");
scanf("%d",&k);
pos=linear(a,n,k); if(pos!=-1)
printf("\n Search successful, Element found at Position %d",pos);
else
}
printf("Searchunsuccessful, element not found ");
int linear(int a[ ],int n,int low, int k)
{
if(low>= n) return -1;
else if(k==a[low] return low;
else
return linear(a,n,low+1,k);
}
}
return -1;
}
Output:-
Enter ‘n’ value : 6
Enter elements for an array : 10 32 22 84 55 78
Enter the element to be searched : 55
Search successful, Element found at Position : 4
Search successful, Element found at Position : 4

/*C program that searches a value in a stored array using non recursive binary
search.*/

#include<stdio.h>
int bsearch(int [],int,int);
void main( )
{
int a[20],pos,n,k,i; clrscr();
printf("\nEnter the n value:"); scanf("%d",&n);
printf("\nEnter elements for an array:"); for(i=0;i<n;i++)
scanf("%d",&a[i]); printf("\nEnter the key value:"); scanf("%d",&k);
pos=bsearch(a,n,k);
if(pos!= -1)
printf("Search successful, element found at position %d",pos);
else
printf("Search unsuccessful, element not found");
getch( );
}
int bsearch(int a[ ],int n, int k)
{
intlb=0,ub,mid; lb=0;
ub=n-1; while(ub>=lb)
{
mid=(lb+ub)/2; if(k<a[mid])
ub=mid-1; else if(k>a[mid])
lb=mid+1; else if(k==a[mid])
return(mid);
}
return -1;
}
OUTPUT:
Enter n’ value :7
Enter elements for an array : 35 10 32 25 84 55 78
Enter the element to be searched : 25
Search successful, Element found at Position : 3
UNIT III

Functions: Introduction to structured programming, function declaration, signature of a


function, parameters and return type of a function, categories of functions, parameter passing
techniques, passing arrays and strings to functions, recursion, merits and demerits of recursive
functions, storage classes.
Strings: Introduction to strings, operations on characters, basic string functions available in C -
strlen, strcat, strcpy, strrev, strcmp, String operations without string handling functions, arrays of
strings.

Why Use Functions? (Need for Functions)


The ability to divide a program into abstract, reusable pieces is what makes it possible to write
largeprograms that actually work right.
The following reasons make functions extremely useful and practically essential:
Enhances redability
Easy to understand.
Allows Code reusability
Structured organization.
Achieves Modular programming
Easy identification of bugs
Data abstraction
Reduction of code repetition so reduces lines of code.
Best suited for large programs or complex programs.
It is used to check logical conditions involving multiple objects and just returns the result.

Designing structured programs:


Structured programming is a programming technique in which a larger program is divided into
smaller sub programs to make it easy to understand, easy to implement and makes the code
reusable etc,. The structuredprogramming enables code reusability.
Code reusability is a method of writing code once and using it many times. Structured
programming alsomakes the program easy to understand, improves the quality of the program,
easy to implement and reducestime.In C, the structured programming can be designed using
functions concept.

Definition:
A function is a group of statements that togetherperform a task. Every C program has at least
onefunction, which is main(), and all the most trivialprograms can define additional functions.

Main Function in C:
In C, the "main" function is treated the same as every function, it has a return type (and in some
cases accepts inputs via parameters called command line arguments).In C, program execution
starts from the main () function. The only difference is that the main function
is "called" by the operating system when the user runs the program.The main function can in-
turn may call other functions. When main calls a function, it passes theexecution control to that
function. The function returns control to main when a return statement isexecuted or when end of
function is reached.
Types of Functions:
Depending on whether a function is defined by the user or already included in C compilers, there
aretwo types of functions in C programming.
Standard library functions
User defined functions Standard

Library functions:
The standard library functions are built-in functions in C programming .
They handle tasks such as mathematical computations, I/O processing, string handling
etc.
These functions are defined in the header file.
When we include the header file, eg: #include<string.h> these functions are available for
use.
For example: The “printf()” is a standard library function to send formatted output to the
screen(display output on the screen).
This function is defined in “stdio.h” header file.
Implementation details are not known to the user.
In order to use these functions programmers should only know the
name of the function
header file in which it is available.
Inputs and their type and order.
Return type of the function.
User Defined Functions in C:
A user can create their own functions for performing any specific task of program are
calleduser defined functions. To create and use these function we have to know these 3 elements.
A. Function Declaration
B. Function Definition
C. Function Call
1. Function declaration
The program or a function that calls a function is referred to as the calling
program or calling function. The calling programshould declare any function that is to be
used later in the program this is known as the function declaration orfunction prototype.

2. Function Definition
The function definition consists of the whole description and code of a function. It
tells that what the function is doingand what are the input outputs for that. A function is
called by simply writing the name of the functionfollowed by the argument list inside the
parenthesis. Function definitions have two parts:

Function Header
The first line of code is called function Header. Intsum(int x, int y)
It has three parts
(i) The name of the function i.e. sum
(ii) The parameters of the function enclosed in parenthesis
(iii) Return value type i.e. int
Function Body
Whatever is written with in { } is the body of the function.

3. Function Call
In order to use the function we need to invoke it at a required place in the
program.This is known as the function call.

Signature of a function:
A function’s signature includes the function's name and the number, order and type of its formal
parameters.
Syntax: return-type function-name (parameters)
{
declarations
Statements
return value
}
Different Sub parts of Above Syntax :
return-type
1. Return Type is Type of value returned by function
2. Return Type may be “Void” if function is not going to return a value.

function-name
1. It is Unique Name that identifies function.
2. All Variable naming conversions are applicable for declaring valid function name.

parameters
Comma-separated list of types and names of parameters
Parameter injects external values into function on which function is going to operate.
Parameter field is optional.
If no parameter is passed then no need to write this field value
1. It is value returned by function upon termination.
2. Function will not return a value if return-type is void.
It contain Executable Code (Executable statements )
First Line is called as Function Header .
Function Header should be identical to function Prototype with the exception of
semicolon
Example:
Terminology associated with functions:

Parameter:The term parameter refers to any declaration within the parentheses following the
function name in a function declaration or definition.

Example:void sum (int a, int b); // a,b are parameters.

Argument:The term argument refers to any expression within the parentheses of a function call.

Example:sum(num1, num2); //Call Function Sum With Two Parameters

Calling function:The function which is making a call to any function is called calling function

Example: Calling function main()

Called function:The function which is being executed due to function call is known as called
function.

Example: // sum is a called function by main function int


sum(num1, num2)
{
return(num1+num2);
}

Categories of user defined functions in C:


A function depending on whether arguments are present or not and whether a value is returned or
not maybelong to any one of the following categories:

i) Functions with no arguments and no return values.


ii) Functions with arguments and no return values.
iii) Functions with arguments and return values.
iv) Functions with no arguments and return values.

(i)Functions with no arguments and no return values:-


When a function has no arguments, it does not receives any data from calling
function. When a function doesnot return a value, the calling function does not receive
any data from the called function. Functions that don’treturn a value are known as void
functions.That is there is no data transfer between the calling function and thecalled
function.

Example
#include<stdio.h>
void add();
void main()
{
add();
}
void add ()
{
intz,a,b ;
printf(“enter values of a and b:\n”);
scanf(“%d%d”,&a,&b);
z=x+y;
printf ("The sum of two numbers is :%d",z);
}
Output :enter values of a and b:
35
The sum of two numbers is :8

(ii) Functions with arguments and no return values:-


When a function has arguments data is transferred from calling function to called
function. The called functionreceives data from calling function and does not send back
any values to calling function. Because it doesn’t havereturn value.

Example
#include<stdio.h>
#include <conio.h>
void add(int,int);
void main()
{
int a, b;
printf(“enter values of a and b:\n”);
scanf(“%d%d”,&a,&b);
add(a,b);
}
void add (int x, int y)
{
int z ; z=x+y;
printf ("The sum of two numbers is :%d",z);
}

Output :enter values of a and b :


35
The sum sum of two numbers is : 8

(iii) Functions with arguments and return values:-


In this data is transferred between calling and called function. That means called
function receives data fromcalling function and called function also sends the return
value to the calling function.

Example
#include<stdio.h>
#include <conio.h>
int add(int, int);
main()
{
inta,b,c;
printf(“enter values of a and b:\n”);
scanf(“%d%d”,&a,&b);
c=add(a,b);
printf ("The sum of two numberas is :%d",c);
}
int add (int x, int y)
{
int z; z=x+y;
return z;
}

Output :enter values of a and b:


35
The sum of two numbers is :8

(iv) Function with no arguments and return type:-


When function has no arguments data cannot be transferred to called function.
But the called function can sendsome return value to the calling function.

Example
#include<stdio.h>
int add( );
void main()
{
int c;
c=add();
printf ("The sum of two numbers is :%d",c);
}
int add ()
{
intx,y,z;
printf(“enter values of a and b:\n”);
scanf(“%d%d”,&a,&b);
z=x+y;
return z;
}

Output: enter values of a and b:


35
The sum of two numbers is : 8

Parameter Passing Techniques in C:


In C functions exchange information by means of parameters and arguments
(which are inputs given to a function).There are two ways to pass arguments/parameters
to function calls -- call by value and call by reference.

Call by value:
In call by value a copy of actual arguments is passed to respective formal arguments.

#include <stdio.h>
void swap(int, int);
int main ()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(x, y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
printf("Values of a and b is %d %d\n",a,b);
}

Output:
Enter the value of x and y 2
3
Before Swapping x
=2
y=3
Values of a and b is 3 2
After Swapping
x=2
y=3

Call by reference:
In call by reference the location (address) of actual arguments is passed to formal
arguments, hence anychange made to formal arguments will also reflect in actual arguments.

#include <stdio.h>
void swap(int*, int*);
int main()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y); swap(&x,
&y);
printf("After Swapping\nx = %d\ny = %d\n", x, y); return 0;
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

Output:
Enter the value of x and y 2 3
Before Swapping x = 2 y = 3
Values of a and b is 3 2
After Swapping
x=3
y=2

Call by Value vsCall by Reference:

S NO CALL BY VALUE CALL BY REFERENCE


1 It is also known as pass by value It is also known as pass by reference.
2 Values are passed as inputs. Addresses are passed as inputs.
3 The actual arguments are variables, The actual arguments are addresses of
constants or expressions. variables.
4 The formal arguments are also variables. The formal arguments are pointers.
5 Changes made in the called function are Changes made in the called function are
not reflected back in the calling function. reflected back in the calling function.
6 The calling and the called function The calling and the called function
maintains separate copies of data. maintains or shares a common location.
7 A copy of contents is maintained by The called function shares common data.
calling function
8 Example of function proto type: Example of function proto type:
void Swap(int a, int b); void Swap(int *p, int *q);
9 Example of function call: Example of function call:
Swap(a,b); Swap(&a,&b);
Parameters vs Arguments in C:
The term parameter (sometimes called formal parameter) is often used to refer to
thevariable as found in the function definition, while argument (sometimes called actual
parameter) refers to the actual input supplied at function call.

Actual parameters vs Formal parameters:

S NO Actual parameters Formal parameters


1 These are the variable found in the These are the variable found in the
function call. function definition or declaration.
2 They can be variables, constants or They can only be variables
expressions or another function calls.
3 Example: Example:
func1(12, 23); // constants Void func1(int x, int y); //always variables
unc1(a, b); // variables
func1(a + b, b + a); // expression
4 They are the original source of They get the values after function call
information occurs.
5 They are supplied by the caller or They are initialized with the values of actual
programmer. arguments.

Note:
1. Order, number, and type of the actual arguments in the function call must match with formal
arguments of the function (except for functions with variable list of arguments).
2. If there is type mismatch between actual and formal arguments then the compiler will try to
convertthe type of actual arguments to formal arguments if it is legal, otherwise a garbage value
will be passed to the formal argument.
3. When actual arguments are less than formal arguments, the garbage value is supplied to the
formalarguments.
4. Changes made in the formal argument do not affect the actual arguments.

Passing arrays to functions (Arrays with functions)


To process arrays in a large program, we need to pass them to functions. We can pass arrays in
twoways:
1. passing individual elements
2. passing the whole array.

1. Passing Individual Elements:


One-dimensional Arrays:
We can pass individual elements by either passing their data values or by passing theiraddresses.
We pass data values i.e; individual array elements just like we pass any data value.As long as the
array element type matches the function parameter type, it can be passed. The calledfunction
cannot tell whether the value it receives comes from an array, a variable or an expression.
Program using call by value
void func1( int );
void main()
{
int a[5]={ 1,2,3,4,5};
func1(a[3]);
}
void func1( int x)
{
printf(“%d”,x+100);
}

Two-dimensional Arrays:
The individual elements of a 2-D array can be passed in the same way as the 1-D array. We can
pass2-D array elements either by value or by address.

Ex: Program using call by value


void fun1(int );
void main()
{
int a[2][2]={1,2,3,4};
fun1(a[0][1]);
}
void fun1(int x)
{
printf(“%d”,x+10);
}
2. Passing whole array (idea of call by reference)
As array name is a constant pointer pointing to first element of array(storing the
baseaddress),Passing array name to a function itself indicates, that we are passing address of first
elementof array .

One-dimensional array(passing array name as base address to a function)


To pass the whole array we simply use the array name as the actual parameter. In the
calledfunction, we declare that the corresponding formal parameter is an array. We do not need
to specify thenumber of elements.
Program:
void fun1(int x[],int);
void main()
{
int a[5]={ 1,2,3,4,5};
fun1(a,5);
}
void fun1( int x[],int n)
{
int i, sum=0; for(i=0;i<n;i++)
sum=sum+x[i];
printf(“\nSum of the elements in an array is : %d ”,sum);
}

Two-dimensional array:
When we pass a 2-D array to a function, we use the array name as the actual parameter.
Theformal parameter in the called function header, however must indicate that the array has
twodimensions.

Rules:
1. The function must be called by passing only the array name.
2. In the function definition, the formal parameter is a 2-D array with the size of the
seconddimension specified.
Program:
void fun1(int a[][2]);
void main()
{
int a[2][2]={1,2,3,4};
fun1(a);
}
void fun1(int x[][2])
{
inti,j;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf(“%3d”,x[i][j]);
printf(“\n”);
}
}

Recursion :

Recursion is the process of repeating items in a self-similar way. In programming


languages,if a program allows you to call a function inside the same function, then it is
called a recursivecall of the function.
The C programming language supports recursion, i.e., a function to call itself. But
whileusing recursion, programmers need to be careful to define an exit condition from
thefunction, otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such
ascalculating the factorial of a number, generating Fibonacci series, etc.

The recursion continues until some condition is met to prevent it.


To prevent infinite recursion, if...else statement (or similar approach) can be used where one
branch
makes the recursive call and other doesn't.
When a function calls itself, a new set of local variables and parameters are allocated storage
on the stack, and the function code is executed from the top with these new variables. A
recursive
call does not make a new copy of the function. Only the values being operated upon are new. As
each recursive call returns, the old local variables and parameters are removed from the stack,
and
execution resumes immediately after the recursive call inside the function.
The main advantage of recursive functions is that we can use them to create clearer and simpler
versions of several programs.
Example1: Factorial of a Number Using Recursion
The factorial of a positive number n is given by:
factorial of n (n!) = 1*2*3*4. ....... n
The factorial of a negative number doesn't exist. And the factorial of 0 is 1. #include
<stdio.h>
longintmultiplyNumbers(int n);
int main()
{
int n;
printf("Enter a positive integer: "); scanf("%d",
&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n)); return 0;
}
longintmultiplyNumbers(int n)
{
if (n >= 1)
return n*multiplyNumbers(n-1);
else
return 1;
}
Output
Enter a positive integer: 6
Factorial of 6 = 720
Example 2:C program to generate Fibonacci series using recursive functions.
#include<stdio.h>
Void fibo_rec(int n, int f1, int f2);
Void main()
{
int f1=0, f2=1,n;
printf("Enter any number to print the fibonacci series: ");
scanf("%d",&n);
if(n<=0)
printf("Enter a valid number\n");
else if(n==1)
printf("fibonacci series is: %d",f1);
else if(n==2)
101
printf("fibonacci series is: %d %d",f1,f2); else
{
printf("fibonacci series is: %d %d ",f1,f2);
fibo_rec(n-2,f1,f2);
printf("\n\n");
}
}
voidfibo_rec(int n, int f1, int f2)
{
int f3;
if(n==0)
return;
f3=f1+f2;
printf("%3d ",f3);
fibo_rec(n-1,f2,f3);
}

Difference between Recursion and Non recursion( Iteration)


Both recursion and iteration are used for executing some instructions repeatedly until
somecondition is true. A same problem can be solved with recursion as well as iteration but still
there areseveral differences in their working and performance that I have mentioned below.

Recursion Iteration
definition Recursion refers to a situation where a Iteration refers to a situation
function calls itself again and again wheresome statements are executed
until some basecondition is reached againand again using loops until
somecondition is true
Performance It is comparatively slower because Its execution is faster because it doesn’t
before each function call the current use stack.
state of function is stored in
stack.After the return statement the
previousfunction state is againrestored
from stack.
memory Memory usage is more as stack is Memory usage is less as it doesn’t use
used to store the current functionstate. stack.
Code Size Size of code is comparativelysmaller Iteration makes the code size bigger.
in
recursion.

Limitations of recursion:
Slower than its iterative solution.
For each step we make a recursive call to a function. ...
May cause stack-overflow if the recursion goes too deep to solve the problem.
Difficult to debug and trace the values with each step of recursion.

Storage classes in C :
Variables in C differ in behavior. The behavior depends on the storage class a variable may
assume. From C compilers point of view, a variable name identifies some physical location
within the computer where the string of bits representing the variables value is stored. There are
four storage classes in C.Storage classes specify the scope of objects .We define the storage class
of an object using one of four specifiers.
(1) Automatic storage class
(2) Register storage class
(3) Static storage class
(4) External storage class

(1) Automatic Storage Class:-


The features of a variable defined to have an automatic storage class are as under:

Keyword auto
Storage Memory
Default initial value An unpredictable value, which is often called a garbage value.
Scope Local to the block in which the variable is defined.
Life Till the control remains within the block in which the variable is defined

Following program shows how an automatic storage class variable is declared, and the fact that if
the
variable is not initialized it contains a garbage value.
void main( )
{
autoint i, j ;
printf ( "\n%d %d", i, j ) ;
}
When you run this program you may get different values, since garbage values are unpredictable.
So always make it a point that you initialize the automatic variables properly, otherwise you are
likely to get unexpected results. Scope and life of an automatic variable is illustrated in the
following program.
void main( )
{
autoint i = 1 ;
{
autoint i = 2 ;
{
autoint i = 3 ;
printf ( "\n%d ", i ) ;
}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}
/*Show the use auto variables*/
#include<stdio.h>
void main()
{
inti,x;
for(i=1;i<=3;i++)
{
x=1;
x++;
printf(“Value of x in iteration %d is: \n”,i,x);
}
}

Output :
Value of x in iteration 1 is:2
Value of x in iteration 2 is:2
Value of x in iteration 3 is:2

(2) Static Storage Class:-


The features of a variable defined to have a static storage class are as under:

Keyword static
Storage Memory
Default initial value Zero.
Scope Local to the block in which the variable is defined.
Life Value of the variable persists between different function calls.

The following program demonstrates the details of static storage class:


/*Show the use static variables*/
#include<stdio.h>
void main()
{
int i;
staticint x;
for(i=1;i<=3;i++)
{
x=1;
x++;
printf(“Value of x in iteration %d is: \n”,i,x);
}
}
Output :
Value of x in iteration 1 is:2
Value of x in iteration 2 is:3
Value of x in iteration 3 is:4
(3) Extern Storage Class:-
The features of a variable whose storage class has been defined as external are as follows:

Keyword extern
Storage Memory
Default initial value Zero.
Scope Global
Life As long as the program execution does not come to end.

External variables differ from those we have already discussed in that their scope is global, not
local. External variables are declared outside all functions, yet are available to all functions that
care to use them. Here is an example to illustrate this fact.
Ex:
#include<stdio.h>
externint i;
void main()
{
printf(“i=%d”,i);
}

4)Register Storage Class:-


The features of a variable defined to be of register storage class are as under:
Keyword register
Storage CPU Registers
Default initial value An unpredictable value, which is often called a garbage value.
Scope Local to the block in which the variable is defined.
Life Till the control remains within the block in which the variable is
defined.

A value stored in a CPU register can always be accessed faster than the one that is stored in
memory. Therefore, if a variable is used at many places in a program it is better to declare its
storage class as register. A good example of frequently used variables is loop counters. We can
name their storage class as register.
void main( )
{
registerint i ;
for ( i = 1 ; i <= 10 ; i++ )
printf ( "\n%d", i ) ;
}

Scope rules in C.
Scope: Scope defines the visibility of object.it defines where an object can be referenced.Scope
of a variable is the part of program in which it can be used

Scope rules
The rules are as under:
1. Use static storage class only if you want the value of a variable to persist between different
function calls.

2. Use register storage class for only those variables that are being used very often in a program.
Reason is, there are very few CPU registers at our disposal and many of them might be busy
doing something else. Make careful utilization of the scarce resources. A typical application of
register storage class is loop counters, which get used a number of times in a program.

3. Use extern storage class for only those variables that are being used by almost all the
functions in the program. This would avoid unnecessary passing of these variables as arguments
when making a function call. Declaring all the variables as extern would amount to a lot of
wastage of memory space because these variables would remain active throughout the life of the
program.

4. If we don‟t have any of the express needs mentioned above, then use the auto storage class. In
fact mostof the times we end up using the auto variables, because often it so happens that once
we have used thevariables in a function we don‟t mind loosing them.

STRINGS

INTRODUCTION:
A string is a sequence of characters that is treated as a single data item. Any group of
characters defined between double quotation marks is a string constant.
Example : “ hello world”.
“123ase$”
The common operations performed on character strings include:
• Reading and writing strings
• Combining strings together
• Copying one strings to another
• Comparing strings for equality
• Extracting a portion of a string

DECLARING AND INITIALIZING STRING VARIABLES:

C does not support strings as a data type. However, it allows us to represent strings
as character arrays. The general form of declaration of a string variable is:
char string_name[size];
the size determines the number of characters in the string_name. for example
char city[10];
char name[30];
when the compiler assigns a character string to a character array, it
automatically supplies a null character(‘\0’) at the end of the string.
Therefore, the size should be equal to the maximum number of
characters in the string plus one.
Like numeric arrays, character arrays may be initialized when they
are declared. C permits a character array to be initialized in either
of the following two forms:
char city[9]=”NEW YORK”;
char city[9]={‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’\0’};
C also permits us to initialize a character array without specifying the
number of elements. In such cases, the size of the array will be
determined automatically, based on the number of elements initialized.
For example
char string[]={‘G’,’O’,’O’,’D’,’\0’}; defines the array string as a five element

array.

We can also declare the size much larger than the string
in the initialize. That is,the statement.
char str[10]=”GOOD”;
is permitted. In this case,the computer creates a character array of
size 10, places the value “GOOD” in it, terminates with the null
character, and initializes all other elements to NULL.
The storage will look like:
G O O D \0 \0 \0 \0 \0 \0
However, the following declaration is illegal
char str2[3]=”GOOD”; This will result in a compile time error.
Note: we cannot separate the initialization from declaration.
That is, char str[5]; Str=”GOOD” is not allowed.
READING STRINGS FROM TERMINAL:

Using scanf function: using %s, it automatically terminates the string with
‘\0’ character, so the arrray size should be large enough to hold the input plus
null character.
e.g.- char name[10];
scanf(%s”,name);
Note: in the case of character arrays, the ampersand(&) is not required
before the variable name.
Disadvantage : scanf terminates its input on the first white space it finds.
e.g.- if enters new york then only new will be read in array
name.
We can also specify the field width using the form %ws in scanf
for reading a specified number of characters from the input string.

E.g.- scanf(“%ws”,name);
▪ If w is equal or greater than the number of charcters
typed, then entire string will be stored in thevariable
▪ If w is less , then excess characters will be truncated
and left unread. E.g.-scanf(“%6s”,name)
griet---reads

entire string

gokaraju---

reads only

gokara

Reading a Line ofText:


%s and %ws can read only strings without whitespaces. That is, they cannot be used for
reading a text containing more than one word.However, C supports a format
specification known as the edit set conversion code%[..] that can be used to read a line
containing a variety of characters, including whitespaces. For example
char line[80]; scanf(“%[^\n]”,line); printf(“%s”,line);
will read a line of input from the keyboard and display the same on the screen.
Using getchar and getsfunction: Function getchar is used to read single character from the
terminal. This function repeatedly can be used to read successive single characters from the input
and place them into a character array. Thus, an entire line of text can be read , the reading is
terminated when the newline character (‘\n’) is entered and the null character is then inserted at
the end of the string.
Syntax:char ch; ch=getchar();

Example program:
#include<stdio.h>
void main()
{
char line[50],ch; int i=0;
printf(“\n press enter at the end of input”);
do
{
ch=getchar();
line[i]=ch;
i++;
}while(ch!=’\n’);
i=i-1;
line[i]=’\0’;
printf(“%s”,line);
}
another more convienent method of reading a string of text containing whitespaces is to use the
library function gets available in the <stdio.h> header file.
syntax:gets(str); str is a string variable, gets function reads a characters into str from the
keyboard until a new- line character is encountered and then appends a null character to the
string. unlike scanf, it does not
skip whitespaces.
for example: char line[80];
gets(line); printf(“%s”,line);
the last two statements can be combined as follows printf(“%s”,gets(line));

WRITING STRINGS TO SCREEN



Using printffunction

The format %s can be used to display an array of characters that is terminated ny the null
character using printf function. printf(%s”,line);
We can also specify the precision with which the array is displayed. for instance, the
specification %10.4
indicates that the first four characters are to be printed in a field width of 10 columns. left-
justified.
Features of %s specifications:
1. when the field width is less than the length of the string, the entire string isprinted.
2. the integer value on the right side of the decimal point specifies the number of characters
to be printed.
3. when the number of characters to be printed is specified as zero, nothing isprinted.
4. the minus sign in the specification causes the string to be printedleft-justified.
5. the specification %.ns prints the first n characters of thestring.
Example program:
write a program to store the string and display the string under various format
specifications. void main()
{
char str[14]=”good morning”;
printf(“%14s”,str);
printf(“%4s”,str);
printf(“%14.4s”,str);
printf(“%-14.4s”,str);
printf(“%14.0s”,str);
printf(“%.3s”,str);
printf(“%s”,str);
}
Output:
good morning
good morning
good
good

goo
good morning
Using putchar and putsfunctions: putchar function is used to output the values of character
variables.
syntax: char ch='a'; putchar(ch);
The function putchar requires one parameter. This statement is equivalent to: printf(“%c”,ch);
we can use this function repeatedly to output a string of characters stored in an array using a loop.
Example:

char str[13]=”good morning”;


for(i=0;i<12;i++)
putchar(name[i]);
Another and more convenient way of printing string values is to use the function puts declared in
the header file <stdio.h>.
syntax:
puts(str); where str is a string variable containing a string value, this prints the value
of the string variable str and then moves the cursor to the beginning of the next
line on the screen.

ARITHMETIC OPERATIONS ON CHARACTERS:

C allows us to manipulate characters the same way we do with numbers. Whenever a character
constant or character variable is used in an expression, it is automatically converted into an integer
value by the system. For e.g.- x=‘a’;

printf(“%d”,x);
will display the number 97 on the screen. x=‘a’-1;

printf(“%d”,x)---will print 96, a=97


character constants can also be used in relational expressions. E.g.- ch>=‘A’ && ch<=‘Z’ test
whether the character in the variable ch is an upper-cas letter.

We can convert a character digit to its equivalent integer value using x= character-’0’
E.g.- int x ;
x= ‘7’-’0’;

printf(“%d”,x)
prints x=7 // ASCII value of 7 = 55
ASCII value of 0=48

The C library supports a function atoi (string) that converts a string of digits into their integer
values
e.g.- number =“1988”;

year=atoi(number)
The function converts the string constant “1988”, to its numeric equivalent 1988.
Present in header file <stdlib.h>.C does not provide operators that work on strings directly like :
str1=“ABC”; str2=str1; is invalid

STRING HANDLING FUNCTIONS

The C library supports a large number of string-handling functions that can be used to
carry out many of the string manipulations. following are the most commonly used
string-handling functions.
Function Action
Strcat() Concatenates two strings
Strcmp() Compares two strings
Strcpy() Copies one string over another
Strlen() Finds the length of a string excluding null character
Strrev() Reverse a string

strcat() Function:

the strcat function joins two strings together. it takes the following form:

strcat(string1, string2);
string1 and string2 are character arrays. when the function strcat is executed, string2 is
appended to string1. it does by removing the null character at the end of string1 and
placing string2 from there. the string at the string2 remains unchanged. For example
consider the following three strings:

str1 V E R Y \0 \0

str2 G O \0

strcat(str1,str2) will result in:


V E R Y G O \0

We must make sure that the size of str1 to which str2 is appended is large enough to
accommodate the final string.
strcat function may also append a string constant to a string variable. the
following is valid: strcat(str1,”good”);
C permits nesting of strcat functions. for example, the statement
strcat(strcat(str1,str2),str3);
is allowed and concatenates all the three strings together. the resultant string is stored in
str1.
strcmp() Function:

the strcmp function compares two strings identified by the arguments and has a value 0
if they are equal. if they are not, it has the numeric difference between the first
nonmatching characters in the strings. it takes the form: strcmp(str1,str2);
str1 and str2 may be string variables or string constants. examples are:
strcmp(str1,str2);
strcmp(str1, “john”);
strcmp(“rom”, “ram”);
strcpy() Function:

The strcpy() function works almost like a string-assignment operator. it takes a form:
strcpy(str1,str2);
and assigns the contents of str2 to str1. str2 may be a character array variable or a string
constant. for example: strcpy(city, “DELHI”);
will assign the string “DELHI” to the string variable city. similarly,the statement
strcpy(city1,city2) will assign the contents of the string variable city2 to the string
variable city1. the size of the array city1 should be large enough to store the contents of
city2.

strlen() Function:

This function counts and returns the number of characters in a string. it takes the form
n=strlen(string)
where n is an integer variable, which receives the value of the length of the string.
Example :
write a program that reads 2 strings s1,s2, and check whether they are equal or not, if
they are not , join them together. then copy the contents of s1 to the variable s3. at the
end , the program should print the contents of all the 3 variables and their lengths.
#include<stdio.h>
void main()
{
char s1[20],s2[20],s3[20];
int x,l1,l2,l3;
printf("\n enter two strings constants:");
scanf("%s%s",s1,s2);
x=strcmp(s1,s2);
if(x!=0)
{
printf("\n strings are not equal");
strcat(s1,s2);
}
else
printf("\n strings are equal");
strcpy(s3,s1);
l1=strlen(s1);
l2=strlen(s2);
l3=strlen(s3);
printf("\ns1=%slength=%d characters",s1,l1);
printf("\n s2=%s length=%d characters",s2,l2);
printf("\n s3=%s length=%d characters",s3,l3);
}

output:
enter two strings constants: welcome students
strings are not equal
s1=welcome students length=15 characters
s2=students length=8 characters
s3=welcomestudents length=15 characters

strrev() function:
strrev( ) function reverses a given string in C language. Syntax for strrev( ) function is
given below.
char *strrev(char *string);
example: string “Hello” is reversed using strrev( ) function and output is displayed as
“olleH”.
Program:
#include <stdio.h>
#include <string.h>
void main()
{
char s[100];
printf("Enter a string to reverse:\n");
gets(s);
strrev(s);
printf("Reverse of the string: %s\n", s); }
Output:
Enter a string to reverse: rajesh
Reverse of the string: hsejar
Strings with out string handling function:
string length:
#include<stdio.h>
void main()
{
char str[30];
int i,len=0;
clrscr();
printf("\n enter the string");
gets(str);
for(i=0;str[i]!='\0';i++)
len++;
printf("\n the total no.of characters in the given string is:%d",len-1);
getch();
}
//String concatenation with out string handling function

#include <stdio.h>
void main()
{
char str1[50], str2[50], i, j;
printf("\nEnter first string: ");
scanf("%s",str1);
printf("\nEnter second string: ");
scanf("%s",str2);
/* This loop is to store the length of str1 in i
* It just counts the number of characters in str1
* You can also use strlen instead of this.
*/
for(i=0; str1[i]!='\0'; ++i);

/* This loop would concatenate the string str2 at


* the end of str1
*/
for(j=0; str2[j]!='\0'; ++j, ++i)
{
str1[i]=str2[j];
}
// \0 represents end of string
str1[i]='\0';
printf("\nOutput: %s",str1);
}

// string copy with out string handling function


#include<stdio.h>
void main()
{
char str1[30],str2[30];
int i;
printf("enter the string 1:");
gets(str1);
for(i=0;str1[i]!='\0';i++)
str2[i]=str1[i];
str2[i]='\0';
printf("the string after copy is :");
puts(str2);
}

// string reverse with out string handling function


#include<stdio.h> void main()
{
char str1[20],str2[20];
int i,len=1,j=0;
printf("\n enter the string");
scanf("%s",str1);
for(i=0;str1[i]!='\0';i++)
{
len++;
}
printf("the length of the string is:%d",len);
for(i=len-1;i>=0;i--,j++)
str2[j]=str1[i];
str2[j]='\0';
printf("the reverse of a given string is %s",str2);
}

String comparison with out string handling function


#include<stdio.h>
void main()
{
char str1[30],str2[30];
int i,j,flag=0;
printf("enter the strings to be compared:");
scanf("%s %s",str1,str2);
for (i=0,j=0;str1[i]!='\0'||str2[i]!='\0';i++,j++)
{
if(str1[i]!=str2[j])
{
flag=1; break;
}
}
if(flag==0)
printf("the two strings are equal");
else
printf("the two strings are not equal");
}

Array of Strings:

We often use list of character strings, such as a list of the names of students in a class, list
of the names of employees in an organization etc. A list of names can be treated as a table of
strings and a two-dimensional character array can be used to store the entire list. for example, a
character array city[5][15] may be used to store a list of 30 city names, each of length not more
than 15 characters. e.g.-
C H A N D I G A R h \0
M A D R A S \0
A H M E D A B A D \0
H Y D E R A B A D \0
B O M B A Y \0
This table can be conveniently stored in a character array city by using the following declaration:
char city[ ][ ]= { “CHANDIGARH”, “MADRAS”, “AHMEDABAD”, “HYDERABAD”,
“BOMBAY”};

Example Programs:
#include<stdio.h>
int main()
{
char city[20][20]; // city [no. of cities][max length of each string]
int i,n;
printf("Enter no. of cities:");
scanf("%d",&n); //n=4
printf("Enter %d cities names:\n",n);
for(i=0;i<n;i++)
scanf("%s",&city[i]);
printf("\nThe cities are:\n");
for(i=0;i<n;i++)
printf("%s\n",city[i]);
return 0;
}

Output:
Enter no. of cities: 4
Enter 4 city names:
Madras
Hyderabad
Goa
Bangalore

The Cities are:


Madras
Hyderabad
Goa
Bangalore
UNIT IV
Pointers and Structures:
Pointers: Idea of pointers, declaration and initialization of pointers, pointer to pointer,
voidpointer, null pointer, pointers to arrays and structures, function pointer.
Structures and Unions: Defining structures, declaring and initializing structures, arrays within
structures, array of structures, nested structures, passing structures to functions, unions, typedef.

Introduction to pointers:
Pointers are like special utilities, which make it easy to map around in a program
code. Unlike other variables, pointers store the addresses of other variables.
What are Pointers in C?
The pointer in C language is a variable which stores the address of another variable.
This variable can be of type int, char, array, function, or any other pointer. The size of the
pointer depends on the machine architecture.

What are the uses of Pointers in C?

1. Pointers save memory space.


2. Execution time with pointers is faster because data are manipulated with the address,
that is, direct access to memory location.
3. Memory is accessed efficiently with the pointers. The pointer assigns and releases the
memory as well. Hence it can be said the Memory of pointers is dynamically
allocated.
4. Pointers are used with data structures. They are useful for representing two-
dimensional and multi-dimensional arrays.
5. An array, of any type, can be accessed with the help of pointers, without considering
its subscript range.
6. Pointers are used for file handling.
7. Pointers are used to allocate memory dynamically.

What are the drawbacks of Pointers in C?

1. If pointers are pointed to some incorrect location then it may end up reading a wrong
value.
2. Erroneous input always leads to an erroneous output
3. Segmentation fault can occur due to uninitialized pointer.
4. Pointers are slower than normal variable
5. It requires one additional dereferences step.
6. If we forgot to deallocate a memory then it will lead to a memory leak.
7. There is always a chance of dangling pointers and wild pointers.

How to create Pointers in C?

CREATION OF POINTERS

A pointer is a variable that stores the memory address of another variable as its value.
A pointer variable points to a data type (like int) of the same type, and is created with the *
operator. The address of the variable you are working with is assigned to the pointer:

DECLARATION OF POINTER:

In C, every variable must be declared for its type before it is used in the program. Since
pointer variable contain addresses that belong to a specific data type, they must be declared
and initialized.

Declaration:
The declaration of a pointer variable takes the following form: data type *pointer_name;
This tells the compiler three things about the variable pointer_name:

1. The * tells that the variable pointer_name is a pointer variable.


2. pointer_name needs a memory location
3. pointer_name points to a variable of type data_type
Example: int *ptr;
Declares the variable ptr as a pointer variable that points to an integer data type.

INITIALIZATION OF POINTERS:

The process of assigning the address of a variable to a pointer variable is known as


initialization. Once a pointer variable has been declared we can use assignment operator to
initialize the variable.
Example:
int quantity ;
int *p; //declaration
p=&quantity; //initialization
We can also combine the initialization with the declaration:
int *p=&quantity;
Always ensure that a pointer variable points to the corresponding type of data.
It is also possible to combine the declaration of data variable, the declaration of pointer
variable and the initialization of the pointer variable.

ACCESSING THROUGH POINTERS:

In C, there are two equivalent ways to access and manipulate a variable content –
1. Direct Access
2. Indirect Access
Direct access: We use directly the variable name to get its value.
Indirect access:We use a pointer to the variable and through an indirection operator access
the variable.

Example Program:
// ACCESSING VARIABLES THROUGH POINTER
#include <stdio.h>
intvar = 1;
int *ptr; // declaration of pointer
int main( )
{
ptr = &var; //Initialization of pointer
printf("\nDirect access, var = %d", var);
printf("\nIndirect access, var = %d", *ptr); // accessing
/* Display the address of var two ways */
printf("\n\nThe address of var = %d", &var);
printf("\nThe address of var = %d\n", ptr);
*ptr=48; // modifying by accessing indirectly
printf("\nIndirect access, var = %d", *ptr);
return 0;
}

Output:

Direct access, var = 1


Indirect access, var = 1
The address of var = 4202496
The address of var = 4202496
Indirect access, var = 48

What is address of operator in C?


This address operator is denoted by “&”. This & symbol is called an ampersand. This
& is used in a unary operator. The purpose of this address operator or pointer is used to return
the address of the variable.The address of operator '&' returns the address of a variable. But,
we need to use %u or %p to display the address of a variable.

Example Program:
#include<stdio.h>
int main(){
int number=50;
printf("value of number is %d, address of number is %u",number,&number);
return 0;
}
Output
value of number is 50, address of number is fff4

What is indirection operator in C?


An indirection operator, is an operator used to obtain the value of a variable to which
a pointer points.The indirection operator is a unary operator represented by the symbol (*)
that can be used to obtain the value stored at the memory location referenced by a pointer
variable.
The indirection operator must precede the pointer variable name, with no intervening space.
The unary indirection operator ( * ) accesses a value indirectly, through a pointer.The
indirection operator is also known as the dereference operator.

Example:
int x; // the notation &x means "address of x"
//This is the best way to attach a pointer to an existing variable:
int * ptr; // a pointer
intnum; // an integer
ptr = &num; // assign the address of num into the pointer
// now ptr points to "num"!

Example Program:
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;
printf("value of number is %d, Address of number is %u",*p,p);
return 0;
}
Output
value of number is 50, address of number is fff4

Indirection (*) vs Addressof(&) :


The (*) symbol is used in declaring pointer types and in performing pointer
indirection, while the ‘address-of’ operator () returns the address of a variable. Hence, the
indirection operator and the address-of operator are inverses of each other.

What are types of pointers in C?


There are majorly four types of pointers, they are:
1. Null Pointer
2. Void Pointer
3. Wild Pointer
4. Dangling Pointer

Null Pointer:
NULL Pointer is a pointer which is pointing to nothing. In case, if we don’t have
address to be assigned to a pointer, then we can simply use NULL. If you assign a NULL
value to a pointer during its declaration, it is called Null Pointer.
Example Program:
// TO IMPLEMENT NULL POINTER IN C
#include <stdio.h>
int main()
{
// Null Pointer
int *ptr = NULL;
printf("The value of ptr is %p", ptr);
return 0;
}
Output :
The value of ptr is (nil)

Note:

NULL vsUninitialized pointer – An uninitialized pointer stores an undefined value. A null


pointer stores a defined value, but one that is defined by the environment to not be a valid
address for any member or object.
NULL vs Void Pointer – Null pointer is a value, while void pointer is a type

Void Pointer:
Void pointer is a specific pointer type – void * – a pointer that points to some data location in
storage, which doesn’t have any specific type. Void refers to the type. Basically the type of
data that it points to is can be any. If we assign address of char data type to void pointer it
will become char Pointer, if int data type then int pointer and so on. “Any pointer type is
convertible to a void pointer hence it can point to any value.”

The void pointer in C is a pointer that is not associated with any data types. It points to some
data location in the storage. This means that it points to the address of variables. It is also
called the general purpose pointer or generic pointer. In C, malloc() and calloc() functions
return void * or generic pointers.

Note:
1. void pointers cannot be dereferenced.
2. It can however be done using typecasting the void pointer.
3. Pointer arithmetic is not possible on pointers of void due to lack of concrete value and
thus size.

Example Program:
// TO IMPLEMENT VOID POINTER IN C
#include<stdlib.h>
int main()
{
int x = 4;
float y = 5.5;
void *ptr;//A void pointer
ptr = &x;
// (int*)ptr - does type casting of void
// *((int*)ptr) dereferences the typecasted
// void pointer variable.
printf("Integer variable is = %d", *( (int*) ptr) );
// void pointer is now float
ptr = &y;
printf("\nFloat variable is= %f", *( (float*) ptr) );
return 0;
}
Output:
Integer variable is = 4
Float variable is= 5.500000
Refer void pointer article for details.

Dangling Pointer:

A pointer pointing to a memory location that has been deleted (or freed) is called dangling
pointer. There are three different ways where Pointer acts as dangling pointer.

Wild Pointer:

A pointer which has not been initialized to anything (not even NULL) is known as wild
pointer. A wild pointer is only declared but not assigned an address of any variable. They are
very tricky, and they may cause segmentation errors.

Example Program:
// TO IMPLEMENT WILD POINTER IN C
int main()
{
int *p; /* wild pointer */
int x = 10;
// p is not a wild pointer now
p = &x;
return 0;
}

What are the operations possible on pointers?

Pointers directly store address in them and they indirectly point to values stored by the
variables they point to.So the possible or allowed or valid operations on pointers is called
pointer arithmetic.
It is of two types –
1. Pointer address arithmetic – Pointer arithmetic
2. Pointer value arithmetic – Pointer Expressions

Pointer address arithmetic:


Address arithmetic is a method of calculating the address of an object with the help of
arithmetic operations on pointers and use of pointers in comparison operations.A pointer in c
is an address, which is a numeric value. Therefore, you can perform arithmetic operations on
a pointer just as you can on a numeric value. There are four arithmetic operators that can be
used on pointers: ++, --, +, and -

Valid operations:
The operations possible on addresses stored in pointers are –

1. A constant can be added to a pointer.


2. A constant can be subtracted from a pointer.
3. Two pointers of similar type can be subtracted.
4. Pointer variables can be incremented and decremented.
5. Pointers of same type can also be compared using relational operators.
6. Using assignment operator, pointers of similar type can be assigned.
Invalid operations:

The operations not possible or invalid on addresses stored in pointers are –

1. Multiplication of pointers is not allowed.


2. Two pointers cannot be divided.
3. Addition of pointers is also not valid.
4. The indirection operator cannot be applied to a void pointer.
5. Multiplication of a pointer with a constant value.
6. Division of a pointer with a constant value.

Example Program:

#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+1;
p=p-3;
printf("After increment: Address of p variable is %u \n",p);
// in our case, p will get incremented by 4 bytes.
printf("After Decrement: Address of p variable is %u \n",p);
return 0; }
Output:

Address of p variable is 3214864300


After increment: Address of p variable is 3214864304
After Decrement: Address of p variable is 3214864292
Pointer Expressions:
Like other variables pointer variables can be used in expressions.
If p1 and p2 are properly declared and initialized pointers, then the following statements are
valid:

Y=*p1**p2;
Sum=sum+*p1;
Z=5*-*p2/*p1;
*p2=*p2+10;
*p1=*p1+*p2;
*p1=*p2-*p1;

Example Program:

#include <stdio.h>
int main()
{
int m = 5, n = 10, o = 0;
int *p1 ,*p2;
p1 = &m; //printing the address of m
p2 = &n; //printing the address of n
printf("\n *p1 = %d *p2 = %d",*p1,*p2);
o = *p1+*p2;
printf("\n *p1+*p2 = %d", o);
o = *p1-*p2;
printf("\n *p1 - *p2 = %d", o);
printf("\n *p1**p2 = %d", *p1**p2);
printf("\n ++*p1 = %d", ++*p1);
printf("\n *p2-- = %d", *p2--);
return 0;
}

Output:
*p1 = 5 *p2 = 10
*p1+*p2 = 15
*p1 - *p2 = -5
*p1**p2 = 50
++*p1 = 6
*p2-- = 10

What is pointer to pointer?

In c a pointer to a pointer is a form of multiple indirection, or a chain of pointers.


Normally, a pointer contains the address of a variable.When we define a pointer to a pointer,
the first pointer contains the address of the second pointer, which points to the location that
contains the actual value as shown below.
POINTER TO POINTER

Example Program:
//POINTER TO POINTER IN C
#include <stdio.h>
int main ( ) {
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var; /* take the address of var */
pptr = &ptr; /* take the address of ptr using address of operator & */
/* take the value using pptr */
printf("VARIABLE var = %d\n",var );
printf("POINTER : *ptr = %d\n",&ptr,ptr,*ptr );
printf("POINTER TO POINTER : **pptr = %d\n",**pptr);
return 0;
}

Output:

VARIABLE :var = 3000


POINTER :*ptr= 3000
POINTER TO POINTER :**pptr= 3000

Illustration:

What is size of pointer?

Any Pointer stores address. Addresses are always numbers and it can’t be a character,
a string or real/floating/double numbers.The size of the pointer basically depends on
the architecture of the systemin which it is implemented. For example the size of a
pointer in 32 bit is 4 bytes (32 bit) and 8 bytes (64 bit) in a 64 bit machines.
Irrespective of their data types, the size of pointer is fixed / constant and same for all
types of pointers.Size of a pointer is fixed, it doesn't depend on the data type it is
pointing to. We can use size of operator to get the size of a pointer.

The size of pointer variable is independent of the data type of the variable it is
pointing to because at the end it is pointing to a memory location.

Hence the size of char pointer, int pointer, float pointer, NULL pointer etc are all
same.

Size of int pointer = Size of char pointer = Size of float pointer = Size of any
other type of pointer.

Example Program:

#include<stdio.h>
int main()
{
int *p1;
char *p2;
float *p3;
printf("\n The size of integer pointer = %d",sizeof(int *));
printf("\n The size of character pointer = %d",sizeof(p2));
printf("\n The size of float pointer = %d",sizeof(p3));
printf("\n The size of double pointer = %d",sizeof(double *));
return 0;
}
Output:

The size of integer pointer = 8


The size of character pointer = 8
The size of float pointer = 8
The size of double pointer = 8

What is constant pointer?

These type of pointers are the one which cannot change address they are pointing to.
This means that suppose there is a pointer which points to a variable (or stores the address of
that variable). Now if we try to point the pointer to some other variable (or try to make the
pointer store address of some other variable), then constant pointers are incapable of this.
Note: However, these pointers can change the value of the variable they point to but cannot
change the address they are holding.A constant pointer which points to a variable cannot
be made to point to any other variable.

Example Program:

#include<stdio.h>
int main(void)
{
int var1 = 0, var2 = 0;
int *constptr = &var1;
ptr = &var2;
printf("%d\n", *ptr);
return 0;
}

Output :
Error
In function ‘main’:
constptr.c:7: error: assignment of read-only variable ‘ptr’

We assigned an address to a constant pointer and then tried to change the address by
assigning the address of some other variable to the same constant pointer that results in an
error.

What is pointer to a constant?

A pointer to constant is a pointer through which the value of the variable that the pointer
points cannot be changed. The address of these pointers can be changed, but the value of the
variable that the pointer points cannot be changed.

The qualifier const can be applied to the declaration of any variable to specify that its value
will not be changed. const keyword applies to whatever is immediately to its left. If there is
nothing to its left, it applies to whatever is immediately to its right.

As evident from the name, a pointer through which one cannot change the value of variable it
points is known as a pointer to constant. These type of pointers can change the address they
point to but cannot change the value kept at those address.

A pointer to constant is defined as:


const<type of pointer>* <name of pointer>

An example of definition could be :


const int* ptr;

Example Program:

#include<stdio.h>
int main(void)
{
int var1 = 0;
const int* ptr = &var1;
*ptr = 1;
printf("%d\n", *ptr);
return 0;
}

Output :

Error
constptr.c: In function ‘main’:
constptr.c:7: error: assignment of read-only location ‘*ptr’

So we see that the compiler complains about ‘*ptr’ being read-only.This means that we
cannot change the value using pointer ‘ptr’ since it is defined a pointer to a constant.

Pointers and Functions:

Pointers as function arguments:

Pointer as a function parameter is used to hold addresses of arguments passed during function
call.This is also known as call by reference.When a function is called by reference any
change made to the reference variable will effect the original variable.The actual arguments
are addresses of variables.The formal arguments are Pointers of specific data type like int,
char, float, structure, File etc.

Example Program:

#include <stdio.h>
intmain()
{
int a, b;
a = 5 ; b = 20 ;
swap (&a, &b) ;
printf (“\n a = %d, b = %d”, a, b);
}
void swap (int *x, int *y)
{
int t ;
t = *x ;
*x = *y ;
*y = t ;
}

Output

a = 20, b = 5

Pointers as function return type:

A function can also return a pointer to the calling function. In this case you must be careful,
because local variables of function doesn't live outside the function.They have scope only
inside the function.Hence if you return a pointer connected to a local variable, that pointer
will be pointing to nothing when the function ends that becomes a “dangling pointer “. If
local variables are to be returned then they should be static variables.

Example Program:

#include <stdio.h>
int* larger(int*, int*);
void main( )
{
int a = 15,b=92,*p;
p = larger(&a, &b);
printf("%d is larger",*p);
}
int* larger(int *x, int *y)
{ if(*x > *y)
return x;
else
return y;
}

Output :

92 is larger.

Explanation:

x, y are pointers that store the addresses of the variables of main function a,b respectively.
*x refers to value of a and *y referes to value of b so if *x>*y we return the address of a that
is x
Otherwise, we return the address of b that is ySo that’s why the return type of the function is
an integer type pointer.

Returning multiple Values through function using pointers:

Category 5 functions: Multiple values modified by the sub program can be reflected back in
the main program not by the return statement but by using pointers.

The return” statement cannot return more than one value.If at any time we want more than
one value of a sub program need to be returned or reflected to calling function then it is
possible using the concept of call by reference.When a function is called by reference any
change made to the reference variable will effect the original variable. The actual arguments
are addresses of the output or resultant variables in addition to input variables.The formal
arguments are Pointers of specific data type.

Example Program:

#include <stdio.h>
void compute(int *,int *,int *,int *,int *);
int main( )
{
int a=5, b=10,sum,dif,prod;
compute(&a, &b,&sum,&dif,&prod);
printf (“\n a = %d \n b = %d \n Sum =%d \n Diff= %d \n Product = %d”, a,
b,sum,dif,prod);
}
void compute (int *x, int *y, int *s, int *d, int *p )
{
*s=*x+*y;
*d=*x-*y;
*p=*x * *y;
}

Output :

a=5
b=10
Sum=15
Diff =-5
Product =50

Note:
Here we don’t use a return statement but using call by reference thevalues computed will be
reflected in main function. Thus we tend to show multiple value changes.

Pointer to a function or Function pointer:

In C, like normal data pointers (int *, char *, etc), we can have pointers to functions.It is
possible to declare a pointer pointing to a function.
A pointer to a function is declared as follows :
Declaration:
Return type (*pointer-name)(parameter);
Example :
int (*sum)(); //legal declaration of pointer to function
int *sum(); //This is not a declaration of pointer to function

Assigning and Calling a Function using Function Pointer:


A function pointer can point to a specific function when it is assigned the name of that
function.
Initializing Function Pointer:
int sum(int, int); // this is function declaration
int (*fptr)(int, int); // This is pointer declaration for that function
fptr = sum; // initializing function pointer
Here fptr is a pointer to a function sum. Now sum can be called using function pointer s along
with providing the required argument values.
Function call using Function Pointer:
fptr (10, 20); // function call using function pointer

Example Program:
//To implement function pointer.
#include <stdio.h>
int sum(int x, int y) ; // function declaration
{
int res;
int (*fptr)(int, int); // Declaration of function pointer
fptr = sum; // initialization of function pointer
res = fptr(10, 15); // function call using function pointer
printf(“\n Sum is %d", res);
return 0;
}
int sum(int x, int y) // function definition
{
returnx+y;
}

Output:

Sum is 25

Example -2 : Write a C program to usea function pointer to two different functions.

#include <stdio.h>
int sum(int x, int y) ; // function declaration
int multiply(int x, int y);
int main( )
{
int res;
int (*fptr)(int, int); // Declaration of fnptr
fptr = sum; // initialization
res = fptr(10, 15); // function call
printf(“\n Sum is %d", res);
fptr = multiply; // initialization
res = fptr(10, 15); // function call
printf(“\n Product is %d", res);
return 0;
}
int sum(int x, int y) // function definition
{
returnx+y;
}
int multiply(int x, int y) // function definition
{
return x*y;
}

Output :

Sum is 25
Product is 150

Following are some interesting facts about function pointers:


1. Unlike normal pointers, a function pointer points to code, not data. Typically a
function pointer stores the start of executable code.
2. Unlike normal pointers, we do not allocate de-allocate memory using function
pointers.
3. A function’s name can also be used to get functions’ address.
4. Like normal pointers, we can have an array of function pointers.
5. Like normal data pointers, a function pointer can be passed as an argument and can
also be returned from a function.

Pointers and Arrays:

Yes language C supports having pointer to arrays. Pointer to arrays is anormal pointer of that
data type.A pointer variable can store the address of only one variable at a time. An array
name is a constant pointer to the first element of the array.

When an array is declared,the compiler allocates a base address and sufficient amount of
storage to contain all the elements of the array in contiguous memory locations.The base
address is the location of the first element (index 0) of the array.The compiler also defines the
array name as a constant pointer to the first element.

If ‘p’ is a Pointer to a one Dimensional array ‘a’ then

The array name “a” is a constant pointer pointing to first element of that array
&a[0] => a => (base address)
To access the value , a[i] = we use *(p+i)
To access the address ,&a[i] = we use (p+i)

Declaration:
datatype *ptr; Eg: int *p; char *r;
Initialization:
// Let us assume a is the name of the array then
ptr=a;
or
ptr=&a[0];
Accessing:
Each character a[i]is accessed as *(ptr+i).
Example Program:

// POINTERS TO 1 D ARRAYS
// W A C P TO READ AND WRITE THE ELEMENTS OF 1 D ARARY USING
POINTERS
#include <stdio.h>
int main()
{
int a[5],i;
int *p; // declaration of pointer to 1 d array
p=&a[0]; // p=a; initialization of 1 d ararys
for(i=0;i<5;i++)
{
printf("\n Enter a value into a[%d] :",i);
scanf("%d",(p+i)); //&a[i]
}
printf("\n Array Elements \n");
for(i=0;i<5;i++)
{
printf("\n a[%d] = %d",i,*(p+i) );//a[i]
}
return 0;
}

Output :
Enter a value into a[0] :1

Enter a value into a[1] :2

Enter a value into a[2] :3

Enter a value into a[3] :4

Enter a value into a[4] :5

Array Elements

a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5

Pointers to 2 Dimensional Arrays

When an array is declared, the compiler allocates a base address and sufficient amount of
storage to contain all the elements of the array in contiguous memory locations.
The elements of a 2 D array are stored row wise contagious,xi.e after first row ,the first
element of second row is stored and so on..
The base address is the location of the first element (index [0][ 0]) of the array.
The compiler also defines the array name as a constant pointer to the first element.

If ‘p’ is a Pointer to a Two Dimensional array ‘a’ then with ‘r’ rows and ‘c’ columns….

The array name a, is a constant pointer pointing to first element of array


&a[0][0] the address of first element = >&a[0] the address of the first row => a => (base
address)
To access the value, a[i][j] = we use *(p+i*c+j) OR *(*(p+i)+j)
To access the address, &a[i] = we use (p+i*c+j) OR (*(p+i)+j)

Let us suppose a two-dimensional array - int matrix[3][3];

Example Program:

// W A C P TO READ AND WRITE a matrix/ 2 d array USING POINTERS


#include <stdio.h>
int main() {
int a[5][5],r,c,i,j;
int *p;
p=&a[0][0];
printf("\n Enter order of matrix A :");
scanf("%d %d",&r,&c);
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
printf("\n Enter a value into a[%d][%d] : ",i,j);
scanf("%d",(p+i*c+j)); //&a[i][j] => (p+i*c+j) } }
printf("\n MATRIX A \n");
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
printf("\t %d",*(p+i*c+j)); // a[i][j] => *(p+i*c+j)
}
printf("\n");
}
return 0;
}

Output :

Enter order of matrix A :22

Enter a value into a[0][0] : 1

Enter a value into a[0][1] : 2

Enter a value into a[1][0] : 3

Enter a value into a[1][1] : 4

MATRIX A
12
34

Pointers to Strings or Pointers to Character Arrays:

To store,read,write and access strings using pointers in C programming language is possible


as we know that a string is a sequence of characters which we save in contagious memory
locations.A pointer to a string in C can be used to point to the base address of the string array,
and its value can be dereferenced to get the value of the string. To get the value of the string
array is iterated using a while loop until a null character is encountered.

If ‘p’ is a Pointer to a a string str then,


&str[0] =>str => (base address)
To access the value, str[i] = we use *(p+i)
To access the address,&str[i] = we use (p+i)

Declaration: char *ptr;


Initialization: charstr[20]; ptr=str; or ptr=&str[0];
Accessing:
Each character Str[i]is accessed as *(ptr+i).
Example Program:

// pointers to 1 D CHAR ARRAYS


// TO READ AND display string using pointers
#include <stdio.h>
int main()
{
charstr[20];
char *p; // pointer to string or 1 d char array -- declaration
p=&str[0]; // initialization : base address then p starts pointing to array a.
// p=str;
printf("\n Enter a string :");
scanf("%s",p);
// str = p
printf("\n STRING = %s ",p);
return 0;
}

Output:

Enter a string :hello


STRING = hello

What is Array of Pointers in c?

Array of Pointers :An array of pointers would be an array that holds memory locations.
Such a construction is often necessary in the C programming language.In computer
programming, an array of pointers is an indexed set of variables in which the variables
are pointers (a reference to a location in memory).

Example Program:

// w A C P TO implement array of Pointers


#include <stdio.h>
int main()
{
int *ptr[4];
int a=5,b=7,c=9,d=56,i;
ptr[0]=&a;
ptr[1]=&b;
ptr[2]=&c;
ptr[3]=&d;
for(i=0;i<4;i++)
{
printf("\n*ptr[%d] = %d",i,*ptr[i]);
}
return 0;
}
Output:

Array of Pointers
*ptr[0] = 5
*ptr[1] = 7
*ptr[2] = 9
*ptr[3] = 56

Pointers and Structure:

Pointer to a Structure in C:

We have already learned that a pointer is a variable which points to the address of another
variable of any data type like int , char, float etc.Similarly, we can have a pointer to
structures, where a pointer variable can point to the address of a structure variable.Yes , we
can have pointers for structure.

How to declare Structures Pointer?

To access the members of a structure using pointers we need to perform the following
operations:

1. Declare the structure variable


2. Declare a pointer to a structure
3. Assign address of structure variable to pointer
4. Access members of structure using (. ) operator or using (->)member selection
operator or arrow operator.

How to initialize pointer to


Structures?

Syntax:

structtagname
{
Data type member1;
Data type member2;
--------------------------
};
struct tag-name var; // create a variable
struct tag-name *ptr; // create a pointer
ptr = &var; //assign structure variable address to structure pointer

To access members of a structure using pointers, we use the -> operator.

(*ptr).member1;
(or)
ptr->member1;
How to access data members of a structure using its pointer?

The parentheses around *ptr are necessary because the member operator “.” has a higher
precedence than the operator “*”

Accessing members
using pointer to structures
Note:The -> operator can be chained;
For Example: In a linked list, one may refer to n->next->next for the second following node
(assuming that n->next is not null).
struct student *ptr = &s1;
struct employee * p = &e1;
ptr->rollno;
ptr->name;
ptr->marks;
p->eid;
p->sal;

Example:

//Program to read and display student details using pointers to structures


#include<stdio.h>
struct student
{
int HTNO;
char NAME[20];
float AVG;
};
int main()
{
struct student s1;
struct student *ptr;
ptr=&s1;
printf("Enter student details:");
scanf("%d%s%f",&ptr->HTNO,ptr->NAME,&ptr->AVG);
printf("HTNO=%d",ptr->HTNO);
printf("NAME=%s",ptr->NAME);
printf("AVERAGE MARKS=%f",ptr->AVG);
}

OUTPUT:
Enter student details:
301
ajay
56.78
HTNO=301 NAME=ajay AVERAGE MARKS=56.779999
Introduction to Structures

In C programming, a structure (struct) is a collection of variables (can be of different types) under


a single name.Structure in c is a user-defined data type that enables us to store the collection of
different data types. Structures are a way to group several related variables into one place. Unlike
an array, a structure can contain many different data types (int, float, char, etc.).

What are Structures in C?

A structure is user defined data type in C. A structure creates a data type that can be used to group
items of possibly different types into a single type/entity. Structures are a way to group several
related variables into one place. Each variable in the structure is known as a member of the
structure.The key word that creates structures is struct.

Why do we needStructures in C?

C has built in primitive and derived data types. Still not all real world problems can be solved
using those types.You need custom data type for different situations.
For example, if you need to store 100 student record that consist of name, age and mobile
number.
• We need a method for packing together data of different types.
• Need a helpful tool to handle a group of logically related data items.

Advantages ofStructures in C

1. Structures gather more than one piece of data about the same object together in the same
place.
2. It is helpful when you want to gather the data of similar data types and parameters like
first name, last name, etc.
3. It is very easy to maintain as we can represent the whole record by using a single name.
4. In structure, we can pass complete set of records to any function using a single parameter.
5. You can use an array of structure to store more records with similar types.

Disadvantages of Structures in C:

1. If the complexity of IT project goes beyond the limit, it becomes hard to manage.
2. Change of one data structure in a code necessitates changes at many other places.
Therefore, the changes become hard to track.
3. Structure is slower because it requires storage space for all the data.

How to createStructures in C?

The following is the procedure to create structures –

1. “struct” keyword is used to declare structure.


2. Members of structure are enclosed within opening and closing braces.
3. Declaration of Structure reserves no space.
4. It is nothing but the “ Template / Map / Shape ” of the structure .
5. Memory is created, very first time when the variable is created / Instance is created.

What is StructureTemplate?

Structure template is a collection of all the logically related data members of a structure into a
single unit.
It has an optional name called structure tag name.
All the data members of a structure are listed between { } and terminated with (semicolon);
It has no memory allocated to it.
It is a collection of data members when variable for structure is created memory is allocated to it.

How to define a Structure template in C?


A structure template must be declared before using it. A structure template definition can inside
or outside the main program or any function.In general is it written above the main function in c.
A structure template must be defined with all the data members of the structure that make up a
unit.
How do you declare a template?
To declare a structure
• Create the beginning and ending statements for the structure using keyword "srtuct".
• You can specify the name to it.
• Add elements to the body of the structure.
• A structure must have at least one element.

StructureDeclaration

A structure is a collection of one or more variables of different data types, grouped together under
a single name. By using structures, variables, arrays, pointers etc..can be grouped together.
Before using any variable in c it must be declared to the compiler,likewise structures also must be
declared

What are the types ofStructures in C?


Structures can be declared using two methods:
• Tagged Structure
• Type-defined structures

What isTaggedStructurein C?
• The structure definition associated with the structure name is referred as tagged structure.
• It doesn’t create an instance of a structure and does not allocate any memory.
• Tag name is further used to access different structures defined in a program.
• Since each structure has different attributes, tag name helps to identify tem uniquely.
• The tag name is also optional in C.
• If tag name is not given it restricts variable creation to only along with template.

Syntaxof aTagged Structure

struct TAGNAME //Tagname is the name of the structure.


{ // struct is keyword
DataType varaible1;
DataType variable2;
…… //variable1, variable2 … are called members of the structure.
…… //The members are declared within curly braces.
Data Type variable-n;
}; // The closing brace must end with the semicolon.

Example of Tagged structure :

Example -1 :

struct student
{
int rollno;
char name[20];
int marks[6];
};

Example -2 :

struct Employee
{
int eid;
char name[20];
floatsal;
};

What isType Defined Structurein C?

• The structure definition associated with the keyword typedef is called type-defined
structure.
• This is the most powerful way of defining the structure...
• Type defined structures are very handy in implementing Data structures in C.
• They also become useful in passing structures to functions.
• They enhance readability.

The syntax of type defined structure is:

typedef struct // typedef is keyword


{ // struct is keyword
Type varaible1;
Type variable2;
…… //variable1, variable2…are called members of the structure
Type variable-n;
}Type;
//The closing brace must end with type definition name which in turn ends with semicolon.

ExampleofType-DefinedStructure:

Example -1:
typedef struct
{
Int rollno;
char name[20];
int marks[6];
} Student;

Example -2:
typedef struct
{
inteid;
char name[20];
intsal;
}Emp;

*Note : We cannot create variables along with template in this type-defined structure.

What isStructure Variable?

Memory is not reserved for the structure definition or structure template since no variables are
associated with the structure definition.
The members of the structure do not occupy any memory until they are associated with the
structure variables.
Structure variables are created after defining the structure template to allocate storage.

How do we declare/ create structure variables?

After defining the structure, variables can be defined as follows:

For Tagged Structure method,


struct TAGNAME v1,v2,v3….vn;

For, Type-defined structures which is most powerful is,


TypeDefinedName v1,v2,v3,….vn;

// Here v1,v2,v3 becomes variables

Examplesof creating structure variables

For Tagged Structure method,

• struct student s1,s2,s3;

• Struct Employee e1,e2,e3;

For, Type-defined structures ,


• Student s1,s2;
• Emp e1,e2;
Creation of structure variables inside main() or inside any function making it local :

void main( )
{
structtagname v1,v2,..vn;
// local
}
(or)

void function( )
{
structtagname v1,v2,..vn;
}

Example:
struct book
{
char name[30];
int pages;
float price;
};
void main( )
{
struct book b1,b2,b3;
-----
}

Creation of structure variables outside main() in global declaration section making it


global :

structtagname v1,v2,..vn;
//global
void main( )
{
------
-----
}

Example:
struct book
{
char name[30];
int pages;
float price;
};
struct book b1,b2,b3;

Creation of structure variables along with the structure templatemaking it global:

Syntax:

struct TAG
{
Type varaible1;
Type variable2;
……
……
Type variable-n;
} v1, v2, v3;

Example:
struct book
{
char name[30];
int pages;
float price;
}b1,b2,b3;

* Note: Here it becomes Global Declaration.

What is a method of accessing members of Structure?

Structure members cannot be accessed directly only with their name.


They cannot be accessed just like that in any function.
Structure members are accessed only using the structure variable.
A membership operator is used to access members of a structure using its variable.

What is membership operator in C?

It is also called as (.) Dot Operator.

Dot operator (.) :

In C programming language (.) is used to access members of a structure directly through a normal
structure variable.
It is used to access members of a union directly through a normal union variable.
Yes, dot (.) is actually an operator in C/C++ which is used for direct member selection via object
name. It has the highest precedence in Operator Precedence and Associativity chart after the
Brackets.
How toaccess members of Structure?
Structures use a dot (.) operator also called period operator or member operator to refer its
elements.
Before dot, there must always be a structure variable.After the dot, there must always be a
structure element.The syntax to access the structure members as follows:

SYNTAX: structure_variable_name .structure_member_name

Examples:

s1.rollno
s2.name
S3.marks
e1.eid
e2.sal
e3.name
Can weInitializeStructuresin C?

Yes, Structures can be initialised.


Is it in Structure Template?
Structures does not support initialization of data members inside template as it has no memory.
Is it a Structure Variable?
So Structures are initialized through or using their respective Structure variables.
What is Structure Initialization?

It is a process of giving some default values to structure data members through its variables.
• The rules for structure initialization are similar to the rules for array initialization.
• The initializers are enclosed in braces and separated by commas.
• They must match their corresponding types in the structure definition.

SYNTAX:
The syntax is shown below:
struct tag_name variable = { value1, value2,… value-n };

What are the ways to initialize structures?


Structure variable initialization can be done in anyone of the following ways:
(i) Initialization Along with Structure template or definition.

(ii) Initialization Inside main during variable creation.

(iii) Initialization Outside main during variable creation.

Initializing along with Structure template or definition

struct student
{
char name [5];
int rollno;
floatavg;
} s1= {“Ravi”, 10, 67.8};

Initializing Inside main during variable creation

struct student
{
char name [5];
introll_number;
floatavg;
};
void main( )
{
struct student s1= {“Ravi”, 10, 67.8};
---------
-------
}
Initializing Outside main during variable creation
struct student
{
char name [5];
introll_number;
floatavg;
};
struct student s1= {“Ravi”, 10, 67.8};
void main( )
{
---------
-------
}

Initializing TYPEDEFStructures

typedef struct
{
char name [5];
introll_number;
floatavg;
} student ;

student s1= {“Ravi”, 10, 67.8};


// outside main global
void main( )
{
student s1= {“Ravi”, 10, 67.8};
// inside main local
-------------
-------------
}
Note: In this method we cannot initialize along with template

PartialInitialization:

Yes, structure variable can be initialized with few values.

Example:

student s1= {“Ravi”}; => s1.rollno -> 0


=> s1.avg -> 0.0
The uninitialized values are filled with 0,0.0,NULL depending on data type of data member .

Points to remember:
• Initializers must match in type , order and number(count).
• String values are enclosed in “ “ and characters in ‘ ‘.
• Partial initialization is made for first few data members only.
• We cannot initialize structures members in random order and also with more initializers.

How to read andwrite data in structurein C?

To read and write structure members,we can use printf or scanf or any other I/O function.

Points to remember:

• Use the data member names only like variablename.data_membername


• Also do not use & for string members.

ExampleProgram:

Write a C program to read and writestructure in C?


struct Book
{
char Title[30];
int pages;
char Author[30];
int price;
};
void main( )
{
struct Book b1;
printf(“\n Enter Title , Pages , Author and Price of Book : ”);
scanf(“%s %d %s %d”, b1.Title,&b1.pages,b1.Author,&b1.price);
printf(“\n The details of the Book are:”);
printf(“\n Title : %s”, b1.Title);
printf(“\n Author : %s ”, b1.Author,);
printf(“\n Pages : %d \n Price : %d ”, b1.pages,b1.price);
}

Output:
Enter Title , Pages , Author and Price of Book :
Letusc250 Yaswanthkanitker 320
The details of the Book are :
Title :Letusc
Author :Yaswanthkanitker
Pages : 250
Price : 320
Write a C program to read and write the details of a student like name,roll number and
average?

Program:

#include<stdio.h>
struct student
{
char name [15];
int rollno;
floatavg;
}s1;
void main( )
{
printf("\n Enter Name , Rollno and Average of a student :");
scanf("%s %d %f",s1.name,&s1.rollno,&s1.avg); //read
printf("%s %d %f",s1.name,s1.rollno,s1.avg); //write
}

Output:
Enter Name , Rollno and Average of a student :ARUNU IMA 563
87.67
ARUNIMA 563 87.669998

What are the operations possible on structures?

In C a Structure has two things-Structure variables and Structure data members.


So let us See what are the possible operations on Structures.

• Operations on Structures Data members


• Operations on Structure Variables

Operations on Structures Data Members:

The operations on data members of a Structure depend upon the data type of that structure.
Depending on the data type all the operations are possible on that data type are allowed on that
data type.So all operation on integers are allowed on integer data members of a structure and so
on.

Example:

s1.rollno=si.rollno-2; // int member --- valid


strcpy (s1.name,”Hello”); // string member --- valid
s1.marks = s1.marks/10; // int member --- valid
// s1.avg = s1.avg % 5; Invalid
// sinceavg is a float data member of structure student , % is not allowed so it is invalid.

Operations on Structure Variables:

Operations are possible on Structure Variables ---


A structure variable can be copied to another of similar type.

Example:
Struct Student
{
Int rollno;
char name[20];
}s1={73,”Sindhu”}, s2;
But if we have e1 as an employee structure variable then
e1=s1 ; is invalid as they are of different structures

Here,
s2=s1;
Copies all values of s1 to s2.

So
Printf(“%d %s”,s2.rollnos2.name);
Output : 73 Sindhu

Can we compareStructure Variables?

Though we can copy one structure variable to another in C, we cannot compare one structure
variable with another.

Operations not possible on Structure Variables ---


A structure variable cannot be compared to another with a relational operator (= = ).

Example:

Struct Student
{
Int rollno;
char name[20];
}s1={73,”Sindhu”}, s2;
s2=s1; // valid

But when we have to compare

if(s1==s2) // not possible


printf(“similar”);

But it is Invalid

So they can be compared only by comparing individual members.

Example:Comparingstructure variables

Struct Student
{
Int rollno;
char name[20];
}s1={73,”Sindhu”}, s2;
s2=s1; // valid
// if(s1==s2) // invalid

But How do we compare then..??


if(s1.rollno==s2.rollno && (strcmp(s1.name,s2.name)==0))
printf(“Similar”);
else
printf(“Not Similar”);

ARRAYSWITHIN STRUCTURES:

Arrays as structures members.

Is it possible to have structure members as arrays?


Yes we can have arrays as data members of structures. It is also possible to declare an array as a
member of structure.

Need for arrays within Structures:

Example: To store marks of a student in six subjects then we can have the following as a data
member of a structure.
int marks[6];

Example: To store name of each student then we can have the following as a data member of a
structure.
char name[20];

Working with array of structures:

Declaration:
They are declared just as normal data members of structures.
Example :
To store the details of a student we can have the following as a template of a structure.
struct student
{
char name [20]; // character array to store name of student
introll_number;
int marks [6]; // marks of 6 subjects of a student
floatavg;
};

Initialization of arrays within Structures:


Then the initialization of the array marks done as follows:
struct student s1= {“Raghu”, 34, {60,70,80,40,90,85} };
The values of the member marks array are referred as follows:
s1.marks [0] --> will refer the 1 st value of marks.
s1.marks [1] --> will refer the 2 nd value of marks.
s1.marks [2] --> will refer the 3 rd value of marks.

Accessing arrays within Structures:


To access array members of a Structure we use structure variable ,dot operator, array data
member.
Syntax:
Structure_variable_name.arraydatamembername[index];
Example :
Struct student s1;
//use a for loop from i=0 to n (size) and use
s1.marks[i]

Reading and writing arrays within structures:

To Read:

printf(“Enter details of Student – 1 Name , Rollno:”);


scanf(“%s %d”,s1.name,&s1.rollno);
printf(“\n Enter marks of 5 Subjects :”);
for(i=0;i<5;i++)
{
scanf(“%d”,&s1.marks[i]);
sum+=s1.marks[i];
}

To write:

Printf(“\n Details of students are : \n Name : %s Roll no : %d \n Marks : ”, s1.name,s1.rollno);


for(i=0;i<5;i++)
printf(“%d ”,s1.marks[i]);
printf(“\n Total : %d “,sum;

Write a C program to implement arrays within structures?

PROGRAM:
//ARRAYS WITHIN STRUCTURES
#include<stdio.h>
struct student
{
char name [15];
int rollno;
int marks[3];
int total;
}s1;

int main( )
{
inti;
printf("\n Enter Name , Rollno");
scanf("%s %d",s1.name,&s1.rollno);
s1.total=0;
for(i=0;i<3;i++)//read
{
printf("\n Enter marks of subject %d:",i+1);
scanf("%d",&s1.marks[i]);
s1.total+=s1.marks[i];
}
printf("\nNAME: %s \nROLL NO: %d \nTOTAL: %d",s1.name,s1.rollno,s1.total); //write
return 0;

}
Output :
Enter Name , Rollno: ARUNIMA
501

Enter marks of subject 1:90


Enter marks of subject 2:89
Enter marks of subject 3:78

NAME: ARUNIMA
ROLL NO: 501
TOTAL: 257

ARRAYOFSTRUCTURES:

Need for Array of Structures:

An array is a collection of elements of same data type that are stored in contiguous
memorylocations. A structure is a collection of members of different data types stored in
contiguous memory locations.An array of structures is an array in which each element is a
structure.
This concept is very helpful in representing multiple records of a file, where each record is a
collection of dissimilar data items.Used in implementing various operations on real time data like
employee, student, books etc.

As we have an array of integers, we can have an array of structures also.


For example, suppose we want to store the information of class of 60 students, consisting of
name, roll_number and marks.A better approach would be to use an array of structures.
Array of structures means having array of structure Variables.A structure variable can be an
array holding fixed number of variables.

Array of structures can be declared as follows:

struct tag_namearrayofstructurevariable[size];

Let’s take an example, to store the information of 3 students, we can have the following structure
definition and declaration,
struct student
{
char name[10];
intrno;
floatavg;
};
struct student s[3]; // declaration of array of structure

Defines an array called s, which contains three elements. Each element is defined to be of type
struct student.

Initialization:
Array of structures can be declared as follows:

struct tag_namearrayofstructurevariable[size]={set of records};


Let’s take an example, to store the information of 3 students, we can have the following structure
definition and declaration,
struct student
{
char name[10];
intrno;
floatavg;
};
struct student s[3]; // declaration of array of structure

Defines an array called s, which contains three elements. Each element is defined to be of type
struct student.

struct student s[3]={


{“ABC”,1,56.7},
{“xyz”,2,65.8},
{“pqr”,3,82.4}
};

struct employee emp[5] = {


{1,”ramu”25,20000},
{2,”ravi”,65000},
{3,”tarun”,82000},
{4,”rupa”,5000},
{5,”deepa”,27000}
};

Access members of array of Structures:

To access members of array of structure, since Structure Variable is an array, we need to use an
array structure variable with proper index , dot operator , data member name using a for loop.

Syntax:

Structure
variable[index].datamembername;

Example:s[0].name; => name of 1 st student


s[2].rollno; =>rollno of 3 rd student
s[1].marks; => marks of 2 nd student.
If the member is an array then like…
s[ i ].marks[ j ] ; => (j+1) th subject marks of ( i+1) th student
like…..
s[1].marks[2] ; => 3 rd subject marks of second.

Write a C program to implement arrays within structures?

PROGRAM:

//structures array of structures


#include<stdio.h>
struct student
{
intrno;
char name[20];
int marks;
};

int main()
{
struct student s[10];
inti,n;
printf("\n Enter n:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter details of Studnet 1 rno,name,marks:");
scanf("%d %s %d",&s[i].rno,s[i].name,&s[i].marks);
}
printf("\n ROLLNO NAME MARKS\n");
for(i=0;i<n;i++)
{
printf("\n%d\t%s\t%d",s[i].rno,s[i].name,s[i].marks);
}
return 0;
}

Output:

Distinguish between Arrays within Structures and Array of Structures with examples.

Arrays within structure:


It is also possible to declare an array as a member of structure, like declaring ordinary variables.
For example to store marks of a student in three subjects then we can have the following
definition of a structure.
struct student
{
char name [5];
introll_number;
int marks [3];
floatavg;
};

Then the initialization of the array marks done as follows:


struct student s1= {“ravi”, 34, {60,70,80}};
The values of the member marks array are referred as follows:
s1.marks [0] --> will refer the 0th element in the marks s1.marks [1] --> will refer the 1st element
in the marks s1.marks [2] --> will refer the 2ndt element in the marks

Array of structures:

An array is a collection of elements of same data type that are stored in contiguous memory
locations. A structure is a collection of members of different data types stored in contiguous
memory locations. An array of structures is an array in which each element is a structure. This
concept is very helpful in representing multiple records of a file, where each record is a collection
of dissimilar data items.

Example:

An array of structures for structure employee can be declared as


struct employee emp[5];
Let‟s take an example, to store the information of 5 employees, we can have the following
structure definition and declaration,
struct employee
{
intempid; char name[10]; float salary;
};
struct employee emp[5];

Defines array called emp, which contains five elements. Each element is defined to be of type
struct student.

For the student details, array of structures can be initialized as follows, struct employee emp[5] =
{{1,”ramu”25,20000},{2,”ravi”,65000},{3,”tarun”,82000},{4,”rupa”,5000},{5,”deep”,27000}};

NESTED STRUCTURES:

Yes it is allowed to nest structures in C.Like Loops, Nested structures in C are the Structures
inside the Structure. A structure can be used as a member of another structure.
In other words, the members of a structure can be of any other type including structure.
For example, we have two structures named Address and Employee.We can make Address
nested to Employee.

Need for Nested Structures:

Nested structure in C is nothing but structure within structure.C provides us the feature of nesting
one structure within another structure by using which, complex data types are created. Using this
one structure can become a part of multiple structures. For Example , Using this, we can create
one structure called address and add door number, street name, city members under it.
Now, we can call this address structure from the Employee, Student, and Person structures.

How to declare Nested Structures?


A structure which includes another structure is called nested structure or structure within
structure. There are two methods for declaration of nested structures.

• Defining template and variable of one structure inside another structure.


• Creating variable of one structure inside another structure.
(template is defined for inner structure separately)

How to Define nestedstructures??

METHOD-1:Defining template and variable of one structure inside another structure.


Synatx:
struct Outerstructure
{
datatype mem1;
datatype mem2;
--------------------
--------------------
struct Innerstructure
{
datatype dm1;
datatype dm2;
----------------
----------------
} Innervariable;
-----------
-----------
} <outervariable>;

In this method :

• Inner structure template and variable both are declared inside the outer structure template
itself.
• Also the inner structure is local to outer structure only.
• It means inner structure is not available outside.
• It can be used only along with outer structure.

Example:

struct Student
{
introllno;
char name[20];
struct Address
{
inthno;
char street[20];
char city[20];
} ad;
int marks;
} s1;

In this method,Outer structure is Student whose members arerollno ,name and marks and
Also another structure as member i.e Address.So the inner structure is address whose members
are hno,street,city.Address is only accessed through student structure only.Variable for inner
structure must be created only along with template.
METHOD-2:Creating variable of one structure inside another structure.
Syntax:
struct Innerstructure
{
datatype dm1;
datatype dm2;
----------------
----------------
};
struct Outerstructure
{
datatype mem1;
datatype mem2;
--------------------
--------------------
structInnerstructureInnervariable;
----------------------
} <outervariable>;

struct Innerstructure
{
datatype dm1;
datatype dm2;
----------------
----------------
};
struct Outerstructure
{
datatype mem1;
datatype mem2;
--------------------
--------------------
structInnerstructureInnervariable;
----------------------
} <outervariable>;

In this method, Inner structure template is defined separately outside and above the outer
structure. Only variable of inner structure is created inside the outer structure template.Here the
inner structure can be used separately and also in any other structures as well as outer structure .
It means inner structure is available outside as well .
Example:

struct Address
{
inthno;
char street[20];
char city[20];
};

struct Student
{
introllno;
char name[20];
struct Address ad;
int marks;
} s1;
In this method Outer structure is Student whose members arerollno ,name and marks and
Also another structure as member i.e Address.So the inner structure is address
Whose members are hno,street,city.Only variable for inner structure is created inside outer
structure. Template of inner structure must be created Outside and always above the outer
structure.

How toInitialize Nested Structures?

struct Student
{
introllno;
char name[20];
struct Address
{
inthno;
char street[20];
char city[20];
} ad;
int marks;
} s1={21,”Raghu”,{123”SBI Bank street”,”Hyderabed”},90};

struct Student s2={22,”Ravi”,{13”street No 8”,”Hyd”},80};

How to accessdata members of Nested Structures?

A nested structure has two types of data members -Direct members.


(data members of outer structure)
Nested members.
(they are the data members of inner structure)
So direct members of Outer structure are accessed by
Outerstructurevariable.outerstructuredirectmembername;

Where as nested structure members can be accessed by

Outerstructurevariable. Innerstructurevariable.nestedmembername;

Example- Accessing data members of nested Structures

struct Student
{
introllno;
char name[20];
struct Address
{
inthno;
char street[20];
char city[20];
} ad;
int marks;
} s1;
Direct members. (rollno,name,marks)
Nested members.(hno,street,city)
To access direct members is like - Outerstructurevariable.outerstructuredirectmembername;
s1.rollno , s1.name, s1.marks
Where as nested structure members can be accessed like
Outerstructurevariable. Innerstructurevariable.nestedmembername;
s1.ad.hno, s1.ad.street, s1.ad.city.

PASSINGSTRUCTIRES TOFUNCTIONS:

Can we pass Structures to functions?

Yes structures can be made as function arguments.A structure can be passed as an argument to a
function and also a function can return a structure type variable as well.Even a function in C can
have a pointer to structure as function argument and also return a pointer to structure as well.
Passing structures to functions is another way of sending multiple heterogeneous data at once to a
function.An entire record can be passed to a function for some processing.

How to pass Structures to functions?

Structures can be passed to functions and to do that we need to have a structure type variable.
In general since a structure variable can be copied into another variable of similar type it is
possible to do so.They can be passed in both Call by value and call by reference techniques.
• Passing normal Structure Variables => Pass by Value
• Passing Address of structure Variables => Pass by Reference
Even we can pass individual elements of a structure to a function.

In How many ways we pass Structures?

Structures are more useful if we are able to pass them to functions and return them.

They can be passed in many ways:

• By passing individual members of structure.


• By passing a structure variable to a function.
• By passing reference of a structure variable to a function.
• By passing array of structure variables to a function.

Structure variables can also be a return type of a function:


• Returning a Structure Variable from a function.
• Returning a Pointer to a Structure Variable from a function.

Passing individual members of structure:

Structures are more useful if we are able to pass them to functions and return them.
By passing individual members of structure
This method is to pass each member of the structure as an actual argument of the function
call. The actual arguments are treated independently like ordinary variables. This is the most
elementary method and becomes unmanageable and inefficient when the structure size is
large.
Program:
#include<stdio.h>
typedef struct emp

{
char name[15];
intemp_no;
float salary;
}record;

void main ( )

floatarriers (char *s, int n, float m);

record e1 = {"smith",2,20000.25};

e1.salary = arriers(e1.name,e1.emp_no,e1.salary);

floatarriers(char *s, int n, float m)

m = m + 2000;
printf("\n%s %d %f ",s, n, m);
return m;

}
}

Output

smith 2 22000 250000

Passing a structure variable to a function:


Structures are more useful if we are able to pass them to functions and return them.

Passing Whole Structure:


This method involves passing a copy of the entire structure to the called function. Any changes to
structure members within the function are not reflected in the original structure. It is therefore,
necessary for the function to return the entire structure back to the calling function.
The general format of sending a copy of a structure to the called function is:

return_typefunction_name (structure_variable_name);

The called function takes the following form:

data_typefunction_name(struct_typetag_name)
{
………
………
return(expression);
}

The called function must be declared for its type, appropriate to the data type it is expected to
return.The structure variable used as the actual argument and the corresponding formal argument
in the called function must be of the same struct type.The return statement is necessary only when
the function is returning some data back to the calling function. The expression may be any
simple variable or structure variable or an expression using simple variables.When a function
returns a structure, it must be assigned to a structure of identical type in the calling function. The
called functions must be declared in the calling function appropriately.

Program:

#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};

voidfunc(struct student record);


int main()
{
struct student record;

record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
return 0;
}
voidfunc(struct student record)
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}

Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Passing a pointer to astructure to a function.
Example Program:
#include<stdio.h>
struct student
{
char name [20];
introllno;
int marks;
};
voiddisplay_student(struct student *ptr);
int main( )
{
struct student s1;
printf("Enter details of Student – 1 Name , Rollno and Marks:");
scanf("%s %d %d",s1.name,&s1.rollno,&s1.marks);
display_student(&s1);
return 0;
}
voiddisplay_student(struct student *ptr)
{
printf("\n Details of students are : \n Name : %s Roll no : %d \n Marks : %d : ",ptr->name,ptr-
>rollno,ptr->marks);
}

OUTPUT:

Enter details of Student – 1 Name , Rollno and Marks:Aditya


564
87
Details of students are :
Name : Aditya Roll no : 564
Marks : 87 :

STRUCTURES AS FUNCTION RETURN TYPE OR FUNCTIONS RETURNING


STRUCTURES:

Can a function return structure type?

Yes a function can have a structure type variable as its return type.It can be structure type
variable or can also be a pointer to structure.

The Prototype of such functions would be like –


struct<tag name>function_name ( arguments );
=>Here fn returns a structure type variable.
struct<tag name> * function_name ( arguments );
=>Here fn returns a pointer to a structure variable.
Example Program:

Develop a c program for illustrating a function returning a structure.

typedef struct
{
char name [15];
intemp_no;
float salary;
} record;

#include<stdio.h.>
#include<string.h>
void main ( )
{
record change (record);
record e1 = {"Smith", 2, 20000.25};

printf ("\nBefore Change %s %d %f",e1.name,e1.emp_no,e1.salary); e1 = change(e1);


printf ("\nAfter Change %s %d %f ",e1.name,e1.emp_no,e1.salary);
}

record change (record e2)


{
strcpy (e2.name,"Jones"); e2.emp_no = 16; e2.salary = 9999;
return e2;
}

Output:
Smith 2 20000.25
Jones 16 9999.99

Write a c program to implement function returning structures?

// STRUCTURES AND FUNCTIONSCOMPLEX NUMBERS


// using typedef
#include <stdio.h>
struct COMPLEX
{
intrel;
intimg;
};

typedef struct COMPLEX CMPLX;


CMPLX sum(CMPLX c1,CMPLX c2);

int main()
{
CMPLX c1,c2,c3;
printf("\n Enter real and imaginary parts of complex number c1:");
scanf("%d %d",&c1.rel,&c1.img);
printf("\n Enter real and imaginary parts of complex number c2:");
scanf("%d %d",&c2.rel,&c2.img);
c3=sum(c1,c2);
printf("\n SUMOF COMPLEX NUMBERS C1 AND C2 IS C3");
printf("\n COMPLEX NUMBER C3 = %d +i %d",c3.rel,c3.img);
return 0;
}

CMPLX sum(CMPLX c1,CMPLX c2)


{
CMPLX c3;
c3.rel=c1.rel+c2.rel;
c3.img=c1.img+c2.img;
return(c3);
}

OUTPUT:

Enter real and imaginary parts of complex number c1:237


Enter real and imaginary parts of complex number c2:5 9

SUMOF COMPLEX NUMBERS C1 AND C2 IS C3


COMPLEX NUMBER C3 = 28 +i16

UNIONS IN C:

What is aUnion?
A union is one of the User Defined data types.Union is a collection of variables referred under a
single name. The syntax, declaration and use of union is similar to the structure but
itsfunctionality is different.
Syntax:
unionunion_name
{
<data-type> element 1;
<data-type> element 2;
………………
} union_variable;

Example:
union techno
{
intcomp_id;
char nm;
floatsal;
} tch;

How to work with Unions?


A union variable can be declared in the same way as structure variable.
uniontag_name var1, var2...;
A union definition and variable declaration can be done by using any one of the following
A union variable can be declared in the same way as structure variable.
uniontag_name var1, var2...;
A union definition and variable declaration can be done by using any one of the following

Memory Map of Unions:


We can access various members of the union as mentioned:a.c,a.i, a.f
A union creates a storage location that can be used by any one of its members at a time.
“When a different member is assigned a new value, the new value supersedes the previous
members value”.

Here , the member f requires 4 bytes which is the largest among all the members.
All the three variables share the same address.
The size of the union here is 4 bytes.

SIZE OF STRUCTURES AND UNION:


Size of structure:
It is the sum of sizes of all its data members in addition to extra slack bytes if any – arise due to
structure padding during allocation.
int x= sizeof(struct <tagname>);
(0r)
int x =sizeof(structureVariablename);
struct Test
{
int x;
charstr[10];
float y;
} t1;

Here :
int x = sizeof(struct Test);
int x = sizeof(t1); x => 16
=> 2 bytes for int + 10 bytes for string + 4 bytes for float
Size of Union:
It is the size of its largest data member.
int x= sizeof(union <tagname>);
(0r)
int x =sizeof(unionVariablename);
union Test
{
int x;
charstr[10];
float y;
} t1;
Here :
int x = sizeof(union Test);
int x = sizeof(t1); x => 10
=>Maximum(2 bytes for int , 10 bytes for string , 4 bytes for float ).

Write a C program to implement Unions?


Program:
//implementing union
#include <stdio.h>
#include <string.h>
union Test
{
int x;
charstr[10];
}t1={7};
int main()
{
printf("\n x = %d",t1.x);
strcpy(t1.str,"Griet");
printf("\n str = %s",t1.str);
printf("\n Size of union = %d",sizeof(t1));
return 0; }
Output:
x = 7 str = Griet
Size of union = 10

Differentiate between Structures and Unions in c


The important difference between structure and union:
Structure Union
We use a struct keyword to define a structure. We use a union keyword to define a union.
Every member within structure is assigned a In union, a memory location is shared by all
unique memory location. the data members.

It enables you to initialize several members at It enables you to initialize only the first
once. member of union.

Changing the value of one data member will Changing the value of one data member will
not affect other data members in structure. change the value of other data members in
union.

The total size of the structure is the sum of the The total size of the union is the size of the
size of every data member. largest data member.

It is mainly used for storing various data It is mainly used for storing one of the many
types. data types that are available.
It occupies space for each and every member It occupies space for a member having the
written in inner parameters. highest size written in inner parameters.
You can retrieve any member at a time. You can access one member at a time in the
union.

Advantages of structures:

1. Structures gather more than one piece of data about the same subject together in the same
place.
2. It is helpful when you want to gather the data of similar data types and parameters like
first name, last name, etc.
3. It is very easy to maintain as we can represent the whole record by using a single name.
4. In structure, we can pass complete set of records to any function using a single parameter.
5. You can use an array of structure to store more records with similar types.
Advantages of union
1. It occupies less memory compared to structure.
2. When you use union, only the last variable can be directly accessed.
3. Union is used when you have to use the same memory location for two or more data
members.
4. It enables you to hold data of only one data member.
5. Its allocated space is equal to maximum size of the data member.
Disadvantages of structure
1. If the complexity of IT project goes beyond the limit, it becomes hard to manage.
2. Change of one data structure in a code necessitates changes at many other places.
Therefore, the changes become hard to track.
3. Structure is slower because it requires storage space for all the data.
4. You can retrieve any member at a time in structure whereas you can access one member
at a time in the union.
5. Structure occupies space for each and every member written in inner parameters while
union occupies space for a member having the highest size written in inner parameters.
6. Structure supports flexible array. Union does not support a flexible array.

Disadvantages of union

1. You can use only one union member at a time.


2. All the union variables cannot be initialized or used with varying values at a time.
3. Union assigns one common storage space for all its members.
UNIT-V
Files: Text and Binary files, Creating and Reading and writing text and binary files, Random access to
files, Error Handling in files Command line arguments, Enumeration data type.
Preprocessor: Commonly used Preprocessor commands like include, define, undef, if, ifdef, ifndef, elif.

File : A file is an external collection of related data treated as a unit. A file is a place on a disk
where a group of related data is stored and retrieved whenever necessary without destroying
data.
The primary purpose of a file is to keep record of data. Record is a group of related fields. Field
is agroupof characters which conveymeaning. Files are stored in auxiliary or secondary storage
devices. The two common forms of secondary storage are disks (hard disk, CD and DVD) and
tapes.

Each file ends with an end of file (EOF) at a specified byte number, recorded in file structure.

A file must first be opened properly before it can be accessed for reading or writing. When a
file is opened an object (buffer) is created and a stream is associated with the object.
It is advantageous to use files in the following circumstances.

When large volume of data are handled by the programand


When the data need to be stored permanently without getting destroyed when program
isterminated.

There are two kinds of files depending upon the format in which data is stored:

1)Text files
2) Binaryfiles

Textfiles:
A text file stores textual information like alphabets, numbers, special symbols, etc.

Actually the ASCII code of textual characters its stored in text files. Examples of some text
filesincludec,java,c++sourcecodefilesandfileswith.txtextensions.Thetextfilecontains
the characters in sequence. The computer process the text files sequentially and in forward
direction. One can perform file reading, writing and appending operations. These operations
are performed with the help of inbuilt functions of c.
Binary files:

Textmodeisinefficientforstoringlargeamountofnumericaldatabecauseitoccupieslarge
space.Onlysolutiontothisistoopenafileinbinarymode,whichtakeslesserspacethanthe text mode.
These files contain the set of bytes which stores the information in binary form. One main
drawback of binary files is data is stored in human unreadable form. Examples of binary files
are .exe files, video stream files, image files etc. C language supports binary file operations
with the help of various inbuiltfunctions

Modes of opening files :


To store data in a file three things have to be specified for operating system. Theyinclude
FILENAME:
It is a string of characters that make up a valid file name which may contain two parts,a
primary name and an optional period with the extension.
Prog1.c
DATASTRUCTURE:
It is defined as FILE in the library of standard I/O function definitions. Therefore all files are
declared as type FILE.FILE is a define data type.
FILE *fp;
PURPOSE:
It defines the reason for which a file is opened and the mode does this job.
fp=fopen(“filename”,”mode”);

The different modes of opening files are :


“r” (read) mode:

The read mode (r) opens an existing file for reading. When a file is opened in this mode, the.
file marker or pointer is positioned at the beginning of the file (first character).The file must
alreadyexist:ifitdoesnotexistaNULLisreturnedasanerror.Ifwetrytowriteafileopened in read
mode, an erroroccurs.
Syntax:fp=fopen (“filename”,”r”);

“w” (write) mode:


The write mode (w) opens a file for writing. If the file doesn‟t exist, it is created. If italready
exists, it is opened and all its data is erased; the file pointer is positioned at the beginning of the
file It gives an error if we try to read from a file opened in writemode.
Syntax: fp=fopen (“filename”,”w”);

“a” (append) mode:


Theappendmode(a)opensanexistingfileforwritinginsteadofcreatinganewfile.However, the
writing starts after the last character in the existing file ,that is new data is added, or
appended,attheendofthefile.Ifthefiledoesn‟texist,newfileiscreatedandopened.Inthis case, the
writing will start at the beginning of thefile.
Syntax: fp=fopen (“filename”,”a”);

“r+” (read and write) mode:


In this mode file is opened for both reading and writing the data. If a file does not exist then
NULL, is returned.
Syntax: fp=fopen (“filename”,”r+”);

“w+” (read and write) mode:


In this mode file is opened for both writing and reading the data. If a file already exists its
contents are erased and if a file does not exist then a new file is created.
Syntax:fp=fopen (“filename”,”w+”);

“a+” (append and read) mode:


In this mode file is opened for reading the data as well as data can be added at the end.

Syntax:fp=fopen (“filename”, “a+”);


NOTE: To perform operations on binary files the following modes are applicable with an
extension b like rb,wb,ab,r+b,w+b,a+b,which has the same meaning but allows to perform
operationson binaryfiles.

Basic operations on file:

Naming afile
Opening afile
Reading data fromfile
Writing data intofile
Closing aFile
In order to perform the basic file operations C supports a number of functions .Some of the
Important file handling functions available in the C library are as follows:

FUNCTION OPERATION
NAME
fopen() Creates a new file for use or Opens an existing file for use

fclose() Closes a file which has been opened for use

fcloseall() Closes all files which are opened

getc()/fgetc() Reads a character from a file

putc()/fputc() Writes a character to a file

fprintf() Writes a set of data values to files

fscanf() Reads a set of data values from files

getw() Reads an integer from file

putw() Writes an integer to a file

fseek() Sets the position to a desired point in a file

ftell() Gives the current position in the file

rewind() Sets the position to the beginning of the file

Naming and opening a file:

Anameisgiventothefileusedtostoredata.Thefilenameisastringofcharactersthatmake up a
valid file name for operating system. It contains two parts. A primary name and an
optional period with theextension.

Examples: Student.dat, file1.txt, marks.doc, palin.c The general format of declaring and
opening a file is
FILE *fp; //declaration
fp=fopen (“filename”,mode”); //statement to open file.

Here FILE is a data structure defined for files. fp is a pointer to data type FILE.
filename is the name of the file. mode tells the purpose of opening this file.

Reading data from file:

Input functions used are ( Input operations on files)


getc(): It is used to read characters from file that has been opened for readoperation.
Syntax: c=getc (filepointer);

Writing data to a file:


To write into a file, following C functions are used
putc():This function writes a character to a file that has been opened in writemode.
Syntax: putc(c,fp);

Closing a file:

A file is closed as soon as all operations on it have been completed.Closing a file ensures that
alloutstandinginformationassociatedwiththefileisflushedoutfromthebuffersandalllinks
tothefilearebroken.Anotherinstancewherewehavetocloseafileistoreopenthesamefile in a
differentmode.
Library function for closing a file is,

fclose(file pointer);

Example: fclose(fp);

Where fp is the file pointer returned by the call to fopen(). fclose() returns 0 on success (or)
- 1 on error. Once a file is closed, its file pointer can be reused for another file. Note: fcloseall()
can be used to close all the opened files at once.

A program that demonstrates w and w+ modes is given below −

#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp=fopen("abcd.txt","w+"); //change w+ to w and see output
fputs(" lgriet",fp);
rewind(fp);
/*reading with w+ mode, with w u can't read the file content */
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
}

A program that demonstrates r and r+ modes is given below −

#include <stdio.h>
int main()
{
FILE* fp;
char ch;
fp = fopen("abcd.txt", "r+");
while((ch=getc(fp))!=EOF)
putchar(ch);
printf("\n");
fprintf(fp, " this is pps lab."); //change r+ to r and see if this content is
updated in file
rewind(fp); //sets the file position to the beginning of the file
while(1)
{
ch = fgetc(fp);
if (ch == EOF)
break;
printf("%c", ch);
}
fclose(fp);
}

A program that demonstrates a and a+ modes is given below –

#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("abc.txt","w");
printf("enter the some characters and press @ to stop:\n");
while((ch=getchar())!='@')
{
putc(ch,fp);
}
fclose(fp);

fp = fopen("abc.txt", "a+"); //change a+ to a mode and see if u can read the content from file
fprintf(fp, "%s %s", "Arsenal",”Gunner");
rewind(fp);
printf("Appended file content:\n");
while((ch = fgetc(fp))!= EOF)
{
printf ("%c", ch);
}
fclose(fp);
return 0;
}

File I/O functions:


In order to perform the file operations in C we must use the high level I/O functions which are
in C standard I/O library. Theyare

getc() and fgetc()functions:


getc()/fgetc() : It is used to read a character from a file that has been opened in a read mode. It
reads a character from the file whose file pointer is fp. The file pointer moves by one character
for every operation of getc(). The getc() will return an end-of –marker EOF, when an end of
file has been reached.fgetc runs more slowly than getc, but takes less space per invocation.fgetc
behaves like getc, but is a genuine function, not a macro; it may therefore be used as an
argument.
Syntax:
getc(fp);Ex:char ch; ch=getc(fp);
fgetc(FILE *pointer)

A program that demonstrates getc is given below −

#include <stdio.h>

int main ()
{
int i;

printf("Enter a character: ");


i = getc(stdin);

printf("\nThe character entered is: ");


putchar(i);

return(0);
}
A program that demonstrates fgetc is given below –

#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("file.txt", "w");
fprintf(fp, "griet");
fclose(fp);
int i;
fp = fopen("file.txt","r");
if(fp == NULL){
perror("Error in opening file");
return(-1);
}

while((i=fgetc(fp))!=EOF)
{
printf("%c",i);
}

fclose(fp);
return(0);
}

putc()/fputc() -:
It is used to write a character contained in the character variable to thefile associated with the
FILE pointer fp. fputc() also returns an end-of –marker EOF, when an end of file has been
reached.fputc behaves like putc, but is a genuine function rather than a macro; it may therefore
be used as an argument. fputc runs more slowly than putc, but takes less space per invocation.

Syntax: putc(c,fp);
Example: char c; putc(c,fp);
int fputc(int char, FILE *pointer)

A program that demonstrates getc is given below −

#include<stdio.h>

int main () {
char c;

printf("Enter character: ");


c = getc(stdin);
printf("Character entered: ");
putc(c, stdout);

return(0);
}
Program using fgetc() and fputc():
#include<stdio. h>
void main()
{
FILE *fp;
char ch;
fp=fopen("input1.txt","w");
printf("\n enter some text and press@ to stop:\n");
while( (ch=getchar())!='@')
fputc(ch,fp);
fclose(fp);
fp=fopen("input1.txt","r");
printf("\n The entered text is : \n");
while((ch=fgetc(fp))!=EOF)
putchar(ch);
fclose(fp);
}

fprintf() andfscanf():

In order to handle a group of mixed data simultaneously there are two functions that are
fprintf()andfscanf().Thesetwofunctionsareidenticaltoprintfandscanffunctions,exceptthat they
work on files. The first argument of these functions is a file pointer which specifies the file to
beused.
fprintf(): The general form of fprintf() is
Syntax: fprintf(fp,”control string”,argument list);
where fp is a file pointer associated with a file that has been opened for writing . The control
string contains output specifications for the items in the list. .
Example:fprintf(fp,”%s%d”,name,age);
fscanf() : It is used to read a number of values from a file.
Syntax: scanf(fp,”control string”,argument list);
Example: fscanf(fp2,”%s%d”,item,&quantity);
like scanf , fscanf also returns the number of items that are successfully read. when the end of
file is reached it returns the valueEOF.

Program using fscanf() andfprintf():

#include <stdio.h>
int main ()
{
char str1[10], str2[10], str3[10];
int year;
char dept[20]="CSE";
FILE * fp;
fp = fopen ("file", "w+");
fprintf(fp,"We are GRIETIANs 2022 %s",dept);
rewind(fp);
fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
printf("%s year value is %d",str3,year);
fclose(fp);
return(0);
}

getw() andputw():
The getw() and putw()are integer oriented functions .They are similar to the getc() and putc()
functionsandareusedtoreadandwriteintegervalues.Thesefunctionswouldbeusefulwhen we deal
with only integer data. The general form of getw() and putw()are:
Syntax:
putw (int num, FILE *fp);
int getw (FILE *fp);
A program that demonstrates getw and putw is given below −
#include<stdio.h>
int main()
{
FILE *fp;
int i;
fp = fopen ("num.txt", "w");
for (i =1; i<= 10; i++) {
putw (i, fp);
}
fclose (fp);
fp =fopen ("num.txt", "r");
printf ("file content is\n");
for (i =1; i<= 10; i++){
i= getw(fp);
printf ("%d ",i);
}

fputs() andfgets():

fgets(): It is used to read a string from a file pointed by file pointer. It copies the string to a
memory location referred by an array.
Syntax: char* fgets(char *s, int n, FILE *stream)
Example: fgets(text,50,fp1);

fputs(): It is used to write a string to an opened file pointed by file pointer.

Syntax: fputs(char *s, FILE *stream); Example: fputs(text,fp);

Programs using fgets() andfputs():

#include<stdio.h>
int main()
{
char string[20];
printf("Enter the string: ");
fgets(string,200,stdin); //reading from stdin stream
printf("\nThe string is: %s",string);
return 0;
}
#include<stdio.h>
int main()
{
FILE *fp;
char text[300];
fp=fopen("abc.txt","r"); //reading from abc.txt
fgets(text,50,fp);
printf("%s",text);
fclose(fp);

#include<stdio.h>
int main()
{
FILE *fp;
fp=fopen(“abc.txt","w");
fputs("hello c programming",fp);
fclose(fp);
}

fread and fwrite:

Large amount of integers or float data require large space on disk in text mode and turns out to
be inefficient.fwrite and fread make task easier when you want to write and read blocks of
data.
fread() andfwrite() syntax:
fwrite(void *buffer,int size,int count,FILE *fp);
fread (void *buffer, int size, int count, FILE *fp);
where,

buffer - is pointer to array of elements to be written.

size - is the size in bytes of each element to be written/read.

count - is the number of elements, each one with a size of “size” bytes.

stream - is the pointer to a FILE object that specifies an output stream/input stream.

Following program demonstrates the use of fread and fwrite function to read blocks of
data:

#include <stdio.h>
#include <stdlib.h>

int main()
{

FILE *fp;
char content[100];
fp=fopen("abc.txt","wb");
fwrite("Arsenal Football Club",sizeof(char),16,fp);
fclose(fp);
fp = fopen("abc.txt", "rb");
fread(&content, sizeof(char),7,fp);
printf("The file content is:\n %s \n",content);
fclose(fp);

return 0;
}

fwrite(): is alsoe used for writing an entire structure block to a given file in binary mode.

Syntax: fwrite(&structure variable,sizeof(structure variable),1,filepointer);


Example: fwrite(&stud,sizeof(stud),1,fp);

fread(): is also used for reading an entire structure block from a given file in binarymode.

Syntax: fread(&structure variable,sizeof(structure variable),1,filepointer);


Example: fread(&emp,sizeof(emp),1,fp1);

Example :Program using fread() and fwrite() to read/write structure data:

#include<stdio.h>
struct player
{
char pname[50];
int age;
int runs;
};
int main()
{
struct player p1,p2;
FILE *f3;
f3=fopen("player.txt","wb+");
printf("\n Enter details of player name ,age and runs scored :\n");
scanf("%s %d %d",p1.pname,&p1.age,&p1.runs);
fwrite(&p1,sizeof(p1),1,f3);
rewind(f3);
fread(&p2,sizeof(p2),1,f3);
printf("\nPLAYERNAME:=%s\nAGE:=%d\nRUNS:=%d",p2.pname,p2.age,p2.runs);
fclose(f3);
}
Random access to files :

At times we needed to access only a particular part of a file rather than accessing all the data
sequentially, which can be achieved with the help of functions fseek, ftell and rewind functions.
ftell():-
ftell takes a file pointer and returns a number of type long, that corresponds to the current
position. This function is useful in saving the current position of the file, which can later be used
in the program.
Syntax:n=ftell(fp);

n would give the Relative offset (In bytes) of the current position. This means that already n
bytes have a been read or written.

rewind():-
It takes a file pointer and resets the position to the start of the file.

Syntax:rewind(fp);
n=ftell(fp);

would assign 0 to n because the file position has been set to start of the file by rewind().The first
byte in the file is numbered 0, second as 1, so on. This function helps in reading the file more
than once, without having to close and open thefile.
Whenever a file is opened for reading or writing a rewind is done implicitly.

fseek():- fseek function is used to move the file pointer to a desired location within the file.
Syntax: fseek(file*ptr,offset,position);

file pointer is a pointer to the file concerned, offset is a number or variable of type long and
position is an integer number which takes one of the following values mentioned in the table.
The offset specifies the number of positions(Bytes) to be moved from the location specified by
the position, which can be positive implies moving forward and negative implies moving
backwards.

POSITION VALUE VALUE MEANING


CONSTANT
0 SEEK_SET BEGINNING OF FILE
1 SEEK_CUR CURRENT POSITION
2 SEEK_END END OF FILE

Example: fseek(fp,10,0) ;
fseek(fp,10,SEEK_SET);// file pointer is repositioned in the forward direction 10 bytes. .
When the operation is successful fseek returns 0 and when we attempt to move a file beyond
boundaries fseek returns -1. Some of the Operations of fseek function are as follows:

Examples Meaning
fseek(fp,0L,0); Go to beginning similar to rewind()
fseek(fp,0L,1); Stay at current position
fseek(fp,0L,2); Go to the end of file, past the last character of the file.
fseek(fp,m,0); Move to (m+1)th byte in the file.
fseek(fp,m,1); Go forward by m bytes
fseek(fp,-m,1); Go backwards by m bytes from the current position
fseek(fp,-m,2); Go backwards by m bytes from the end.(positions the file to the mth character from
the end)
Examples on random access to files:

#include <stdio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("myfile.txt","w+");
fputs("Invincibles Arsenal",fp);
fseek(fp,6L,0); // 0 or SSEK_SET
fputs("GRIET",fp); //also can apply rewind function after this line
and observe output
while((ch=fgetc(fp))!=EOF)
{
printf("%c", ch);
}
fclose(fp);
}

Content of file: InvincGRIET Arsenal


Output: Arsenal

#include <stdio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("myfile.txt","w+");
fputs("Invincibles Arsenal",fp);
fseek(fp,-7L,SEEK_END); // 2 or SEEK_END
fputs("GRIET",fp);
printf("current position of file pointer:%ld\n",ftell(fp));
rewind(fp);
while((ch=fgetc(fp))!=EOF)
{
printf("%c", ch);
}
fclose(fp);
}
Output:
current position of file pointer:17
Invincibles GRIETal

Program to reverse content of a file using random access functions:

#include<stdio.h>
int main()
{
FILE *fp;
char ch;
int i,pos;
fp=fopen("arsenal.txt","r"); //content of file: North London is Red
if(fp==NULL)
{
printf("File does not exist..");
}
fseek(fp,0,SEEK_END);

pos=ftell(fp);

printf("Current postion of fp: %d\n",pos);


i=0;
printf("the reversed file content is:\n");
while(i<pos)
{
i++;
fseek(fp,-i,SEEK_END);
ch=fgetc(fp);
printf("%c",ch);
}
return 0;
}

Output:
Current postion of fp: 19
the reversed file content is:
deR si nodnoL htroN

Error handling in files:


It is possible that an error may occur during I/O operations on a file. Typical error situations include:
Trying to read beyond the end of file mark. Device overflow.
Trying to use a file that has not been opened.
Trying to perform an operation on a file, when the file is opened for another type of operations.
Opening a file with an invalid filename. Attempting to write a write protected file.
If we fail to check such read and write errors, a program may behave abnormally when an error
occurs. An unchecked error may result in a premature termination of the program or incorrect
output. In C we have two status - inquiry library functions feof and ferror thatcan help us detect
I/O errors in thefiles.
feof(): The feof() function can be used to test for an end of file condition. It takes a FILE pointer
as its only argument and returns a non zero integer value if all of the data from the specified file
has been read, and returns zero otherwise.

ferror():The C library function int ferror(FILE *stream) tests the error indicator for the given
stream. If the error indicator associated with the stream was set, the function returns a non-zero
value else, it returns a zero value.
int ferror(FILE *stream);

fp==NULL: We know that whenever a file is opened using fopen function, a file pointer is
returned. If the file cannot be opened for some reason, then the function returns a nullpointer.
This facility can be used to test whether a file has been opened ornot.
Example

if(fp==NULL)
printf(“File could not be opened.\n”);

perror(): It is a standard library function which prints the error messages specified by the
compiler. Forexample:
if(ferror(fp)) perror(“Message:”);

Program for error handling in files:

#include <stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
int c;
fp = fopen("file.txt","r"); //give unexisting file name and see error message
given by compiler
if(fp == NULL)
perror("Error Message:");
while(1)
{
c = fgetc(fp);
if(feof(fp))
{
perror("End of the file reached");
break;
}
printf("%c", c);
}
fclose(fp);
}

Program to demonstrate ferror function in error handling


#include <stdio.h>
#include<stdlib.h>
int main ()
{
FILE *fp;
char c;
fp = fopen("file.txt", "w"); //Opening file in w mode
fputs("Gunners",fp);
rewind(fp);
while((c=fgetc(fp))!=EOF) //trying to read the file
{
putchar(c);
}
if(ferror(fp)!=0)
{
perror("Error:");
exit(0);
}
fclose(fp);
return(0);
}

Output:
Error:: Bad file descriptor

Introduction to stdin, stdout and stderr (or) Special File Pointers:


When we say Input, it means to feed some data into a program. An input can be given in the
form of a file or from the command line. C programming provides a set of built-in functions to
read the given input and feed it to the program as per requirement.
When we say Output, it means to display some data on screen, printer, or in any file. C
programming provides a set of built-in functions to output the data on the computer screenas
well as to save it in text or binaryfiles.

The Standard Files


C programming treats all the devices as files. So devices such as the display are addressed in
the same way as files and the following three files are automatically opened when a program
executes to provide access to the keyboard and screen.
There are 3 special FILE *'s that are always defined for a program. They are stdin
(standard input), stdout (standard output) and stderr (standarderror).

Standard File File Pointer Device

Standard input stdin Keyboard

Standard output stdout Screen


Standard error stderr Your screen
Thefilepointersarethemeanstoaccessthefileforreadingandwritingpurpose.Thissection
explains how to read values from the screen and how to print the result on thescreen.
Standard Input:
Standard input is where things come from when you use scanf(). In other words, scanf("%d",
&val);
is equivalent to the following fgets:
fgets(string, n, stdin);

StandardOutput:
Similarly, standard output is exactly where things go when you use printf(). In other words,
printf("Value = %d\n", val) is equivalent to the following fputs:
fputs(string,stdout);

Standard Error:
standard error stream (stderr) - used to log error or debug messages during run-time.
Standard error is normally associated with the same place as standard output; however,
redirecting standard output does not redirect standard error.

Following program demonstrates stdin and stdout text streams:

#include <stdio.h>
int main()
{
char string[256];
printf( "Please enter string: " );
fgets(string, 6, stdin); //enter Griet PPS lab and see the output
fputs(string,stdout);
return 0;
}

Following program demonstrates stderr:

#include<stdio.h>
#include <stdlib.h>
int main()
{
int f;
printf("enter the number:");
scanf("%d",&f);
if (f==0)
{
printf("Division by Zero is not allowed"); //observe output
carefully
fprintf(stderr, "Division by zero! Exiting...\n");
exit(0);
}
else
{
f = 200/ f;
printf("output is: %d", f);
}
}

Simulate a c program to read and display the contents of a file?

#include<stdio. h>
int main()
{
FILE*f1;
char ch;
f1=fopen("data.txt","w");
printf("\n enter some text here and press @ to stop:\n");
while((ch=getchar())!='@')
fputc(ch,f1);
fclose(f1);
printf(“\n the contents of file are \n:”);
f1 = fopen(“data.txt”,"r");
while((ch=fgetc(f1))!=EOF )
putchar(ch);
fclose(f1);
}

Develop a c program to copy the contents of one file to another?

#include<stdio.h>
int main(){
FILE *f1,*f2;
char ch;
f1=fopen("mynew2.txt","w");
printf("\n enter some text here and press @ to stop :\n");
while((ch=getchar())!='@')
fputc(ch,f1);
fclose(f1);
f1=fopen("mynew2.txt","r");
f2=fopen("dupmynew2.txt","w");
while((ch=getc(f1))!=EOF)
putc(ch,f2);
fcloseall();
printf(“\n the copied file contents are :”);
f2 = fopen(“dupmynew2.txt”,"r");
while(( ch = fgetc(f2))!=EOF )
putchar(ch);
fclose(f2);
}

Write a c program to merge two files into a third file?(Or)


Develop a c program for the following .there are two input files named “file1.txt”
and “file2.txt” .The files are to be merged. That is,copy the contents of first.txt
andthen second.txt to a new file named result.txt?

#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *f1,*f2,*f3;
char ch;
f1=fopen("file1.txt","w");
printf("\nEnter text into f1: \n");
while((ch=getchar())!='@')
putc(ch,f1);
fclose(f1);
f2=fopen("file22.txt","w");
printf("\nEnter text into f2: \n");
while((ch=getchar())!='@')
putc(ch,f2);
fclose(f2);
f1=fopen("result.txt","r");
if(f1==NULL)
{
printf("\ncannot open, file doesnot exist");
exit(0);
}
f3=fopen("hai3.txt","w");
while((ch=getc(f1))!=EOF)
{
putc(ch,f3);
}
fclose(f1);

f2=fopen("hai2.txt","r");
while((ch=getc(f2))!=EOF)
{
putc(ch,f3);
}
fclose(f3);
fclose(f2);

printf("\nThe contents of merged file 3 are : \n");


f3=fopen("hai3.txt","r");
while((ch=getc(f3))!=EOF)
{
putchar(ch);
}
fclose(f3);
}

Write a C program to append the contents of a file?


#include<stdio.h>
int main()
{
FILE *fp1;
char ch;
fp1=fopen("sunday.txt","w");
printf("\n Enter some Text into file :\n");
while((ch=getchar())!='@')
fputc(ch,fp1);
fclose(fp1);
fp1=fopen("sunday.txt","a+"); //to append
printf("\n Enter some MORE Text into file:\n");
while((ch=getchar())!='@')
fputc(ch,fp1);
rewind(fp1);
printf("\n The complete Text in file is:\n");
while((ch=fgetc(fp1))!=EOF)
putchar(ch);
fclose(fp1);
}

Command line arguments :

The arguments passed from command prompt are called command line arguments.
These arguments are handled by main() function.To support command line argument,
you need to change the structure of main() function as given below.
int main(int argc, char *argv[] )
Here, argc counts the number of arguments. It counts the file name as the first
argument.
The argv[] contains the total number of arguments. The first argument is the file name
always.

Example 1:

#include <stdio.h>
void main(int argc, char *argv[] )
{
printf("Program name is: %s\n", argv[0]);
if(argc < 2)
{
printf("No argument passed through command line.\n");
}
else
{
printf("First argument is: %s\n", argv[1]);
}
}
Compile the above program in windows using following command:
gcc filename.c –o filename.exe
then execute using:
filename.exe
Example 2:
#include <stdio.h>
int main( int argc, char *argv[] )
{
printf("\n Number of arguments are:%d",argc);
if( argc < 2 )
{
printf("No argument passed through command line.\n");
}
else if( argc == 4 )
{
int i;
for(i=0;i<argc;i++)
printf("%s\t", argv[i]);
}
else
{
printf("wrong number of arguments.\n");
}
}

Following Program computes the sum of numbers passed through command line:

#include <stdio.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
int i=1,sum=0;
printf("\n The numbers are :");
for(i=1;i<argc;i++){
sum+=atoi(argv[i]); //replace with sum+=*argv[i]; and observe change
in output
printf("\t %s",argv[i]);
}
printf("\n SUM = %d ",sum);
return 0;
}

Enumertaion Datatype :

Another user-defined datatype is ―enumerated data type(enum)

Syntax: enumidentifier{value1, value2,……….valuen};


Where identifier is user-defined datatype which is used to declare variables that can
have one of the values enclosed within the braces. value1 ,value2,……valuen all
these are known as enumeration constants.

Ex:- enum identifier v1, v2,……vn


v1=value1; v2=value3;………

Ex:- enum day {Monday,Tuesday…………. sunday};


enum day week-f,week-end
Week-f = Monday

-
-
enum day{Monday…Sunday}week-f, week-end;

EXAMPLE 1:
// An example program to demonstrate working of enum in C
// Enum is used to assign names to the integral constants
// enum statrts its values from 0 (if not oinitialized) and every next value is 1 + its
previous value

#include<stdio.h>
enum week{Mon, Tue, Wed, Thur=6, Fri, Sat, Sun};
int main()
{
enum week day; // variables of type enum and can assing the values
day = Wed;
printf("\n Mon=%d",Mon);
printf("\n Wed= %d",day);
printf("\n Fri=%d",Fri);
printf("\n Sun=%d",Sun);
return 0;
}

Output:
Mon=0
Wed= 2
Fri=7
Sun=9

EXAMPLE 2:
#include<stdio.h>
enum week{Mon=1, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;
day = Wed;
for(day=Mon;day<=Sun;day++)
{
printf("\n Day = %d",day);
}
return 0;
}

Output:
Day = 1
Day = 2
Day = 3
Day = 4
Day = 5
Day = 6
Day = 7

Interesting facts about initialization of enum:


Two enum names can have same value. For example, in the following C program both
‘Failed’ and ‘Freezed’ have same value 0.

#include <stdio.h>
enum State {Working = 1, Failed = 0, Freezed = 0};
int main()
{
printf("%d, %d, %d", Working, Failed, Freezed);
return 0;
}
Output:
1, 0, 0

2. If we do not explicitly assign values to enum names, the compiler by default assigns
values starting from 0.
3. We can assign values to some name in any order. All unassigned names get value as
value of previous name plus one.

#include <stdio.h>
enum day {sunday = 1, Monday, tuesday = 5, wednesday, thursday = 10, friday,
saturday};
int main()
{
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday, wednesday,
thursday, friday, saturday);
return 0;
}

Output:
1 2 5 6 10 11 12
4. All enum constants must be unique in their scope. For example, the following program fails in
compilation.

enum state {working, failed};


enum result {failed, passed};
int main()
{
return 0;
}

Output:
Compile Error: 'failed' has a previous declaration as 'state failed'

Enum vs Macro:
We can also use macros to define names constants. For example we can define ‘Working’ and
‘Failed’ using following macro.
#define Working 0
#define Failed 1
#define Freezed 2
There are multiple advantages of using enum over macro when many related named constants have
integral values.
a) Enums follow scope rules.
b) Enum variables are automatically assigned values. Following is simpler
enum state {Working, Failed, Freezed};

C Preprocessors:

The C Preprocessor is not part of the compiler but is a separate step in the compilation
process. In simplistic terms, a C Preprocessor is just a text substitution tool and they
instruct compiler to do required pre-processing before actual compilation. We refer to the
C Preprocessor as the CPP. All preprocessor commands begin with # symbol.
There are 3 Main Types of Preprocessor Directives:
1. Macros
2. File Inclusion
3. Conditional Compilation

Macros
Macros are pieces of code in a program that is given some name. Whenever this name is
encountered by the compiler, the compiler replaces the name with the actual piece of
code. The ‘#define’ directive is used to define a macro.

#define macro_name value

Let us now understand the macro definition with the help of a program:
#include <stdio.h>
// macro definition
#define LIMIT 5
intmain()
{
for(inti = 0; i < LIMIT; i++)
{
printf("%d \n",i);
}

return0;
}

In the above program, when the compiler executes the word LIMIT, it replaces it with 5.
The word ‘LIMIT’ in the macro definition is called a macro template and ‘5’ is macro
expansion.
Note: There is no semi-colon (;) at the end of the macro definition. Macro definitions do
not need a semi-colon to end.
Macros With Arguments: We can also pass arguments to macros. Macros defined with
arguments work similarly to functions. Let us understand this with a program:
#include <stdio.h>
// macro with parameter
#define AREA(l, b) (l * b)
intmain()
{
intl1 = 10, l2 = 5, area;
area = AREA(l1, l2);
printf("Area of rectangle is: %d", area);
return0;
}
We can see from the above program that whenever the compiler finds AREA(l, b) in the
program, it replaces it with the statement (l*b).

File Inclusion

This type of preprocessor directive tells the compiler to include a file in the source code
program. There are two types of files that can be included by the user in the program.
Header files or Standard files:
These files contain definitions of pre-defined functions like printf(), scanf(), etc.

Syntax: #include<filename.h>
where filename is the name of the file to be included. The ‘<‘ and ‘>’ brackets tell the
compiler to look for the file in the standard directory.

User-defined files: When a program becomes very large, it is a good practice to divide it
into smaller files and include them whenever needed. These types of files are user-
defined files. These files can be included as:
Syntax:#include"filename"

Conditional Compilation
Conditional Compilation directives are a type of directive that helps to compile a specific
portion of the program or to skip the compilation of some specific part of the program
based on some conditions.
Syntax:
#ifdef macro_name
statement1;
statement2;
statement3;
#endif
Conditional compilation Preprocessors (#if, #ifdef, #ifndef, #elif, #else,#endif):

1. #ifdef
Returns true if this macro is defined.

2. #ifndef
Returns true if this macro is not defined.

3. #if
Tests if a compile time condition is true.
4. #else
The alternative for #if.

5. #elif
#else and #if in one statement.

6. #endif
Ends preprocessor conditional.

7. #undef
Undefines a preprocessor macro.

8. #error
Prints error message
#if,#elif,#elif and #else:

Syntax:
#if expression
//if code
#elif expression
//elif code
#else
//else code
#endif
Example Program:

#include <stdio.h>
#define AGE 150
int main()
{
#if AGE <= 18
printf("NOT ELIGIBLE TO VOTE \n");
#elif AGE > 18 && AGE<=100
printf("ELIGIBILE TO VOTE");
#else
printf("INVALID AGE");
#endif
return 0;
}

#ifdef:
Syntax:
#ifdef MACRO
//successful code
#else
//else code
#endif
Example program using #ifdef macro:
#include <stdio.h>
#define INPUT 20
void main()
{
int a=0;
#ifdef INPUT
printf("Value is: %d\n", INPUT);
#else
printf("Enter a:");
scanf("%d", &a);
printf("value is: %d\n",a);
#endif
}

#ifndef example:
#include <stdio.h>
#define INPUT 20
void main()
{
int a=0;
#ifndef INPUT
printf("Value is: %d\n", INPUT);
#else
printf("Enter a:");
scanf("%d", &a);
printf("value is: %d\n",a);
#endif
}

Predefined Macros
ANSI C defines a number of macros. Although each one is available for your use in
programming,
the predefined macros should not be directly modified.

Sr.No Macro & Descriptions

1 __DATE__The current date as a character literal in "MM DD YYYY"


format.

2 __TIME__The current time as a character literal in "HH:MM:SS" format.

3 __FILE__This contains the current filename as a string literal.

4 __LINE__This contains the current line number as a decimal constant.


Sr.No Macro & Descriptions

5 __STDC__Defined as 1 when the compiler complies with the ANSI


standard.

#include <stdio.h>
int main()
{
printf("File :%s\n", __FILE__ );
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("ANSI :%d", __STDC__ );
}

Preprocessor Macro Continuation Operator

Macro Continuation (\)


A macro usually must be contained on a single line. The macro continuation operator is
used to continue a macro that is too long for a single line.

#include <stdio.h>
#define display(a, b) \
printf(#a" Football "#b)

int main()
{
display(Arsenal, club);
return 0;
}

Creating Your Own Header Files In C :


#include is used to incorporate the predefined header files in to our c programs.
It also allows the programmers to create their own header files and incorporate user created
header files into other programs.
Method 1: #include<stdio.h> ....> the computer will search for the definitions header files
in predefined / standard locations.
Method 2: #include"myown.h" ---> the computer will search for the definitions header
files in the current folder.(own header files)
How to write your own header file in C?
As we all know that files with .h extension are called header files in C.
header files are simply files in which you can declare your own functions that you can use
in your main program or these can be used while writing large C programs.
NOTE: Header files generally contain definitions of data types, function prototypes and C
preprocessor commands.
Below is the short example of creating your own header file and using it accordingly.
Creating myhead.h : Write the below code and then save the file as myhead.h or you can
give any name but the extension should be .h indicating its a header file.

void add(int a, int b)


{
printf("Added value=%d\n", a + b);
}
void multiply(int a, int b)
{
printf("Multiplied value=%d\n", a * b);
}

Including the .h file in other program : Now as we need to include stdio.h as #include in
order to use printf() function,we also need to include the above header file myhead.h as
#include “myhead.h”.
The “ ” here are used to instructs the preprocessor to look into the present folder and into
the standard folder of all header files if not found in present folder.
So, if you wish to use angular brackets instead of “ ”to include your header file you can
save it in the standard folder of header files otherwise.
If you are using “ ” you need to ensure that the header file you created is saved in the same
folder in which you will save the C file using this header file.
Using the created header file:
// C program to use the above created header file.
#include <stdio.h>
#include "myhead.h"
int main()
{
add(4, 6); //calling the function defined in header file.
multiply(5, 5);
return 0;
}
Output:
Added value:10
Multiplied value:25
Important Points:
The creation of header files are needed generally while writing large C programs so that
the modules can share the function definitions, prototypes etc.In short, Put only what is
necessary and keep the header file concise.
Frequently Asked Questions in Exams:

Unit-1:

1. Explain the steps followed in problem solving and program development in details?
2. Write about general structure of C with example?
3. Explain in detail about data types in C with example?
4. Explain about type conversion with an example program?
5. Explain about operators in C with examples?
6. Define a variable? How to declare and initialize variables in C? What are the rules
for naming variables in C?
7. Define a flow chart and draw a flowchart for finding the factorial of a give number?
8. Explain Define an algorithm and design an algorithm for finding bigger of three numbers?
9. Design an algorithm for determining a number is prime or not?
10. Write about formatted and unformatted I/O operations in c?
11. Define algorithm,flowchart,Pseudo code and write an example for each.Also list their merits
and demerits?
UNIT-2:

1. Write about selection statements and explain using example program?


2. Explain about loops in C with an example? Give their syntax and flowchart?
3. Explain about switch statement in C with example? Give its syntax and flowchart?
4. Write a c program to implement arthematic operations using switch case?
5. Differentiate between break and continue in C?
6. Differentiate between while and do while loops in C?
7. Write a C program to determine if a number is palindrome or not?
8. Write a C program to display prime numbers till a given number?
9. Define array?Explain types of Arrays?How to declare and initialize arrays with example?
10. Write a c program to add two matrices?
11. Implement C program for multiplication of matrix?
12. Implement c program for matrix transpose?
13. Write a c program to find the minimum and maximum in a list of elements?
14. Write a c program to sort a given list of elements?
15. Algorithm/ Program/Example for Linear search.
16. Algorithm/ Program/Example for binary search.

Unit-3:

1. Define string?Explain How to declare and initialize string with example?


2. Explain about string handling functions in C?
3. Write a C program to determine if a string is palindrome or not?
4. Write a C program to compare two strings without using string handling functions?
5. Explain about different parameter passing techniques in detail with an exampleprogram?
6. Define recursion? What are its merits and demerits? Write a C program to find
the factorial using recursion and non-recursion?
7. Difference between call by value and call by reference?
8. Differentiate between formal and actual arguments?
9. Explain about various categories of functions with examples.
10. Explain Different storages classes in c with examples?
11. Write a c program to find the GCD of two numbers using recursion?
12. How to pass arrays to functions? Explain with example program?

Unit-4:
1. Define pointer and explain about how to declare, initialize and access using pointer?
2. With an example program explain about pointer to arrays?
3. Explain function pointer using an example program?
4. Can we have pointer to structure? Illustrate with example program?
5. What is pointer arithmetic? Explain in detail?
6. Define structure? Explain how to declare and initialize structure and access structure
members?
7. Explain about nested structures with an example program?
8. Differentiate between structures and union
9. Explain about array of structures with an example program. Write a C program to find the
total marks of n students. Use a structure of student containing name, id, and marks of 3
subjects.
10. Define a self-referential structure? Explain the use of pointers in self-referential
structures and self-referential structures in linked lists?
11. Explain about how to access members of a structure using pointers with an
example program?
12. How to pass structures to functions? Write a program?
Unit-5:
1. Write a C program to merge two files into a third file?
2. Write a C program to append the contents of a file into another?
3. Define a File? Explain about different modes of opening a file?
4. Write a C program to read and display the contents of a file?
5. Explain about random access to files in detail with an example?
6. Explain about command line argument with an example in C?
7. Explain about the following pre-processor commands with example
(i) include (ii) define (iii) undef (iv) if (v)ifdef
Short answer Questions: (2 marks)
1. Write the output for the following code:
main()
{
char s[]=”STANDARD”;
int i; for(i=0;s[i]!=’\0’;i++)
printf(“\n%c”,*(s+i));
}
2. Define Void Pointer.
3. Write an algorithm to find biggest of two numbers
4. Differentiate between Formal Arguments and Actual Arguments.
5. What are the advantages of using typedef in a program?
6. List any four String Handling Functions.
7. What is the purpose of Structures in C?
8. Give the Syntax of ‘while’ loop in C.
9. Write a C Program to determine a number is Even or Odd Using Ternary Operator.
10. Draw a Flowchart to find greatest of two numbers.
11. With example Differentiate between Pre Increment and Post Increment Operators.
12. Differentiate between Entry Controlled Loops and Exit Controlled Loops.
13. Give the Syntax of Switch Statement.
14. Declare a Multidimensional Array.
15. Which String Handling Function reverses the given String? Give its syntax.
16. Declare a Character Pointer and an Integer Pointer? Give their sizes.
17. What are the different Storage Classes available in C Language.
18. Differentiate between Structure and Union.
19. What are Command Line Arguments?
20. Differentiate Variable and Constant
21. What is Type Casting in C?
22. How to declare and initialize an Array
23. What is Recursion?
24. Write the syntax for declaring a Pointer to Pointer.
25. What is a Nested Structure and how to declare?
26. Differentiate EOF and foef().
27. What are the limitations of Binary Search? (only works on sorted list)
28. What are the prerequisite / essential condition of Binary Search?
29. Define Algorithm. Write an algorithm for addition of two numbers
30. WRITE/ GIVE THE STRUCTURE OF C PROGRAM
31. LIST THE STEPS IN PROGRAM DEVELOPMENT.
32. GIVE THE SYNTAX OF SIZEOF() OPERATOR.
33. Define FLOWCHART
34. LIST MERITS AND DEMERITS OF ALGORITHMS AND FLOWCHARTS
35. GIVE THE SYNTAX / FLOWCHARTOF IF’S(SIMPLE IF,IF ELSE ,NESTED OR
LADDER)
36. GIVE THE SYNTAX OF DO WHILE /FOR LOOPS
37. DIFFERENTIATE BETWEEN WHiLE AND DO WHILE LOOPS
38. DIFFERENTIATE BETWEEN BREAK AND CONTINUE
39. DIFFERENTIATE BETWEEN BREAK AND CONTINUE
40. DIFFERENTIATE BETWEEN BREAK AND exit()
41. WRITE ABOUT EXIT and return
42. WRITE ABOUT PARTIAL INITIALIZATION OF ARARYS IN C
43. WRITE ABOUT BITWISE OPERARTORS
44. Write about special operators
45. DEFINE OPERATOR PRECEDENCE AND ASSOCIATIVITY
46. WRITE A C PROGRAM TO CONVERT CELSIUS TEMPERATURE TO FARENHEIT
47. WHAT HAPPENES IF BREAK IS NOT USED IN switch ?
48. WHAT IS THE PURPOSEOF DEFAULT?
49. Write about goto statement with appropriate example
50. What are the advantages and disadvantage of array?
51. Write a C Program to concatenate two Strings.
52. Write about Nested Functions.
53. Different Call by Value and Call by Reference.
54. What is the necessity of storing data in Files?
55. Differentiate between binary and linear search.
56. List the applications of pointers?.
57. List the advantages of arrays in c?
58. What is the difference between text file and binary files?.
59. WHAT IS ENUM ? GIVE ITS SYNTAX WITH EXAMPLE
60. WRITE ABOUT fseek();
61. Define ftell() and rewind ()
62. Define stdin,stdout and stderr ?
63. DEFINE BLOCK Read AND Write FUNCTIONS i.e fread() and fwrite() ?
64. WRITE ABOUT MODES OF OPENING A FILE ?
65. DEFINE NULL POINTER ?
66. DEFINE DANGLING POINTER ?
67. WHAT ARE POSSSIBLE OPERARTIONS ON POINTERS and POINTER ADDRESS
ARITHMETIC?
68. DEFINE A TYPE DEFINED / TAGGED STRUCTURE ?
69. WHAT IS SIZE OF STRUCTURE AND UNION?
70. DEFINE UNION ?
71. WHAT IS THE DIFFERENCE BETWEEN READING STRING USING SCANF AND
GETS
72. WRITE A C PROGRAM TO FIND LENGTH OF A STRING WITHOUT USING
STRING.H
73. WRITE A C PROGRAM TO FIND LENGTH OF A STRING
74. DECLARE AN ARRAY OR TABLE OF STRINGS
75. WRITE ABOUT SIGNATURE OF FUNCTION
76. WHAT ARE TYPES OF FUNCTIONS
77. WHAT IS THE NEED FOR FUNCTIONS
78. WHAT ARE ADVANTAGES OF FUNCTIONS
79. WHAT ARE MERITS AND DEMERITS OF RECURSION
80. DEFINE SCOPE AND LIFETIME OF VARIABLES
81. DIFFERENTIATE BETWEEN A LOCAL VARIABEL AND A GLOBAL VARIABLE?

You might also like