You are on page 1of 211

Programming for Problem Solving

COURSE OBJECTIVES
• To relate basics of programming language constructs and problem-
solving techniques
• To classify and implement control structures and derived data types
• To analyse and develop effective modular programming
• To construct mathematical problems and real time applications using
C Language

COURSE OUTCOMES: After completion of the course, the student will be


able to
CO-1: Illustrate the flowchart, algorithm, pseudo code for a given problem
CO-2: Execute programs using various data types and operators
CO-3: Implement programs using conditional and iterative statements for a
given problem
CO-4: Exercise on programs using arrays, pointers, dynamic memory
management, structures and unions
CO-5: Develop solution for a given problem using modular approach and
perform file handling
Syllabus:
UNIT-I: Introduction to Programming:
Compilers, compiling and executing a program.
Representation of Algorithm, Flowchart/ Pseudocode with examples, Program
design and structure of C programming.
Variables, Data types, Operators, expressions and precedence, Expression
evaluation,
Storage classes, type conversion.
I/O: Simple input and output with scanf and printf, formatted I/O,
Introduction to stdin, stdout and stderr.
Conditional Branching: Branching with if, if-else, nested if-else, else-if ladder,
switch case, goto,
UNIT-II: Loops, Arrays, Strings: Loops: Iteration with for, while, do- while
loops, break and continue statements. Arrays: One and two dimensional
arrays, creating, accessing and manipulating elements of arrays Strings:

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Introduction to strings, handling strings as array of characters, string
functions available in C arrays of strings.
UNIT-III: Searching, Sorting, Functions: Searching: Basic searching in an
array of elements (linear and binary search techniques) Sorting: Basic
algorithms to sort array of elements (Bubble, Insertion and Selection sort
algorithms), Basic concept of order of complexity through the example
programs Functions: Designing structured programs, Declaring a function,
Signature of a function, Parameters and return type of a function, passing
parameters to functions, call by value. Recursion with examples. Some C
standard functions and libraries.
UNIT-IV: Structures and Pointers: Structures: Defining structures,
initializing structures, unions, Array of structures, Pointers: Idea of pointers,
defining pointers, Pointers to Arrays and Structures, Passing arrays to
functions and structures to functions. Dynamic memory allocation, self-
referential structures
UNIT-V: Preprocessor Directives and File Handling in C: Preprocessor
Directives: Symbolic constants, macro expansion and file inclusion. User
Defined Data Types: enum, typedef Files: Text and Binary files, file
input/output operations, Error Handling in Files, random access of files,
command line arguments.
TEXT BOOKS:
1. The C Programming Language , Brian W. Kernighan and Dennis M.
Ritchie, Prentice Hall of India
2. C Programming and Data Structures, B. A. Forouzan and R. F. Gilberg,
3rd Edition, Cengage Learning
3. C: The Complete Reference, Herbert Schildt, 4th Edition, McGraw-Hill
REFERENCES:
1. Problem Solving and Program Design in C, Jeri R. Hanly and Elliot B.
Koffman, 7th Edition, Pearson
2. Computer Fundamentals and C, E. Balagurusamy, 2nd Edition,
McGraw-Hill
3. Let us C, Yashavant Kanetkar, 18th Edition, BPB
4. How to Solve it by Computer, R. G. Dromey, 16th Impression, Pearson
5. Programming in C, Stephen G. Kochan, 4th Edition, Pearson Education
ONLINE RESOURCES:
1. https://nptel.ac.in/courses/106105171
2. https://ugcmoocs.inflibnet.ac.in/index.php/courses/view_ug/307

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
UNIT-1
Compilers
Definition: compiler is a translator which translates high level
programming language into machine understandable format.
Algorithm: An Algorithm is a step-by-step procedure to solve a
given problem. Characteristics of an Algorithm:

1. Finiteness: An algorithm terminates after a fixed number of steps.


2. Definiteness: Each step of the algorithm is precisely defined, i.e.,
the actions to be carried out should be specified unambiguously.
3. Effectiveness: All the operations used in the algorithm are basic
(division, multiplication, comparison, etc.) and can be performed
exactly in a fixed duration of time.
4. Input: An algorithm has certain precise inputs, i.e. quantities.
5. Output: An algorithm has one or more outputs, that is, the results
of operations which have a specified relation to the inputs.

Exercises:

1. Write an algorithm to swap two numbers without using temporary


variable.

2. Write an algorithm to find roots of a quadratic equation.

3. Write an algorithm to find largest of three numbers

4. Write an algorithm to find sum of first N numbers

5. Write an algorithm to find factorial of a given number.

6. Write an algorithm to generate first N Fibonacci series values.

Flowchart: Flowchart is a graphical representation of an algorithm. The


pictorial representation of the algorithm is called flowchart.

A flowchart is a picture, which shows the sequence in which data are


read, Computing is performed, decisions are made and results are obtained.
It makes use of the basic operations in programming. All symbols are
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
connected among themselves to indicate the flow of information and
processing.
The symbols which are used in flowchart are
i) Terminal: The oval represents any terminal point in a program and
generally contains such words as BEGIN, START, END or STOP.

ii) Input/Output: The parallelogram represents the Input/Output


function i.e. making data available for processing (input) or recording of
the processed information (output).

iii) Process: The rectangle represents the processing operation. A process


changes or moves data. An assignment is normally represented by this
symbol.

iv) Flow direction: Lines or arrows represent the flow direction


function – the flow of control. Normal flow direction is from left to right
or from top to bottom.

vi) Decision making symbol: The diamond represents a decision or

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
switching type of operations that determines which of the alternative
paths is to be followed.

vii) Connector: The circle represents a function in a flow line.

Exercises

1. Write an algorithm to swap two numbers without using temporary


variable.

2. Write an algorithm to find roots of a quadratic equation.

3. Write an algorithm to find largest of three numbers

4. Write an algorithm to find sum of first N numbers

5. Write an algorithm to find factorial of a given number.

6. Write an algorithm to generate first N Fibonacci series values.

PSEUDO CODE
A Pseudocode allows the programmer to represent the implementation of an
algorithm.
A Pseudo code is an informal way of programming description that does not
require any strict programming language syntax or underlying technology
considerations.
Advantages of Pseudocode
1. Improves the readability.
2. Acts as a bridge between the algorithm and program.
3. The main goal of a pseudo code is to explain what exactly each line of a
program should do, hence making the code construction phase easier
for the programmer.
Example: Consider the following source code example:

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
int n = 10
for( i=0;i<n;i++)
printf(n);

The above source code is converted into a pseudo-code to understand in a


better way.

The value ten is assigned to the variable n.


For value = zero to less than a number.
Display the numbers.

BRIEF HISTORY OF C

1. The C programming language is a structure-oriented programming


language, developed at Bell Laboratories in 1972 by Dennis Ritchie.
2. C programming language features were derived from an earlier language
called “B” (Basic Combined Programming Language – BCPL)
3. C language was invented for implementing UNIX operating system.
4. In 1978, Dennis Ritchie and Brian Kernighan published the first edition
“The C Programming Language” and is commonly known as K&R C.
5. In 1983, the American National Standards Institute (ANSI) established a
committee to provide a modern, comprehensive definition of C. The
resulting definition, the ANSI standard, or “ANSI C”, was completed late
1988.
6. Many of C’s ideas & principles were derived from the earlier language B,
thereby naming this new language “C”.

CHARACTERISTICS OF C

● ‘C’ is a structured programming language i.e., a C program can be


divided into multiple blocks where each block represents a function.
● ‘C’ language is suitable for developing both application software as
well as system software.

● It has a wide variety of derived datatypes like arrays, structures,


pointers and unions apart from fundamental data types like integers,
floating point numbers and characters. This makes the language

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
simple and small.
● ‘C’ is a highly portable language. i.e. programs written in one
machine can be easily run on some other machine without any
modifications.
● ‘C’ provides a rich set of built-in functions.
● ‘C’ supports all types of applications in engineering, medical,
scientific, marketing etc.

STRUCTURE OF A ‘C’ PROGRAM

A ‘C’ Program contains the following sections:

1. Documentation Section
2. Link Section
3. Definition Section
4. Global Declaration Section
5. main() function Section
6. Sub program Section

1. Documentation Section: It consists of a set of comment lines which


contain user interested details like name of author, program and any other
details which makes the program more easy to understand.

Comment lines should be enclosed within /* and */ and can appear


anywhere in the program. These comment lines are omitted by the
compiler at the time of compilation.

E.g.,

/* program 1 */
/* VNR college */

2. Link Section: ‘‘C’ has a rich set of built-in functions and they can be
used to write any complex program. These functions are kept in various

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
system libraries such as stdio.h (standard input-output header file), math.h
(mathematical functions header file), ctype.h (character testing and conversion
functions header file), string.h (string manipulations header file), conio.h
(configuration input-output header file) etc.

If we want to use the functions of these libraries, we have to provide


information to the compiler to link the functions from the corresponding
system library. This can be achieved through the link section of the ‘C’
program structure by using #include directive.

E.g., #include<stdio.h>
#include<math.h>

3. Definition Section: Some problems require constant values to solve


the problem. Constant values are declared in the definition section using
#define directive.
Eg: Formula to find area of the circle is a= ∏r2 . Where ∏ is a constant
whose value is
3.14. Such symbolic constants can be defined in definition section using
Syntax: #define directive

Example: #define PI 3.14

4. Global Declaration Section: Some variables are used in more than one
function, such variables are called global variables. Which are declared in
the global declaration section.
5. main( ) function Section: The main( ) indicates starting of the program.
Every ‘C’ program must have one main( ) function section. This section
contains two parts.
(a) Declaration Section

(b) Executable Section

Declaration section declares all the variables used in the executable part
and the entire code for the program is written in the executable part.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
These two parts must appear between 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 part and executable part end
with a semicolon (;).
Syntax:

main( )

{
declaration part;
executable part;
}

6. Subprogram Section: This section consists of one or more functions


which are defined by the user. These functions can be called from main( )
function or any other user-defined function.

NOTE:- All sections except the main( ) function section may be absent
whey they are not required.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
‘C’ CHARACTER SET
The characters supported by ‘C’ language are:
▪ Letters: a to z, A to Z
▪ Digits: 0 to 9
▪ Special Characters: , . ; : ? ‘ “ ! ? / \ ~ - % & | ^ +
_ *
< > ( ) [ ] { } # =
▪ White spaces.
‘C’ TOKENS
Smallest individual unit in a C program is known as a token.
C has 6 types of tokens.

KEYWORDS
▪ Keywords are the English words which have fixed meaning which
cannot be changed.
▪ Keywords should always be written in lowercase.
▪ The keywords available in ‘C’ language are

IDENTIFIERS
▪ Identifiers refer to the user-defined names such as names of variables,
arrays, functions.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
CONSTANTS
▪ Constants refer to the fixed values that do not change during the
execution of a program.


Integer Constants
▪ An integer constant is a sequence of digits without any fractional part.
There are three types of integer constants in C language. They are:
▪ Decimal integer constants: It consists of set of digits 0 to 9, preceded
by an optional sign + or -.
▪ Eg., +125, 0, -525, 68 etc.
▪ Octal integer constants: It consists of a set of digits 0 to 7, preceded by
0.
▪ Eg., 0, 031 , 0642, 0426 etc.
▪ Hexadecimal constants: It consists of a sequence of digits 0 to 9, A to F
preceded by 0X. The letters A to F represents the numbers 10 to 15.
▪ Eg., 0X5, 0XF, OXABC etc.
Real Constants
▪ Integer constants are not suitable to represent continuously varying
quantities such as distances, heights, temperatures etc. These quantities
can be represented by numbers containing fractional part. Such constants
are known as real(or floating point) constants.
Eg., 0.7, -0.63, 7.5, 8.40, -0.0089 etc.
▪ A real number may also be expressed in exponential notation.
▪ Syntax: mantissa e exponent
▪ Eg., 0.56e3, 10e-3, 3.5E3, -2.5E-2 etc.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Character Constants & String Constants
Single Character Constants: A single character constant contains a single
character enclosed within a pair of single quotation marks.
▪ Eg., ‘5’, ‘x’, ‘;’, ‘ ‘ etc.
Every character value has an equivalent integer value known as ASCII value.
ASCII stands for American Standard Code for Information Interchange.
String Constants: A string constant is a sequence of characters enclosed
within a pair of double quotation marks.
▪ Eg., “abcd”, “2006”, “A+B”, “5+8” etc.
SYMBOLIC CONSTANTS
▪ A symbolic Constant is a name that substitutes for a sequence of
characters. The characters may represent a numeric constant, a character
constant or a string constant.
# define name text
▪ Where name represents a symbolic name, typically written in uppercase
letters, and text represents the sequence of characters associated with the
symbolic name. Note that text does not end with a semicolon.
# define TAXRATE 0.25
# define PI 3.1415
# define TRUE 1
# define FALSE 0
# define FRIEND “rama”
▪ Notice that the symbolic names are written in uppercase, to distinguish
them from ordinary C identifiers.
VARIABLE
▪ A variable is one which is used to store a data value.
▪ A variable may take different values at different times during program
execution.
▪ The following rules have to be followed while declaring a variable.
1. It consists of letters, digits, underscore character ( _ ).
2. Must begin with a letter or an underscore.
3. Maximum distinguishable length should be 8 characters.
4. It should not be a keyword.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
5. White spaces are not allowed.
▪ Eg., x, a1, value, a_b, sum etc. – are valid variable names
1abc, abc xyz, int are invalid variable names
DATA TYPES
BASIC DATATYPES AND SIZES:
▪ Data given to the system may be of different types like integers, real
numbers, letters, words etc. Each and every data has to be represented
with the appropriate datatype.
▪ Data types are classified into three types:-
1. Primary data type or Fundamental data types
2. Derived data types
3. User-defined data types
Primary or Fundamental data types

Primary or Fundamental data types are divided into four categories:


1) Integer 2) Float 3) Character 4) void
1) Integer:
▪ Integers are the whole numbers in the range –32768 to +32767
including 0. An integer can be represented with the keyword int. It is
stored in 16 bits as its storage location. An integer can be stored as
short int, int, long int both in signed and unsigned forms depending
upon the value stored.
Type Size Range
Int or singed int 2 bytes -32768 to 32767
Unsigned int 2 bytes 0 to 65535

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Short int or singed short int 1 byte -128 to +127
Unsigned short int 1 byte 0 to 255
Long int or singed long int 4 bytes -2147483648 to
+2147483647
Unsigned long int 4 bytes 0 to 4294967295

2) Floating point types


▪ Floating point numbers are stored in 32 bits with 6 digits of precision.
▪ Floating point numbers are defined in C by the keyword – float.
▪ To improve the accuracy, we go for the datatype double, which is an
extension of floating-point datatype. A double datatype number uses
64 bits with a precision of 14 digits.
▪ Long double used 80 bits.
Type Size Range
Float 4 bytes 3.4e-3.8 to 3.4e+38
Double 8 bytes 1.7e-308 to 1.7e+308
Long double 10 bytes 3.4e-4932 to 1.1e+4932

3) Character data type


▪ A single character can be defined as a character.
▪ Characters are defined by the datatype char.
▪ Characters are stored in 8 bits of internal storage.
Type Size Range
signed char 1 byte -128 to +127
unsigned char 1 byte 0 to 255

4) Void data type


▪ Void type has no values
▪ It is used to specify the type of functions
▪ The type of function is said to be void when it doesn’t return any value
to the calling function.
User-defined data types
▪ C provides two types of user defined data types.
1) typedef 2) enum

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
typedef
▪ It allows the user to define an identifier that would represent an
existing data type.
▪ The user defined data type identifier can later be used to declare
variable.
▪ Syntax: typedef datatype identifier;
Eg., typedef int marks;
marks s1,s2;
enum:
▪ Syntax:- enum identifier { value1,value2,……,value n};
Where identifier is a user defined enumerated data type. Which can be used
to declare variables that can be used to declare variables that can have one
of the values enclosed with in the braces.
After this declaration, we can declare variables to be of the new type.
enum dentifier v1, v2, v3, ………, vn;
v1 = value3;
v5 = value1;
Eg., enum day{ Monday,Tuesday,Wednesday……..,Sunday};
enum day week_st,week_end;
week_st = Monday; week_end = Saturday;
Derived datatype:
▪ Derived data types are the data types such as arrays, functions,
structures, pointers.
OPERATORS
▪ An operator is a symbol that tells the compiler to perform certain
mathematical or logical manipulation.
▪ The value on which an operation is performed is called operand.
▪ C operators can be classified into 8 categories. They are
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operator

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
5. Increment / Decrement Operators
6. Ternary or Conditional Operators
7. Bitwise Operators
8. Special Operators
1. Arithmetic Operators: These are the operators which perform
mathematical operations. The available arithmetic operators are

OPERATOR MEANING

+ Addition or Unary plus

- Subtraction or Unary Minus

* Multiplication

/ Division

% Modulo Division

Eg., a+b, 25%5, x-y*z, 52/2 etc.


Integer Arithmetic: The arithmetic operation is performed on integers is
called as integer arithmetic.
Note:
1. Integer division truncates any fraction part
2. The modulo division operation produces the remainder of an integer
division.
3. % operator cannot be used on floating point data
4. C does not have an operator for exponent.
Examples: if a =14 and b=4
1. a – b = 10
2. a + b = 14
3. a * b = 56
4. a / b = 3 (decimal part truncated)
5. a % b = 2 (remainder of division0

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Note
1. If both operands are of the same sign, the result is truncated towards
zero. If one of the them is negative, the direction of truncations
machine dependent.
Real Arithmetic: An arithmetic operation involving only real operands is
called real arithmetic.
▪ E.g if x, y and z are floats
X = 6.0 / 7.0 = 0.857143
Note:
1. % operator cannot be used with real operands.
Mixed mode Arithmetic: When one of the operands is real and the other is
integer, the expression is called a mixed mode arithmetic expression.
The result of mixed mode arithmetic is floating point number only.
E.g: 15/10.0 = 1.5 where as 15/10 = 1

2. Relational Operators
These types of operators check the relationship between two of the available
operands. In case the relation happens to be true, then it returns to 1. But in
case this relation turns out to be false, then it returns to the value 0. We use
the relational operators in loops and in the cases of decision making.
In C, we have six types of relational operators. They are

The result of relational expression is either true or false.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Example
1. 10 < 20 is True
2. 10 > 20 is False
Syntax: arithmetic expression-1 relational operator arithmetic expression-2
Note: arithmetic operators have a higher priority over relational operators

3. Logical Operators
We use logical operators to perform various logical operations on any set of
given expressions. The result of logical operation is either true or false.
Example
a > b && x == 10 is TRUE if a=3 and b = 2
C provides three types of logical operators. Which are
1. Logical AND (&&) 2. Logical OR (||) 3. Logical NOT (!)

Operator Description Example

Called Logical AND operator. If both the


(A && B)
&& operands are non-zero, then the condition
is false.
becomes true.

Called Logical OR Operator. If any of the two


(A || B)
|| operands is non-zero, then the condition
is true.
becomes true.

Called Logical NOT Operator. It is used to reverse


!(A &&
the logical state of its operand. If a condition is
! B) is
true, then Logical NOT operator will make it
true
false.

Note: An expression consists of arithmetic, relational and logical operators,


first arithmetic operators are evaluated, then relational operators are
evaluated and finally logical operations are evaluated.
4. Assignment Operators
Assignment operators are used to assign the value or result of an expression
to a variable.
‘=‘ is called assignment operator
Syntax: variable = expression;

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Shorthand notation:
variable op= expression same as variable = variable op expression
Example: x=5 then x+=5; same as x = x+5 ; x value 10

Simple Assignment Operator Shorthand operator


a = a+1 a += 1
a = a-1 a -=1
a = a*(m+n) a *= (m+n)
a = a/(m+n) a /= (m+n)
a=a%b a %= b

Advantages of shorthand notation


1. What appears on the left-hand side need not be repeated and therefore
it becomes easier to write.
2. It is more concise and easier to read
3. It is more efficient.

5. Increment and Decrement Operators


Increment operator is represented with ++ and decrement operator is
represented with --
The operator ++ adds 1 to the operand and – subtracts 1 from the operand.
E.g: ++m or m++ or –m or m—
If m=5 y = ++m; [ the value of y and m would be 6]
if m=5 y = m++; [ the value of y is 5 and m is 6]
A prefix operator first adds 1 to the operand and then the result is assigned
to the variable on left.
A postfix operator first assigns the value to the variable on the left and then
increments the operand.
Note:
1. Increment and decrement operators are unary operators and thus
require variable as their operands.
2. When postfix ++ / -- is used with a variable in an expression, the
expression is evaluated first using the original value of the variable and
then the variable is incremented / decremented by 1.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
3. When prefix ++ / -- is used in an expression the variable is incremented
/ decremented by 1 first then the expression is evaluated using the new
value of the variable.
4. The precedence and associativity of ++ and – operators same.

6. Conditional Operator (Ternary Operator)


Ternary operator (?: ) is used to construct a conditional expressions of the
following form
Syntax: exp1 ? exp2 : exp3 ; (exp are expressions)
Exp1 is evaluated first, if it is true then exp2 is executed otherwise exp3 is
executed.
Example: a = 10 , b= 15 x = (a > b) ?: a : b; // x will be assigned the
value b
7. Bitwise Operators
These operators are used to manipulate data at bit level. C has 6 types of
bitwise operators.

Note:
1. Left shift performs multiply a number with 2
2. Right shift performs divide a number by 2

8. Special Operators
Comma: the comma operator can be used to link the related expressions
together.A comma linked list of expressions are evaluated left to right and
the value of the rightmost expression is the value of the combined
expression.
Example: value = (x=10, y=5, x+y);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Sizeof(): the size is a compile time operator and when used with an operand.
It returns the number of bytes the operand occupies. The operand may be a
variable, comment or data type qualifier.
E.g: int a; m = sizeof(a); // m is 2
Pointer operator ( & and * )
Member Selection Operator ( . and ->)

Evaluation of Expressions
An expression can be evaluated based on the precedence of operators. After
the expression is evaluated, then the value of the expression is assigned to
the variable.
Eg., x=5*6-4=26 A=3+2*6=15 z=3%2+1=2
Precedence
Operator precedence determines the grouping of terms in an expression and
decides how an expression is evaluated. Certain operators have higher
precedence than others. For example, the multiplication operator has a higher
precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator *
has a higher precedence than +, so it first gets multiplied with 3*2 and then
adds into 7.
Associativity
Associativity rules decide the order in which multiple occurrences of the same
level operator are applied.
Rules for Evaluation of Expressions:
1. First parenthesized subexpressions from left to right are evaluated.
2. If parentheses are nested, the evaluation begins with the innermost sub
expression.
3. The precedence rule is applied in determining the order of operations in
evaluating sub expressions.
4. The associativity rule is applied when two or more operators of the same
precedence level appear in a sub expression.
5. Arithmetic expressions are evaluated from left to right using the rules of
precedence.
6. When parentheses are used, the expression within parentheses assumes
highest priority.
Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom. Within an expression, higher
precedence operators will be evaluated first.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= Right to left
|=
Comma , Left to right

Let's understand through an example.


6*2/( 2+1 * 2/3 +6) +8 * (8/4)
Evaluation of expression Description of each operation
6*2/( 2+1 * 2/3 +6) +8 * (8/4) An expression is given.
6*2/(2+2/3 + 6) + 8 * (8/4) 2 is multiplied by 1, giving value 2.
6*2/(2+0+6) + 8 * (8/4) 2 is divided by 3, giving value 0.
6*2/ 8+ 8 * (8/4) 2 is added to 6, giving value 8.
6*2/8 + 8 * 2 8 is divided by 4, giving value 2.
12/8 +8 * 2 6 is multiplied by 2, giving value 12.
1+8*2 12 is divided by 8, giving value 1.
1 + 16 8 is multiplied by 2, giving value 16.
17 1 is added to 16, giving value 17.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Storage Classes
Storage classes are used to describe the features of the variables. These
features include scope, visibility, and lifetime which help us to trace the
existence of a particular variable during the execution of a program.
Scope – The scope of a variable determines over what region of the program
a variable is available for use (Active).
Scopes are divided into 5 types
1. Program Scope: The variable is available throughout the program
2. File Scope: the variable is available throughout the file
3. Block scope: the variable is available within the block
4. Function scope: the variable is available within the function
5. Prototype scope: the prototype variables are available till the function exits.
Note: File scope and Program scope come under the global scope
Visibility – It refers to the accessibility of a variable from the memory.
Longevity – It refers to the period during which a variable retains a given
value during the execution of a program (Alive).
The variables may also be categorized depending on the place of their
declaration
1. Internal (Local): Internal variables are those which are declared within a
particular function
2. External (Global): External or Global variables are those which are
declared outside of a function.
There are 4 storage classes
1. Auto 2. External 3. Static 4. Register
Automatic Variables:
1. Automatic variables are represented with the keyword ‘auto’ and it is
the default storage class.
2. These are declared inside a function in which they are utilized, when a
function is called these are created and destroyed automatically when
the function is exited, hence the name automatic.
3. These variables are declared inside the function, so these variables are
also called local or internal variables
4. Initial values for automatic variables are garbage or unknown values.
5. The scope of this variable is local to the block in which it is defined.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
6. This variable is alive within the block in which the variable is defined.
7. Automatic variables are stored in the stack memory
External Variables:
Variables that are active and alive throughout the program are called external
variables and these variables are also known as global variables.
External variables are represented with the keyword extern and these are
declared outside of the function.
Example:
int fun1(void);
int fun2(void);
int fun3(void);
int x;
void main()
{
x = 10;
printf(“ x = %d\n”,x);
printf(“x = %d\n”,fun1());
printf(“x = %d\n”,fun2());
printf(“x = %d\n”,fun3());
}
int fun1( )
{
x = x+10;
return x;
}
int fun2( )
{
int x;
x = 1;
return x;
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
int fun3( )
{
x = x+10;
return x;
}
The above program displays the following output
10
20
1
30
Once a variable has been declared as global any function can use it and
change its value.
Example
main( )
{
extern int y;
……………
}
fun1( )
{
extern int y;
……………..
}
int y;
The variable y has been defined after both functions. The external declaration
of y inside the function informs the compiler that y is an integer type defined
somewhere else in the program.
Note:
1. The external declaration doesn’t allocate storage space for variables.
2. The default value for external variables is zero

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
3. The visibility and lifetime are throughout the program.
4. External or global variables are stored in the data segment memory
Static variables
The value of the static variables persists until the end of the program. These
are declared with the keyword static.
Static variables may be internal or external depending on the place of
declaration. If these are declared inside a function then it is internal static
variables otherwise it is the external static variable. The internal static
variables
extend up to the end of the function in which they are defined.
Syntax
Static int var1, var2,…,varn;
Note:
1. The scope of this variable is limited to the block in which it is declared.
2. The lifetime of this variable is throughout the program.
3. Static variables are stored in the data segment memory.
4. The static variable is initialized only once when the program is compiled.
5. The initial value of the static variable is zero.
void stat( );
void main( )
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
stat();
}
getch();
}
void stat( )

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Static int i =0;
x = x+1;
printf(“%d\n”,x);
}
The above program displays the numbers from 1 to 10.
Register variables
Register variables are kept in machine registers because register access is
much faster than memory access. Keeping the frequently accessed variables
in the register will lead to faster execution of programs.
Register variables are represented with the keyword register.
Syntax:
register int count;
Note:
1. Most compilers allow only int or char variables to be placed in the register.
2. The initial value for register variables is the garbage value.
3. The scope and lifetime of this variable are local to the block
Type Conversion
Type conversion is the process of converting one data type into another data
type.
There are two types of type conversions.
1. Implicit type conversion
2. Explicit type conversion
Implicit Type conversion:

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
C automatically converts any intermediate values to the proper type so that
the expression can be evaluated without losing any significance. This
automatic conversion is known as implicit type conversion.
Always the lower type is automatically converted to higher type.
Explicit Type conversion
In explicit type conversion, user manually convert values of one data type to
another type. This process is also called as type casting and it is user-defined.
Here the user can typecast the result to make it of a particular data type.
Syntax: (type) expression;
Examples:
1. x = (int) 7.5; // x value is 7
2. a = (int) 21.3 / (int) 4.5
3. a = (float) 3/2
4. a = float 3/2

Input and Output statements


C has two types of input and output statements. They are
1. Formatted Input output statements
2. Unformatted Input Output statements
Formatted Input output statements:
scanf():
It is an input statement that is used to read all kinds of data from the user. It
reads the data from standard input (keyword), converts it into a specified
format
string and finally assigns the value to the variable.
Syntax: scanf(“format-string”, Address of variables);
Here format-string refers to the type of data that is going to be read for the
variable. The format string always starts with %.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Format Purpose Format Purpose
String String

%d To read an integer value %Lf To read an long double value

%c To read a single character %[..] To read only the specific


character

%f To read an float value %^[..] To read other than the specified


character

%lf To read an long float value %o To read an octal number

%s To read a string %x To read a hexadecimal number

%e To read an exponent value %lu To read an long unsigned value

%u To read an unsigned value

While reading values for the variables using scanf() statement, we must
specify the address of the variable. For a simple variable, the & (address)
operator should be present in front of the variable.
Note: The number of format strings must match the number of variables.

The scanf() statement first reads the data from the keyboard, converts them
as per the format-string specifications and finally assigns the converted
value to the variable.
How to read one integer value? First, the variable must be declared as an
integer data type and then use scanf() with %d as a format specifier as
follows:
int a;
scanf("%d", &a);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
By this way we can read a value for a variable. See the following example to
know more about the scanf() with provisions.
1. scanf("%d", &a); //To read an integer data for the variable a
2. scanf("%c", &c); //To read the character data for the variable c.
3. scanf("%lf",&i); //To read the double value for the variable i.
4. char name[15];
scanf("%s", name); //Read a string, group of characters for the variable
name The scanf() statement supports the reading of values for more than
one variable. The format-string from left to right for the variables is in the
same order.
In the following example, the format string %d and %f are assigned to the
variables a and b respectively.
5. scanf("%d%f",&a, &b); //To read integer and float values for a and b.
Specifying the format string as follows can restrict the number of characters
of the input.
6. scanf("%3d", &a); //To read integer value, but a accepts only 3 digits If we
give 12345, only the first 3 digits will be accepted and so the variable a will
have the value 123. The remaining digits will be omitted or may be assigned
to the next variable.
7. int a, b; scanf("%2d%d",&a, &b); //While giving the inputs, the first two
digits are assigned only to a, and the remaining will be assigned to b.
For example, if we give the value 12345 as input, the first two digits 12 will
be assigned for a and the remaining digits 345 are assigned to b.
8. scanf("%x", &n); //To read the hexadecimal value for n and the given
value is assigned as hexadecimal. For example, if we give 10, the value
assigned to the variable n is a, which is a hexadecimal equivalent of 10.
9. scanf("%o", n); // To read the octal value to 'n', the given value is
assigned as octal. For example, if we give 10, the value assigned to n is 8
(octal equivalent of 10 is 8).
Let us consider the declaration as char str[25] for the following examples.

Reading the Restricted Characters


By using the format string %[...], the character can be restricted while
reading. Only the characters specified inside the brackets are accepted.
10. scanf("%[a-f]", str)
Accepts the characters from 'a' to 'f'. If we try to give other characters, they
are not accepted.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
11. scanf("%[^a-f] ", str)
Accepts other than the characters from 'a' to 'f'.
12. scanf("%[a,b,1,2]", str)
Here 'str' accepts only the characters 'a','b','1' and '2'
13. scanf("%[^\n]", str)
Here str accepts all the characters except the '\n' character. So it can be
used to read a higher number of characters.
printf()-An Output Statement
The output statements are necessary for any programming language to
produce the result of any calculation or process in different ways.
Syntax
1. printf("format string", variable(s) );
2. printf("Message");
3. printf("Escape sequence character");
We can use any one of the above output statements or combinations of
printf() depending on the need.
The general form of output statement transaction
From variable → Format-string → Output device

The value of any variable is first converted according to the format-string


character and it will get printed in the corresponding output devices.
1. int a=100;
printf("%d", a); // display 100

2. printf("a = %d\n b = %d ",a,b);


It produces the result as follows:
a = 10
b=20
Because \n character second part, i.e. b=20 will be displayed in the next
line. Transfer the control to the 1st column of the next line.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
3. printf("Sum=%d ", a+b);
We are allowed to have a simple expression as above and the result is
Sum=30.

How to print the message like Hello "Sathya" sir? Double quotes are treated
as the end of the string. So this is going to be replaced by \", equivalent to
double quotes.
4. printf("Hello \"Sathya\" sir ");
The result of this statement is Hello "Sathya" sir.

5. int a=8;
printf("Octal = %o", a); //The result of this statement is 10. (Octal equivalent
of 8)

6. int age=25; char name[]="Karthi";


printf("Age = %d \t Name = %s ", age, name);
The result of this statement is
Age = 25 Name = Karthi
(\t (Tab) can be used to give more spaces)

7. int a=12345; printf("a %d\b", a);


• The result of this statement is 12345
• The cursor will be at 5 not in the next location.
• Because \b adjusts the cursor to the previous location

8. We can specify the field width (i.e. how many 'spaces' the item prints in).
Defaults to right-justification. Place a number between the % and the d. In
this
example, field width is 10:
printf("FSU has %10d students", numStudents); // Output:
// FSU has 35123 students
9. To left justify, use a negative number in the field width:

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("FSU has %-10d students", numStudents); // Output:
// FSU has 35123 students

10. If the field width is too small or left unspecified, it defaults to the
minimum number of characters required to print the item:
printf("FSU has %2d students", numStudents); // Output:
// FSU has 35123 students
Specifying the field width is most useful when printing multiple lines of
output that are meant to line up in a table format.
Printing Floating-point numbers
11. Use the %f modifer to print floating point values in fixed notation:
double cost = 123.45;
printf("Your total is $%f today\n", cost); // Output:
// Your total is $123.450000 today

12. Use %e for exponential notation:


printf("Your total is $%e today\n", cost); // Output:
// Your total is $1.234500e+02 today
Note that the e+02 means "times 10 to the 2nd power"

13. We can also control the decimal precision, which is the number of places
after the decimal. Output will round to the appropriate number of decimal
places, if necessary:
printf("Your total is $%.2f today\n", cost); // Output:
// Your total is $123.45 today

14. Field width can also be controlled, as with integers:


printf("Your total is $%9.2f today\n", cost); // Output:
// Your total is $ 123.45 today
• In the conversion specifier, the number before the decimal is field width,
and the number after is the precision. (In this example, 9 and 2).
o %-9.2 would left-justify in a field width of 9, as with integers

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Printing characters and strings
15. Use the formatting specifier %c for characters. Default field size is 1
character:
char letter = 'Q';
printf("%c%c%c\n", '*', letter, '*'); // Output is: *Q*

16. Use %s for printing strings. Field widths work just like with integers:
printf("%s%10s%-10sEND\n", "Hello", "Alice", "Bob"); // Output:
// Hello AliceBob END

UNFORMATTED INPUT/OUTPUT STATEMENTS


The unformatted statements are used to read/write the data without any
specification of data format. These statements are mostly used for reading
character-based data. So, all are character-based statements and they are:
Unformatted input statements Unformatted output statements

1. getchar() 1. purchar ()
2. getch( ) 2. putch()
3. getche() 3. puts()
4. gets() 4. putc()
5. getc()

getchar() (To Read Single Character)


getchar is used to read a single character. The format and the example are
given in the following passage.
Syntax: ch= getchar();
The character is stored in the variable ch.
/* Example for getchar() */
main()
{
char ch;
ch=getchar();
printf("\nGiven character is: %c", ch);
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
For example, if we give the input characters like abcdefg and press the ENTER
key, only the character a is assigned and all the other characters will be
ignored.
getch() and getche():
getch() and getche () (To Read a Single Character)
The drawback of the getchar() function is that the user must press the ENTER
key. This problem can be solved by using another function getch().
getch()
This statement is waiting for just a key touch. Pressing the ENTER key is not
compulsory, and any valid key can be pressed. The character that we have
given will not be displayed on the screen. We may use the getch() function as
a wait statement on the programs.
getche():
Suppose the user who wishes to see the character which he has typed while
using the getch() statement, can use the getche() function. The function
getche() is the same as getch(), but the first one echoes the character on the
screen (echo) and it is not echoed in the latter case.
gets() (To Read a String)
The gets() function is used to read the string, which is a group of characters.
Problems in scanf(): The inputs for the scanf() statement are identified by
using delimiters such as blank space, comma, and new line character. When
we use the scanf() function to read the string, it does not accept a blank space.
Suppose the user wishes to give an input like "karthi keyan", the scanf()
statement takes only the string "karthi" as input. Because, a blank space
appeared after the string "karthi". By using the gets() function, we can read
the string including the blank spaces.
The gets() function reads any number of and any type of characters until the
new line (\n) character.
Syntax: gets(name); // here name is a string data type.
Program to read a string using gets()
/* Program to read a string with spaces */
void main()
{
char name[10];
printf(“\n Enter name: “);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
gets(“%s”,name);
printf(“\n Your name is : %s”,name);
}
Output:
Enter name: Naga Raju
Your name is : Naga Raju
Drawback of gets(): It allows only one argument
How to read a more than one line of characters
The scanf() statement is used to read the characters until the delimiters and
the gets() is used to read the characters including the blank space until the
new line character. Suppose we need to read more than one line of input
characters, then we use the format string %[...], it can be used to read the
specified characters only.
1. %[^.] - read any character except the specified character (including new
line character).
2. %[^0] - read any number of characters except the 0 (zero).
putchar() and puts():
Putchar(): putchar is used to display one character at a time.
Syntax:
int putchar(character);
Examples:
1. putchar(‘a’); // prints the character a.
2. putchar(65); //prints the actual ASCII character of 65 as A
Puts(): puts is used to display the whole string.
Syntax: int puts(string);
Examples:
1. puts(“Good morning”); //it displays the entire string as Good morning
2. Char name[]=”Naga Raju”;
puts(name); //it produces the output as Naga Raju.
Both putchar() and putch() are used for displaying a character. The difference
between then is, pitch() can be used only for the text windows, but puthcar()
sends a character to any output stream.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
getc() and putc():
getc(): getc() is used for reading a character from the file.
putc(): putc() is used to write a character to the file.

Decision Making and Branching


Decision making statements in c are
1. If statement
2. switch statement
3. goto statement
Note: these statements control the flow of execution, so these statements are
also known as control statements.
If statements are divided into 4 categories
1. Simple is
2. If………..else
3. Nested if…else
4. Else if ladder
Simple if statement: simple if statement has only true block. If the given
condition is true then it executes a true block statement. otherwise, it can
execute the statements after the if statement.
Syntax:
if(expression)
{
// True block statements
}
if-else statement: If-else statement has two blocks which are true block
statements and false block statements. If the given condition is true then it
executes the true block statements, otherwise it executes the false block
statements.
Syntax:
if(expression)
{
// True block statements
}
else
{

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
//False block statements
}
Flowchart

Nested if-else statement: An if statement is placed in another if statement


is called nested if statement.
Syntax:
if (boolean_expression_1)
{
if(nested_expression_1)
{
// If boolean_expression_1 and
// nested_expression_1 both are true
}
else
{
// If boolean_expression_1 is true
// but nested_expression_1 is false
}
// If boolean_expression_1 is true
}
else
{
if(nested_expression_2)
{
// If boolean_expression_1 is false
// but nested_expression_2 is true
}
else
{
// If both boolean_expression_1 and
// nested_expression_2 is false

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}

// If boolean_expression_1 is false
}

Flowchart:

Else if ladder statement:


First condition1 is tested, if it is true then statement1will be executed and
control comes out of the whole if else ladder. If condition1 is false, then only
condition2 is tested. Control will keep on flowing downward. The last else is
the default block of code which will gets executed if none of the conditional
expressions is true.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Syntax:

Flowchart:

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
C Programs on if statements:
1. Find Largest of two numbers
2. Find Smallest of two numbers
3. Find the given number is even or odd
4. Find the given number is positive or negative
5. Find the given year is leap year or not
6. Find the given character is alphabet or not
7. Find the given character is lowercase or uppercase
8. Find the given alphabet as a vowel or consonant.
9. Find the largest of three numbers.
10.Find Roots of a quadratic equation
11.Write a C program to input marks of five subjects Physics, Chemistry,
Biology,
Mathematics and Computer. Calculate percentage and grade according to
following:
Percentage>=90%:GradeA
Percentage>=80%:GradeB
Percentage>=70%:GradeC
Percentage>=60%:GradeD
Percentage>=40%:GradeE
Percentage < 40% : Grade F

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Switch Statement
The switch case statement is similar to the else-if ladder as it provides
multiple branching or multi-conditional processing.
The switch case statement tests the value of a variable or expression against
a series of different cases or values, until a match is found. If a match is found
then the blockof code within the match case is executed. If there are no
matches found, the optional default case is executed.
Syntax
switch( expression )
{
case value-1: Block-1;
break;
case value-2: Block-2;
break;
case value-n: Block-n;
break;
default : Block-1;
}
Statement-x;

Flowchart

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Important points to remember
1. The expression can be an integer expression or a character expression.
2. Value-1, 2, n are case labels which are used to identify each case
individually. Remember that case labels should not be the same as it may
create a problem while executing a program. Suppose we have two cases
with the same label as '1'. Then while executing the program, the case that
appears first will be executed even though you want the program to execute
a second case. This creates problems in the program and does not provide
the desired output.
3. Case labels always end with a colon ( : ). Each of these cases is associated
with a block.
4. A block is nothing but multiple statements which are grouped for a
particular case.
5. Whenever the switch is executed, the value of test-expression is compared
with all the cases which we have defined inside the switch. Suppose the
test expression contains value 4. This value is compared with all the cases
until case whose label four is found in the program. As soon as a case is
found the block of statements associated with that particular case is
executed and control goes out of the switch.
6. The break keyword in each case indicates the end of a particular case. If
we do not put the break in each case then even though the specific case is
executed, the switch in C will continue to execute all the cases until the
end is reached. This should not happen; hence we always have to put the
break keyword in each case. Break will terminate the case once it is
executed and the control will fall out of the switch.
7. The default case is an optional one. Whenever the value of test-expression
is not matched with any of the cases inside the switch, then the default
will be executed. Otherwise, it is not necessary to write default in the
switch.
8. Once the switch is executed the control will go to the statement-x, and the
execution of a program will continue.
9. The switch case statement evaluates the value of an expression and a block
of code is selected on the basis of that evaluated expression.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
10. The data type that can be used in switch expression is integer type only.
11. The switch case takes decision on the basis of equality.

Differences between else if ladder and switch case

1. In the else if ladder, the control goes through every else if statement until
it finds the true value of the statement or it comes to the end of the else if
ladder. In the switch case, as per the value of the switch, the control jumps
to the corresponding case.
2. The switch case is more compact than the if else ladder. So, switch is
considered to be more readable, it takes less time for execution.
3. The use of break statements in switch is essential but there is no need of
use of break in else if ladder.
4. The variable data type that can be used in expression of switch is integer
only whereas in else if ladder accepts integer type as well as character.
5. Another difference between switch case and else if ladder is that the switch
statement is considered to be less flexible than the else if ladder, because
it allows only testing of a single expression against a list of discrete values.
6. Since the compiler is capable of optimizing the switch statement, they are
generally considered to be more efficient. Each case in the switch
statement is independent of the previous one. In case of else if ladder, the
code needs to be processed in the order determined by the programmer.
7. Switch case statement works on the basis of equality operator whereas else
if ladder works on the basis of true false( zero/non-zero) basis.

C programs using switch statement

1. Write a c program to implement a simple calculator.

2. Write a c program to check the given character is vowel or not

3. Write a c program to find grade of a student using switch statement.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
goto statement

• Goto statement is an unconditional jump statement.


• When the compiler reaches the goto statement, then it will jump
unconditionally (both forward and backward) to the location specified
in the goto statement (we call it as label).
• The goto statement has two types of jumps, which are forward and
backward jumps
• We can place the label anywhere in the program. It doesn't matter if you
put it before or after the goto statement.
• Forward goto: The label is placed after the goto label is called forward
goto. It skips the statements between goto label and label.
• Backward goto: The label is placed before the goto label is called
backward goto. It forms the loop with statements between label and
goto label.

C Programs using goto

1) Write a c program to display numbers from 1 to 10.


2) Write a c program to display multiplication table
3) Write a c program to find reverse of a given number
4) Write a c program to check the given number is palindrome or not
5) Write a c program to check the given number is Armstrong number or
not
6) Write a c program to find factorial of a given number

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
UNIT-II
Syllabus

Loops, Arrays, Strings: Loops: Iteration with for, while, do- while loops, break
and continue statements. Arrays: One and two dimensional arrays, creating,
accessing and manipulating elements of arrays Strings: Introduction to
strings, handling strings as array of characters, string functions available in
C arrays of strings.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Loops

Iterative statements:

Iteration is the process where a set of instructions or statements is executed


repeatedly for a specified number of times or until a condition is met.

These statements also alter the control flow of the program and thus can also
be classified as control statements in C Programming Language

Iteration statements are most commonly known as loops. Also, the repetition
process in C is done by using loop control instruction.

There are three types of looping statements:

1. For Loop
2. While Loop
3. Do-while loop

A loop basically consists of three parts: initialization, test expression,


increment/decrement or update value.

Depending upon the position of a control statement in a program, looping in


C is classified into two types:

1. Entry controlled loop

2. Exit controlled loop

Entry controlled loop: In an entry-controlled loop a condition is checked


before executing the body of a loop. It is also known as a pre-checking loop.

Exit controlled loop: In an exit-controlled loop, a condition is checked after


executing the body of a loop. It is also known as a post-checking loop.

Examples

Entry controlled loop statements : while and for

Exit controlled loop statement: do-while

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Differences between Entry controlled and Exit controlled loop
statements

for loop

For loop is the most commonly used looping technique. The reason why it is
so popular is because it has all the three parts of the loop: initialization, test
expression, update expression in the same line.

The syntax of a for loop is:

for(initialization; test expression; update expression)

//body of loop

Example: display numbers from 1 to 10


#include <stdio.h>
int main()
{
int i;

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
for(i=1; i<=5; i++)
{ printf(“%d”,i); }
return 0;

Infinite for loop:

An infinite for loop is the one which goes on repeatedly for infinite times.
This can happen in two cases:

1.When the loop has no expressions.

for(;;)

printf(“Hello");

}
The above code runs infinite times because there is no test expression to
terminate the loop. Hence, Hello gets printed infinite times

2. When the test condition never becomes false.

for(i=1;i<=5;)

printf(“Hello");

}
In the above case, the statement Hello gets printed infinite times because the
test condition never becomes false. The value of i remains the same because
it is never updated and thus the value of i remains smaller than 5 for each
iteration

Empty for loop:

An empty for loop is the one which has got no body. In simple words, it
contains no statements or expressions in its body. It can be used for time-
consuming purposes.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Each iteration takes its own time for compilation and execution. Usually, it is
too small to be of any significant importance. Here’s the syntax of an empty
for loop:

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

{ }

C programs using for loop


1. C Program to Calculate the Sum of Natural Numbers

#include<stdio.h>

int main()

int i,n,sum;

printf("\n Enter the n value:");

scanf("%d",&n);

for(i=1,sum=0;i<=n;i++)

sum=sum+i;

printf("\n Sum = %d",sum);

return 0;

}
2. C Program to Find Factorial of a Number
#include<stdio.h>
int main()
{
int i,n,fact;
printf("\n Enter the n value:");
scanf("%d",&n);
for(i=1,fact=1;i<=n;i++)
{

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
fact=fact*i;
}
printf("\n factorial = %d",fact);
return 0;
}

3. C Program to Generate Multiplication Table


#include<stdio.h>
int main()
{
int i,n;
printf("\n Enter the n value:");
scanf("%d",&n);
for(i=1;i<=10;i++)
{
printf("\n %d X %d = %d",n,i,n*i);
}
return 0;
}
4. C Program to Display Fibonacci Sequence
#include<stdio.h>
int main()
{
int f0,f1,f2,n,count;
printf("\n Enter the n value:");
scanf("%d",&n);
f0=0;
f1=1;
printf("\n %d \n %d",f0,f1);
for(count=2;count<n;count++)
{
f2=f0+f1;
printf("\n %d",f2);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
f0=f1;
f1=f2;
}
return 0;
}
5. C Program to Find GCD of two Numbers
#include<stdio.h>
int main()
{
int m,n,max,gcd,i;
printf("\n Enter two values:");
scanf("%d%d",&m,&n);
max=(m>=n)?m:n;
for(i=1;i<=max;i++)
{
if((m%i==0) && (n%i==0))
{
gcd=i;
}
}
printf("\n GCD = %d",gcd);
return 0;
}
6. C Program to Find LCM of two Numbers
int main()
{
int m,n,max,gcd,i,lcm;
printf("\n Enter two values:");
scanf("%d%d",&m,&n);
max=(m>=n)?m:n;
for(i=1;i<=max;i++)
{
if((m%i==0) && (n%i==0))

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
{
gcd=i;
}
}
lcm = (m*n)/gcd;
printf("\n LCM = %d",lcm);
return 0;
}
7. C Program to Display Characters from A to Z Using Loop
#include<stdio.h>
int main()
{
char c;
for(c='A';c<='Z';c++)
{
printf("\n %c",c);
}
return 0;
}
8. C Program to count number of digits in an Integer
#include<stdio.h>
int main()
{
int i,n,count=0;
printf("\n Enter a number:");
scanf("%d",&n);
for(;n>0;n=n/10)
{
count++;
}
printf("\n Number of digits = %d",count);
return 0;
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
9. C Program to Reverse a Number
#include<stdio.h>
int main()
{
int i,m,n,sum=0;
printf("\n Enter a number:");
scanf("%d",&n);
for(;n>0;n=n/10)
{
m = n%10;
sum = sum*10+m;
}
printf("\n Reverse of a Number is %d",sum);
return 0;
}
10. C Program to Calculate the Power of a Number

11. C Program to Check Whether a Number is Palindrome or Not

#include<stdio.h>
int main()
{
int i,m,n,sum=0,temp;
printf("\n Enter a number:");
scanf("%d",&n);
temp=n;
for(;n>0;n=n/10)
{
m = n%10;
sum = sum*10+m;
}
if(temp==sum)
{

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("\n %d is a palindrome",temp);
}
else
{
printf("\n %d is not a palindrome",temp);
}
return 0;
}
12. C Program to Check Whether a Number is Prime or Not
#include<stdio.h>
int main()
{
int i,n,count;
printf("\n Enter a number:");
scanf("%d",&n);
for(i=1,count=0;i<=n;i++)
{
if(n%i==0)
{
count++;
}
}
if(count==2)
{
printf("\n %d is a prime number",n);
}
else
{
printf("\n %d is not a prime number",n);
}
return 0;
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
13. C Program to Display Prime Numbers Between Two Intervals
#include<stdio.h>
int main()
{
int i,j,m,n,count;
printf("\n Enter a range:");
scanf("%d%d",&m,&n);
for(i=m;i<=n;i++)
{
for(count=0,j=1;j<=i;j++)
{
if(i%j==0)
{
count++;
}
}
if(count==2)
{
printf("\n %d is a prime number",i);
}
}
return 0;
}
14. C Program to Check Armstrong Number
#include<stdio.h>
int main()
{
int i,m,n,sum=0,temp;
printf("\n Enter a number:");
scanf("%d",&n);
temp=n;
for(;n>0;n=n/10)
{

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
m = n%10;
sum = sum+m*m*m;
}
if(temp==sum)
{
printf("\n %d is an Armstrong number",temp);
}
else
{
printf("\n %d is not an Armstrong number",temp);
}
return 0;
}
15. C Program to Display Armstrong Number Between Two Intervals
#include<stdio.h>
int main()
{
int i,k,m,n,sum=0,temp;
printf("\n Enter a range:");
scanf("%d%d",&m,&n);
for(i=m;i<=n;i++)
{

for(k=i,sum=0;k>0;k=k/10)
{
m = k%10;
sum = sum+m*m*m;
}
if(i==sum)
{
printf("\n %d is an Armstrong number",i);
}
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
return 0;
}
16. C Program to Display Factors of a Number
#include<stdio.h>
int main()
{
int i,n;
printf("\n Enter a value:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if(n%i==0)
{
printf("\n %d",i);
}
}
return 0;
}

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):
for(initialization; test; update)
{
for(initialization;test;update)//using another variable
{
//body of the inner loop
}
//body of outer loop(might or might not be present)
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
C Programs using nested for loops
1. Half pyramid of *
2. Half pyramid of numbers
3. Half pyramid of alphabets
4. Inverted half pyramid of *
5. Inverted half pyramid of numbers
6. Full pyramid of *
7. Full pyramid of numbers
8. Inverted full pyramid of *
9. Pascal's triangle
10. Floyd's triangle

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
While loop

While loop is a entry controlled statement


Syntax
while (test expression)
{
// statements inside the body of the loop
}
Flowchart

The while loop evaluates the test expression inside the parenthesis (). If the
test expression is true, statements inside the body of the while loop are
executed. Then, the test expression is evaluated again. This process goes on
until the test expression is evaluated to false. If the test expression is false,
the loop terminates (ends).

C Program to display numbers from 1 to 5 using while loop.

#include <stdio.h>
int main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
++i;
}
return 0;
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Comparison between for loop and while loop

for loop While loop

for(initialization; condition; iteration){ while ( condition) {


//body of 'for' loop //body of loop
} }

Initialization, condition checking, Only initialization and condition


iteration statements are written at the checking is done at the top of the
top of the loop. loop

The 'for' loop is used only when we The 'while' loop is used only when
already know the number of the number of iterations are not
iterations. exactly known.

If the condition is not put up in 'for' If the condition is not put up in the
loop, then loop iterates infinite times. 'while' loop, it provides compilation
error.

In the 'for' loop the initialization once In the while loop if initialization is
done is never repeated. done during condition checking,
then initialization is done each
time the loop iterates.

In the 'for' loop iteration statement is In the 'while' loop, the iteration
written at top, hence, executes only statement can be written anywhere
after all statements in the loop are in the loop.
executed.

do-while

In do-while, for the first time the body of the loop statements are executed
then it checks the condition. If the condition is true then it executes the body
of the loop statements. This process is repeated until the condition becomes
false.

In do-while, condition is placed after the body of the loop statements.

It is an exit controlled loop statement.

Syntax
do
{
// statements inside the body of the loop
}while (testExpression);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
The body of do...while loop is executed once. Only then, the test expression is
evaluated.

flowchart:

C program to display numbers from 1 to 10 using do-while.


#include <stdio.h>
int main()
{
int j=1;
do
{
printf("Value of variable j is: %d\n", j);
j++;
}while (j<=10);
return 0;
}

Differences between while and do-while

While Loop Do-While Loop

This is an entry controlled loop. It This is an exit control loop. It


checks the condition before entering checks the condition at the end of
into loop the loop

The while loop may run zero or more do-While may run more than one
times time but at least once.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
The variable of test condition must be The variable for loop condition may
initialized prior to entering into the also be initialized in the loop also.
loop

while(condition){ do{
//statement //statement
} }while(condition);

Differences between for loop and do-while

For loop Do-While loop

Statement(s) is executed once the Condition is checked after the


condition is checked. statement(s) is executed.

It might be that the statement(s) gets Statement(s) is executed at least


executed zero times. once.

For the single statement, brackets Brackets are always compulsory.


are not compulsory.

for loop is entry controlled loop. do-while is an exit controlled loop.

for ( init ; condition ; iteration ) do {


{ //statement(s);
//statement (s); }while (condition);
}

Break and continue

We want to jump out of the loop even if the condition is true or continue
repeated execution of code skipping some of the parts. To do this we can use
break and continue.

Break: break is used to jump out of loop skipping the code below it without
caring about the test condition.

It interrupts the flow of the program by breaking the loop and continues the
execution of code which is outside the loop.

The common use of break statement is in switch case where it is used to skip
the remaining part of the code.

The break statement ends the loop immediately when it is encountered.


Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Syntax:
break;
The break statement is almost always used with the if...else statement inside
the loop.

Program to calculate the sum of numbers (10 numbers max). If the user enters
a negative number, the loop terminates.

Continue:

The continue statement skips the current iteration of the loop and continues
with the next iteration.

syntax:
continue;
The continue statement is almost always used with the if...else statement.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Program to calculate the sum of numbers (10 numbers max). If the user enters
a negative number, it's not added to the result.

Differences between break and continue

BREAK CONTINUE

It terminates the execution of the It terminates only the current iteration


remaining iteration of the loop. of the loop.

'break' resumes the control of the 'continue' resumes the control of the
program to the end of the loop program to the next iteration of that
enclosing that 'break'. loop enclosing 'continue'.

It causes early termination of the It causes early execution of the next


loop. iteration.

'break' stops the continuation of 'continue' does not stop the


the loop. continuation of the loop, it only stops
the current iteration.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
'break' can be used with 'switch', 'continue' can not be executed with
'label'. 'switch' and 'labels'.

Arrays

If the user wants to store marks of 500 students, this can be done by creating
500 variables individually but, this is rather tedious and impracticable. These
types of problems can be handled in C programming using arrays.
Definition: An array is a group of similar data elements which are stored in
contiguous memory locations.
All arrays consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last element.

During array declaration, the size of the array has to be specified.


The size used during declaration of the array informs the compiler to
allocate and reserve the specified memory locations.
Syntax:
data_type array_name[n];
where, n is the number of data items (or) index(or) dimension and the range
is 0 to (n-1).
E.g: int a[5]; //compiler allocates 5 memory locations a[0], a[1], a[2], a[3],
a[4]
float x[10];
int age[5];

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Initialization of Arrays

The different types of initializing arrays are

1. Compile time initialization

(i) Initializing all specified memory locations.

(ii) Partial array initialization

(iii) Initialization without size.

(iv) String initialization.

2. Run Time initialization

The general form of initialization of arrays is


Syntax: type array-name[size]={ list of values};
Initializing all specified memory locations: Arrays can be initialized at the
time of declaration when their initial values are known in advance. Array
elements can be initialized with data items of type int, char etc.
Ex:- int a[5]={10,15,1,3,20};
During compilation, 5 contiguous memory locations are reserved by the
compiler for the variable a and all these locations are initialized as shown in
figure.

int a[3]={9,2,4,5,6}; //error: no. of initial values are more than the size of
array.
Partial array initialization: Partial array initialization is possible in c
language. If the number of values to be initialized is less than the size of the
array, then the elements will be initialized to zero automatically.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
E.g: int a[5]={10,15};
Even though the compiler allocates 5 memory locations, using this declaration
statement; the compiler initializes first two locations with 10 and 15, the next
set of memory locations are automatically initialized to 0's by the compiler as
shown in figure.

Initialization with all zeros:


Ex:- int a[5]={0};

Initialization without size: Consider the declaration along with the


initialization.
Ex:- char b[]={'C','O','M','P','U','T','E','R’};
In this declaration, even though we have not specified the exact number of
elements to be used in array b, the array size will be set off the total number
of initial values specified. So, the array size will be set to 8 automatically. The
array b is initialized as shown in figure.

Array initialization with a string: Consider the declaration with string


initialization.
Ex:- char b[]="COMPUTER"; The array b is initialized as shown in figure

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Even though the string "COMPUTER" contains 8 characters, because it is a
string, it always ends with a null character. So, the array size is 9 bytes (i.e.,
string length 1 byte for null character).
Ex:- char b[9]="COMPUTER"; // correct
char b[8]="COMPUTER"; // wrong
Run time initialization:
An array can be explicitly initialized at run time. This approach is usually
applied for initializing large arrays.
Ex:- scanf can be used to initialize an array.
int x[3];
scanf(“%d%d%d”,&x[0],&x[1],&x[2]);
The above statements will initialize array elements with the values entered
through the keyboard. (Or)
for(i=0; i<100;i++) {
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 initialized to 1.0 at run time.
Programs list
1. Program to find the average of n numbers using arrays.
2. Program to find the minimum value from array elements.
3. Program to find the maximum value from array elements.
4. Program to find the minimum value from the given array
elements.
5. Program to find the maximum value from the given array
elements.
6. Program to find the sum of array elements.
7. Program to insert an element into the specified position in an
array..
8. Program to delete an element from the specified position in the
array.
9. Program to find the second smallest element in the array.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
10. Program to search an element in the array using linear
search.
11. Program to search an element in the array using binary
search..
12. Program to sort array elements.
13. Program to remove duplicates from the array.
14. Program to merge two arrays.

1. Write a C program to find average of n array elements

#include <stdio.h>
void main(int argc, char *argv[]) {
int a[10],n,sum=0,i;
float avg;

printf("\n Enter array size:");


scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Array elements are:");
for(i=0;i<n;i++)
{
printf("\n %d",a[i]);
}
//the below for loop is used to calculate the sum of array
elements
for(i=0;i<n;i++)
{
sum=sum+a[i];
}
avg = (float)sum/(float)n;
printf("\n Average = %f",avg);
}
Output:
Enter array size:6

Enter array elements:10


20
30
40
50
60

Array elements are:


10
20

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
30
40
50
60
Average = 35.000000

2. Write a C Program to find the minimum value from array elements

#include <stdio.h>

void main(int argc, char *argv[]) {

int a[10],n,min,i;

printf("\n Enter array size:");

scanf("%d",&n);

printf("\n Enter array elements:");

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

scanf("%d",&a[i]);

printf("\n Array elements are:");

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

printf("\n %d",a[i]);

//the below for loop is used to calculate the minimum number


from array elements

for(min=a[0],i=1;i<n;i++)

if(a[i]<min)

min = a[i];

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}

printf("\n Minimum = %d",min);

Output:

Enter array size:5

Enter array elements:100

20

30

Array elements are:

100

20

30

Minimum = 2

3. Write a C Program to find the maximum value from array elements

#include <stdio.h>

void main(int argc, char *argv[]) {

int a[10],n,max,i;

printf("\n Enter array size:");

scanf("%d",&n);

printf("\n Enter array elements:");

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

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
{

scanf("%d",&a[i]);

printf("\n Array elements are:");

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

printf("\n %d",a[i]);

//the below for loop is used to calculate the minimum number


from array elements

for(max=a[0],i=1;i<n;i++)

if(a[i]>max)

max = a[i];

printf("\n Maximum = %d",max);

Output:

Enter array size:5

Enter array elements:100

10

200

Array elements are:

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
100

10

200

Maximum = 200

Program to insert an element into the specified position in an array


#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {


int a[10],pos,n,i,val;
printf("\n Enter array size\n");
scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Enter insert position:");
scanf("%d",&pos);
printf("\n Enter new value to be inserted into the array:");
scanf("%d",&val);
for(i=n-1;i>pos;i--)
{
a[i+1]=a[i];
}
a[i]=val;
printf("\n Array elements are:");
for(i=0;i<=n;i++)
{
printf("\n %d",a[i]);
}
return 0;
}

Program to delete an element from the specified position in the array.


#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {


int a[10],pos,n,i,val;
printf("\n Enter array size\n");
scanf("%d",&n);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Enter delete position:");
scanf("%d",&pos);

for(i=pos;i<n-1;i++)
{
a[i]=a[i+1];
}

printf("\n Array elements are:");


for(i=0;i<n-1;i++)
{
printf("\n %d",a[i]);
}
return 0;
}

Program to find the second smallest element in the array


#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {


int a[10],small,ssmall,n,i;
printf("\n Enter array size\n");
scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
if(a[0]<a[1])
{
small=a[0];
ssmall=a[1];
}
else
{
small=a[1];
ssmall=a[0];
}

for(i=2;i<n;i++)
{
if(a[i]<small)

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
{
ssmall=small;
small=a[i];
}
else if(a[i]<ssmall)
{
ssmall=a[i];
}
}

printf("\n Enter second smallest = %d:",ssmall);

return 0;
}

Program to remove duplicates from the array.


#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char *argv[]) {


int a[10],i,j,k,size;
printf("\n Enter array length:");
scanf("%d",&size);
printf("\n Enter array elements:");
for(i=0;i<size;i++)
{
scanf("%d",&a[i]);
}

for(i=0;i<size;i++)
{
for(j=i+1;j<size;j++)
{
if(a[i]==a[j])
{
for(k=j;k<size-1;k++)
{
a[k]=a[k+1];
}

size--;
j--;
}
}
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("\n Array elements are:");
for(i=0;i<size;i++)
{
printf("\n %d",a[i]);
}
return 0;
}

Two Dimensional Arrays


An array consisting of two subscripts is known as a two-dimensional array.
These are often known as array of the array. In two dimensional arrays the
array is divided into rows and columns.
These are well suited to handle a table of data.
In 2-D array we can declare an array as :
Syntax
data_type array_name[row_size][column_size];
Example: int arr[3][3];
where the first index value shows the number of the rows and the second
index value shows the number of the columns in the array.
Initializing two dimensional arrays
Compile time Initialization
Like the one-dimensional arrays, two-dimensional arrays may be initialized
by following their declaration with a list of initial values enclosed in braces.
Ex: int a[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 can also be written as
int a[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 a[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.
Ex: int a[][3]={
{0,2,3},
{2,1,2}
};

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
If the values are missing in an initializer, they are automatically set to zero.
Ex: int a[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.
Runtime Initialization
for(i=0; I < row_size; i++)
{
for(j=0; j < colum_size; j++)
{
scanf(“%d”,&array_name[i][j]);
}
}
Programs
1. C program to read and display matrix A elements.
2. C program to perform addition of two matrices.
3. C program to perform subtraction of two matrices.
4. C program to perform multiplication of two matrices.
5. C program to find the trace of a matrix.
6. C program to display lower matrix elements.
7. C program to display upper matrix elements.
8. C Program to find the transpose of a matrix.
9. C program to check whether the given matrix is symmetric or not.
10. Write a c program to display a lower triangular matrix.
11. Write a c program to display an upper triangular matrix.

1. Write a C Program to read and display matrix A elements.

#include <stdio.h>
void main(int argc, char *argv[]) {
int A[3][3],i,j;
printf("\n Enter Matrix Elements:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&A[i][j]);
}
}
printf("\n Matrix Elements are:\n");
for(i=0;i<3;i++)
{

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
for(j=0;j<3;j++)
{
printf("\t %d",A[i][j]);
}
printf("\n");
}
}
Output:
Enter Matrix Elements:10
20
30
40
50
60
70
80
90

Matrix Elements are:


10 20 30
40 50 60
70 80 90

2. Write a c program to find addition of two matrices


#include <stdio.h>

void main(int argc, char *argv[]) {


int A[3][3],B[3][3],C[3][3],i,j;
printf("\n Enter Matrix-A Elements:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&A[i][j]);
}
}
printf("\n Enter Matrix-B Elements:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&B[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
C[i][j]=A[i][j]+B[i][j];

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
}
printf("\n Matri-C Elements are:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\t %d",C[i][j]);
}
printf("\n");
}
}
Output:
Enter Matrix-A Elements:1 1 1
2
2
2
3
3
3

Enter Matrix-B Elements:4


4
4
5
5
5
6
6
6

Matri-C Elements are:


5 5 5
7 7 7
9 9 9
3. Write a c program to find multiplication of two matrices
#include <stdio.h>

void main(int argc, char *argv[]) {


int A[3][3],B[3][3],C[3][3],i,j,k;
printf("\n Enter Matrix-A Elements:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&A[i][j]);
}
}
printf("\n Enter Matrix-B Elements:");

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&B[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(C[i][j]=0,k=0;k<3;k++)
{
C[i][j]=C[i][j]+A[i][k]*B[k][j];
}
}
}
printf("\n Matri-C Elements are:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\t %d",C[i][j]);
}
printf("\n");
}
}
Output:
Enter Matrix-A Elements:1
1
1
1
1
1
1
1
1

Enter Matrix-B Elements:1


2
3
4
5
6
7
8
9

Matri-C Elements are:

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
12 15 18
12 15 18
12 15 18
4. Write a c program to find trace of a matrix
#include <stdio.h>

void main(int argc, char *argv[]) {


int A[3][3],i,j,trace;
printf("\n Enter Matrix-A Elements:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&A[i][j]);
}
}

for(trace=0,i=0;i<3;i++)
{
trace=trace+A[i][i];

}
printf("\n Trace of a matrix = %d\n",trace);

}
Output:
Enter Matrix-A Elements:1
2
3
4
5
6
7
8
9

Trace of a matrix = 15
5. Write a c program to find transpose of a matrix
#include <stdio.h>

void main(int argc, char *argv[]) {


int A[3][3],B[3][3],i,j;
printf("\n Enter Matrix-A Elements:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&A[i][j]);
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}

for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
B[i][j]=A[j][i];
}

}
printf("\n Transpose Matrix Elements are:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\t %d",B[i][j]);
}
printf("\n");
}
}
Output:
Enter Matrix-A Elements:1 2 3
456
789
Transpose Matrix Elements are:
1 4 7
2 5 8
3 6 9

Strings

Character Arrays
In a character array, each element stores one character.
e.g: char c[5];
c[0]='H'; c[1]='e'; c[2]=c[3]='l'; c[4]=‘o’;

c[0] H

c[1] e

c[2] l

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
c[3] l

c[4] o

character array initialization:


Like other type one-dimensional arrays, the character array can be
initialized in the same way.
e.g. char c[5] = { 'H', 'e', 'l', 'l', 'o’ };
If the number of initializers is less than the declared size, the remaining
elements are initialized to null character ('\0').
e.g. char c[6] = { 'H', 'e', 'l', 'l', 'o' };
If the number of initializers is more than the declared size, the compiler will
produce an error.
e.g. char c[4] = { 'H', 'e', 'l', 'l', 'o' };
If the number of initializers is equal to the declared size, the size may be
omitted.
e.g. char c[ ] = { 'H', 'e', 'l', 'l', 'o' };
Note: The character array can be used as other type one-dimensional arrays.
main()
{
char c[10] = { 'I', 'V', 'a', 'm', 'V', 'h', 'a', 'p', 'p', 'y' };
int i;
for ( i = 0; i < 10; i++ )
printf ( "%c", c[i] );
}
The above code displays the output as “I am happy”
A string is a group of characters ending with a null character.
Initialization of string:
Compile time initialization:
char name[20]=“I am happy”;
Runtime Initialization:
formatted input function:- scanf can be used with %s format specification to
read a string.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Ex:- char name[10]; scanf(“%s”,name);
Here don’t use ‘&’ because the name of the string is a pointer to an array.
Drawback of scanf(): The problem with scanf is that it terminates its input
on the first white space it finds.
Ex:- NEW YORK Reads only NEW (from above example).
Unformatted input functions:
getchar():- It is used to read a single character from the keyboard. Using
this function repeatedly we may read entire line of text
Ex:- char ch=‟z‟;
ch=getchar();
gets():- It is a more convenient method of reading a string of text including
blank spaces.
Ex:- char line[100];
Syntax: gets(line);
Writing strings on to the screen
Using formatted output functions:
printf with %s format specifier we can print strings in different formats on to
screen.
Ex:- char name[10];
printf(“%s”,name);
Ex:- char name[10];
printf(“%0.4”,name);

/* If name is JANUARY prints only 4 characters ie., JANU */


printf(“%10.4s”,name);

printf(“%-10.4s”,name);

Using unformatted output functions:


putchar():- It is used to print a character on the screen.
syntax:- putchar(ch);
puts():- It is used to print strings including blank spaces.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Ex:- char line[15]=”Welcome to lab”;
puts(line);

C program to the following string pattern


V
V
V
V
V
V
V
#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char *argv[]) {


char name[10]="VNRVJIET";
int i;
for(i=1;i<8;i++)
{
printf("\n%*.*s",i,1,name);
}
return 0;
}
C program to the following string pattern
V
VN
VNR
VNRV
VNRVJ
VNRVJI

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
VNRVJIE
VNRVJIET

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {


char name[10]="VNRVJIET";
int i;
for(i=1;i<9;i++)
{
printf("\n%10.*s",i,name);
}
return 0;
}

C program to the following string pattern


V
VN
VNR
VNRV
VNRVJ
VNRVJI
VNRVJIE
VNRVJIET
#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char *argv[]) {


char name[10]="VNRVJIET";

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
int i;
for(i=1;i<9;i++)
{
printf("\n%-10.*s",i,name);
}
return 0;
}

String handling functions


C supports various string handling functions for manipulations.These
functions are defined in the string.h.

Method Description

strcat() It is used to concatenate(combine) two strings

strlen() It is used to show length of a string

strcpy() Copies one string into another

strcmp() It is used to compare two string

strlen():
This function is used to find the length of the string excluding the NULL
character. In other words, this function is used to count the number of
characters in a string. Its syntax is as follows:
n = strlen(string)
Note:
1. strlen() function takes string argument.
2. The return type of strlen() is integer.

Example: char str1[ ] = “WELCOME”;


int n;
n = strlen(str1);
Here n is the length of the string.
C Program to find the string length using strlen function.
#include <stdio.h>

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char name[10];
int len;
printf("\n Enter a string");
scanf("%s",name);
len=strlen(name);
printf("\n String length=%d",len);
return 0;
}

strcpy():
This function is used to copy one string to the other. Its syntax is as follows:
Syntax: strcpy (string1, string2);
where string1 and string2 are one-dimensional character arrays.
This function copies the content of string2 to string1.
E.g., string1 contains Hyderabad and string2 contains india, then string1
holds india after execution of the strcpy (string1, string2) function.

Example:
char str1[ ] = “WELCOME”;
char str2[ ] =”HELLO”;
strcpy(str1,str2); // string1 contains HELLO
C Program to copy one string into another string using strcpy function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {


char name1[20],name2[20];
int len;
printf("\n Enter a string");
scanf("%s",name1);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
strcpy(name2,name1);
printf("\n String1=%s String2=%s ",name1,name2);
return 0;
}

strcmp()
This function compares two strings character by character (ASCII
comparison) and returns one of three values {-1,0,1}. The numeric difference
is 0 if two strings are equal. If it is negative, string2 is alphabetically above
string1. If it is positive, string1 is alphabetically above string2.
Syntax: int strcmp(str1,str2);
Note:
1. Str1 and str2 are string variables or string literals.
Example:
char str1[ ] = “ROM”;
char str2[ ] =”RAM”;
strcmp(str1,str2);
(or)
strcmp(“ROM”,”RAM”);

C program to compare two strings using strcmp function.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {


char name1[20],name2[20];
int n;
printf("\n Enter first string");
scanf("%s",name1);
printf("\n Enter second string");
scanf("%s",name2);
n=strcmp(name2,name1);
if(n==0)
{
printf("\n strings are equal");
}
else

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
{
printf("\n strings are not equal");
}

return 0;
}

strcat()
This function is used to concatenate two strings. i.e., it appends one string
at the end of the specified string.
syntax: strcat(string1, string2);
where string1 and string2 are one-dimensional character arrays.
This function joins two strings together. In other words, it adds the string2
to string1 and the string1 contains the final concatenated string.
E.g., string1 contains prog and string2 contains ram, then string1 holds the
program after execution of the strcat() function.
Example:
char str1[10 ] = “VERY”;
char str2[ 5] =”GOOD”;
strcat(str1,str2);
C program to concatenate two strings using strcat function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {


char name1[20],name2[20];
printf("\n Enter first string");
scanf("%s",name1);
printf("\n Enter second string");
scanf("%s",name2);
strcat(name2,name1);
printf("\n string1=%s string2=%s",name1,name2);

return 0;
}

C program to find the string reverse.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {


char str1[10],str2[10];
printf("\n Enter a string");
gets(str1);
strcpy(str2,str1);
strrev(str2);
printf("\n %s reverse is %s",str1,str2);
return 0;
}
C program to check the given string is palindrome or not
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {


char str1[10],str2[10];
int n;
printf("\n Enter a string");
gets(str1);
strcpy(str2,str1);
strrev(str2);
n=strcmp(str1,str2);
if(n==0)
{
printf("\n Palindrome");
}else
{
printf("\n Not palindrome");
}
return 0;
}

Two Dimensional Strings


Two dimensional strings are the array of strings. Two dimensional strings
are used to store names of the cities, persons, etc…

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Declaration:
char arr[row][col];
where
arr - name of the array
row - represents number of strings
col - represents size of each string
Initialization:
char arr[row][col] = { list of strings };
Example:
char city[5][10] = { “DELHI”, “CHENNAI”, “BANGALORE”, “HYDERABAD”,
“MUMBAI” };
The visual representation of the above declaration is shown below

Run time declaration


C code for initializing the 2D strings is shown below.
for(i=0;i<n;i++)
{
scanf(“%s”,arr[i]);
}

C program to sort city names


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char name[10][10],temp[10];
int n,i,j;

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("\n Enter number of cities");
scanf("%d",&n);
printf("\n Enter city names:\n");

for(i=0;i<n;i++)
{
scanf("%s",name[i]);
}

for(i=0;i < n-1;i++)


{
for(j=0;j<(n-i-1);j++)
{
if(strcmp(name[j],name[j+1])>0)
{
strcpy(temp,name[j]);
strcpy(name[j],name[j+1]);
strcpy(name[j+1],temp);
}

}
}
printf("\n city name are:\n");
for(i=0;i<n;i++)
{
printf("\n %s",name[i]);
}

return 0;
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
UNIT-III
Searching, Sorting, Functions:
Searching: Basic searching in an array of elements (linear and binary search
techniques)
Sorting: Basic algorithms to sort array of elements (Bubble, Insertion and
Selection sort algorithms), Basic concept of order of complexity through the
example programs
Functions: Designing structured programs, Declaring a function, Signature
of a function, Parameters and return type of a function, passing parameters
to functions, call by value.
Recursion with examples. Some C standard functions and libraries.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
UNIT -3
Searching -Linear search and Binary search
Sorting algorithms – Bubble sort, Insertion sort and Selection sort
Searching:
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

Program:
/*
Linear search
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,key,flag=0,n;
clrscr();
printf("\n Array length(No of elements)\n");
scanf("%d",&n);
printf("\n ENter array elements\n");
for(i=0;i<n;i++)
{
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
scanf("%d",&a[i]);
}
printf("\n Enter key\n");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(key == a[i])
{
flag=1;
break;
}
}
if(flag == 1)
{
printf("\n Search is successful\n");
}
else
{
printf("\n Search is unsuccessful\n");
}
getch();
}

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: Best case – O(1) worst and average case - O(n)

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
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.
Algorithm:

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Program:
/*
Binary search
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],low,i,high,key,flag=0,n,mid;
clrscr();
printf("\n Array length(No of elements)\n");
scanf("%d",&n);
printf("\n Enter array elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Enter key\n");
scanf("%d",&key);
low=0;
high=n-1;

while(low<=high)
{
mid = (low+high)/2;
if(key == a[mid])
{
flag=1;
break;
}
else if(key < a[mid])
{
high = mid-1;

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
else
{
low = mid+1;
}
}
if(flag==1)
{
printf("\n Search is successful\n");
}
else
{
printf("\n Search is unsuccessful\n");
}
getch();
}

Sorting:
Sorting is a technique to rearrange the elements of a list in ascending or
descending order, which can be numerical, lexicographical, or any user-
defined order. Sorting is a process through which the data is arranged in
ascending or descending order. Sorting can be classified in two types
Internal Sorts:- This method uses only the primary memory during sorting
process. All data items are held in main memory and no secondary memory
is required this sorting process. If all the data that is to be sorted can be
accommodated at a time in memory is called internal sorting.
There is a limitation for internal sorts; they can only process relatively small
lists due to memory
constraints. There are 3 types of internal sorts.
(i) SELECTION SORT :- Ex:- Selection sort algorithm, Heap Sort algorithm
(ii) INSERTION SORT :- Ex:- Insertion sort algorithm, Shell Sort algorithm
(iii) EXCHANGE SORT :- Ex:- Bubble Sort Algorithm, Quick sort algorithm
Bubble Sort: (Exchange sort)
Bubble sort is an algorithm that compares the adjacent elements and swaps
their positions if they are not in the intended order. The order can be
ascending or descending
Starting from the first index, compare the first and the second elements. If
the first element is greater than the second element, they are swapped.
Now, compare the second and the third elements. Swap them if they are not
in order.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
The above process goes on until the last element.

The same process goes on for the remaining iterations. After each iteration,
the largest element among the unsorted elements is placed at the end.

In each iteration, the comparison takes place up to the last unsorted element.

The array is sorted when all the unsorted elements are placed at their correct
positions.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Algorithm:
bubbleSort(array)
for i <- 1 to indexOfLastUnsortedElement-1
if leftElement > rightElement
swap leftElement and rightElement
end bubbleSort
Program:
*
Bubble sort
*/
#include<stdio.h>
#include<conio.h>
void main()
{

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
int a[10],i,j,n,temp;
clrscr();
printf("\n Array length(No of elements)\n");
scanf("%d",&n);
printf("\n Enter array elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<(n-i-1);j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\n Sorted array is \n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
getch();
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Insertion Sort:
Suppose an array A with N elements A[0], A[1], . . . . A[N-1] is in memory. The
insertion sort algorithm scan A from A[0] to A[N-1], inserting each element
A[K] into its proper position in the previously sorting sub array A[0], A[1], . . .
.A[K-1]. That is:
Pass 1: A[1] is inserted either before or after A[0] so that: A[0], A[1] is sorted.
Pass 2: A[2] is inserted into its proper place in A[0], A[1], so that A[0], A[1],
A[2] are sorted.
Pass 3: A[3] is inserted into its proper place in A[0], A[1], A[2] so that: A[0],
A[1], A[2], A[3] are sorted.
...........................................................
.
Pass N-1: A[N-1] is inserted into its proper place in A[0], A[1], . . . . . A[N-1] so
that: A[0], A[1], . . . . A[N-1] are sorted.
This sorting algorithm is frequently used when N is small. There remains only
the problem of deciding how to insert A[K] in its proper place in the subarray
A[0], A[1], . . . . A[K-1]. This can be accomplished by comparing A[K] with A[K-
1], comparing A[K] with A[K-2], comparing A[K] with A[K-3], and so on, until
first meeting an element A[i] (where i start from k-1) such that A[i] ≤ A[K]. then
each of elements A[K-1], A[K-2], . . . . A[i+1] is moved forward one location,
and A[K] is then inserted in the i+1 st position in the array.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
The algorithm is simplified if there always is an element A[i] such that A[i] ≤
A[K]; other wise we must constantly check to see if we are comparing A[K]
with A[0].

Insertion sort Program:


/*
Insertion sort
*/

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,k,n,temp;
clrscr();
printf("\n Array length(No of elements)\n");
scanf("%d",&n);
printf("\n Enter array elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(k=1;k<n;k++)
{
temp=a[k];
j=k-1;
while((j>=0) && (temp<a[j]))
{
a[j+1] = a[j];
j--;
}
a[j+1]=temp;
}

printf("\n Sorted array is \n");


for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
getch();
}
Selection Sort:
Suppose an array A with N elements A[0], A[1], . . . A[N-1] is in memory. The
Selection sort algorithm for sorting A works as follows. First find the smallest
element in the list and put it in the first position. Then find the second
smallest element in the list and put it the second position. And so on.
Pass 1: Find the location LOC of the smallest in the list of N elements A[0],
A[1], . . . . . A[N-1], and then interchange A[LOC] and A[0]. Then: A[0] is sorted.
Pass 2: Find the location LOC of the smallest in the sub list of N-1 elements
A[1], A[2], . . . A[N-1], and interchange A[LOC] and A[1]. Then: A[0], A[1] is
sorted. Since A[0] ≤ A[1].
...........................................................
................
Pass N-1: Find the location LOC of the smallest A[N-2] and A[N-1], and then
interchanged A[LOC] and A[N-1]. Then: A[0], A[1], A[2], . . . . A[N-1] is sorted.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Selection sort Program:
/*
Selection sort
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,k,n,temp,min,loc;
clrscr();
printf("\n Array length(No of elements)\n");
scanf("%d",&n);
printf("\n Enter array elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(k=0;k<n-1;k++)
{
min=a[k];
loc=k;
for(j=k+1;j<n;j++)
{
if(a[j]<min)
{

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
min = a[j];
loc = j;
}
}
printf(" min = %d a[k] = %d k = %d loc = %d\n",min,a[k],k,loc);
temp=a[k];
a[k]=a[loc];
a[loc]=temp;
}

printf("\n Sorted array is \n");


for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
getch();
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Functions

Definition: A function is a block of code that performs a specific task.

• It has a name and it is reusable. It can be executed from as many


different parts in a program as required, it can also return a value to
the calling program.
• All executable code resides within a function. It takes input, does
something with it, then gives the answer.
• A C program consists of one or more functions.
• A computer program cannot handle all the tasks by itself. It requests
other programs like entities called functions in C.
• We pass information to the function using arguments.
• A function either can return a value or returns nothing. Function is a
subprogram that helps reduce coding.

Advantages of Functions:

• Function makes the lengthy and complex programs easy and in short
forms.
• By using functions, memory space can be properly utilized, and less
memory is required to run the program.
• It allows more than one person to work on one program.
• Function increases the execution speed of the program and makes the
programming simple.
• By using the function, portability of the program is very easy.
• It removes the redundancy.
• Debugging (removing error) becomes very easier and fast using the
function sub-programming
• Functions are more flexible than library functions.
• Testing (verification and validation) is very easy by using functions.

Types of Functions:

There are two types of functions, which are.

1. Built in functions (Pre defined functions or library functions)


2. User defined functions.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Built-in functions (library functions): Built in functions are also called as
predefined functions, which are already developed by some experts and keep
it in the C standard libraries. C provides library functions for performing some
operations.

For example, sqrt() is a mathematical library function which is used for


finding the square root of any number.

The function scanf() and printf() are input and output library functions
similarly we have strcmp() and strlen() for string manipulations.

Note: To use a library function, we have to include the corresponding header


file using the preprocessor directive #include.

For example: To use input and output functions like printf() and scanf() we
have to include stdio.h, for math library functions we have to include math.h,
for string library functions string.h should be included.

User Defined Functions in C

A user can create their own functions for performing any specific task of a
program called user defined functions.

To create and use these functions we have to know these 3 elements.

1. Function Declaration
2. Function Definition
3. Function Call

Function Declaration:

The program or a function that calls a function is referred to as the calling


program or calling function. The calling program should declare any
function that is to be used later in the program, this is known as the function
declaration or function prototype.

Syntax:

return_type function_name(arg_type1, ……,arg_typen);

Function call:

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
When we wish to use a function, we can "call" it by name, then control is sent
to the block of code with that name.

Any values that the function needs to perform its job are listed in the
parentheses which are also called as arguments.

The computer will retrieve the values held by the variables and hand them off
to the function for its use.

The number of arguments (or values) must match the variables in the
definition by type and number.

A semicolon must be present, when the function is called within the main()
function.

The arguments which are used in function call are called as actual
arguments and the arguments which are used in function definition are
called as formal arguments.

Syntax:

function_name (actual parameters);

The following figure illustrates function prototype, function call and function
definition.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Function definition:

The function definition consists of the whole description and code of a


function. It tells what the function is doing and what are the inputs and
outputs for the funtion.

A function is called by simply writing the name of the function followed by the
argument list inside the parenthesis.

Function definitions have two parts:

1. Function Header
2. Function body

Function Header- The first line of code is called Function Header.

E.g; int sum( 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

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Function Body Whatever is written with in { } is the body of the function.

Categories of functions:

The functions are categorized into 4 types based on the arguments and return
type. They are

1. Functions with no arguments and no return value.


2. Functions with arguments and no return value.
3. Functions with no arguments but return value.
4. Functions with arguments and return value.

Functions with no arguments and no return type:

Here, the called function does not receive any data from the calling function
and it does not return any data back to the calling function. Hence, there is
no data transfer between the calling function and the called function.
Write a c program to find factorial of a given number using functions
with no arguments and no return type.

#include <stdio.h>
#include <stdlib.h>

void fact();
int main(int argc, char *argv[]) {

fact();

return 0;
}
void fact()
{
int i,f=1,n;

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("\n Enter a number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("\n fact(%d)=%d",n,f);
}

Functions with arguments and no return value

Here, the called function receives the data from the calling function. The
arguments should match in number, data type and order. But, the called
function does not return any value back to the calling function. Instead, it
prints the data or results in its scope only. It is one-way data communication
between the calling function and the called function.

Write a c program to find factorial of a given number using functions


with arguments and no return type.

#include <stdio.h>
#include <stdlib.h>

void fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter two numbers:");
scanf("%d",&n);
fact(n);

return 0;

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
void fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("\n fact(%d)=%d",n,f);
}

Functions with no arguments but return value

Here, the called function does not receive any data from the calling function.
It manages with its local data to carry out the specified task. However, after
the specified processing the called function returns the computed data to the
calling function. It is also a one-way data communication between the calling
function and the called function.
Write a c program to find factorial of a given number using functions
with no arguments and return type.

#include <stdio.h>
#include <stdlib.h>

int fact();
int main(int argc, char *argv[]) {

int f;

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
f=fact();
printf("\n fact=%d",f);
return 0;
}
int fact()
{
int i,f=1,n;
printf("\n Enter a number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}

Functions with arguments and return value.

Here, the called function receives data from the calling function and it can
compute the task using these arguments. After computing the task, the called
function returns the results to the calling function. In this way the main()
function will have control over the function. It is the two-way communication
between the calling function and the called function.

Write a c program to find factorial of a given number using functions


with arguments and return type.

#include <stdio.h>

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
#include <stdlib.h>

int fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter two numbers:");
scanf("%d",&n);
f=fact(n);
printf("\n fact(%d)=%d",n,f);
return 0;
}
int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}

Parameter Passing Mechanism

A method of information interchange between the calling function and called


function is known as parameter passing. There are two methods of
parameter passing:

1. Call by Value

2. Call by Reference

Call by Value: The call-by-value method copies the value of an argument into
the formal parameter of the function. Therefore, changes made by the function
to the parameters have no effect on the variables used to call it.

Call by Reference: Call by reference method copies the address of an


argument into the formal parameter. Inside the function, this address is used
to access the argument used in the call. In this way, any changes made to the
formal parameters affect the actual parameters used in the function call.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Call by reference is achieved by passing a pointer as the argument. Of course,
in this case, the parameters must be declared as pointer types.

Differences between call by value and call by reference

Call By Value Call By Reference


While calling a function, we pass While calling a function, instead of
values of variables to it. Such passing the values of variables, we
functions are known as “Call By pass address of variables (location of
Values”. variables) to the function known as
“Call By References”.
In this method, the value of each In this method, the address of actual
variable in calling function is copied variables in the calling function are
into corresponding dummy variables copied into the dummy variables of
of the called function. the called function.

With this method, the changes made With this method, using addresses
to the dummy variables in the called we would have access to the actual
function have no effect on the values variables and hence we would be
of actual variables in the calling able to manipulate them.
function.
// call by value // Call by Reference
void swapx(int x, int y); // Main #include<stdio.h> // Function
function int main() Prototype void swapx(int*, int*);
{ int a = 10, b = 20; int main()
swapx(a, b);
{ int a = 10, b = 20;
printf("a=%d b=%d\n", a, b);
return 0; swapx(&a, &b);
} printf("a=%d b=%d\n", a, b);
return 0;
void swapx(int x, int y)
}
{ int t;
void swapx(int* x, int* y)
t = x;
{ int t;
x = y;
t = *x;
y = t;

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("x=%d y=%d\n", x, *x = *y;
y); *y = t;
} printf("x=%d y=%d\n", *x, *y);
Output: x=20 y=10 }
a=10 b=20 Output: x=20 y=10
a=20 b=10
The actual values of a and b remain The actual values of a and b get
unchanged even after exchanging changed after exchanging values of x
the values of x and y. and y.

In call by value, we cannot alter the In call by reference, we can alter the
values of actual variables through values of variables through function
function calls. calls.
Values of variables are passes by Pointer variables are necessary to
Simple technique. define to store the address values of
variables.

Passing Arrays to functions

Array can be passed to function by two ways:

1. Pass entire array

2. Pass array element by element.

1. Pass Entire array (Formal Parameters as a pointer, sized array,


sized unsized array)

• In the function call we can only write the name of the array without
subscripts and specify the array length.
• Here the entire array can be passed as an argument to function.
• Function gets complete access to the original array.
• While passing the entire array address of first element is passed to
function, any changes made inside function, directly affects the
Original value.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
• It is similar to “call by reference” or “pass by address”
Note: Whenever we are sending an array to the function, we must pass
array name and array length.

2. Pass Array element by element

• Here individual elements are passed to function as argument.


• Duplicate carbon copy of original variable is passed to function.
• Any changes made inside function do not affect the original value.
• Function doesn’t get complete access to the original array element.
• This method is similar to the “Pass by value”
Disadvantages of Pass Array element by element

1. In which we are calling the function again and again but with different
array element is too much time consuming.

2. It is better to pass complete array to the function so that we can save


some system time required for pushing (insertion) and popping
(remove).

Passing 2D arrays to functions

Like one dimensional array, we can also pass multidimensional arrays to the
functions. The approach is similar to the passing one-dimensional arrays.

1. The function must be called by passing only the array name.

2. In the function definition, we must indicate that the array has two
dimensions by including two sets of brackets.

3. The size of the second dimension must be specified.

4. The prototype declaration should be like the function header.

Passing Strings to functions

The strings are treated as character arrays in C and therefore the rules for
passing strings to functions are very similar to those for passing arrays to
functions.

Basic rules are.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
1. The string to be passed must be declared as formal argument of the
function when it is defined.

▪ Example

void display (char item names[ ])

……………….

2. The function prototype must show that the argument is a string. For the
above function definition, the function prototype can be written as

▪ void display (char str[ ]);

3. A call to the function must have a string array name without subscripts
as its actual argument.

▪ Example display(name)
▪ Write a c program to find length of the string using functions.
Recursion

Definition: A function called itself is called recursion.

Advantages of recursion

1. The code may be easier to write if the problem is in recursive nature.


2. Reduce unnecessary calling of function.
3. Extremely useful when applying the same solution.
4. Recursions reduce the length of code.
5. It is very useful in solving the data structure problems like infix, prefix,
postfix evaluations.

Disadvantages of recursion

1. Recursive functions are generally slower than non-recursive function.


2. It may require a lot of memory space to hold intermediate results on the
system stacks.
3. Hard to analyze or understand the code.
4. It is not more efficient in terms of space and time complexity.
5. The computer may run out of memory if the recursive calls are not
properly checked.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
A recursive algorithm uses itself to solve one or more smaller identical
problems.

Recursive Methods Must Eventually Terminate:

▪ A recursive method must have at least one base or stopping case.


▪ A base case does not execute a recursive call stops the recursion.
Each successive call to itself must be a "smaller version of itself.”

▪ An argument that describes a smaller problem

▪ A base case is eventually reached.

Example: Finding factorial of a given number N

N! = (N-1)! * N [for N > 1]

= 1 [for N= 1]

= 3!
= 2! * 3
= (1! * 2) * 3
= 1*2*3
C Program to find factorial of a given number.

#include <stdio.h>
#include <stdlib.h>
int fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a number:");
scanf("%d",&n);
f=fact(n);
printf("\n Factorial of a given number %d is %d",n,f);
return 0;
}
int fact(int n)
{

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
if(n==1||n==0)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
C program to find GCD of two number using recursion

#include <stdio.h>
#include <stdlib.h>
int gcd(int,int);
int main(int argc, char *argv[]) {
int a,b,f;
printf("\n Enter two numbers:");
scanf("%d%d",&a,&b);
f=gcd(a,b);
printf("\n GCD of %d and %d is %d",a,b,f);
return 0;
}
int gcd(int n1,int n2)
{
if(n2==0)
{
return n1;
}
else
{
return gcd(n2,n1%n2);
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
C program to display fibonacci series using recursion

Fib(n) = fib(n-1)+fib(n-2)

Fib(0) = 0 fib(1)=1

Program

#include <stdio.h>
#include <stdlib.h>
int fib(int);
int main(int argc, char *argv[]) {
int i,n;
printf("\n Enter no of elements in the series:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n%d",fib(i));
}
return 0;
}
int fib(int n)
{
if(n==0)
{
return 0;
}
else if(n==1)
{
return 1;
}
else
{

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
return fib(n-1)+fib(n-2);
}
}

C Program to implement Ackermann function

#include <stdio.h>
#include <stdlib.h>
int ack(int,int);
int main(int argc, char *argv[]) {
int a,b;
printf("\n Enter two numbers:");
scanf("%d%d",&a,&b);
printf("\n ack(%d,%d) = %d",a,b,ack(a,b));
return 0;
}
int ack(int x,int y)
{
if(x==0)
{
return y+1;
}
else if(y==0)
{
return ack(x-1,1);
}
else
{

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
return ack(x-1,ack(x,y-1));
}
}
C Programs using functions
1. Write a c program to find factorial of a given number using functions with
no arguments and no return type.
#include <stdio.h>
#include <stdlib.h>

void fact();
int main(int argc, char *argv[]) {

fact();

return 0;
}
void fact()
{
int i,f=1,n;
printf("\n Enter a number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("\n fact(%d)=%d",n,f);
}
2. Write a c program to find factorial of a given number using functions with
arguments and no return type.
#include <stdio.h>
#include <stdlib.h>

void fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter two numbers:");
scanf("%d",&n);
fact(n);

return 0;
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
void fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("\n fact(%d)=%d",n,f);
}
3. Write a c program to find factorial of a given number using functions with
no arguments and return type.
#include <stdio.h>
#include <stdlib.h>

int fact();
int main(int argc, char *argv[]) {

int f;
f=fact();
printf("\n fact=%d",f);
return 0;
}
int fact()
{
int i,f=1,n;
printf("\n Enter a number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}
4. Write a c program to find factorial of a given number using functions with
arguments and return type.
#include <stdio.h>
#include <stdlib.h>

int fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter two numbers:");
scanf("%d",&n);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
f=fact(n);
printf("\n fact(%d)=%d",n,f);
return 0;
}
int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}
5. Write a c program to sort array elements using functions.
#include <stdio.h>
#include <stdlib.h>

void sort(int[],int);
int main(int argc, char *argv[]) {
int a[10],n,i;
printf("\n Enter array lenth:");
scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Before sorting array elements are:");
for(i=0;i<n;i++)
{
printf("\n%d",a[i]);
}
sort(a,n);
printf("\n After sorting array elements are:");
for(i=0;i<n;i++)
{
printf("\n%d",a[i]);
}
return 0;
}
void sort(int a[],int n)
{
int i,j,temp;

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
for(i=1;i<n;i++)
{
for(j=0;j<=(n-i-1);j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
6. Write a c program to check whether given number is prime number or
not using functions.
#include <stdio.h>
#include <stdlib.h>

int prime(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a number:");
scanf("%d",&n);
f=prime(n);
if(f==2)
{
printf("\n %d is a prime number",n);
}
else
{
printf("\n %d is not a prime number",n);
}
return 0;
}

int prime(int n)
{
int i,count=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
{
count++;

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
}
return count;
}
7. Write a c program to check whether the given number is a palindrome or
not.
#include <stdio.h>
#include <stdlib.h>

int palindrome(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a value:");
scanf("%d",&n);
f=palindrome(n);
if(f==1)
{
printf("\n %d is a palindrome",n);
}
else
{
printf("\n %d is not a palindrome",n);
}
return 0;
}
int palindrome(int n)
{
int rev,rem,temp;
temp=n;
while(n>0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
if(rev==temp)
{
return 1;
}
else
{
return 0;
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
8. Write a c program to swap two integers using call by value.
#include <stdio.h>
#include <stdlib.h>

void swap(int,int);
int main(int argc, char *argv[]) {
int a,b;
printf("\n Enter two values:");
scanf("%d%d",&a,&b);
//printf("\n Before swapping a=%d b=%d\n",a,b);
swap(a,b);
return 0;
}
void swap(int m,int n)
{
int temp;
temp=m;
m=n;
n=temp;
printf("\n After swapping a=%d b=%d\n",m,n);
}
9. Write a c program to swap two integers using call by reference.
#include <stdio.h>
#include <stdlib.h>

void swap(int*,int*);
int main(int argc, char *argv[]) {
int a,b;
printf("\n Enter two values:");
scanf("%d%d",&a,&b);
printf("\n Before swapping a=%d b=%d\n",a,b);
swap(&a,&b);
printf("\n After swapping a=%d b=%d\n",a,b);
return 0;
}
void swap(int *m,int *n)
{
int temp;
temp=*m;
*m=*n;
*n=temp;
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
10. Write a c program to find largest value from the given array elements
using passing array to the function.
#include <stdio.h>
#include <stdlib.h>

void largest(int[],int);
int main(int argc, char *argv[]) {
int a[10],n,b,i;
printf("\n Enter array length:");
scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
largest(a,n);
return 0;
}
void largest(int a[],int n)
{
int i,max;
max=a[0];
for(i=1;i<n;i++)
{
if(a[i]>max)
{
max=a[i];
}
}
printf("\n largest number = %d",max);
}
11. Write a c program to implement Fibonacci series using functions.
#include <stdio.h>
#include <stdlib.h>

int fib(int);
int main(int argc, char *argv[]) {
int n,f,i;
printf("\n Enter a value:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
f=fib(i);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("\n %d",f);
}
return 0;
}
int fib(int n)
{
int i,f0,f1,f2;
if(n==0||n==1)
{
return n;
}
else
{
f0=0;
f1=1;
for(i=2;i<=n;i++)
{
f2=f0+f1;
f0=f1;
f1=f2;
}
return f2;
}
}
12. Write a c program to find sum of matrix elements using functions.
#include <stdio.h>
#include <stdlib.h>

void addition(int[][3],int[][3],int[][3],int,int);
int main(int argc, char *argv[]) {
int a[3][3],b[3][3],c[3][3],i,j;
printf("\n Enter Matrix-A elements:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}

printf("\n Enter Matrix-B elements:");


for(i=0;i<3;i++)
{

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}

addition(a,b,c,3,3);
printf("\n Matrix-C elements are:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\t%4d",c[i][j]);
}
printf("\n");
}
return 0;

void addition(int a[3][3],int b[3][3],int c[3][3],int m,int n)


{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
}
13. Write a c program to implement matrix multiplication using functions.
#include <stdio.h>
#include <stdlib.h>

void multiply(int[][3],int[][3],int[][3],int,int);
int main(int argc, char *argv[]) {
int a[3][3],b[3][3],c[3][3],n,i,j;
printf("\n Enter Matrix-A elements:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
scanf("%d",&a[i][j]);
}
}

printf("\n Enter Matrix-B elements:");


for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}

multiply(a,b,c,3,3);
printf("\n Enter Matrix-C elements:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\t%4d",c[i][j]);
}
printf("\n");
}
return 0;
}

void multiply(int a[3][3], int b[3][3], int c[3][3], int m, int n)


{
int i,j,k;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
for(c[i][j]=0,k=0;k<m;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
}
14. Write a c program to find the length of a string using functions.
#include <stdio.h>
#include <stdlib.h>

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
int stringlength(char[]);
int main(int argc, char *argv[]) {
char str[10];
int l;
printf("\n Enter a string:");
gets(str);
l=stringlength(str);
printf("\n string length = %d\n",l);

return 0;
}

int stringlength(char str[])


{
int i;
for(i=0;str[i]!='\0';i++);
return i;
}
15. Write a c program to sort city names using functions.
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

void sort_citynames(char[][10],int n);


int main(int argc, char *argv[]) {
char str[10][10];
int n,i;
printf("\n Enter number of cities:");
scanf("%d",&n);
printf("\n Enter city names:");
for(i=0;i<n;i++)
{
scanf("%s",str[i]);
}
sort_citynames(str,n);
printf("\n After sorting city names are:");
for(i=0;i<n;i++)
{
printf("\n %s",str[i]);
}
return 0;
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
void sort_citynames(char str[][10],int n)
{
int i,j;
char temp[10];

for(i=0;i<n-1;i++)
{
for(j=0;j<(n-i-1);j++)
{
if(strcmp(str[j],str[j+1])>0)
{
strcpy(temp,str[j]);
strcpy(str[j],str[j+1]);
strcpy(str[j+1],temp);
}

}
}

}
16. Write a c program to find Fibonacci series using recursion.
#include <stdio.h>
#include <stdlib.h>

int fib(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a number:");
scanf("%d",&n);
f=fib(n);
printf("\n fib(%d)=%d",n,f);
return 0;
}
int fib(int n)
{
if(n==0||n==1)
{
return n;
}
else
{
return fib(n-1)+fib(n-2);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
}
17. Write a c program to find factorial of a given number using recursion.
#include <stdio.h>
#include <stdlib.h>

int fact(int);
int main(int argc, char *argv[]) {
int n,f;
printf("\n Enter a number:");
scanf("%d",&n);
f=fact(n);
printf("\n fact(%d)=%d",n,f);
return 0;
}
int fact(int n)
{
if(n==0||n==1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
18. Write a c program to find addition of the two numbers using
recursion.
#include <stdio.h>
#include <stdlib.h>

int addition(int,int);
int main(int argc, char *argv[]) {
int m,n,f;
printf("\n Enter two numbers:");
scanf("%d%d",&m,&n);
f=addition(m,n);
printf("\n add(%d,%d)=%d",m,n,f);
return 0;
}
int addition(int m,int n)
{
if(n==0)

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
{
return m;
}
else
{
return addition(m,n-1)+1;
}
}
19. Write a c program to find multiplication of two numbers using
recursion.
#include <stdio.h>
#include <stdlib.h>

int multiply(int,int);
int main(int argc, char *argv[]) {
int m,n,f;
printf("\n Enter two numbers:");
scanf("%d%d",&m,&n);
f=multiply(m,n);
printf("\n mul(%d,%d)=%d",m,n,f);
return 0;
}
int multiply(int m,int n)
{
if(n==0)
{
return m;
}
else
{
return multiply(m,n-1)+n;
}
}
20. Write a c program to implement binary search using recursion.
#include <stdio.h>
#include <stdlib.h>

void binarysearch(int[],int,int,int);
int main(int argc, char *argv[]) {
int a[10],n,i,key;
printf("\n Enter array length:");
scanf("%d",&n);
printf("\n Enter array elements:");

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Enter key:");
scanf("%d",&key);
binarysearch(a,0,n-1,key);
return 0;
}
void binarysearch(int a[],int l,int h,int k)
{
int mid;
if(l<=h)
{
mid=(l+h)/2;
if(a[mid]==k)
{
printf("\n Search is successful");
}
else if(k < a[mid])
{
binarysearch(a,l,mid-1,k);
}
else
{
binarysearch(a,mid+1,h,k);
}

}
else
{
printf("\n Search is unsuccessful");
}
}
21. Write a c program to find GCD of two numbers using recursion.
#include <stdio.h>
#include <stdlib.h>

int gcd(int,int);
int main(int argc, char *argv[]) {
int m,n,f;
printf("\n Enter two numbers:");
scanf("%d%d",&m,&n);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
f=gcd(m,n);
printf("\n gcd(%d,%d)=%d",m,n,f);
return 0;
}
int gcd(int m,int n)
{
if(n==0)
{
return m;
}
else
{
return gcd(n,m%n);
}
}
22. Write a c program to implement Ackermann function using recursion.
#include <stdio.h>
#include <stdlib.h>

int ack(int,int);
int main(int argc, char *argv[]) {
int m,n,f;
printf("\n Enter two numbers:");
scanf("%d%d",&m,&n);
f=ack(m,n);
printf("\n ack(%d,%d)=%d",m,n,f);
return 0;
}
int ack(int m,int n)
{
if(m==0)
{
return n+1;
}
else if((m>0)&&(n==0))
{
return ack(m-1,1);
}
else
{
return ack(m-1,ack(m,n-1));
}
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
UNIT-IV
Structures and Pointers: Structures: Defining structures,
initializing structures, unions, Array of structures,
Pointers: Idea of pointers, Defining pointers, Pointers to Arrays and
Structures, Passing arrays to functions and structures to
functions.
Dynamic memory allocation, self-referential structures

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
UNIT-IV

STRUCTURES AND UNIONS

A structure is a collection of different data types, where as an array is a


group of similar data elements.
Definition1: A structure is a collection of data items of different types using
a single name.
Definition2: Structure is a convenient tool for handling a group of logically
related data items
Examples:
Time : seconds, minutes, hours
Date : day, month, year
Book : author, title, price, year
City : name, country, population
Address : name, door-number, street, city
Customer : name, telephone, city, category
Structures must be defined first for their format that may be used later to
declare structure variables.
Example: Book database
Defining a Structure
Book database consisting of book title, author, number of pages, and price.
We define a structure to hold this information as follows.
struct book_bank
{
char title[10];
char author[10];
int pages;
float price;
};

The keyword struct declares a structure to hold the details of four data fields,
namely title, author, pages and price. These fields are called structure
elements or structure members. Each member may belong to a different data
type.
book_bank is the name of the structure and is also called as structure tag.
The tag name may be used subsequently to declare variables.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
General format of a structure definition is as follows.
struct tag_name
{
Data type member1;
Data type member2;
------------- --------------
};

Remember:

1. The template is terminated with a semicolon.


2. While the entire definition is considered as a single statement, each
member is declared independently for its name and type in a separate
statement inside the template.
3. The tag_name can be used to declare structure variables of its type,
later in the program.

Differences between arrays and structures

1. An array is a collection of related data elements of same type whereas


structures can have elements of different types.
2. An array is derived data type, where as a structure is a programmer-
defined one.
3. Any array behaves like a built-in-data type. All we have to do is to
declare an array variable and use it. But in the case of a structure,
first we have to design and declare a data structure before the
variables of that type are declared and used.

Declaring structure variables

After defining a structure, we can declare variables of that type. It includes


the following elements.

1. The keyword struct.


2. The structure tag name
3. List of structure variables (separated by commas)
4. A terminating semi colon.

Example: struct book_bank book1,book2,book3;

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Declares book1, book2 and book3 as variables of type struct book_bank;
The use of tag is optional
struct
{
char title[10];
char author[10];
int pages;
float price;
}book1,book2,book3;

Declares book1,book2 and book3 as structure variables representing three


books, but does not include a tag name. This approach is not recommended
for the following reason.

Without a tag name, we cannot use it for future declarations.

Accessing Structure Members

Three ways to access structure members, they are


“.” (dot operator) – n.x ( structure variable)
Using indirection notation – (*ptr).x
Using selection notation - ptr->x (arrow operator) –A pointer points to the
structure

Structure Initialization

There are two ways to initialize structure members.


1. Compile time initialization
2. Runtime initialization

Compile time Initialization

Example:
struct book_bank
{
char title[20];
char author[20];
int pages;
int price;
}book1= {“Cprogramming”,”balaguruswamy”,100,200};
(OR)
struct book_bank book1 ={“Cprogramming”,”balaguruswamy”,100,200};

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
This assigns the value “Cprogramming” to book1.title, “balaguruswamy” to
book1.author, 100 to book1.pages and 200 to book1.price.

The compile time initialization of a structure variable must have the


following elements.

1. The keyword struct.


2. The structure tag name.
3. The name of the variable to be declared.
4. The assignment operator =.
5. A set of values for the members of the structure variable, separated by
commas and enclosed in braces.
6. A terminating semicolon.
Write a c program to create a structure named as Book, initialize
structure members at run time and display structure members.

#include <stdio.h>
#include <stdlib.h>
struct book_bank
{
char author[10];
char title[10];
float price;
int pages;
};
int main(int argc, char *argv[]) {

struct book_bank book1;


printf("\n Enter author:");
scanf("%s",book1.author);
printf("\n Enter title:");
scanf("%s",book1.title);
printf("\n Enter price:");
scanf("%f",&book1.price);
printf("\n Enter pages");
scanf("%d",&book1.pages);*/
printf("\n Structure members are:\n");
printf("Author: %s\n",book1.author);
printf("Title: %s\n",book1.title);
printf("Price: %f\n",book1.price);
printf("Pages: %d\n",book1.pages);
return 0;
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
2. Write a c program to create a structure named as Book, initialize
structure members at compile time and display structure members.

#include <stdio.h>
#include <stdlib.h>

struct book_bank
{
char author[10];
char title[10];
float price;
int pages;
};
int main(int argc, char *argv[]) {

struct book_bank
book1={"Balaguruswamy","CProgramming",199.50,300};
printf("\n Structure members are:");
printf("Author: %s\n",book1.author);
printf("Title: %s\n",book1.title);
printf("Price: %f\n",book1.price);
printf("Pages: %d\n",book1.pages);
return 0;
}

Copying and Comparing Structure Members

Two variables of the same structure type can be copied the same way as
ordinary variables. If book1 and book2 belong to the same structure, then
the following statements are valid.

book2=book1

however the statement such as

book1 == book2 is invalid.

Note:
C does not permit any logical operations on structure variables. In case we
need to compare them, we may do so by comparing members individually.
Write a c program to illustrate copy and comparison of two structures
variables.

#include <stdio.h>
#include <stdlib.h>
#include<string.h>

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
struct book_bank
{
char author[20];
char title[20];
float price;
int pages;
};
int main(int argc, char *argv[]) {
struct book_bank book1,book2;
printf("\n Enter author:");
scanf("%s",book1.author);
printf("\n Enter title:");
scanf("%s",book1.title);
printf("\n Enter price:");
scanf("%f",&book1.price);
printf("\n Enter pages");
scanf("%d",&book1.pages);
book2=book1;
if(!strcmp(book1.author,book2.author)&&
!strcmp(book1.title,book2.title) && (book1.price==book2.price) &&
(book1.pages==book2.pages))
{
printf("\n Book1 and Book2 fileds are same");
}
else
{
printf("\n Book1 and Book2 fileds are not equal");
}

return 0;
}

Array of structures

For example in analyzing the marks obtained by a class of students, we may


use a template to describe student name and marks obtained in various
subjects and then declare all the students as structure variables.

In such cases, we may declare an array of structures, each element of the


array representing a structure variable.

e.g: struct class student[100];


defines an array called student, that consists of 100 students. Each element
is defined to be of the type struct class.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Consider the following declaration.
struct marks
{
int subject1;
int subject2;
int subject3;
};

struct marks student[3] = {{1,2,3},{4,5,6},{7,8,9}};


This declares the student as an array of three elements student[0], student[1]
and student[2] and initializes their members as follows.
student[0].subject1 = 1
student[0].subject2 = 2
student[0].subject3 = 3
student[1].subject1 = 4
student[1].subject2 = 5
student[1].subject3 = 6
student[2].subject1 = 7
student[2].subject2 = 8
student[2].subject3 = 9

Write a c program to calculate student total marks, subject’s total marks


and total marks using array of structures.

#include <stdio.h>
#include <stdlib.h>

struct student
{
int sub1;
int sub2;
int sub3;
int total;
};
int main(int argc, char *argv[]) {

struct student std[3];


int sub1_total,sub2_total,sub3_total;
int total_marks;
int i;
for(i=0;i<3;i++)
{
printf("\n Enter student- %d marks:",i+1);
scanf("%d%d%d",&std[i].sub1,&std[i].sub2,&std[i].sub3);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}

sub1_total=0;
sub2_total=0;
sub3_total=0;

for(i=0;i<3;i++)
{
std[i].total = std[i].sub1+std[i].sub2+std[i].sub3;
sub1_total=sub1_total+std[i].sub1;
sub2_total=sub2_total+std[i].sub2;
sub3_total=sub3_total+std[i].sub3;
}
total_marks = sub1_total + sub2_total + sub3_total;

printf("\n Student marks are:");


for(i=0;i<3;i++)
{
printf("\nstudent Marks are =
%d\t%d\t%d",std[i].sub1,std[i].sub2,std[i].sub3);
}
printf("\n Student marks are:");
for(i=0;i<3;i++)
{
printf("\n student[%d] total marks = %d",i+1,std[i].total);
}
printf("\n Subject total marks are:");
printf("\n%d\n%d\n%d",sub1_total,sub2_total,sub3_total);
printf("\n Grand total marks are:");
printf("\n%d",total_marks);
return 0;
}

Arrays within structures

C permits the use of arrays as structure members.


e.g
struct marks
{
int number;
float subject[3];
}student[2];

Here the member subject contains three elements, subject[0], subject[1] and
subject[2]. These elements can be accessed using appropriate subscripts.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
For example the name
student[1].subject[2]; // Would refer to the marks obtained in the third
subject by the second student.

Write a c program to calculate student total marks, subject’s total marks


and total marks using array with in the structures

#include <stdio.h>
#include <stdlib.h>

struct student
{
int sub[3];
int total;
};
int main(int argc, char *argv[]) {

struct student std[3];


int sub1_total,sub2_total,sub3_total;
int total_marks;
int i,j;
for(i=0;i<3;i++)
{
printf("\n Enter student- %d marks:",i+1);
for(j=0;j<3;j++)
{
scanf("%d",&std[i].sub[j]);
}
}
sub1_total=0;
sub2_total=0;
sub3_total=0;

for(i=0;i<3;i++)
{
std[i].total=0;
for(j=0;j<3;j++)
{
std[i].total=std[i].total+std[i].sub[j];
}
sub1_total+= std[i].sub[0];
sub2_total+= std[i].sub[1];
sub3_total+= std[i].sub[2];
}
total_marks = sub1_total + sub2_total + sub3_total;

printf("\n Student marks are:");

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
for(i=0;i<3;i++)
{
printf("\nstudent- %d Marks are:",i+1);
for(j=0;j<3;j++)
{
printf("\t %d",std[i].sub[j]);
}
printf("\nstudent %d total marks are: %d
",i+1,std[i].total);
}

printf("\n Subject total marks are:");


printf("\n%d\n%d\n%d",sub1_total,sub2_total,sub3_total);
printf("\n Grand total marks are:");
printf("\n%d",total_marks);
return 0;
}

Structures within structures

Structures within a structure means nesting of structures. Nesting of


structures is permitted in C.
e.g:
struct salary
{
char name[10];
char department;
int basic_pay;
int dearness_allowance;
int house_rent_allowance;
int city_allowance;
}employee;

This structure defines name, department, basic pay and three kinds of
allowances. We can group all the items related to allowance together and
declare them under a substructure as shown below.
struct salary
{
char name[10];
char department;
struct

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
{
int dearness_allowance;
int house_rent_allowance;
int city_allowance;
}allowance;
}employee;

The salary structure contains a member named allowance, which itself is a


structure with three members. The members contained in the inner structure
namely dearness, house_rent, and city can be referred to as

Employee.allowance.dearness
Employee.allowance.house_rent
Employee.allowance.city
Note:

1. An inner-most member in a nested structure can be accessed by


chaining all the concerned structure variables with the member using
dot operator.
Write a c program to calculate total salary of an employee using nested
structure.

#include <stdio.h>
#include <stdlib.h>

struct salary
{
char name[10];
char department[10];
int basicpay;
struct
{
int DA;
int HRA;
int CA;
}allowance;
};

int main(int argc, char *argv[]) {

struct salary emp;


int total_salary;
printf("\n Enter employee name:");
scanf("%s",emp.name);
printf("\n Enter employee department:");

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
scanf("%s",emp.department);
printf("\n Enter employee basic pay:");
scanf("%d",&emp.basicpay);
printf("\n Enter DA:");
scanf("%d",&emp.allowance.DA);
printf("\n Enter HRA:");
scanf("%d",&emp.allowance.HRA);
printf("\n Enter City Allowance:");
scanf("%d",&emp.allowance.CA);

total_salary=emp.basicpay+emp.allowance.DA+emp.allowance.HRA+emp.allo
wance.CA;
printf("\n\n \t Emploee salary is:%d",total_salary);

Structures and functions

There are three methods by which the values of a structure can be transferred
from one function to another.
1. The first method is to pass each member of the structure as an actual
argument of the function call. The actual arguments are then treated
independently like ordinary variables. This is the most elementary
method and becomes unmanageable and inefficient when the structure
size is large.
2. The second method involves passing of a copy of the entire structure to
the called function. Since the function is working on a copy of the
structure, 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, all
compilers may not support this method of passing the entire structure
as a parameter.
3. The third approach employs a concept called pointers to pass the
structure as an argument. In this case, the address location of the
structure is passed to the called function. The function can access
indirectly the entire structure and work on it. This is similar to the way
arrays are passed to function. This method is more efficient as
compared to the second one.

Structures and functions - Important Points

1. The called function must be declared for its type, appropriate to the
data type it is expected to return. For example, if it is returning a copy
of the entire structure, then it must be declared as a struct with an
appropriate tag name.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
2. The structure variable used as the actual argument and the
corresponding formal argument in the called function must be of the
same struct type.
3. 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.
4. When a function returns a structure, it must be assigned to a
structure of identical type in the calling function.
5. The called functions must be declared in the calling function
appropriately.
Write a c program to pass a student structure to function and display
structure members in the function.

#include <stdio.h>
#include <stdlib.h>

struct student
{
char name[10];
int age;
};
void display(struct student);
int main(int argc, char *argv[]) {
struct student s1;
printf("\n Enter name and age:");
scanf("%s%d",s1.name,&s1.age);
display(s1);
return 0;
}
void display(struct student s2)
{
printf("\n Name = %s\n Age=%d\n",s2.name,s2.age);
}

Write a c program to add to complex numbers by passing complex


numbers to functions.

#include <stdio.h>
#include <stdlib.h>

struct complex
{

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
int real;
int img;
};
void sum(struct complex,struct complex,struct complex*);
int main(int argc, char *argv[]) {
struct complex c1,c2,c3;
printf("\n Enter C1 real part and imaginary part:");
scanf("%d%d",&c1.real,&c1.img);
printf("\n Enter C2 real part and imaginary part:");
scanf("%d%d",&c2.real,&c2.img);
sum(c1,c2,&c3);
printf("\n result = %d+i%d",c3.real,c3.img);
return 0;
}
void sum(struct complex c4,struct complex c5,struct complex *c6)
{
c6->real=c4.real+c5.real;
c6->img = c4.img + c5.img;
}

UNIONS

A union is a collection of different data types, in union all members share the
same memory location.
Union is a derived datatype.
Union is similar to structure, but the difference is in structure each member
has its own storage location, whereas all the members of a union use the same
location.
Like structures, a union can be declared using the keyword union as follows.
union item
{
int m;
float x;
char c;
}code;

This declares a variable code of type union item. The union contains three
members, each with a different data type. However, we can use only one of
them at a time. This is due to the fact that only one location is allocated for a
union variable, irrespective of its size.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
The compiler allocates a piece of storage that is large enough to hold the
largest variable type in the union.
In the declaration above the member x requires 4 bytes which is the largest
among the members. The above figure shows how all the three variables share
the same address. This assumes that a float variable requires 4 bytes of
storage.
Dot (.) operator is used to access a union member. Like
code.m
code.x
code.c
all are valid member variables. During accessing, we should make sure that
we are accessing the member whose value is currently stored.
e.g:
code.m = 379;
code.x=12.35;
printf(“%d”,code.m);
would produce erroneous output.
A union creates a storage location that can be used by any of its members at
a time. When a different member is assigned a new value, the new value
supersedes the previous member’s value.
Unions may be initialized when the variable is declared. But unlike
structures, it can be initialized only with a value of the same type as the first
union member.
e.g:
union item abc = {100} is valid
union item abc = {10.5} is invalid, because the type of the first member is
int. other members can be initialized by either assigning values or reading
from the keyboard.
sizeof()
sizeof operator tells the size of a structure or union.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Syntax: sizeof(union x);
Will evaluate the number of bytes required for union x.

Write a c program to illustrate union.

#include <stdio.h>
#include <stdlib.h>

union number
{
int n1;
float n2;
};
int main(int argc, char *argv[]) {
union number x;

printf("Enter the value of n1: ");


scanf("%d", &x.n1);
printf("Value of n1 = %d", x.n1);
printf("\nEnter the value of n2: ");
scanf("%f", &x.n2);
printf("Value of n2 = %f\n", x.n2);
printf("\n sizeof union = %d",sizeof(x));
return 0;
}

Structure Programs

1. Write a c program to illustrate array of structures

#include <stdio.h>
#include <stdlib.h>

struct student
{
int marks1;
int marks2;
int marks3;
};
int main(int argc, char *argv[]) {

struct student std[3];


int i;
for(i=0;i<3;i++)
{
printf("\n Enter student- %d marks:",i+1);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
scanf("%d%d%d",&std[i].marks1,&std[i].marks2,&std[i].marks3);
}
printf("\n Structure members are:");
for(i=0;i<3;i++)
{
printf("\n %d student Marks are:",i+1);

printf("\t%d\t%d\t%d",std[i].marks1,std[i].marks2,std[i].marks3);

}
return 0;
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
POINTERS
Pointer is a derived data type.
Definition: Pointer is a variable which contains the address in memory of
another variable.
Benefits of Pointers
1. Pointers are more efficient in handling arrays and data tables.
2. Pointers can be used to return multiple values from a function.
3. Pointers permit references to functions and thereby facilitating
passing of functions as arguments to other functions
4. The use of pointer arrays to character strings results in saving of data
storage space in memory.
5. Pointers support dynamic memory management
6. Pointers provide an efficient tool for manipulating dynamic data
structures such as structures, linked lists, queues, stacks and trees.
7. Pointers reduce length and complexity of programs
8. They increase execution speed and thus reduce the program execution
time.

Whenever we declare a variable, the system allocates memory to hold the


value of the variable. Consider the following statement.
int quantity = 179;
This statement instructs the system to find a location for the integer variable
quantity and puts the value 179 in that location. Let us assume that the
system has chosen the address location 5000 for quantity.

Quantity Variable

179 Value

5000 Address

During execution of the program the system always associates the name
quantity with the address 5000. We may have access to the value 179 by
using either name quantity or the address 5000. Since memory address are
simply numbers, they can be assigned to some variables that can be stored
in some memory. Such variables that hold memory addresses are called
pointer variables.
A pointer variable is a variable that contains an address which is a location
of another variable in memory.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Variable Value Address

Quantity 179 5000

P 5000 5048

The value of the variable P is the address of the variable quantity, we may
access the value of quantity by using the value of p and therefore, we say that
the variable p points to the variable quantity. Thus P gets the name pointer.
Underlying pointer concepts (Not required for your exam)
Pointers are built on the three underlying concepts. They are
1. Pointer constants 2. Pointer value 3. Pointer variable
Pointer Constants: Memory address within a system are referred to as
pointer constants. We cannot change them, we can only use them to store
data values.
Pointer Value: We cannot save the value of a memory address directly. We
can only obtain the value through the variable stored there using the address
operator (&) . The value thus obtained is known as pointer value. The pointer
value may change during execution of the program.
Pointer variable : once we have a pointer value, it can be stored into another
variable. The variable that contains a pointer value is called a pointer variable.
Accessing the address of a variable
The address of operator (&) returns the address of the variable associated
with it.
e.g: p = &quantity;
would assign the address 5000 to the variable P.
The & operator can be used only with a simple variable or an array element.
The following are illegal use of address operator.
1. &125 (pointing at constant)
2. int x[10];
&x (pointing at array name)
3. &(x+y) (pointing at expression).

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
If x is an array, then expressions such as &x[0] and &x[i+3] are valid and
represent the address of 0th and (i+3)th elements of x.
C program to print the address of a variable along with its value.
Declaring Pointer Variables
Syntax
data_type *pt_name;
This tells three things about the variable pt_name
1. the asterisk (*) tells that the variable pt_name is a pointer variable.
2. pt_name needs a memory location
3. pt_name points to a variable of type data_type.
e.g: int *p; //p is a pointer variable that points to an integer data type.
p? ?
contains garbabe points to unknown location
Initialization of Pointer variables
The process of assigning address of a variable to a pointer variable is known
as initialization. Once pointer variable has been declared we can use the
assignment operator to initialize the variable.
Example: int quantity;
int *p;
p = &quantity;
or
we can also combine the initialization with the declaration.
int *p = &quantity;
Note:
1. We must ensure that the pointer variable always point to the
corresponding type of the data.
It is possible to combine the declaration of data variable, the declaration of
pointer variable and the initialization of the pointer variable in one step.
e.g: int x,*p = &x; //valid
int *p = &x, x; //invalid
we could also define a pointer variable with an initial value of NULL or 0.
int *p = NULL;

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Accessing a Variable Through its Pointer:
The indirection operator (*), dereferencing operator id used to access the
value of the variable using the pointer.
e.g:
int quantity, *p,n;
quantity = 179;
p = &quantity;
n = *p;
The first line declares quantity and n as integer variables and p as a pointer
variable pointing to an integer. The second line assigns the value 179 to
quantity and the third line assigns the address of quantity to the pointer
variable p. the fourth line contain the indirection operator * . When the
operator * is placed before a pointer variable in an expression, the pointer
returns the value of the variable of which the pointer value is the address. So
*p returns the value of the variable quantity.

C Program to accessing a variable through its pointer


#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
int *ptr;
x=10;
ptr = &x;
y = *ptr;
printf(“\n value of x is %d \n”,x);
printf(“\n %d is stored at address %u \n”,x, &x);
printf(“\n %d is stored at address %u \n”,*&x, &x);
printf(“\n %d is stored at address %u \n”,*ptr, ptr);
printf(“\n %d is stored at address %u \n”,ptr,&ptr);
printf(“\n %d is stored at address %u \n”,y,&y);
}

Chain of Pointers
It is possible to make a pointer to point to another pointer, thus creating a
chain of pointers.
p2 p1 variable
Address 2 Address 1 Value

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
here the pointer p2 contains the address of the pointer variable p1, which
points to the location that contains the desired value. This is known as
multiple indirections.
int **p2;
This declaration tells the computer that p2 is a pointer to a pointer of int
type. The pointer p2 is not a pointer to an integer, but rather a pointer to an
integer pointer.
void main()
{
int x, *p1, **p2;
x = 100;
p1 = &x;
p2 = &p;
printf(“%d”,**p2);
}
This code will display the value 100. Here p1 is declared as a pointer to an
integer and p2 as a pointer to a pointer to an integer.

Pointer Expressions
The following statements are valid
y = *p1 * *p2;
sum = sum + *p1;
z = 5 * - *p2/ *p1;
*p2 = *p2 + 10;
The following is wrong
Z = 5 * - *p2 /*p1;

The symbol /* is considered as the beginning of a comment and therefore


the statement fails.
Note:
1. C allows us to add to or subtract integers from the pointer.
2. If p1 and p2 are the pointers point to the same array, then p2-p1 gives
the number of elements between p1 and p2.
3. Pointers can be compared using the relational operators.
4. We may not use pointers in division or multiplication.
5. Two pointers cannot be added.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Pointer Increments and scaling factor

An expression like
p1++;
will cause the pointer p1 to point to the next value of its type. For example,
if p1 is an integer pointer with an initial value, say 2800, then after the
operation p1 = p1 + 1, the value of p1 will be 2802, and not 2801. That is,
when we increment a pointer, its value is increased by the length of the data
type that it points to, this is called the scale factor.

Data Type Scale factor


Characters 1 byte
Integers 2 bytes
Float 4 bytes
long integers 4 bytes
Double 8 bytes

Important Points on pointers


1. A pointer variable can be assigned the address of another variable
2. A pointer variable can be assigned the value of another pointer
variable
3. A pointer variable can be initialized with NULL or zero value
4. A pointer variable can be prefixed or post fixed with increment or
decrement operators
5. An integer value may be added or subtracted from a pointer variable
6. When two pointers point to the same array, one pointer variable can
be subtracted from another
7. When two pointers point to the objects of the same data types, they
can be compared using relational operators
8. A pointer variable cannot be multiplied by a constant
9. Two pointer variables cannot be added
10. A value cannot be assigned to an arbitrary address (i.e. &x = 10; is
illeagal).

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Pointers and 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 base address is the location of the first
element of the array. The compiler also defines the array name as a constant
pointer to the first element. Suppose we declare an array x as follows:

int x[5] = {1,2,3,4,5};


Suppose the base address of x is 1000 and assuming that each integer
requires two bytes, the five elements will be stored as follows:

X[0] x[1] x[2] x[3] x[4] x[5]


Elements
Value
1 2 3 4 5 6

Address 1000 1002 1004 1006 1008 1010

Write a C program to find sum of array elements using pointers

#include<stdio.h>
#include<conio.h>
void main()
{
int *p,a[5],sum=0,i;
clrscr();
p=a;
printf("Enter array elements\n");
for(i=0;i<5;i++)
{
scanf("%d",p);
p++;
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
p=a;
for(i=0;i<5;i++,p++)
{
sum=sum+*p;
}
printf("\n Sum of array = %d",sum);
getch();
}

Write a C program to find largest element from the given array


elements using pointers.

#include<stdio.h>
#include<conio.h>
void main()
{
int *p,a[5],max,i;
clrscr();
p=a;
printf("Enter array elements\n");
for(i=0;i<5;i++)
{
scanf("%d",p);
p++;
}
p=a;
max=*p;
p++;
for(i=1;i<5;i++,p++)
{
if(max < *p)
{
max=*p;
}
}
printf("\n largest value = %d\n",max);
getch();
}

Write a C program to find smallest element from the given array


elements using pointers.

#include<stdio.h>
#include<conio.h>
void main()
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
{
int *p,a[5],min,i;
clrscr();
p=a;
printf("Enter array elements\n");
for(i=0;i<5;i++)
{
scanf("%d",p);
p++;
}
p=a;
min=*p;
p++;
for(i=1;i<5;i++,p++)
{
if(min > *p)
{
min=*p;
}
}
printf("\n Smalest value = %d\n",min);
getch();
}

Write a C program to sort array elements using pointers.

#include<stdio.h>
#include<conio.h>
void main()
{
int *p,a[5],min,i,j,*temp;
clrscr();
p=a;
printf("Enter array elements\n");
for(i=0;i<5;i++)
{
scanf("%d",p);
p++;
}
p=a;
for(i=0;i<4;i++)
{
for(j=0;j<(5-i-1);j++)
{
if(*(p+j) > *(p+j+1))
{

*temp = *(p+j);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
*(p+j) = *(p+j+1);
*(p+j+1) = *temp;
}
}
}
printf("\n After sotring array elements are\n");
for(i=0;i<5;i++,p++)
{
printf("%d\n",*p);
}
getch();
}

Pointers and character strings

String initialization and declaration


char str[5] = “good”;
The compiler automatically inserts the null character ‘\0’ at the end of the
string. C supports an alternative method to create strings using pointer
variable of type char.
e.g: char *str = “good”;
This creates a string for the literal and then stores its address in the pointer
variable str. The pointer str now points to the first character of the string
“good”.
We can also use the run time assignment for giving values to a string pointer.
e.g: char *str;
str = “good”;
The assignment
str1 = “good”;
Is not a string copy, because the variable str1 is a pointer, not a string.
We can print the content of the string str1 using either printf or puts functions
as follows

printf(“%s”,str1);
puts(str1);

Although str1 is a pointer to the string, it is also the name of the string.
Therefore we do not need to use indirection operator *.
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
C program to count the string length using pointers.

#include<stdio.h>
void main()
{
char a[10],*s,len=0;
int i;
printf("\n Enter a string");
gets(a);
s=a;
while(*s!='\0')
{
s++;
len++;
}
printf("\n length = %d",len);
}

Write a c program to copy one string into another using pointers.

#include<stdio.h>
void main()
{
char a[10],b[10],*s1,*s2;
int i;
printf("\n Enter a string");
gets(a);
printf("\n Enter a string");
gets(b);
s1=a;
s2=b;

printf("\n s1=%s \n s2 = %s",s1,s2);


i=0;
while(*(b+i)!='\0')
{
*(a+i)=*(b+i);
i++;
}
*(a+i)='\0';
printf("\n s1 = %s",s1);
printf("\n s1 = %s",s2);

In C, a constant character string always represents a pointer to that string.


And therefore, the following statements are valid.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
char *name;
name = “delhi”;

These statements will declare name as a pointer to character and assign to


name the constant character string “delhi”. We might remember that this type
of assignment does not apply to character arrays.
The statements like
char name[20];
name = “Delhi”;
do not work.
Array of Pointers

Consider the following array of string


char name[3][25];
this says that the name is a table containing three names, each with a
maximum length of 25 characters. The total storage requirements for the
name table are 75 bytes.

We know that rarely the individual strings will be equal lengths. Therefore,
instead of making each row a fixed number of characters, we can make it a
pointer to a string of varying length.
For example:
Char *name[3] = {
“New Zealand”;
“Australia”,
“India”
};
Declares name to be an array of three pointers to characters, each pointer
pointing to a particular name as:
This declaration allocates only 28 bytes, sufficient to hold all the characters
as shown.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
The following statements would print out all the three names:
for(i=0;i<3;i++)
{
Printf(“%s\n”,name[i]);
}
To access the jth character in the ith name, we may write as
*(name[i]+j)
Note:
1. The character arrays with the rows of varying length are called ‘ragged
arrays’ and are better handled by pointers.
2. *p[3] declares p as an array of three pointers.
3. (*p)[3] declares p as a pointer to an array of three elements.

C program to display city names using array of pointers.

#include<stdio.h>
#include<conio.h>
void main()
{
int i;
char *name[3];
clrscr();
for(i=0;i<3;i++)
{
printf("\n Enter %d th city name\n",i+1);
fflush(stdin);
scanf("%s",name[i]);
}
for(i=0;i<3;i++)

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
{
printf("\n %d city is %s\n",i+1,name[i]);
}
getch();
}

Write a c program to sort city names using pointers.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */
int main(int argc, char *argv[]) {
char (*p)[10],name[5][10],temp[10];
int i,j,k;
p=name;
printf("\n Enter 5 city names\n");
for(i=0;i<5;i++)
{
fflush(stdin);
scanf("%s",p[i]);
}
for(i=1;i<5;i++)
{
for(j=0;j<=(5-i-1);j++)
{
if(strcmp(p[j],p[j+1])>0)
{
strcpy(temp,p[j]);
strcpy(p[j],p[j+1]);
strcpy(p[j+1],temp);
}
}
}
printf("\n After sorting city names are\n");
for(i=0;i<5;i++)
{
printf("\n%s",p[i]);
}

return 0;
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Pointers as Function Arguments
When we pass address to a c=function, the parameters receiving the address
should be pointers. The process of calling a function using pointers to pass
the addresses of variables is known as call by reference.
The function which is called by reference can change the value of the variable
used in the call.

C program to swap two numbers using call by reference.

#include<stdio.h>
#include<conio.h>
void swap(int *a,int *b);
void main()
{
int x,y,z;
clrscr();
printf("Enter two numbers\n");
scanf("%d%d",&x,&y);
printf("\n Before swaping numbers are \n");
printf("%d\t%d\n",x,y);
swap(&x,&y);
printf("\n After swapping numbers are \n");
printf("%d\t%d\n",x,y);
getch();
}
void swap(int *p,int *q)
{
int *t;
*t = *p;
*p = *q;
*q = *t;
}

Output:
Enter two numbers
10
20

Before swaping numbers are


10 20

After swapping numbers are


20 10

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Functions returning pointers

A function can return a single value by its name or return multiple values
through pointer parameters. Since pointers are a data type in C, we can also
force a function to return a pointer to the calling function.
C program to illustrate function returns a pointer

#include<stdio.h>
#include<conio.h>
int *large(int *p, int *q);
void main()
{
Int a=10, b=20, *p;
clrscr();
p=large(&a,&b);
printf(“%d”,*p);
getch();
}
int *large(int *c,int *d)
{
if(*c > *d)
return c;
else
return d
}

The function larger receives the addresses of the variable a and b, decides
which one is larger using the pointers x and y and then returns the address
of its location. The returned value is then assigned to the pointer variable p
in the calling function. In this case, the address of b is returned and assigned
to p and therefore the output will be the value of b., b namely 20.

Pointers to functions

A function like a variable, has a type and an address location in the


memory. It is therefore possible to declare a pointer to a function, which can
then be used as an argument in another function. A pointer to a function is
declared as follows
type (*fptr) ( );
this tells the compiler that fptr is a pointer to a function, which returns type
value. The parenthesis around *fptr are necessary.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
We can make a function pointer to point to a specific function by simply
assigning the name of the function to the pointer. For example
double mul(int, int);
double (*p1) ( );
P1 = mul;
Declare p1 as a pointer to a function and mul as a function and then make
p1 to point to the function mul. To call the function mul, we may now use
the pointer p1 with the list of paremeters.
(*p1) (x, y);
is equivalent to
mul(x,y);

C Program to illustrate a pointer to functions

#include<stdio.h>
#include<conio.h>
int fun(int,int);
int (*f)();
void main()
{
int a,b,c,*p,*q,r;
clrscr();
printf("Enter a & b Values\n");
scanf("%d%d",&a,&b);
//p=&a;
//q=&b;
f=fun;
r=(*f)(a,b);
printf("\nSum=%d",r);
}
int fun(int x,int y)
{
int z;
z = x +y;
return z;
}

Compatibility and Casting (Not required for your exam)


Compatibility – a variable declared as a pointer is not just a pointer type
variable. It is also a pointer to a specific fundamental data type, such as a
character. A pointer therefore always has a type associated with it. We
cannot assign a pointer of one type to a pointer of another type, although

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
both of them have memory addresses as their values. This is known as
incompatibility.

Casting
All the pointer variables store memory addresses. Which are compatible, but
what is not compatible is the underlying data type to which they point to.
We cannot use the assignment operator with the pointers of different types.
We can however make explicit assignment between incompatible pointer
types by using cast operator, as we do with the fundamental types.
Example
int x;
char *p;
p = (char *) &x;

void Pointer (Generic Pointer)


It represents any pointer type. All pointer types can be assigned to a void
pointer and a void pointer can be assigned to any pointer without casting.
Syntax:
void *ptr;
Note:
1. A void pointer has no object type. It cannot be dereferenced.

Pointers and structures

Suppose product is an array variable of struct type. The name product


represents the address of its zeroth element.
struct inventory
{
char name[30];
int number;
int price;
}product[2],*ptr;
This statement declares product as an array of two elements, each of the
type struct inventory and ptr as a pointer to data objects of the type struct
inventory.
The following assignment
ptr = product;
would assign the address of the zeroth element of product to ptr. That is the
pointer ptr will now point to product[0]. Its members can be accessed using
the following statement.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
ptr à name
ptr à number
ptr à price
the symbol à is called the arrow operator (member selection operator) and
is made up of a minus sign and a greater than sign. Ptr is simply another
way of writing product[0].
When ptr is incremented by one, it is made to point to the next record i.e.
product[1].
Also we can access the members using the following statement.
(*ptr).name
C Program to illustrate pointer to structures
#include<stdio.h>
#include<conio.h>
struct inventory
{
char name[10];
int number;
int price;
};
void main()
{
int i;
struct inventory product[3],*ptr;
clrscr();
ptr=product;
for(i=0;i<3;i++,ptr++)
{
printf("Enter name \n");
fflush(stdin);
scanf("%s",ptr->name);
printf("Enter number\n");
scanf("%d",&ptr->number);
printf("Enter price\n");
scanf("%d",&ptr->price);
}
printf("Structure details are\n");
for(i=0,ptr=product;i<3;i++,ptr++)
{

printf("\n %d th name = %s \t number - %d \t price - %d \n",i+1,ptr-


>name, ptr->number, ptr->price);
}
getch();
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Dynamic memory Allocation:

The process of allocating memory at runtime is known as dynamic memory


allocation.
C doesn.t have inherently have this facility, there are four library functions
known as library management functions that can be used for allocating and
freeing memory during program execution.
Memory allocation functions are

Function Task
malloc Allocate required size of bytes and returns a pointer to the
first byte of the allocated space
calloc Allocates space for an array of elements initializes them to 0
and then returns a pointer to the memory
free Frees previously allocated memory
realloc Modifies the size of previously allocated space.

Memory Allocation Process

Local Variables Stack


Free Memory Heap

Global Variables
Permanent
C Programming Instructions
Storage Area

Program instructions and global variables are stored in a region known as


permanent storage area and the local variables are stored in another area
known as stack. The area between these two regions is available for dynamic
memory allocation during execution of a program. This free memory is called
heap. The size of the heap changes when program is executed due to creation
and death of variables that are local to functions and block. Therefore, it is
possible to encounter a overflow during dynamic memory allocation process.
In such situations the memory allocation functions mentioned above return
a NULL pointer.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Malloc:
A block of memory may be allocated using the function malloc. The malloc
function reserves a block of memory of specified size and returns a pointer
of type void. This means we can assign it to any type of pointer.

ptr = ( cast-type *)malloc(byte-size);

ptr is a pointer of type cast-type. The malloc returns a pointer to an area of


memory with size

x = (int *)malloc(100*sizeof(int));

Note:
1. The storage space allocated dynamically has no name and therefore
its contents can be accessed only through pointer.
2. malloc allocates a block of contiguous bytes. The allocation can fail if
the space in the heap is not sufficient to satisfy the request. If it fails
it returns a NULL.

Calloc:

Calloc is used to allocating memory space at run time for storing derived
data types such as arrays and structures. While malloc allocates a single
block of storage space, calloc allocates multiple blocks of storage, each of
the same size, and then sets all bytes to 0.

ptr = (cast-type*)calloc(n, elem-size);

The above statement allocates contiguous space for n blocks, each of size
elem_size bytes. All bytes are initialized to zero and a pointer to the first byte
of the allocated region is returned. If there is not enough space it returns
NULL.

realloc():
realloc is used to allocate or reduce memory size during execution of a
program.
ptr= malloc(size);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Then reallocation of space may be done by the statement.
ptr = realloc( ptr, new size);
This function allocates a new memory space of size new size to the pointer
variable and returns a pointer to the first byte of the new memory block.
If the function is unsuccessful in locating additional space it returns a NULL
pointer and the original block is lost.

free():
Compile time storage of a variable is allocated and released by the system in
accordance with its storage class. With the dynamic run-time allocation, it is
our responsibility to release the space when it is not required
Free is used release the memory is created by malloc or calloc function.
Syntax:

free(ptr);

Note:
1. It is not the pointer that is being released but rather what it points to.
2. To release an array of memory that was allocated by calloc we need only
to release the pointer once. It is an error to attempt to release elements
individually.

Write a C program to illustrate malloc() and free().


#include<stdio.h>
#include<stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
printf("\n Enter no of elements:\n");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int));
if(ptr==NULL)
{
printf("\n Sorry! unable to allocate memory");
exit(0);
}
printf("\n Enter elements");
for(i=0;i<n;i++)
{
scanf("%d",(ptr+i));
sum = sum + *(ptr+i);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
printf("\n sum = %d",sum);
free(ptr);
}

Write a C program to illustrate calloc() and free().

#include<stdio.h>
#include<stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
printf("\n Enter no of elements:\n");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr==NULL)
{
printf("\n Sorry! unable to allocate memory");
exit(0);
}
printf("\n Enter elements");
for(i=0;i<n;i++)
{
scanf("%d",(ptr+i));
sum = sum + *(ptr+i);
}
printf("\n sum = %d",sum);
free(ptr);
}

Self-referential Structure:
Definition: Self-referential structure is a structure in which one member is a
pointer which points to the same type of structure is called self-referential
structure.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Example1: Single Linked list node
struct node
{
int data;
struct node *next;
}

Visual representation

In the above example, each node has two fields, they are data and next. Here
next is a pointer which points to the same type structure. Hence it is called
as a self-referential structure.
Example2: Double linked list node
Struct node
{
Int data;
Struct node *prev;
Struct node *next;
}

In the above example, each node has three fields, they are data, previous and
next. Here prev and next are the pointers which points to the same type
structure. Hence it is also called as a self-referential structure.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
UNIT-5

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Console I/O – it uses scanf() and printf() to read and write data. These
functions always use terminal (keyboard and screen) as the target place.
Advantages: It works better as long as the data is small
Drawbacks
1) It becomes cumbersome and time consuming to handle large volume
of data through terminal.
2) The entire data is lost when either the program is terminated or the
computer is turned off.
To overcome the above drawbacks we use files.
File (Definition) – A file is a place on the disk where a group of related data
is stored.
Types of Files:
There are two types of files, they are 1. Text files 2. Binary files
1. Text file:

• Text file stores information in the form of alphabets, numbers, special


symbols etc…
• It requires conversion from text to binary format.
• This format is human understandable.
• C source files are text files

2. Binary File:

• Binary file stores information in the binary form.


• It doesn’t require conversion from text to binary format.
• This format is machine understandable.
• Every executable file generated by the C compiler is a binary file.

File Operations

• Naming a file
• Opening a file
• Reading data from a file
• Writing data to a file
• Closing a file

Defining and opening a file:


If we want to store data in a file in the secondary memory, we must specify
three things to the operating system. They are

• File name
• Data structure

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
• Purpose

File name is a sequence of characters that make up a valid filename. It may


contain two parts, a primary name and an optional period with file extension.
Data structure of a file is defined as FILE, therefore all files should be declared
as type FILE before they are used.
For what purpose we open a file, whether the file is open for reading, writing
or appending.
Syntax for declaring and opening a file

FILE *fp;
fp = fopen (“filename”,”mode”);

In the first statement fp as a “pointer to the data type FILE”, the second
statement opens a file named filename and assigns an identifier to the FILE
type pointer fp.
Opening a file in one of the three modes. They are.
1. r - open the file for reading only
2. w – open the file for writing only
3. a - open the file for appending (adding) data to it.

1. When the mode is “writing”


• A file with the specified name is created, if the file doesn’t exist
• The file contents are deleted, if the file already exist.
2. When the mode is “reading”
• If the file exist then it is opened and current contents safe
• If the file doesn’t exist it returns NULL
3. When the mode is “appending”
• If the file exists then it is opened with current contents safe.
• If the file doesn’t exist then a file with the specified name is created.

Recent compilers include additional modes of operations.

• r+ -- If the file doesn’t exist it return NULL otherwise the file is opened to
the beginning for both reading and writing
• w+ -- If the file already exist then it erases the previous contents and
open the file for reading and writing. If the file doesn’t exist then it
creates a new file for writing.
• a+ -- same as a except both for reading and writing

CLOSING A FILE

A file must be closed after all operations have been completed.


Syntax:
fclose(file_pointer);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
This would close the file associated with the FILE pointer file pointer.

INPUT-OUTPUT OPERATIONS ON FILES

getc() and putc() functions


getc()
• it is used to read a character from a file.
• The file must be opened in read in mode.
• Syntax

c= getc(fp1);
Read a character from the file whose file pointer is fp1 and store the
character in c.
Putc():
• It is used to write a character to a file.
• The file must be opened in write mode.
• Syntax
Putc(c,fp1);

Write the character contained in the character variable c to the file


associated with FILE pointer fp1.c and putc
Note:
1. The file pointer moves by one character position for every operation of
getc and putc
2. getc will return and end-of-file marker EOF when end of the file has
been reached.

1. Write a c program to write data to the input file after that read
input file contents and display on the screen.
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {


FILE *fp;
char c;
fp=fopen("inputfile.txt","w");
while((c=getchar())!= EOF)
{
putc(c,fp);
}
fclose(fp);
fp=fopen("inputfile.txt","r");
while((c=getc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
return 0;
}

2. Write a c program to write characters to the input file, then read


input file contents and check if it is vowel then store it in VOWEL
file, or it is a consonant then store it in CONSONANT file. Display
VOWEL files contents and CONSONANTS file contents.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, char *argv[]) {


FILE *fp,*fp1,*fp2;
char c;
fp=fopen("inputfile.txt","w");
while((c=getchar())!= EOF)
{
putc(c,fp);
}
fclose(fp);
fp=fopen("inputfile.txt","r");
fp1=fopen("vowel.txt","w");
fp2=fopen("consonant.txt","w");

while((c=getc(fp))!=EOF)
{
if(isalpha(c))
{

if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'|
|c=='O'||c=='U')
{
putc(c,fp1);
}
else
{
putc(c,fp2);
}
}
}
fclose(fp);
fclose(fp1);
fclose(fp2);

fp1=fopen("vowel.txt","r");
printf("\n Vowe file contents are:");
while((c=getc(fp1))!=EOF)
{

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf("%c",c);
}
fclose(fp1);

fp2=fopen("consonant.txt","r");
printf("\n Consonant file contents are:");
while((c=getc(fp2))!=EOF)
{
printf("%c",c);
}
fclose(fp2);
return 0;
}

getw():
• It is used to read an integer from a file.
• The file must be opened in read mode.
• Syntax
c= getw(fp);

putw():
• It is used to write an integer to a file.
• The file must be opened in write mode.
• Syntax
putw(c,fp);

The variable c contains an integer that value writes into a file pointed
by a file pointer fp.

3. Write a c program to write integers to NUMBER file. Read an integer


value from NUMBER file and display integers on the screen.
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {


FILE *fp;
int n;
fp=fopen("number.txt","w");
while(1)
{
printf("\n Enter a number:");
scanf("%d",&n);
if(n<0)
{
break;

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
else
{
putw(n,fp);
}
}
fclose(fp);

fp=fopen("number.txt","r");

while((n=getw(fp))!=EOF)
{
printf("\n%d",n);
}
fclose(fp);
return 0;
}

4. Write a c program to write integers to the NUMBER file. Read


numbers from the NUMBER file check that number if it is even
then stores it in EVEN file otherwise store it in ODD file. Display
EVEN file contents and ODD file contents on the screen.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {


FILE *fp,*fp1,*fp2;
int n;
fp=fopen("number.txt","w");
while(1)
{
printf("\n Enter a number:");
scanf("%d",&n);
if(n<0)
{
break;
}
else
{
putw(n,fp);
}
}
fclose(fp);

fp=fopen("number.txt ","r");
fp1=fopen("even.txt","w");
fp2=fopen("odd.txt","w");

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
while((n=getw(fp))!=EOF)
{
if(n%2==0)
{
putw(n,fp1);
}
else
{
putw(n,fp2);
}
}
fclose(fp);
fclose(fp1);
fclose(fp2);

fp1=fopen("even.txt","r");
printf("\n Even file contents are:");
while((n=getw(fp1))!=EOF)
{
printf("\n%d",n);
}
fclose(fp1);
fp2=fopen("odd.txt","r");
printf("\n Odd file contents are:");
while((n=getw(fp2))!=EOF)
{
printf("\n%d",n);
}
fclose(fp2);
return 0;
}

fscanf():
• It is used to read mixed data from the file
• Syntax
fscanf ( fp, ”control string”, list);

The above statement will read the items in the list from the file
specified by fp.
fprintf()
• It is used to write the list of items into a file
• Syntax
fprintf(fp, ”control string “, list);
The above statement would write the items in the list into a file specified by
fp.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
1) Write a c program to open a file named inventory and store it in
following data.
Item name item number price quantity
Aaa 111 10 2
Bbb 222 15 3
Ccc 333 12 5
Extend the program to read this data from the file inventory and
display the table with values of each item.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, char *argv[]) {


FILE *fp;
char name[10];
int number,quantity,i,value;
float price,values;

fp=fopen("inventory.txt","w");
i=1;
while(i<=3)
{
printf("\n Enter item name:");
scanf("%s",name);
printf("\n Enter item number:");
scanf("%d",&number);
printf("\n Enter price:");
scanf("%f",&price);
printf("\n Enter quantity:");
scanf("%d",&quantity);
fprintf(fp,"\n %s %d %f %d",name,number,price,quantity);
i++;
}
fclose(fp);
fp=fopen("inventory.txt","r");
i=1;
printf("\n Name\t Number\t Price\t Quantity\t Value\n");
while(i<=3)
{
fscanf(fp,"\n %s %d %f
%d",name,&number,&price,&quantity);
values=price*quantity;
printf("\n %s\t %d\t %f\t %d\t
%f",name,number,price,quantity,values);
i++;
}
fclose(fp);
return 0;

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}

Error Handling During I/O Operations:


Errors may occur during the following situations.
1. Trying to read the file beyond the end-of-file mark.
2. Device overflow.
3. Trying to use a file when the file has not been opened.
4. Trying to perform operation on a file, when the file has been opened
for another operation.
5. Opening a file with an invalid filename.
6. Attempting to write to a write protected file.

C provides two library functions to provide file status information. They are
feof() and ferror()

1. feof( ): it takes file pointer as the argument and return a nonzero integer
if all of the data from the specified file has been read and returns zero
otherwise.
Syntax:
if(feof(fp))
{
Printf(“End-of-data\n”);
}
would display the message “End-of-data” on reaching the end of file
condition.

2. ferror( ): It takes the file pointer as an argument and returns a nonzero


integer if an error has been detected up to that point during processing. It
returns zero otherwise.
if(ferror(fp) != 0)
printf(“An error has occurred \n”);

3. Clearerr( ) – clears the EOF and error indicator for the given stream.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
C Program to illustrate fclearerr()

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

void main()
{
FILE *fp;
char c;

clrscr();
fp=fopen("ece2.txt","w");

c=getc(fp);
if(ferror(fp))
{
printf("\n error in reading file \n");
}
clearerr(fp);

if(ferror(fp))
{
printf("error in reading from file : file.txt\n");
}
fclose(fp);
}

Random Access Files:


To access any part of the file we use ftell, fseek and rewind functions.
1. ftell( ): It takes file pointer as an argument and returns number that
represents the current position of the file pointer.
Syntax:
n= ftell(fp);
n would give the relative offset of the current position.

2. rewind( ): takes file pointer as an argument and resets the position to the
start of the file.
rewind(fp);
n=ftell(fp);
would assign 0 to the n because the file position has been set to the start of
the file by rewind.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
3. fseek( ): It is used to move the file position to the desired position in the
file.
Syntax:
fseek(file_poinger, offset, Position);
file_pointer is a file pointer, offset is a number and position is an integer
number.
Offset species the number of positions to be moved from the location
specified by the position.
Position can take one of the following three values.

Value Meaning
0 Beginning of the file
1 Current position
2 End of file

The offset may be positive meaning move forwards, or negative meaning


move backwards.
Statement Meaning
fseek(fp,0L,0) go to the beginning
fseek(fp,0L,1) stay at the current position
fseek(fp,0L,2) go to the end of the file, past the last character of the
file
fseek(fp,m,0) move to the (m+1)th byte in the file
fseek(fp,m,1) go forward by m bytes
fseek(fp,-m,1) go backward by m bytes from the current position
fseek(fp,-m,2) go backward by m bytes from the end

Write a C program to print file contents in reverse order.

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
int i,n;
clrscr();

fp=fopen("xyz.txt","w");

while((ch=getchar())!=EOF)
{
putc(ch,fp);
}
fclose(fp);

fp=fopen("xyz.txt","r");

fseek(fp,0L,2);
n=ftell(fp);
printf("\n No of characters are = %d\n",n);
for(i=n;i>=0;i--)
{
fseek(fp,i,0);
ch=getc(fp);
printf("%c",ch);
}
fclose(fp);
}

Write a c program to print 6th and 8th character in the file.


#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {

FILE *fp;
char ch;
int i,n;

fp=fopen("xyz.txt","w");

while((ch=getchar())!=EOF)
{
putc(ch,fp);
}
fclose(fp);

fp=fopen("xyz.txt","r");

fseek(fp,6L,0);
ch=getc(fp);
printf("\n 6th character is = %c\n",ch);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
fseek(fp,8L,0);
ch=getc(fp);
printf("\n 8th character is = %c\n",ch);

fclose(fp);

return 0;
}

Binary files
Binary files are very similar to arrays of structures, except the structures
are in a disk-file rather than an array in memory.
Binary files have two features that distinguish them from text files:
• We can instantly use any structure in the file.
• We can change the contents of a structure anywhere in the file.

After we have opened the binary file, we can read and write a structure or
seek a specific position in the file. A file position indicator points to record
0 when the file is opened.

A read operation reads the structure where the file position indicator is
pointing to. After reading the structure the pointer is moved to point at the
next structure.

A write operation will write to the currently pointed-to structure. After the
write operation the file position indicator is moved to point at the next
structure.

The fread and fwrite function takes four parameters:

1) A memory address
2) Number of bytes to read per block
3) Number of blocks to read
4) A file variable

Syntax: fread(&my_record,sizeof(struct rec),1,file_pointer);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
This fread statement says to read x bytes (size of rec) from the file
file_pointer into memory address &my_record. Only one block is requested.
Changing the one into ten will read in ten blocks of x bytes at once.

Syntax: fwrite(&my_record,sizeof(struct rec),1,file_pointer)

This fwrite statement says to write x bytes (size of rec) from the my record
into the file pointed by the file pointer.

Write a C program to write data from the file using binary file
concept

#include<stdio.h>
#include<conio.h>
struct rec
{
int x,y,z;
};
void main()
{
struct rec a;
FILE *f;
int i;
clrscr();
f=fopen("xyz","rb");
if(!f)
{ printf("\n File was not opened\n");
exit(0);
}
for(i=1;i<=3;i++)
{
fread(&a,sizeof(a),1,f);
printf(" \n %d record contents\n",i);
printf("%d\t%d\t%d\n",a.x,a.y,a.z);
printf("\n\n\n\n");
}
fclose(f);
}

Write a C program to write data to the file using binary file

#include<stdio.h>
#include<conio.h>
struct rec
{

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
int x,y,z;
};
void main()
{
struct rec a;
FILE *f;
int i;
clrscr();
f=fopen("xyz","wb");
if(!f)
{
printf("\n File was not opened\n");
exit(0);
}
for(i=1;i<=3;i++)
{
a.x=i;
a.y=i+1;
a.z=i+2;
fwrite(&a,sizeof(a),1,f);
}
fclose(f);
}

Command Line Arguments

It is a parameter supplied to a program when a program is invoked. The


parameter may represent a filename the program should process.
If we want to execute a program to copy the contents of a file named X_FILE
to another one named Y_FILE, then we may use a command line like

C:\>PROGRAM X_FILE Y_FILE

Where PROGRAM is the filename where the executable code of the program is
stored. This eliminates the need for the program to request the user to enter
the filenames during execution.

Main takes two arguments called argc and argv and the information contained
in the command line is passed on to the program through these arguments,
when main is called up by the system.

argc: it counts the number of arguments on the command line.


argv: it is an argument vector and represents an array of character pointers
that point to the command line arguments.

e.g: argc value is three

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
argv[0] à PROGRAM
argv[1] à X_FILE
argv[2] à Y_FILE

In order to access the command line arguments, we must declare the main
function and its parameters as follows.
main(int argc, char *argv[])
{
…………..
…………..
…………..

Command Line Arguments programs

1. Write a C program to add two numbers using command line


arguments.
#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char *argv[]) {


int a,b,c;
a=atoi(argv[1]);
b=atoi(argv[2]);
c=a+b;
printf("\n Sum = %d",c);
return 0;
}

2. Write a C program to find factorial of a given number using


command line arguments.

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char *argv[]) {


int fact=1,i,n;
n=atoi(argv[1]);
for(i=1;i<=n;i++)
{
fact = fact*i;
Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
}
printf("\n Fact = %d",fact);
return 0;
}

3. Write a C program to find string length using command line


arguments.
#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char *argv[]) {


int i;
printf("\n str= %s",argv[1]);
for(i=0;argv[1][i]!='\0';i++);
printf("\n string length = %d",i);
return 0;
}

4. Write a C program to copy one file contents into another file


using command line arguments.

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char *argv[]) {


FILE *fp1,*fp2;
char c;
fp1=fopen(argv[1],"r");
fp2=fopen(argv[2],"w");

while((c=getc(fp1))!=EOF)
{
putc(c,fp2);
}
fclose(fp1);
fclose(fp2);

fp2=fopen(argv[2],"r");
printf("\n %s file contents are \n",argv[2]);
while((c=getc(fp2))!=EOF)
{
printf("%c",c);
}

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
fclose(fp2);
return 0;
}

Preprocessor commands
Preprocessor commands

❖ ‘Preprocessor’ is a program that processes the source code before it


passes through the compiler.
❖ It operates under the control of preprocessor directives which begin
with the symbol #
❖ Can be placed anywhere in the program.
The preprocessor directives are broadly classified under three categories:

1) File inclusion directives/commands


2) Macro substitution directives/commands
3) conditional compilation commands
1) File inclusion directives:

An external file containing functions or macro definitions can be included as


part of a program so that we need not rewrite those functions or macro
definitions. This is achieved by the preprocessor directive #include

#include “filename”
Or
#include <filename>
Where filename is the name of the file containing the required definitions or
functions. At this point, the preprocessor inserts the entire contents of
filename into the source code of the program.

Note:

1. Nesting of included files is allowed. That is, an included file can


include other files.
2. A file cannot include itself.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
3. Copying one or more files into a program. These files are usually
called header files.

File inclusion command comes in two formats.

Syntax

1. # include <filename>
2. #include “filename”
The # inlcude<filename> makes the preprocessor to include header files from
the system library.

The #inlcude"filename" makes the preprocessor to include files from the user-
defined directory.

Eg:

#include <stdio.h>
Output
#include <conio.h>
hai welcome to cpds
#include "hello.c"
main ( )
{
clrscr();
printf (“hai”);
display();
}
The contents of hello.c are

int display();

int display()

printf("welcome to cpds");

return 0;

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
The definition of the function printf ( ) is present in <stdio.h>header file.

The definition of the function display() is present in file name hello.c in user
defined directory .

2). Macro substitution directives/commands

❖ It replaces every occurrence of the identifier by a predefined string.


Macro substitution is a process where an identifier in a program is replaced
by a predefined string. The preprocessor accomplishes this task under the
direction of #define statement.

Syntax for defining a macro

# define identifier string

If this statement is included in the program at the beginning, then the


preprocessor replaces every occurrence of the identifier in the source code by
the string.

The string may be any text, while the identifier must be a valid C name.

There are different forms of macro substitution. The most common forms are:

1) Simple macro substitution

2) Augmented macro substitution

3) Nested macro substitution

1). Simple macro substitution

Simple macro substitution is commonly used to define constants. It can be


done by #define.

Ex: #define M 5

will replace occurrences of M with 5, starting from the line of definition to the
end of the program. Consider the following two lines:

total = M * value;

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
printf(“ M= %d \n “, M);

these two lines would be changed during preprocessing as follows:

total = 5 * value;

printf(“M = %d \n”, 5);

A macro definition can include expressions also. Following are valid


definitions.

# define AREA 5 * 12.46

# define SIZE sizeof(int) * 4

# define TWO-PI 2.0 * 3.1415926

2). Argumented macro substitution

The preprocessor permits us to define more complex and more useful form
of replacements. It takes the following form:

#define identifier(f1, f2, f3,-------,fn) string

Note that there is no space between the identifier and the left parentheses.
The identifiers f1, f2, f3, ---, fn are formal macro arguments that analogous to
the formal arguments in a function definition.

Subsequent occurrence of a macro with arguments is known as a macro call


(similar to a function call). When a macro is called, the preprocessor
substitutes the string, replacing the formal parameters with actual
parameters.

A simple example of a macro with argument is

#define CUBE(x) (x*x*x)

If the following statement appears later in the program

Volume = CUBE(side);

Then the preprocessor would expand this statement to:

Volume = ( side * side * side);

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
3) Nested macro substitution

We can also use one macro in the definition of another macro. That is, macro
definitions may be nested. For instance, consider the following macro
definitions.

#define M 5

#define N M+1

#define SQUARE(X) ( (x) * (x) )

#define CUBE(X) (SQUARE(X) * (X))

#define SIXTH(X) (CUBE(X) * CUBE(X))

The preprocessor expands each #define macro, until no more macros


appear in the text.

For example, the last definition is expanded into

((SQUARE(X) * (X)) * (SQUARE(X) * (X)))

Since SQUARE(X) is still a macro, it is futher expanded into

( ( ( (X) * (X) ) * (X) ) * ( ( (X) * (X) ) * (X) ) )

Which is finally evaluated as x6.

Undefining macros:

Once defined, macro command cannot be redefined. Any attempt to redefine


leads to the compilation error. So, to redefine a macro, we must undefine it
by using #undef command and define it again.

Ex:

#define SIZE 10

--------------

#undefine SIZE

#define SIZE 20

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
Predefined Macros:

The macros which are predefined in C library are called as predefined


macros.

Command Meaning

--DATE-- Provides String “mm dd yyyy” formate

--FILE-- Provides String constant containing name of souce file

--LINE-- Provides interger constant,containing currect statement

--TIME-- Provides a string “hh: mm:ss” formate

--STDC-- Provides a integer constant with value 1 iff the compiler


conforms with ISO implementation.

Eg:

1 #inlcude<stdio.h.>
2 int main(void)
3 {
4 printf(“ line %d \n”, __LINE__);
5 printf(“ date %s \n”, __DATE__);
6 printf (“Time %s\n”,__TIME__);
7 printf(“ line %d \n”, __LINE__);
8 return 0;
9 }
Output:

Line 4

date Aug 15 1947

Time 11:59:59

Line 7

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
3. Conditional Compilation commands

❖ C preprocessor offers a feature known as conditional compilation,


which can be used to switch ON (include) (or) OFF (exclude) a
particular line (or) group of lines in a program.
❖ 6 types: i) Two-way command ii) Multi-way commands iii) Line
commands iv)Error commands v) Null commands vi) pragma
commands.
Eg: #if, #else, #endif,# line,#error,#,#pragma etc.

i) Two-way command:
Syntax:

#if expression

Code to be included if expression is true

#else

Code to be included if expression is false

#endif

ii) Multi-way command:


Syntax:

#if expression1

Code to be included if expression1 is true

#elif expression2

Code to be included if expression2 is true

#else

Code to be included if both expressions are false

#endif

iii) Line Command:


Syntax:1:- # line linenumber

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
It command set the next line of the program to linenumber +1

Syntax:2:- # line linenumber filename

Set the next line of the program to linenumber+1 and create a program
name that is checked by predefined macrocall –FILE—

Eg:

1 # line 100 “myprogram.c”

100 #include <stdio.h>

101 int main(void)

102 {

103 printf(“ Line %d \n”, __LINE__);

104 printf(“ File %s \n”, __FILE__);

105 printf (“Time %s”. __TIME__);

106 printf(“ Line %d \n”, _LINE_);

107 return 0;

108 }

Output:

Line 103

File myprogram.c

Time 11:59:59

Line 106

iv). Error command

Syntax:

#if !defined (identifier)

#error < error message>

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad
#endif

Eg:

#include <stdio.h>

#include<conio.h>

#define B 10

Void main()

#if !defined(A)

# error macro A is not defined

#else

# printf(“ micro found”);

#endif

v). Null command

C allows null command Syntax: #

This is considered as null command and does not generate a compilation


error.

vi) Pragma command

Syntax: #pragma tokens

It makes the compiler perform implementation defined action. It is used in


advanced environments.

Dr. G. Nagaraju, Assistant Professor, Dept of CSE(AIML & IOT), VNRVJIET, Hyderabad

You might also like