You are on page 1of 167

CS3251- PROGRAMMING IN C

SYLLABUS
UNIT I BASICS OF C PROGRAMMING
Introduction to programming paradigms - Structure of C program - C programming: Data
Types – Storage classes - Constants – Enumeration Constants - Keywords – Operators:
Precedence and Associativity - Expressions – Input/Output statements, Assignment statements
– Decision making statements - Switch statement - Looping statements – Pre processor
directives - Compilation process

UNIT II ARRAYS AND STRINGS


Introduction to Arrays: Declaration, Initialization – One dimensional array – Example
Program: Computing Mean, Median and Mode - Two dimensional arrays – Example Program:
Matrix Operations (Addition, Scaling, Determinant and Transpose) – String operations: length,
compare, concatenate, copy – Selection sort, linear and binary search.

UNIT III FUNCTIONS AND POINTERS


Introduction to functions: Function prototype, function definition, function call, Built-in
functions (string functions, math functions) – Recursion – Example Program: Computation of
Sine series, Scientific calculator using built-in functions, Binary Search using recursive
functions – Pointers – Pointer operators – Pointer arithmetic – Arrays and pointers – Array of
pointers – Example Program: Sorting of names – Parameter passing: Pass by value, Pass by
reference – Example Program: Swapping of two numbers and changing the value of a variable
using pass by reference.

UNIT IV STRUCTURES AND UNIONS


Structure - Nested structures – Pointer and Structures – Array of structures – Example Program
using structures and pointers – Self referential structures – Dynamic memory allocation -
Singly linked list - typedef.-Union.

UNIT V FILE PROCESSING


Files – Types of file processing: Sequential access, Random access – Sequential access file -
Example Program: Finding average of numbers stored in sequential access file - Random
access file - Example Program: Transaction processing using random access files – Command
line arguments.

1
CS3251- PROGRAMMING IN C

INTRODUCTION TO PROGRAMMING PARADIGMS:


Programming paradigms are a way to classify programming languages based on their features.
Languages can be classified into multiple paradigms.
Major programming paradigms are:
1. Imperative
2. Logical
3. Functional
4. Object-Oriented
Imperative programming paradigms:
- In imperative programming paradigm , Computations are performed through a guided
sequence of steps, in which the variables are referred to or changed.
- The order of the steps is crucial, because a given step will have different consequences
depending on the current values of variables when the step is executed.
- Popular programming languages are imperative more often than they are any other
paradigm studies in this course. There are two reasons for such popularity:
 The imperative paradigm most closely resembles the actual machine itself, so the
programmer is much closer to the machine;
 Because of such closeness, the imperative paradigm was the only one efficient
enough for widespread use until recently.
Advantages
o Efficient
o close to the machine
o Popular
o Familiar.
Disadvantages
o The semantics of a program can be complex to understand or prove.
o Side effects also make debugging harder;
o Abstraction is more limited than with some paradigms;
o Order is crucial, which doesn't always suit itself to problems.
Logical programming paradigms:
- The Logical Paradigm takes a declarative approach to problem-solving.
- Various logical assertions about a situation are made, establishing all known facts.
- Then queries are made. The role of the computer becomes maintaining data and logical
deduction.
- A logical program is divided into three sections:
 a series of definitions/declarations that define the problem domain
 statements of relevant facts
 statement of goals in the form of a query
Advantages:
The advantages of logic oriented programming are

2
CS3251- PROGRAMMING IN C

o The system solves the problem, so the programming steps themselves are kept to a
minimum;
o Proving the validity of a given program is simple.
3. Functional programming paradigms:
- The Functional Programming paradigm views all subprograms as functions in the
mathematical sense-informally, they take in arguments and return a single solution.
- The solution returned is based entirely on the input, and the time at which a function is
called has no relevance.
- The computational model is therefore one of function application and reduction.
Advantages:
o Higher level of abstraction
o The lack of dependence on assignment operations
o Possess referential transparency.
Disadvantages
o Perhaps less efficiency
o Problems involving many variables or a lot of sequential activity are sometimes easier
to handle imperatively or with object-oriented programming.
4. Object-Oriented
- Object Oriented Programming (OOP) is a paradigm in which real-world objects are
each viewed as separate entities having their own state which is modified only by built
inprocedures, called methods.
- Because objects operate independently, they are encapsulated into modules which
contain both local environments and methods. Communication with an object is done
by message passing.
- Objects are organized into classes, from which they inherit methods and equivalent
variables. The object-oriented paradigm provides key benefits of reusable code and
code extensibility.
Benefits and Features:
o A new class (called a derived class or subclass) may be derived from another class
(called a base class or superclass) by a mechanism called inheritance. The derived
class inherits all the features of the base class: its structure and behavior(response to
messages.
o Inheritance gives OOP its chief benefit over other programming paradigms - relatively
easy code reuse and extension without the need to change existing source code.Also,
encapsulation and information hiding are inherent benefits of OOP.
INTRODUCTION TO C PROGRAMMING:
- C is a general-purpose computer programming language developed in 1972 by Dennis
M. Ritchie at the Bell Telephone Laboratories to develop the UNIX Operating System.
- C is also called mother Language of all programming Language. It is the most widely
use computer programming language.
- All other programming languages were derived directly or indirectly from C
programming concepts.
3
CS3251- PROGRAMMING IN C

- This language is used for develop system software and Operating System.
Features of C:

Simplicity:
- It is very easy to understand.
Portability:
- It is the concept of carrying the instruction from one system to another system
Powerful:
- C is a very powerful programming language, it have a wide verity of data types,
functions, control statements, decision making statements, etc
Structure oriented:
- Structure oriented programming language aimed on clarity of program, reduce the
complexity of code, using this approach code is divided into sub-program/subroutines.
These programming have rich control structure.
Modularity
- In c programming we can break our code in subprogram.
Middle level language:
- C programming language can supports two level programming instructions with the
combination of low level and high level language that's why it is called middle level
programming language
Compiler based:
- C is a compiler based programming language that means without compilation no C
program can be executed
Syntax based language
- C is a strongly tight syntax based programming language.
Efficient use of pointers
- Pointers is a variable which hold the address of another variable, pointer directly direct
access to memory address of any variable due to this performance of application is
improve
Uses(Applications) of C language:

4
CS3251- PROGRAMMING IN C

 To Design Operating system


 To Design Language Compiler and Interpreter
 To Design Database
 Language Interpreters
 Utilities
 Network Drivers
 Assemblers
 UNIX Kernel is completely developed in C Language.

STRUCTURE OF A ‘C’ PROGRAM


Simple C Program:
/* Simple C program to display the text */
#include<stdio.h>:
int main()
{
printf(“good morning\n”);
return(0);
}
/*……..*/
A comment starts with star and asterisk /* and ends with asterisk and start */ .
comment lines used to give description and it is ignored by compiler during execution.
#include<stdio.h>
This <stdio.h> is called header file that has functions used for reading input and
generating output.
In order to use printf function, we need to include the required file in our program
using #include preprocessor.
int main()
C program consists of functions with required main() function as a entry point of
program. It is where, actual execution starts.
A program can have only one main function and any number of sub functions.
Curly brackets { …. }
Indicates block of code.
we can have statements inside the brackets to determine what the function does when
executed.
printf(“good morning\n”);
printf is a build-in functions which is used to display output in the screen.
\n is called escape sequence to go to next line It always begin with \ (back slash).
Semicolon(;)
It is used to terminate the statement.
return(0);
- This statement terminates the main function.

5
CS3251- PROGRAMMING IN C

- Returns the value 0 to the operating system indicating Successful completion of


program.
- Any other number indicates that the program is failed.

Fig, Structure of C program


Documentation Section
o This section consists of set of comment lines which gives the name of programmer and
other details like time and date of writing the program.
o Comment lines used to give description and it is ignored by compiler during
execution.
o Documentation section helps anyone to get an overview of the program.
There are two types of comments.
Single line comment (// program for addition)
Multiple line comment(/* ……..*/)
Link Section
- The link section consists of the header files of the functions that are used in the
program.
- It provides instructions to the compiler to link functions from the system library.
- Some of the header files are,
#include<stdio.h>
#include<conio.h>
#include<math.h>
Here, #include is the preprocessor directive.
Definition Section
All the symbolic constants are written in definition section.
Macros are known as symbolic constants.
Ex: #define PI 3.14
Global Declaration Section

6
CS3251- PROGRAMMING IN C

The variables that are used in more than one function throughout the program are called
global variables. Global variables declared outside of all the functions.
main() Function Section
Every C program must have one main() function, which specifies the starting point of ‘C’
program.
Main function contains two parts,
i. Declaration part
ii. Executable part
 The declaration part contains all the variables that are used in executable part.
 These two parts must be written in between the opening and closing braces.
 Each statement in the declaration and executable part must end with a semicolon (;).
 The execution of program starts at opening braces“{”and ends at closing braces“}”.
Subfunction(Sub program) Section
Subprogram section contains all the user defined functions that are placed after the main
function.

‘C’ CHARACTER SET


Character set is a set of alphabets, letters and some special characters that are valid in C
language.
The basic character set of C language includes,
2 types :
(i)Source Character Set :
Uppercase letters: A, B,C….Z.
Lowercase letters: a, b, c……z.
Digits: 0 to 9.
Special characters: , . : ; “ # % & ( ) { } [ ] | \/ _ ^~ +,-,~&,!,/,\,*@,etc.
White spaces characters int age; // balnk space between int and age is ignored by
compiler. It is used to distinguish the aqw.
(ii)Execution Character set:
Horizontal tab \t
Vertical Tab \v
New line character \n
Null Character \0

C TOKENS:
 C tokens are the basic buildings blocks in C language which are constructed together to
write a C program.

7
CS3251- PROGRAMMING IN C

IDENTIFIERS:
Identifiers are the name used to identify entities like variable, function, array, structure or any
other user-defined item.
Identifier must be unique.
They are created to give unique name to an entity to identify it during the execution of the
program.
Rules for naming an Identifier
 Identifier name in C can have letters, digits or underscore(_).
 The first character of an identifier name must be a alphabet (a-z, A-Z),underscore( _ ).
 The first character of an identifier cannot be a digit.
 Keywords are not allowed to be used as Identifiers.
 No special character (except underscore) blank space and comma can be used in
Identifier name.
KEYWORDS
 Keywords are reserved words that have a particular meaning in C language.
 The meaning of key word is predefined. These meaning of the keyword cannot be
changed.
 There are total 32 keywords in C language.

VARIABLES:
 It is a name given to the memory location.
 In programming, a variable is a container (storage area) to hold data.
 To indicate the storage area, each variable should be given a unique name called
identifier.

Rules to define variable name


 Variable name in C can have letters ( A – Z ), ( a – z ), numbers and underscore (_),
Digits ( 0 – 9 )
8
CS3251- PROGRAMMING IN C

 No Special Symbols like blank space and Commas are allowed in variable name.
 First Character should be alphabet or underscore and not a number.
 Variable name should not be keyword.
 The maximum number of character(31 characters) is allowed in a variable and it
depends on a compiler.
2 steps:
(i)variable declaration
- Declaration of variables must be done before they are used in the program.
- Declaration does two things.
It tells the compiler , the name of the variable.
It specifies what type of data the variable will hold.
Syntax:
datatype variable;
Example:
int number;
char a;
float price;
char name[20];
(ii)variable initialization
- Initialization is done using assignment operator(=). Also, we can assign the value to the
variable during declaration itself.
If no input values are assigned(initialized) by the user , then the system will give a
default value to the allocated memory which is called garbage value.
Example,
int a=20;

L-Value: R-Value
L- Value Is An Object Locator. R-value refers to ‘Read Value’.
L-Value Stands For Left Value
The L-Value Could Legally Stand On The Left Side R-value can be anything of following:
Of An Assignment Operator. 1.Variable
For Example: Mark=20; // 2.Function
The L- Value Should Be A Variable. 3. Constant
Eg,
num=20; //constant R value
num=20+20; //constant R value
Expression

9
CS3251- PROGRAMMING IN C

L value cannot be a constant and cannot be a datatype.


Eg, 5=num; //Error
int=num;
Example:
Addition of two numbers: Output:
#include< stdio.h> Sum is 100
int main()
{
int a,b,c; //Variable declaration
a=50; //Assigning values to variables
b=50;
c=a+b;
printf("sum is %d",c);
return(0);
}
Variable definition=variable declaration + memory reservation

Scope of variable(Types of variable):


Variable Scope is a region in a program where a variable is declared and used.
i. Local Variable - Variables that are declared inside a function or a block are
called local variables and are said to have local scope.
We can use (or access) a local variable only in the block or function in which it is
declared. It is invalid outside it.
ii. Global Variable:- Variables that are defined outside of all the functions and are
accessible throughout the program are global variables.
It is declared above the main function.
Example:(program using local and gloab Output:
variable) Value of a : 10
#include<stdio.h> Value of b : 20
int a=10; // global variable
int main()
{
int b=20; // local variable
printf("Value of a : %d\n",a);
printf("Value of b : %d\n",b);return(0);}

10
CS3251- PROGRAMMING IN C

DATA TYPES :
 Data types determines the possible values that an identifier can have and the valid
operations that can be applied on it.
 The type of a data determines how much space it occupies in storage.
 In C Language, data types are broadly classified as

Basic/Primitive data types:


1. Character – char
2. Integer - int
3. Floating point – float
4. Double– double
5. No value available – void

1.Basic(Primitive) data types


Integer type:
 Integers are whole numbers that can have both positive and negative values but
no decimal values.
 Keyword for integer is int.
 Size of en integer is 2 bytes or 4 bytes.
 Size of the datatype change with respect to the processor used.
Type Size(bytes) Range
int or signed int 2 -32,768 to 32767
unsigned int 2 0 to 65535
short int or signed short int 1 -128 to 127
long int or signed long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
Floating type
 Float data type is used to store real numbers.

11
CS3251- PROGRAMMING IN C

 Key word is float. The size of floating point number is 4 bytes.


 If the accuracy is not sufficient in floating point, the double data type can be used to
define the number.
 Eg, float height=5.5
Range values are given for 16 bit processor.
Type Size(bytes) Range
Float 4 3.4E-38 to3.4E+38
Double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932
Character type
- Character denotes any alphabet, digit or special symbol to represent information.
- Key word is char.
- Size of character is 1 byte. Eg, char a=‘h’;
Type Size(bytes) Range
char or signed char 1 -128 to127
unsigned char 1 0 to 255
void type
- void means no value.
- This is usually used to specify the type of functions.
Data type modifiers:
It is nothing but modifying the memory space allocated to the variable.
Types:
1. Signed(signed)
2. Unsigned(unsigned)
3. Short(short)
4. Long(long)
Integers and floating point variables can hold both negative and positive values.
Sign modifiers Size modifiers
Signed Unsigned short long
signed keyword unsigned keyword In general int data type It is used to increase
accepts both negative accepts only occupies different the size of the current
or positive value. positive values. memory spaces for a data type to 2 more
.(It is the default different operating bytes.
integer data type). system;
To allocate fixed
memory space short
keyword can be used.
Example: Example: For example: For Example:
signed int number; unsigned int rate; short int a; long int a;
or
int number;
12
CS3251- PROGRAMMING IN C

2. User-defined Data Types


The C language provides flexibility to the user to create new data types. These newly created
data types are called user-defined data types. The use-defined data types in c can be created by
using:
1. typedef
2. Enumeration
typedef:
- typedef keyword is used to give new name to the existing data type..
Syntax:
typedef datattype
variable
In the below program, rollno is the variable name (alias)given to the existing datatype int. So,
after this type definition, roll no can be used instead of datatype int.
Example (using typedef): Output:
#include<stdio.h> Roll number1 is 4001
int main() Roll number2 is 4002
{
typedef int rollno;
rollno num1 = 4001,num2 = 4002;
printf("Roll number1 is %d\n",num1);
printf("Roll number2 is %d\n",num2); return(0); }

Enumerated data type:


- enum is a keyword used.
- It is mainly used to assign the names to integral constants ,as the names make a program
easy to read and maintain.
- The compiler assigns integer values starting from 0 and further increments by 1 for all
enum values(contants values ).
- We can also assign value to the enum constants if we need.
Syntax:
enum variable {value1, value2,.... Value n};
Default Numeric value assigned to first enum value is “0”.
Example: Example(using enum Example 2:
datatype): #include<stdio.h>
#include<stdio.h> main()
main() {
{ enum
enum month{JAN, FEB, month{JAN,FEB=5,MARCH,A
MARCH, APRIL, MAY}; PRIL=2, MAY,JUNE=3,
enum month m1; JULY};
m1=APRIL; enum month m1;
13
CS3251- PROGRAMMING IN C

printf("%d",m1);} m1=MAY;printf("%d",m1);}
Output: Output:
3 3
Explanation: Explanation:
In this example, we Integers are assigned to enum
declared “m1” as the constants.
variable and the value of
“APRIL” is allocated to
m1, which is 3.
3.Derived data types
These data types are derived from the basic data types. Derived data types available in c are:
Array
Structure
Union
Pointer
Type conversion (Type casting):
- A type cast is basically a conversion from one type to another.
There are two types of type conversion:
Implicit Type Conversion (Also known as ‘automatic type conversion’):
- This Implicit conversion is done by the compiler on its own, without any
knowledge to the user.
- Generally type casting takes place when in an expression is having more than one
data type in it.
- Here, It is best practice to convert lower data type to higher data type to avoid
data loss. Because, Data will be truncated when the higher data type is converted
to lower. For example, if a float is converted to int, data which is present after
the decimal point will be lost.
- Hence, Compiler convers all operands into datatype of the largest operand.
bool-> char-> short int -> int -> unsigned int -> long -> unsigned -> long long ->float ->
double -> long double
Example 1:(implicit typecasting) Example 2: :(implicit typecasting)
#include<stdio.h> #include <stdio.h>
main() main() {
{ int i = 17;
int a=10; char c = 'c';
float b=6.1; float sum;
float c; sum = i + c; /* ascii value is 99 */
c=a+b; /*integer value 10 is converted to float value as printf("%f\n", sum );
10.0 automatically*/ }
printf("%f",c); Output:
} 116.000000

14
CS3251- PROGRAMMING IN C

Output:
16.100000
Explicit Conversion(Type casting):
The type conversion performed by the programmer by specifying the data type in the
expression.
Data type should be mentioned before the variable name or value.
Syntax:
(data type)expression
Example1: Example2: :(Explicit typecasting)
#include <stdio.h> #include <stdio.h>
main() main()
{ {
int x=13, y=5 ; int x=13, y=5 ;
float z; float z;
z=x/y; // here, quotient is int datatype and it is z=(float)x/y; // int data type is converted to
stored in float variable float and float value(quotiemt) is stored in
printf("%f",z); float variable
} printf("%f",z);
Output: }
2.000000 Output:
2.600000

STORAGE CLASS:
A storage class defines the scope (visibility) and life-time of variables.
Scope - Where to store a variable (Storage area of variable)
Lifetime- How long the variable can be stored in the memory( alive)
The following storage classes are most often used in C programming.
1.auto 2.static
3.extern 4.register
A variable should be declared in any one of these four storage class.
1.auto storage class:
- auto is the default storage class.
- It is stored in RAM(main memory)
Scope: It can be used only in the block of code where it is declared.(local variable)
Lifetime: It will be alive only inside the block of code where it is declared.
Default value is Garbage Value

Syntax: Example:
auto data_type variablename; (or) auto int a;

15
CS3251- PROGRAMMING IN C

data_type variable; int a;


(both are same since auto is
default storage class )
To print the value using auto storage Output:
class: Value of a is: 11
#include<stdio.h> Value of a is: 11
int main() Value of a is: 11
{
increment();
increment();
increment();
}
int increment()
{
auto int a=10;
a++;
printf("Value of a is: %d\n", a);
}

2.Static Storage class:


Scope: It can be used only in the block of code where it is declared.(local variable)
Lifetime: It can be used throughout the program. That means, the variable will be alive
until the program completes its execution.
Default value is 0.
Syntax: Example:
static data_type variablename; static int a;
To print the value using static storage Output:
class: Value of a is: 11
#include<stdio.h> Value of a is: 12
int main() Value of a is: 13
{
increment();
increment();
increment();
}
int increment()
{
static int a=10;
a++;
printf("Value of a is: %d\n", a);
}
3.Extern Storage Class:
- This process is similar to storing global variable.
- When extern keyword is used, the compiler will come to know that somewhere in the
program , variable is declared or initialized(may be outside or inside the function,etc).
16
CS3251- PROGRAMMING IN C

Scope: Variable can be accessed from anywhere in the program.


Lifetime: It can be used throughout the program. That means, the variable will be alive
until the program completes its execution.
Default Value is 0.
Note: Memory occupied by the variable will be released only after completion of the program.
Syntax: Example:
extern datatype variablename; extern a=10;
Printing the value of the variable using extern storage class.
#include<stdio.h> Output:
int main() 3
{ 10
int a=3;
extern int b;
printf("%d\n",a);
printf("%d\n",b);
}
b=10;

4.Register Storage Class:


- Register variables are also local variables, but stored in register memory.
Whereas, auto variables are stored in main CPU memory.
- These data objects will have a local life time.
- They have to be initialized implicitly otherwise they will have a garbage value.
Advantages: The register variables are faster than remaining variables, because register
variable are stored in register memory in the processor and not in main memory..
Limitation: But, only limited variables can be used as register since register size is very low.
(16 bits, 32 bits or 64 bits).
Scope: It can be used only in the block of code where it is declared.(local variable)
Lifetime: It will be alive only inside the block of code where it is declared.
Default value is Garbage Value
Only difference between auto and register the storage place(RAM/Register)

Syntax: Example:
register data_type variablename; register int a;
Printing the value of the variable using register storage class Output:
#include<stdio.h> Value of a is 11
int main() Value of a is 11
{ Value of a is 11
increment();
increment();
increment();

17
CS3251- PROGRAMMING IN C

}
int increment()
{
register int a=10;
a++;
printf("Value of a is: %d\n", a);
}
Properties of Storage Class:

CONSTANTS (LITERALS):
Constants are the values that cannot be changed during the execution of a program.
Constant is a fixed value which may be an integer, floating point number, character or a string.
Types of constants:

 Integer constants:
- Integer constants are integer values like -1, 2, 8 without any decimal point.
- It can be either positive or negative. If no sign proceeds an integer is assumed to be
positive.
There are three types of integer constants in C language:
- Decimal constant (base 10)
- Octal constant (base 8)
- Hexadecimal constant (base 16)
18
CS3251- PROGRAMMING IN C

 Floating-point constants:
- Floating point constants can be written in fractional form or exponential form. Floating
point constant are values like -23.1, 12.8, -1.8e12.
- The floating point constant in an exponential form has two parts: The mantissa part
and the exponent part. Both parts are separated by e or E.

 Character constants:
- Character constants can have one character enclosed within single quotes.
- For example: 'a', 'l', 'Y', 'A' etc.
Escape Sequences
- C supports some special character constants that are used in output functions.
- Escape sequence consists of a backward slash (\) followed by a character.

Escape Sequences Character


\n Newline
\a Alert
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\0 Null character
 String constants
- String constant can have group of characters enclosed within double quotes.
For example: “hai”, “welcome”
Declaring a variable as constant:
Syntax:
const datatype variable = constant
Example:
const float PI=3.14;
Program using const Output To find area of rectangle Output
keyword: error using const keyword. area : 70
#include<stdio.h> [const value #include <stdio.h>
int main() cannot be changed. int main()
{ {
19
CS3251- PROGRAMMING IN C

const int a=10; const int LENGTH = 10;


printf("%d",a); const int WIDTH = 5;
a=20; int area;
return(0); area = LENGTH * WIDTH;
} printf("area : %d", area);
return(0);
}

OPERATORS IN C:
Operands:
 An operand specifies an entity on which an operation is to be performed.
 An operand can be a variable name, constant, a function call.
Operators:
 Operators are special symbol that tells the compiler to perform specific mathematical or
logical operations.
 Operator specifies the operation to be applied to its operands.
CLASSIFICATION OF OPERATORS:
The operators in c are classified on the basis of the following criteria:
1. The number of operands on which an operator operates.
2. The role of an operator.
Classification based on Number of Operands
Based upon the number of operands on which an operator operates,operators are classified
as,
Unary operator: Binary operator ternary operator
A unary operator operates Binary operator operates Ternary operator operates on three
on only one operand. on two operands. operands. (Conditional operator)
Eg, Eg: Eg,
-3. Here the – is an unary 2-3. Here (-) acts as a ?: is a ternary operator
minus operator. binary operator.
Classification based on role of operator
Based upon their role operators are classified as:
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bitwise operators
6. Increment /Decrement operators
7. Conditional operator
8. Special operators
Arithmetic operators
Arithmetic operations like addition, subtraction, multiplication, divisions, etc. The arithmetic
operators available in c are given here.
20
CS3251- PROGRAMMING IN C

Operato Description Eg Program Output:


r
+ adds two operands a+b #include<stdio.h> 13
- subtract second operands from a-b int main() -3
first { 40
* multiply two operand a*b int a=5,b=8; 0
/ divide numerator by denominator, a/b printf("%d\n",a+b); 40
gives quotient as result printf("%d\n",a-b);
% divide numerator by denominator, a%b printf("%d\n",a*b);
gives remainder as result printf("%d\n",a/b);
printf("%d\n",a*b);
}
Assignment Operators
A variable can be assigned a value by using an assignment operator. The assignment operators
are available in c are given below.
Operator Description Example
= assigns values from right side operands to left side operand a=b
+= adds right operand to the left operand and assign the result to a+=b is same as
left a=a+b
-= subtracts right operand from the left operand and assign the a-=b is same as a=a-b
result to left operand
*= multiply left operand with the right operand and assign the a*=b is same as
result to left operand a=a*b
/= divides left operand with the right operand and assign the a/=b is same as a=a/b
result to left operand
%= calculate modulus using two operands and assign the a%=b is same as
result to left operand a=a%b
Example: Output:
#include <stdio.h> c=5
int main() c=10
{ c=5
int a = 5, c;
c=25
c = a;
printf("c=%d \n", c); c=5
c += a; c=0
printf("c=%d \n", c);
c -= a;
printf("c=%d \n", c);
c *= a;
printf("c=%d \n", c);
c /= a;
printf("c=%d \n", c);
21
CS3251- PROGRAMMING IN C

c %= a;
printf("c=%d \n", c); return 0;
}

Relational operators:
- Relational operators are used to check the conditions.
- If the relation is true, it returns 1; if the relation is false, it returns value 0.
- The operand may be variables, constants or expressions.
Operator Description Example program Output
:
== Check if two operand are equal #include<stdio.h> 0
!= Check if two operand are not equal. int main() 0
> Check if operand on the left is { 1
greater than operand on the right int a=5,b=8; 0
< Check operand on the left is smaller printf("%d\n",a==b); 1
than right operand printf("%d\n",a>b); 1
>= check left operand is greater than or printf("%d\n",a<b);
equal to right operand printf("%d\n",a>=b);
<= Check if operand on left is smaller printf("%d\n",a<=b);
than or equal to right operand printf("%d\n",a!=b);
}
Logical operators:
- Logical operators are used to combine the results of two or more conditions. C has the
following logical operators.
Op Description Example a=5, b=2
erator
&& Logial AND. True only if all operands are true ((a == 5) && (b > 5)) equals to 0.
|| Logical OR. True only if either one operand is true ((a == 5) || (b > 5)) equals to 1.
! Logical NOT. True only if the operand is 0 ! (a == 5) equals to 0.
Note: 1 represents true and 0 represents false.
Example: Output:
#include <stdio.h> 0
int main() 1
{ 1
int a=5,b=7,c=2;
printf("%d\n",((a==b)&&(a==c)));
printf("%d\n",((a==b)||(a>c)));
printf("%d\n",(!(a==b)));
}
Bitwise operators:
- Bitwise operators perform manipulations of data at bit level.
- It operates on individual bits of the operands.
- Bitwise operators are not applicable for float or double data types.

22
CS3251- PROGRAMMING IN C

- The Truth table for &, | and ^ operation.


A B A &B A| B A^B
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Assume A = 60 and B = 13 .
In binary format, A= 0011 1100 and B = 0000 1101
Operator Description A= 0011 1100 and B = 0000 1101
& Bitwise AND (A & B) = 12, i.e., 0000 1100
| Bitwise OR (A | B) = 61, i.e., 0011 1101
^ Bitwise exclusive OR (A ^ B) = 49, i.e., 0011 0001
~ Bitwise Complement (~A ) = -60, i.e,. 1100 0100 in 2's
complement form.
<< left shift A << 2 = 240 i.e., 1111 0000
>> right shift A >> 2 = 15 i.e., 0000 1111

Increment operator/decrement operator:


Increment operator:
- Increment operator is used to increment the value by adding 1.
- The value of i++ is equal to i=i+1.
Syntax:

Increment operator can be classified into two types.


pre increment operator
post increment operator
Pre increment operator: Post increment operator:
First the value of operand is The value of operand is used for the
incremented by 1 and then it is used evaluation of the expression and then it
for evaluation of the expression. is incremented.
For example: ++i For example: i++.
Decrement operator:
- Decrement operator is used to decrement the value by subtracting 1.
- The value of i-- is equal to i=i-1.
Decrement operator can be classified into two types.
pre decrement operator
post decrement operator

23
CS3251- PROGRAMMING IN C

Pre decrement operator: .Post decrement operator:


First the value of operand is The value of operand is used for the
decremented by 1 and then it is used evaluation of the expression and then it
for evaluation of the expression. is decremented.
For example: --i For example: i--.

Example: Preincrement: Postincrement:


#include <stdio.h> #include<stdio.h> #include<stdio.h>
int main() int main() main()
{ { {
int i=10; int x,i; int x,i;
printf("%d\n",i++); i=10; i=10;
printf("%d\n",++i); x=++i; x=i++;
printf("%d\n",i--); printf("x:%d\n",x); printf("x: %d\n",x);
printf("%d\n",--i); printf("i:%d\n",i); printf("i: %d\n",i);
} return(0); return(0);
Output: } }
10 Output: Output:
12 x:11 x: 10
12 i:11 i: 11
10

Special Operator:
Operator Description Example
Sizeof Returns the size of an variable sizeof(x);
& Returns the address of an variable &x ;
* Pointer to a variable *x ;

Example: Output:
#include <stdio.h> Size of integer is 2
int main() Size of Float value is 4
{ Size of character is 1
int a;float b;char c;
printf("Size of integer is %d\n", sizeof(a));
printf("Size of Float value is %d\n", sizeof(b));
printf("Size of character is %d\n", sizeof(c));
}
Conditional operator:
Conditional operator is the ternary operator.
Syntax:
Condition? Expression 1: Expression 2
Condition: condition is checked first. This expression evaluates to 1 if it's true and evaluates
to 0 if it's false.
24
CS3251- PROGRAMMING IN C

Expression1: If the condition is true, this expression is evaluated and return the result of
Expression1.
Expression2: If the condition is false, this expression is evaluated.
Advantages of ternary operator:
Using ?: reduce the number of line codes and improve the performance of application.
Example 1: Use of ternary Example 2: Use of ternary operator
operator
#include <stdio.h> #include<stdio.h>
int main() main()
{ {
int a=89,b; int a=10,b=20,small;
b=(a ==100?1:2); printf((a<b ? printf("a is less") : printf("a is greater")));
printf("%d\n",b);return(0); return(0);
} }
Output: Output:
2 a is less

PRECEDENCE OF OPERATORS:(Associativity)
 Each operator in c has a precedence associated with it..
 High precedence operator *, /,%.
 Low precedence operator +, -.
Precedence rule: This rule decides the order in which different operators are applied.
Associativity rule: This rule decides the order in which multiple occurrence of the same level
operators are applied.
 Several operators of the same precedence appear together, the operator are evaluated
according their associativity.
 If the operators are left-to-right associative, they are applied in left-to –right
order.
 If the operators are right-to-left associative, they are applied in right-to-left order.
 This table lists C operators in order of precedence (highest to lowest) and their
associativity.
Operator Description Associativity
() Parentheses (function call) left-to-right
[] Brackets (array subscript)
Increment right-to-left
++
decrement
--
Unary plus
+
unary minus
-
Address of operator
&
Determine size in bytes on this
sizeof
implementation

25
CS3251- PROGRAMMING IN C

* Multiplication left-to-right
/ Division
% Modulus
+ Addition left-to-right
- Subtraction
< Relational less than operator left-to-right
<= less than or equal to operator
> Relational greater than
>= greater than or equal to
== Relational is equal to left-to-right
!= is not equal to
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Simple Assignment right-to-left
+= assign addition
-= Assign subtraction
*= Assign multiplication
/= Assign division
%= Assign modulus
, Comma operator left-to-right
Examples:
a=9-12/3+3*2-1 int a; a=2*3+4%5-3/2+6 int a= 5+7*4-9*(3,2)
a=? a=2*3.25+((3+6)/2) a=? a=?
a=9-4+3*2-1 a=? a=6+4-3/2+6 a= 5+7*4-9*2
a=9-4+6-1 a=2*3.25+9/2 a=6+4+1+6 a=5+28-18
a=5+6-1 a=6.50+4 a=10-1+6 a=33-18
a=11-1 a=10.50 a=9+6 a=15
a=10 a=10 a=15
(because ‘a’ is an integer)

26
CS3251- PROGRAMMING IN C

b=4*6+3*4<3?4:3 a=2,b=12,c=1 find m=?


b=? d=a<b>c m=-43||8&&0||-2
b=24+3*4<3?4:3 d=2<12>1 d=1>1 m=-43||0||-2
b=24+12<3?4:3 d=0 m=1||-2
b=36<3?4:3 m=1
b=3

EXPRESSIONS:
Expressions:
An expression is a sequence of operands and operators.
The meaningful expression consists of one or more operands or operators that specify
the operations to be performed on operands.
Example: a+b, a-b.
Operands:
An operand specifies an entity on which an operation is to be performed.
Operators:
Operators are special symbol that tells the compiler to perform specific mathematical or logical
operations.
Operator specifies the operation to be applied to its operands.
Based on the number of operators present in an expression, expressions are classified as
simple expression and compound expressions.
Simple expressions:
An expression that has only one operator is known as a simple expression
For example: a+2;
Compound Expressions:
An expression that has more than one operator is known as compound expressions.
For example: b= 2+3*5;
INPUT AND OUTPUT STATEMENTS:
In c language two types of input/output statements are available. They are
1. Formatted input/output statements
2. Unformatted input/output statements

27
CS3251- PROGRAMMING IN C

FORMATTED INPUT AND OUTPUT STATEMENTS:


Formatted input and output refers to input and output, that has been arranged in a particular
format.
It read and writes all types of data values.

scanf() statement:
 scanf() is a built-in library function in c.
 It is a standard input function used to read inputs from the user during execution of the
program.
Syntax:
scanf(“control strings”,&variable1,&variable2….&variable);
Control strings(Format Specifier):
- Control string is the type of data that the input statement going to accept, this
always preceded with a % sign.
- Each variable name must be preceded by an ampersand (&).
- & is the address of operator which gives the address of variable.
- It is built in function defined in the <stdio.h> header file.
- The given table lists some control strings with its meaning.
Format specifier Meaning
%c Single character
%s String
%d Integer
%f Float
%ld Double
scanf() for integer data type(%d)
Example:
scanf(“%d”,&a);
- here, a is a variable holding integer value.
- %d is the integer format specifier to represent integer data.
- ‘&’ symbol is used to represent the memory address of the variable.
scanf() for float data type(%f)
Example:
scanf(“%f”,&b);
- here, b is a variable holding float or fractional value.
- The format specifier %f indicates floating or fractional data.
scanf for character data type(%c)
Example:
scanf(“%c”,&ch);
28
CS3251- PROGRAMMING IN C

- here ch is the character datatype.


- %c is the character format specifier to represent character.
scanf for string(%s)
Example:
scanf(“%s”,name);
- here name is the string datatype.
- %s is the string format specifier to represent string data.
Rules for writing scanf function:
o scanf() statement should end with a semi colon (;). This indicates the compiler that it is
the end of the statement..
o The format specifiers should always be placed in between double quotes (“ ”).
o Separate the variables using comma (,)
o Always use a right format specifier while using scanf() function in C.
o Always use the exact data type of the variable for reading the data.
o As C is a case sensitive language, capital letters are not used while writing scanf()
function.
printf() statement:
 It is used to display the output to the screen.
 printf is used to print the message or value.
 It is builtin function defined in the stdio.h header file.
2 ways of using printf statement:
(i) printf() can print text on the screen without using any format specifier.
Syntax:
printf(“string”);
Example:
printf(“hello my dear friend”);
(ii) printf() is used to print the value of the variable and results of the expressions.Using
format specifier
Syntax:
printf(“control string”, variable1,variable2..);
Example:
printf(“my age is %d”, age)
Control strings(Format Specifier):
- Control string is the type of data that the input statement going to accept, this always
preceded with a % sign.
printf() for integer datatype:
Example:
printf(“%d%d”,a,b); // here a and b variables holding integers.
printf() for float datatype:
Example:
printf(“%f%f”,a,b); //here a and b are variables holding float values.
29
CS3251- PROGRAMMING IN C

printf for character datatype:


Example:
printf(“%c”,ch); //here ch is the character datatype.
printf for string:
Example:
printf(“%s”,name); //here name is the string datatype.
Rules for writing printf statement:
1. The message which is to be printed should be placed in between double quotes (“ ”).
2. The printf() function should follow a semi colon at the end.
3. Separate the format specifiers and variables using comma (,).
Use of printf() and scanf() functions in C: Output:
#include<stdio.h> Enter any character:
int main() s
{ Entered character is s
char ch; Enter any string:
char str[100]; anitha
int num; Entered string is anitha
printf("Enter any character:\n"); Enter the number
scanf("%c", &ch); 301
printf("Entered character is %c \n", ch); entered number is 301
printf("Enter any string: \n");
scanf("%s", str);
printf("Entered string is %s \n", str);
printf("Enter the number\n");
scanf("%d",&num);
printf("entered number is %d:",num);
return(0);
}
Program to add two numbers:
#include<stdio.h
int main() Output:
{ Enter two numbers:
int a,b,c; 2
printf("Enter two numbers:\n"); 2
scanf("%d%d",&a,&b); Sum of entered
c = a + b; numbers is 4
printf("Sum of entered numbers is %d\n",c);
return(0);
}
Program to print student details:
#include<stdio.h> Output:
int main() enter the roll no,mark1,
{ mark2,mark3,name
int rollno,m1,m2,m3; 1001 95 85 95 george
char name[20]; Roll no is 1001
float total,percentage; Name is george
30
CS3251- PROGRAMMING IN C

printf("enter the roll no,mark1,mark2,mark3,name\n"); Marks Obtained is 958595


scanf("%d%d%d%d%s",&rollno,&m1,&m2,&m3,name total marks is 275.000000
); percentage is 91.666664
total=(m1+m2+m3);
percentage=total/3;
printf("Roll no is %d\n",rollno);
printf("Name is %s\n",name);
printf("Marks Obtained is %d%d%d\n",m1,m2,m3);
printf("%total marks is %f\n",total);
printf("percentage is %f\n",percentage);
return(0);
}
Swapping of 2 values using temporary variable: Output:
#include <stdio.h> Enter the value of a and b
int main() 4
{ 5
int a,b,temp; Before Swapping value of a
printf("Enter the value of a and b\n"); and b is: 4 5
scanf("%d%d", &a, &b); After Swapping value of a
printf("Before Swapping value of a and b is: %d and b is: 5 4
%d\n",a,b);
temp=a;
a=b;
b=temp;
printf("After Swapping value of a and b is: %d
%d\n",a,b);
return(0);
}
Swapping of 2 numbers without using temporary variable: Output:
#include <stdio.h> Enter the value of a and b
int main() 4
{ 5
int a,b,temp; Before Swapping value of a
printf("Enter the value of a and b\n"); and b is: 4 5
scanf("%d%d", &a, &b); After Swapping value of a
printf("Before Swapping value of a and b is: %d and b is: 5 4
%d\n",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("After Swapping value of a and b is: %d
%d\n",a,b);
return(0);
}
Program to convert Celsius to Fahrenheit: Output:
#include<stdio.h> Enter the Temperature in
int main () Celcius:10

31
CS3251- PROGRAMMING IN C

{ The Temperature in
float celsius, fahrenheit; Fahrenheit is:50.000000
printf ("Enter the Temperature in Celsius:");
scanf ("%f", &celsius);
fahrenheit = (1.8 * celsius) + 32;
printf ("The Temperature in Fahrenheit is:%f", fahrenheit);
return(0);
}
Program to find slope and midpoint of a line: Output:
#include<stdio.h> Enter the first point x1,y1:
int main () 10
{ 20
float xmp,ymp,x1,y1,x2,y2,slope; Enter the second point
printf ("Enter the first point x1,y1:\n"); x2,y2:
scanf ("%f %f", &x1,&y1); 30
printf ("Enter the second point x2,y2:\n"); 40
scanf ("%f %f", &x2,&y2); Slope is:1.000000
slope=(y2-y1)/(x2-x1); midpoint is:20.000000
xmp=(x1+x2)/2; 30.000000
ymp=(y1+y2)/2;
printf ("Slope is:%f\n", slope);
printf("midpoint is:%f %f",xmp,ymp);
return(0);
}

UNFORMATTED INPUT AND OUTPUT STATEMENTS:


Unformatted I/O functions work only with character data type (char). This is also called
character oriented I/O functions.
There are 2 different types:
o Character I/O
o String I/O
o File I/O
Various functions are,

Input Function Output Function


getchar() putchar()
This function reads one character at a time till This function prints one character on the
the user presses the enter key. screen at a time, which is read by standard

32
CS3251- PROGRAMMING IN C

input.
Syntax: Syntax:
variable name=getchar(); putchar(variable_name);
Example Example:
char c; char c;
c=getchar(); putchar(c );
Program using getchar and putchar function:
#include<stdio.h>
int main()
{
char a;
printf("enter any key");
a=getchar(); // read input and store it in variable ‘a’
putchar(a); //display the output on screen
}
Output:
enter any key
s
s
getch() putch()
- getch() accepts only single character It displays any alphanumeric characters to the
from keyboard. standard output device. It displays only one
- getch() function will just wait for any character at a time.
keyboard input (and press ENTER). It won’t Syntax:
display the given input character in output putch(variable_name)
screen. Example:
Syntax: char a;
variable_name=getch(); putch(a);
Example:
char x;
x=getch();
Program using getch() function:
#include <stdio.h>
int main()
{
printf("Hello World! ");
getch();
return 0;
}
Output:
Hello World!

33
CS3251- PROGRAMMING IN C

getche()
Like getch(), getche() also accepts only single character, but getche() displays the entered input
character in the screen.
Syntax:
Variable_name=getche();
Example:
char x;
x=getche();
To use getch(), getche() functions, you need to include #include <conio.h> header file
which is a non-standard header file.
gets() puts()
- gets() accepts any line of string including puts displays a single / paragraph of text to the
spaces from the standard Input device standard output device.
(keyboard). Syntax:
-gets() stops reading character from keyboard puts(variable_name);
only when the enter key is pressed. Example:
Syntax: char name[25];
gets(variable_name); puts(name);
Example:
char name[25];
gets(name);
Program to read and print the string using
gets and puts:
#include<stdio.h>
main()
{ Output:
char name[20]; enter the string
printf("enter the string\n"); hello my friend
gets(name); hello my friend
puts(name);
return(0);
}

Character Build-in functions:


isalnum(ch)
isalpha(ch)
isdigit(ch)
islower(ch)
isupper(ch)
tolower(ch)
toupper(ch)

34
CS3251- PROGRAMMING IN C

Program to convert character from lower case to uppercase and vice versa:
#include<stdio.h> Output 1:
int main() enter the character
{ g
char a; G
printf("enter the character\n"); Output 2:
a=getchar(); enter the character
if(islower(a)) G
putchar(toupper(a)); g
}
else
{
putchar(tolower(a));
} return(0);
}
Difference Between Formatted And Unformatted Input/Output Functions:
Formatted Unformatted
1. These are standard input output library These are console input output library function.
function.
2. Formatted input and output functions can Unformatted input/output can deal with one
deals with all kind of data types. character at a time and string function for array
of characters (string).
3. Unformatted Input / Output functions Formatted Input / Output functions are several
have fixed format to give the input and standard library functions
obtain the output.

DECISION MAKING( BRANCHING STATEMENTS) IN C:


- Decision making and branching statements are used to decide the order of execution of
statements based on certain conditions.
- Decision making and branching statements are used to transfer the program control from
one point to another.
- They are categorized as
 Conditional statements
 Unconditional statements
Conditional statements:
Conditional statements also known as Selection statements. In this, the program control is
transferred from one point to another based upon the outcome of certain condition. The
following conditional statements are available in C:
1. if statement
2. if-else statement
3. nested if statement
4. else-if ladder
5. switch statements
35
CS3251- PROGRAMMING IN C

1. if statement
 If the condition is true, the statements inside if statement will be executed.
 If the condition is false, the control will be transferred to the statements outside of if.

Program to check the given number is positive Output


#include<stdio.h> Enter the number
int main() 6
{ number is positive
int num;
printf("Enter the number\n");scanf("%d",&num);
if(num>0)
{
printf("number is positive");
}
}
Program to find the purchase value. If >1000, price 200
will deducted from purchase. Output
#include<stdio.h> enter the purchase value50000
int main() deducted amount is 49800
{
int purchase;
printf("enter the purchase value");
scanf("%d",&purchase);
if(purchase>1000)
{
purchase=purchase-200;
}
printf("deducted amount is %d", purchase);
}
2. if...else statement
 In this, else statement can be combined with if statement.
 If Condition is checked first.
 If the condition is true, statements inside the if part is executed
 When the condition is false, statements in else part is executed.

36
CS3251- PROGRAMMING IN C

Program to check vote eligibility Output:


#include<stdio.h> enter your age
int main() 5
{ not eligible to vote
int age;;
printf("enter your age\n"); scanf("%d",&age);
if(age>18)
printf("eligible to vote");
else
printf("not eligible to vote");return(0);
}
Program to find odd or even number Output
#include<conio.h> enter the number
int main( ) 6
{ 6 is even
int n; enter the number
printf("enter the number\n");scanf("%d",&n); 5
if(n%2==0) 5 is odd
printf("%d is even",n);
else
printf("%d is odd",n);return(0);
}
Greatest of 2 numbers: Output
#include<stdio.h> enter the 2 numbers
int main( ) 4
{ 100
int a,b; 100 is greater
printf("enter the 2 numbers\n");scanf("%d%d",&a,&b);
if(a>b)
printf("%d is greater",a);
else
printf("%d is greater",b);return(0);
}

37
CS3251- PROGRAMMING IN C
Leap year or not:
#include <stdio.h> Output:
int main()
{ Enter a year
int year; 2016
printf("Enter a year\n"); leap year
scanf("%d", &year);
if ((year%4 == 0) && (year%100!=0)|| (year%400==0))
printf("leap year.\n");
else
printf("not a leap year.\n");
return(0);
}
Note:
A year is leap year if following conditions are satisfied
1) Year is multiple of 400
2) Year is multiple of 4 and not multiple of 100.
3. Nested if-else statement
 Nested if-else is used to check more than one conditions.
 If there are more than two alternatives to select, then the nested-if statements are used.
 The conditions are executed from top to bottom.
 Enclosing an if statement within another if statement is called nested-if statement.

If 'expression' is false the 'statement-3' will be executed, otherwise it continues to check the
condition for 'expression 1' .
If the 'expression 1' is true the 'statement-1' is executed otherwise 'statement-2' is executed

38
CS3251- PROGRAMMING IN C
Program to find greatest of three number. Output
#include<stdio.h>
int main( )
{ enter 3 numbers
int a,b,c; 6
printf("enter 3 numbers\n"); 8
scanf("%d%d%d",&a,&b,&c); 1
if(a>b) 8 is greatest
{
if( a > c)
printf("%d is greatest",a);
else
printf("c is greatest");
}
else
{
if( b> c)
printf("b is greatest");
else
printf("c is greatest");
}return(0);
}

4.else-if ladder :
 If there are more than three alternatives, we can go for else if ladder.
 Once a true condition(if) is satisfied, the other statements in the ladder will be skipped.
 When all conditions became false, then the final else part which contains default statement will
be executed.

39
CS3251- PROGRAMMING IN C
Program to print class obtained based on percentage of marks Output:
#include <stdio.h> Enter the percentage of marks
int main() obtained by student:
{ 53
int marks; Grade E
printf("Enter the percentage of marks obtained by student:\n");
scanf("%d",&marks);
if(marks>=90)
printf("Grade S");
else if(marks>=80)
printf("Grade A");
else if(marks>=70)
printf("Grade B");
else if(marks>=60)
printf("Grade C");
else if(marks>=55)
printf("Grade D");
else if(marks>=50)
printf("Grade E");
else
printf("Grade U");return(0);
}
Program to find Quadratic Equation: Output:
#include <stdio.h> enter the value of a,b & c
#include<math.h> -1
int main() 2
{ 4
int a,b,c,d; Both roots are real and diff
float x1,x2; First Root x1= -1.236068
printf("enter the value of a,b & c\n"); Second Root x2= 3.236068
scanf("%d%d%d",&a,&b,&c);
d=b*b-4*a*c;
if(d==0)
{
printf("Both roots are equal\n");
x1=-b/(2.0*a);
x2=x1;
printf("First Root x1= %f\n",x1);
printf("Second Root x2= %f\n",x2);
}
else if(d>0)
{
printf("Both roots are real and diff-2\n");
x1=(-b+sqrt(d))/(2*a);
x2=(-b-sqrt(d))/(2*a);
printf("First Root x1= %f\n",x1);

40
CS3251- PROGRAMMING IN C
printf("Second Root x2= %f\n",x2);
}
else
printf("Root are imaginary\n");
}
Program to find the entered key is an alphabet or numeric Output:
or alphanumeric(using character Build-in functions) Enter any key
#include<stdio.h> 8
int main() Entered key is number
{
char a;
printf("Enter any key\n");
a=getchar();
if(isdigit(a))
printf(" Entered key is number");
else if(isalpha(a))
printf("Entered key is alphabet");
else
printf("Entered key is alphanumeric");
return(0);
}
Program to find the entered key is an alphabet or numeric or Output:
alphanumeric(using print, scanf statements) enter a single character or
#include<stdio.h> value
int main() [
{ Alphanumeric
char ch;
printf("enter a single character or value \n"); scanf("%c",&ch);
if((ch>='a')&&(ch<='z'))
printf("Alphabet\n");
else if((ch>='0')&&(ch<='9'))
printf("Number\n");
else
printf(("Alphanumeric\n")); return(0);
}
Note:
In if statement, a single statement can be written without using curly braces { }
Eg, int x=2;
if(x > 4)
printf("welcome");
In the above case, no curly braces are required, but if we have more than one statement
inside if condition, then we must use curly braces.
Other than 0(zero), all other values are considered as true.
Eg, if(9)
printf("welcome");
41
CS3251- PROGRAMMING IN C
In above example, hello will be printed, because the integer 9 is a non zero value.
Switch statement:
 C provides a multi way decision statement called switch statement.
 It allows the user to make a decision from number of choices.
 The expression(condition) in switch case return an integer value or character constant,
which is compared with the values in different cases.
 When the condition matches with the case ,that block of statement is executed.
 If there is no match, then default statement is executed.

Note:
It isn't necessary to use break after each block, but if you do not use it, all the consecutive block of
codes will get executed after the matching block.
int i = 1;
switch(i)
{
case 1:
printf("A"); // No break case 2:
printf("B"); //No break case 3:
printf("C");
break;
}
Output : A B C
- The output was supposed to be only A because only the first case matches, but as there is no break
statement aftertheblock, thenext blocksareexecuted, untilthe cursor encounters a break.
Rules for switch Statement:
42
CS3251- PROGRAMMING IN C
o Default case is optional and can be placed anywhere in the switch case. But Usually we place itattheend.
o Case keyword must terminate with colon(:)
o Case order execution is from top to bottom.
o No two case constant should be same.
Example: To print month using switch case Output:
#include<stdio.h> Enter any number
int main() from 1 to 4 to
{ represent month
int ch; 3
printf("Enter any number from 1 to 4 to represent month\n"); March
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("january");
break;
case 2:
printf("february");
break;
case 3:
printf("march");
break;
case 4:
printf("april");
break;
}
return(0);
}
Arithmetic operations using switch: Output:
#include<stdio.h> 1.Addition
int main() 2.Subtraction
{ 3.Multiplication
int a,b,op; 4.Division
printf("1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n"); Enter the values of a
printf("Enter the values of a & b: "); & b: 20 5
scanf("%d %d",&a,&b); Enter your Choice :
printf("Enter your Choice : ");scanf("%d",&op); 3
switch(op) Multiplication is :
{ 100
case 1 :
printf("Sum is : %d",a+b);
break;
case 2 :
printf("Difference is : %d",a-b);
break;
case 3 :
43
CS3251- PROGRAMMING IN C
printf("Multiplication is : %d",a*b);
break;
case 4 :
printf("Division is %d : ",a/b);
break;
default :
printf(" Enter Your Correct Choice.");
break;
}
return(0);
}
Printing student GPA details using switch case:
#include<stdio.h> Output:
int main() Enter three subject
{ Marks95
int m1,m2,m3,gpa; 94
float tot, avg; 96
printf("Enter three subject Marks"); grade=A
scanf("%d%d%d",&m1,&m2,&m3);
tot=m1+m2+m3;avg=tot/3; gpa=avg/10;
switch(gpa)
{
case 10: printf("grade=S"); break;
case 9 : printf("grade=A"); break;
case 8 : printf("grade=B"); break;
case 7 : printf("grade=C"); break;
case 6 : printf("grade=D"); break;
case 5 : printf("grade=E"); break;
default : printf("grade=F");
}
return(0);
}
LOOPING STATEMENTS / ITERATIVE STATEMENTS:
 In Loop, sequence of statements are executed until a specified condition is true.
 This sequence of statements to be executed is kept inside the curly braces { } known as the Loop
body.
 After every execution of loop body, condition is verified, and if it is found to be true the loop body is
executed again. When the condition check returns false, the loop body is not executed.
 There are 3 type of Loops in C language
for loop
while loop
do-while loop
Entry controlled loop Exit controlled loop
The test condition is checked first before The loop is executed first and then condition
44
CS3251- PROGRAMMING IN C
the loop is executed. is checked.
Example The loop is executed at least once, even
while loop when the condition is false.
for loop Example
do-while loop

while Loop:
 It is an entry controlled looping statement.
 Statements are executed repeatedly until the while condition is true.
 It is completed in 3 steps.
 Variable initialization. ( e.g int x=0; )
 Condition Checking ( e.g while( x<=10) )
 Variable increment or decrement ( x++ or x-- or x=x+2)
Description:
Step 1: The while condition is checked first.
Step 2: If the condition is true, the statements inside the loop will be executed, then the variable
value is incremented or decremented at the end of the looping statement.
Step 3: If the condition is false, the loop body will be skipped and the statements after the while
loop will be executed.

Sum of n natural numbers using while loop Output:


#include<stdio.h> Enter a number
int main() 5
{ The sum of nos: 15
int n,i=1,sum = 0;
printf("Enter a number\n"); scanf("%d",&n);
while(i<=n)
{
sum=sum+i;
i++;
}
printf("The sum of nos: %d\n",sum);return(0);

45
CS3251- PROGRAMMING IN C
}
Sum of Digits of given number using while loop: Output:
#include <stdio.h> enter the number
int main() 555
{ sum of digits of given no is: 15
int n,dig,sum1=0;
printf("enter the number\n");scanf("%d",&n);
while(n>0)
{
dig=n%10;
sum1=sum1+dig;
n=n/10;
}
printf("sum of digits of given no is: %d",sum1);
return(0);
}
To reverse the given number Output:
#include <stdio.h> Enter a no to reverse
int main() 523
{ Reverse of entered no=325
int n,dig,rev=0;
printf("Enter a no to reverse\n"); scanf("%d",&n);
while(n>0)
{
dig=n%10;
rev=(rev*10)+dig;
n=n/10;
}
printf("Reverse of entered no=%d",rev); return(0);
}
To check the given number is palindrome or not: Output:
#include <stdio.h> Enter a number to check
int main() palindrome:
{ 1221
int n,rev=0,temp,dig; It is a palindrome no.
printf("Enter a number to check palindrome:\n");
scanf("%d",&n);
temp=n;
while(temp != 0 )
{
46
CS3251- PROGRAMMING IN C
dig=temp %10;rev=rev*10 + dig; temp=temp/10;
}
if(rev == n )
printf("It is a palindrome no.\n"); else
printf("it is not a palindrome no.\n"); return(0);
}
To Check Armstrong number or not: Output:
#include <stdio.h> Enter a number
int main() 153
{ Its an Armstrong number
int n, arm = 0, dig, temp;
printf("Enter a number\n");
scanf("%d", &n);
temp=n;
while (temp != 0)
{
dig = temp %10;arm= arm + (dig*dig*dig);
temp = temp/10;
}
if(arm==n)
printf("Its an Armstrong number"); else
printf("Its an not Armstrong number"); return(0);
}

do while loop:
 It is an exit controlled looping statement.
 The do-while loop checks its condition at the bottom of the loop whereas for and while loops,
the loop condition is checked at the top of the loop.
 do-while loop is guaranteed to execute the statement at least one time.

47
CS3251- PROGRAMMING IN C

While Do while
Condition is tested first and then statements are Statements are executed at least
executed. once. then the conditions are tested.
While loop is entry controlled loop Do wile loop is exit control
loop.

Sum of 10 natural no’s using do while loop: Output:


#include<stdio.h> Enter a number
int main() 10
{ The sum of digits: 55
int n,i=0,sum = 0;
printf("Enter a number\n"); scanf("%d",&n);
do
{
sum=sum+i;
i++;
}while(i<=n);
printf("The sum of digits: %d\n",sum);return(0);
}
Program to print multiples of 5: Output:
#include<stdio.h> 5
int main() 10
{ 15
int a=5,i=1; 20
do 25
{ 30
printf("%d\n",a*i); 35
i++; 40
} 45
while(i <= 10); 50
}
Program to print the squares of number from 1 to 10: Output:

48
CS3251- PROGRAMMING IN C
#include<stdio.h> numbers squares
#include<math.h> 1 1
int main() 2 4
{ 3 9
int num=1,sq; 4 16
printf("numbers squares\n"); 5 25
do 6 36
{ 7 49
sq=pow(num,2); 8 64
printf("%d%20d\n",num,sq); 9 81
num++; 10 100
}while(num<=10);
return(0);
}
for loop:
for loop is used to execute a set of statements repeatedly until a particular condition is satisfied.

Flow of Execution:
i.The initialization step is executed first, and only once. This step allows to declare and
initialize any loop control variables.
ii.Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop will not be executed and flow of control jumps to the next
statement just after the for loop.
iii.After the body of the for loop executes, the flow of control jumps back up to the
increment statement. This statement allows to update any loop control variables.
iv.The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). When the
condition becomes false, the for loop terminates.
Different ways of implementing for loop:

49
CS3251- PROGRAMMING IN C
Form Comment

for(i=0;i<10;i++)
Single Statement
Statement1;

for ( i=0 ;i <10; i++) Multiple Statements within for


{
Statement1;
Statement2;
Statement3;
}

for ( i=0 ; i < 10;i++) ; For Loop with no Body ( Carefully Look
at the Semicolon )

for(i=0,j=0;i<100;i++,j++) Multiple initialization & Multiple


Statement1; Update Statements Separated by Comma

for ( ; i<10 ; i++) Initialization not used

for ( ; i<10 ; ) Initialization & Update not used

for ( ; ; ) Infinite Loop, Never Terminates


Simple Programs using for loop:
Printing n natural numbers: Output:
#include <stdio.h> enter the maximum no to be
int main() printed:10
{ 1
int n,i; 2
printf("enter the maximum no to be printed:"); 3
scanf("%d",&n); 4
for(i=1;i<=n;i++) 5
{ 6
printf("%d\n",i); // 7
} 8
return(0); 9
} 10
Printing n even numbers: Output:
#include <stdio.h> Enter the number:10
int main() 0
{ 2
int n,i,sum=0; 4
6
printf("Enter the number:"); 8
scanf("%d", &n); 10
50
CS3251- PROGRAMMING IN C
for (i = 0; i <= n; i=i+2)
printf("%d\n",i);
return(0);
}
Sum of n Odd numbers: Output:
#include <stdio.h> Enter the number
int main() 10
{ Sum of entered odd number is
int n,i,sum=0; 25
printf("Enter the number\n");scanf("%d", &n);
for (i = 1; i <= n; i=i+2)
sum = sum + i;
printf("Sum of entered odd number is %d",sum);
return(0);
}
Sum of Squares of a number: Output:
#include <stdio.h> Enter the number:4
int main() sum is 30:
{
int n,i,sum=0;
printf("Enter the number:");scanf("%d", &n);
for (i = 1; i <= n; i=i+1)
{
sum=sum+(i*i);
}
printf("sum is %d:\n",sum);return(0);
}
To find Factorial of the given number: Output:
#include <stdio.h> Enter the number:5
int main() sum is 120:
{
int n,i,fact=1;
printf("Enter the number:");scanf("%d", &n);
for (i = 1; i <= n; i=i+1)
fact=fact*i;
printf("sum is %d:\n",fact);return(0);
}
Sum of series 1+1/2+1/3+…….. + 1/n Output:
#include <stdio.h> Enter the number
int main() 5
{ Sum of the series =2.283333
double sum=0.0,n,i;
printf("Enter the number\n"); scanf("%lf", &n);
for (i = 1; i <= n; i++)
sum = sum + (1/i);
printf("Sum of the series =%lf ",sum);return(0);
51
CS3251- PROGRAMMING IN C
}

Sum of series 1/1!+1/2!+1/3!+…….. + 1/n! Output:


#include <stdio.h> Enter the number
int main() 5
{ Sum of the series =0.008333
double sum=0.0,n,i,fact=1;
printf("Enter the number\n"); scanf("%lf", &n);
for (i = 1; i <= n; i++)
fact=fact*i;
sum = sum + (1/fact);
printf("Sum of the series =%lf ",sum);return(0);
}
Fibonacci Series: Enter the number of terms: 10
#include <stdio.h> 0,1,1,2,3,5,8,13,21,34,
int main()
{
int i, n, a = 0, b = 1, next;
printf("Enter the number of terms: ");
scanf("%d", &n);
for (i = 1; i <= n; ++i)
{
printf("%d,",a);
next=a+b;
a=b;
b=next;
}return 0;
}
To find Factors of a given number: Output:
#include<stdio.h> Enter a number to find
int main() its factors
{ 10
int n,i; factors are: 1
printf("Enter a number to find its factors\n"); factors are: 2
scanf("%d",&n); factors are: 5
for (i=1;i<=n;i++) factors are: 10
{
if(n%i==0)
printf("factors are: %d\n",i);
}
return(0);
}
Program to check the number is prime or not: Output:

52
CS3251- PROGRAMMING IN C
#include<stdio.h> enter the no
int main() 11
{ number is prime
int n,i,flag; printf("enter the no\n");
scanf("%d",&n);
for(i=2;i<n;i++) Note:
{ Flag is a Boolean variable that
if(n%i==0) has only 2 states (0 and 1)
{ Eg, On/Off, True/False,
flag=0; Yes/No
break;
}
}
if(flag==0)
printf("number is not prime \n");
else
printf("number is prime\n");
return(0);
}
Nested for loop:
- One for loop inside another for loop.

Flowchart:

53
CS3251- PROGRAMMING IN C

Program to multiply numbers using nested for: Output:


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

Loop Control Statements:


C language allows jumping from one statement to another within a loop as well as
jumping out of the loop.
1. break
2. continue
3. goto
4. return
1) break statement
 When break statement is encountered inside a loop, the loop is immediately
terminated and program control comes out of the loop and executes the
54
CS3251- PROGRAMMING IN C
statement immediately following the loop.
 It can be used in iteration only(looping statements).
 Cannot be used in conditional statements(if, else, else if).
Syntax:
break;

2) continue statement:
C Continue statement are used to skips the rest of the current iteration in a loop and returns
to the top of the loop.
Syntax:
continue;

Example:
Use of break statement to Output: Use of continue statement to Output:
print numbers: print numbers:
#include <stdio.h> enter the enter the
int main() #include <stdio.h>
number: 10 number: 10
{ int main()
int i,num; 1 { 1
printf("enter the number: "); 2 int i,num; 2
scanf("%d",&num); 3 printf("enter the number: "); 3
for(i=1;i<=num;i++) 4 scanf("%d",&num); 4
{ for(i=1;i<=num;i++)
55
CS3251- PROGRAMMING IN C
if(i==5) { skipped
{ if(i==5) 6
printf("stop"); { 7
break; printf("skipped\n");
8
} continue;
printf("%d\n",i); } 9
} printf("%d\n",i); 10
return(0); }
} return(0);
}
Break Continue
Break statement is used to transfer the Continue is used to skip some statement of
control of the program to outside loop or the loop and moves to the next iteration in
switch case statement. the loop.
It is used in loop as well as switch case. It is used only within the loop.
Syntax: break; Syntax: continue;

3) goto statement:
 The goto statement is used for altering the normal sequence of program execution by
transferring control to some other part of the program.
 When a goto statement is encountered in a C program, the control jumps directly to the
label mentioned in the goto statement.
 It us used when loops are deeply nested and simple break statement cannot work
effieciently.
Syntax:
goto label_name;


label_name

Flowchart: Program to print sum


of no’s using goto
statement:
#include <stdio.h>
int main()
{
int sum=0,i;
for(i = 0; i<=10; i++)
{
sum = sum+i;
56
CS3251- PROGRAMMING IN C
if(i==5)
{
goto addition;
}
}
addition:
printf("sum is %d",
sum);
return(0);
}
Output:
sum is 15

Preprocessor Directives:
 Preprocessor is a program which will be executed automatically before passing the source
program to compiler. This process is called pre-processing.
 The preprocessor provides the ability for the inclusion of header files, macro expansions,
conditional compilation, and line control.
 Commands used in preprocessor are called preprocessor directives.
 They begin with "#" symbol and should be not ended with (;)
 Proprocessor Directive can be place any where in the program, but generally it place top of the
program before defining the first function.
Preprocessor directives in C:
 Macro substitution directives. example: #define
 File inclusion directives. example: #include
 Conditional compilation directive. example: #if, #else, #ifdef, #undef, #endif
 Miscellaneous directive. example: #error, #line

57
CS3251- PROGRAMMING IN C

(i)Macro preprocessor:
Example: To print PI value
#include<stdio.h>
#define PI 3.14
int main()
{
printf("%f",PI);
}
Three types of macros are
Simple macros Augmented macros Nested macros
Define symbolic It is used to define more The macro defined within another
constants complex expressions macro is called nested macro.
Example: Example: Example:
#define A 100 #define sqr(n) (n*n) #define sq(n) (n*n)
#define tablesize 10 #define cube(n) (n*n*n)

(ii)File Inclusion:
This is used to include an external file which contains functions into the program. It enables code
reusability.
Syntax Example
#include "filename" #include"example.c"
#include <filename> #include<stdio.h>
 The filename is quoted in quotes (“ ”), then it searches that file in current directories.
 When the filename is quoted in angle brackets (< >), then it searches the file in standard
directories only.
(iii)Conditional Directives:
#if, #else and #endif:
If given condition is true, "If" clause statement is included in source file . Otherwise, else clause
statement is included in source file for compilation and execution.

58
CS3251- PROGRAMMING IN C
Example: Tocheck the Vote eligibility using #if, #else and #endif
#include<stdio.h> Output:
#define AGE 5 Not eligible
int main()
{
#if (AGE>=18)
{
printf("Eligible for voting");
}
#else
{
printf("\n Not eligible");
}
#endif
return(0);
}
#ifdef, #else and #endif:
- #ifdef" directive checks whether particular macro is defined or not.
- If it is defined, "If" clause statements are included in source file. Otherwise, "else" clause
statements are included in source file for compilation and execution.
- In the below example1 macro is not defined. So, else part is executed.
Example: Example:
#include<stdio.h> #include<stdio.h>
int main() #define AGE 1
{ int main()
#ifdef AGE {
{ #ifdef AGE
printf("Eligible for voting\n"); {
} printf("Eligible for voting\n");
#else }
{ #else
printf("Not eligible\n"); {
} printf("Not eligible\n");
#endif }
return(0); #endif
} return(0);
}
Output: Output:
Not eligible Eligible for voting
undef
This directive undefines existing macro in the program.
In below program we first undefine age variable and again it is defined with new value.
Example: Undefining the macro Output:
#include<stdio.h> First define value for age is:

59
CS3251- PROGRAMMING IN C
#define age 20 20
int main() Age after undef redefine is:
{ 30
printf("First defined value for age is: %d\n",age);
#undef age // undefining variable
#define age 30 // redefining age with new value
printf("Age after undef redefine is: %d",age);
return(0);
}

PART A:
1. What are variables? Give Examples (M/J’16)(N/D’14)
2. Define implicit type conversion (M/J’16)
3. What is an array? Give Example (M/J’16) (M/J’15)
4. Define strings. Give examples(M/J’16)
5. What is meant by linking process? (N/D’15)
6. What are the input functions and output functions in C? (N/D’15) (M/J’15)
7. Write a C program to store Fibonacci series in an array. (N/D’15)
8. List the string functions available in C. (N/D’15)
9. List some pre-processor directives. (N/D’15)
10. What are the importance of keyword in C? (M/J’15)
11. How is a character string declared? (M/J’15)
12. Give the use of pre-processor directives. (M/J’15) (N/D’14) (M/J’14)
13. Give an Example of ternary operator. (N/D’14)
14. Describe float array of size 5 and assign 5 values in it. (N/D’14)
15. Give an example for initialization of string array.
16. Define static storage class. (N/D’14)
17. List different data types available in C. (M/J’14)
18. Write a C program to find factorial of the number using iteration. (M/J’14)
19. Write an example code to declare two dimensional array. (M/J’14)
20. List any 4 string handling functions (M/J’14)

PART B:
1. Explain different types of operators in detail. (M/J’16) (M/J’15) (N/D’14)
2. Discuss basic data types in C (M/J’16)
3. Describe various input and output statements in detail. (M/J’16)
4. Write a C program for the following series 1+2+3+4+…N (M/J’16)
5. Write a C program to convert the number of vowels in your name (M/J’16)
6. Write a C program to multiply two matrices/ Write a C program for two 3*3 Matrix
(M/J’16)/(N/D’15) (N/D’14)
7. Write a C program to check whether the given string is palindrome or not (M/J’16)
8. Write a C program to arrange the given 10 numbers in descending order (M/J’16
9. Explain various storage classes in detail. (M/J’16) (N/D’15) (M/J’15) (M/J’14)
60
CS3251- PROGRAMMING IN C
10. Describe about pre-processors with suitable examples. (M/J’16)
11. Describe the structure of C program using ‘calculator program’ example. (N/D’15)
12. Write short notes on branching statements in C. (N/D’15)
13. Write in detail about various looping statements with suitable example.(N/D’15) (M/J’15)
(N/D’14)
14. Write a C program to find determinant of the resultant matrix. (N/D’15)
15. Write the following programs (N/D’15)
(i) To sort the given set of strings alphabetically
(ii) To print whether each word is palindrome or not
(iii) To count the length of the string
16. What are constants? Explain various types of constants in C. (M/J’15)
17. Write a C program to solve(roots of) Quadratic Equation ((M/J’15) (M/J’14)
18. Write a C program to add two matrices. (M/J’15)
19. Write a C program to search a number in an array of elements. (M/J’15) (N/D’14)
20. Write a C program to arrange the given 10 numbers in ascending order/ Write a C program to
sort array of numbers. (N/D’14) (M/J’15) (M/J’14)
21. Explain various string handling functions in C. (M/J’15)
22. Explain various string operations. Write a C program to find the length of the string without using
build in function. (N/D’14)
23. Write a short notes on (i) #include<stdio.h> (ii) ifdef.. # endif (N/D’14)
24. Write a C program to check the given number is prime or not (M/J’14)
25. Write a C program to find sum of digits of a number (M/J’14)
26. Explain entry and exit checked conditional structure with example(M/J’14)
27. Write a C program to subtract two matrices and display the resultant matrix.(M/J’14)
28. (M/J’14)

***************

61
CS3251- PROGRAMMING IN C

UNIT II ARRAYS AND STRINGS

UNIT II ARRAYS AND STRINGS


Introduction to Arrays: Declaration, Initialization – One dimensional array – Example
Program: Computing Mean, Median and Mode - Two dimensional arrays – Example
Program: Matrix Operations (Addition, Scaling, Determinant and Transpose) – String
operations: length, compare, concatenate, copy – Selection sort, linear and binary search.

INTRODUCTION TO ARRAYS:
An array is a collection of similar data items that are stored under a common name.
Array is defined as finite ordered collection of similar data, stored in contiguous
(continues) memory locations.
It is a derived data type in C.
What is the use of array?
A single variable cannot store multiple values . But an array can store multiple values of
same data type in one single name.
Example where arrays are used,
 to store roll numbers of the students in a class
 to store marks of a students
 to store list of names of employees etc..

Array can store integer, float and double values which is said to be integer array.
Array that is used to store characters are said to be Character array.
Features of array:
Array might be belonging to any of the data types
Array size must be a constant value.
Array index starts with 0 and ends with n-1.
Element of an array is accessed using index or subscript.
Always, Contiguous (adjacent) memory locations are used to store array elements in
memory.
62
CS3251- PROGRAMMING IN C
It is a best practice to initialize an array to zero or null while declaring, if we don’t
assign any values to array.
Advantage of array:
 Code Optimization: Less code is required, one variable can store numbers of
value.
 Easy to traverse data: By using array easily retrieve the data of array.
 Easy to sort data: Easily sort the data using swapping technique.
 Random Access: With the help of array index you can randomly access any
elements from array.

Types of an array:
1. Single dimensional array
2. Multi dimensional array
Single(one)dimensional array:
 Array having only one subscript [ ] variable is called One-Dimensional array.
 It is also called as Single Dimensional Array or Linear Array or list.
 The elements of one dimensional array is also called as linear array
Declaring Array:
data_type array_name[size];
Example:
int roll_num[100];
char name[50];
double balance[10];
Initialization of an Array:
 After an array is declared it must be initialized.
 An array can be initialized in 2 ways (i) Compile time initialization
(ii)Run time initialization

(i) Compile time Array initialization:


- Compile time initialization of array elements is same as ordinary variable initialization.
Syntax:
data type array_name[size] = { list of values };
Example:
int marks[4]={ 67, 87, 56, 77 }; //integer array initialization
float area[5]={ 23.4, 6.8, 5.5 }; //float array initialization
double balance[10]={1000.0,20.0,3.4,7.2,50.0}
char str[10]={‘H’,‘a’,‘i’}; // character array

63
CS3251- PROGRAMMING IN C
Accessing Array Elements:
We can access array elements with the help of index value of element.
Example:
int marks[50]={10,20,30,15,12}
here, marks is the array name and [50] is the maximum number of elements the array can
hold.
Printing array of numbers(Compile time initialization) Output:
#include<stdio.h> the elements in the
int main() array are
{ 95
int arr[40]={95,58,45,78}; 58
int i; 45
printf("the elements in the array are\n"); 78
for(i=0;i<=3;i++)
{
printf("%d\n", arr[i]);
}
return(0);
}
Note: [40] is the maximum size the array can hold.
(ii)Runtime Array initialization:
- An array can also be initialized at runtime using scanf() function.
- This approach is usually used for initializing large array elements , or to initialize
array by getting the input from the user.
Syntax:

for(i=0;i<n;i++)
{
scanf(“%d”,&arr[i]);
}
Reading and Printing array of elements( Run Time Output:
initialization) enter the size of an
#include<stdio.h> array
int main() 5
{ enter the elements of
int arr[100],n,i; an array
printf("enter the size of an array\n"); 45
scanf("%d",&n); 45
printf("enter the elements of an array\n"); 78
for(i=0;i<=n-1;i++) 4
{ 12
scanf("%d",&arr[i]); the elements are
64
CS3251- PROGRAMMING IN C
} 45
printf("the elements are\n"); 45
for(i=0;i<=n-1;i++) 78
{ 4
printf("%d\n",arr[i]); 12
}
return(0);
}
Operations on 1D array:
1. Subscripting an 1D array
It is an action of selecting an element from an array.
printf(“%d”, a[5]);
2. Assigning an array to another array
A variable can be assigned to another variable but array can’t be assigned to
another array directly.
Output:
#include<stdio.h> //compilation error
int main()
{
int a[3], b[3]={1,2,3};
a[3]=b[3];
printf(“%d”, a[0]);eturn(0);
}

Example Programs: (using One Dimensional Array)


C program to find sum of array of elements: Output:
#include<stdio.h> Enter the size of
int main() array:
{ 4
int i, arr[20], n, sum=0; Enter the values:
printf("Enter the size of array:\n"); 2
scanf("%d",&n); 5
printf("Enter the values:\n"); 1
for(i=0;i<n;i++) 12
{
scanf("%d",&arr[i]);
}
for(i=0;i<n;i++)
{
sum=sum+arr[i];
}
printf("the sum of the array is %d",sum);
65
CS3251- PROGRAMMING IN C
return(0);
}
C Program to find the largest element in an array: Output:
#include<stdio.h> enter the size of an
int main() array :3
{ enter the elements of
int arr[10]; an array
int large,i,n; 23
printf("enter the size of an array :"); 2
scanf("%d",&n); 15
printf("enter the elements of an array\n"); largest element is: 23
for(i=0;i<=n-1;i++)
{
scanf("%d",&arr[i]); Note:
} Can also try the size
large=arr[0]; of array and
for(i=1;i<=n-1;i++) elements of array by
{ getting input from
if(arr[i]>large) user.
large=arr[i];
}
printf("largest element is: %d\n",large);
return(0);
}
Note:
(Same can be done to find the smallest element also. use < to
find smallest element)
Program to insert an element in an array at specific position Output:
#include<stdio.h> enter the position
int main() where the new
{ element to be inserted
int arr[50]={10,20,30,40,50},i,pos,element; 2
printf("enter the position where the new element to be enter the new element
inserted\n"); to be inserted
scanf("%d",&pos); 25
printf("enter the new element to be inserted\n"); after insertion
scanf("%d",&element); ,elements are
for(i=4;i>=pos;i--) 10
{ 20
arr[i+1]=arr[i]; //moving the elements 25
} 30
arr[pos]=element; 40
printf("after insertion ,elements are\n"); 50
66
CS3251- PROGRAMMING IN C
for(i=0;i<=5;i++)
{
printf("%d\n",arr[i]);
}
return(0);
}
C program to delete an element in an array: Output:
#include<stdio.h> Enter the size of an
int main() array
{ 4
int n, a[10],i,pos; Enter the array
printf("Enter the size of an array\n"); elements
scanf("%d",&n); 23
printf("Enter the array elements\n"); 12
for(i=0;i<n;i++) 5
{ 47
scanf("%d",&a[i]); Enter the position to
} be deleted
printf("Enter the position to be deleted\n"); 1
{ After deletion:
scanf("%d",&pos); 23
} 5
if(pos>=n) 47
{
printf("deletion is not possible");
}
else
{
for(i=pos;i<n-1;i++)
{
a[i]=a[i+1];
}
}
printf("After deletion:\n");
for(i=0;i<n-1;i++)
{
printf("%d\n",a[i]);
}
return(0);
}
C program to display elements in Descending order: Output:
#include <stdio.h> Enter the size of
int main() array: 5
67
CS3251- PROGRAMMING IN C
{ Enter the elements of
int arr[50],n,i,j; array:
int temp; 2
printf("Enter the size of array: "); 6
scanf("%d",&n); 8
printf("Enter the elements of array:\n"); 9
for(i=0;i<=n-1;i++) 1
scanf("%d",&arr[i]); Array elements after
sorting:
for(i=0;i<=n-1;i++) 9
{ 8
for(j=i+1;j<=n-1;j++) 6
{ 2
if(arr[i]<arr[j]) //sort array 1
{
temp =arr[i];
arr[i] =arr[j];
arr[j] =temp;
}
}
}
printf("\nArray elements after sorting:\n");
for(i=0;i<=n-1;i++)
{
printf("%d\n",arr[i]);
}
return 0;
}

Illustrative Programs:
Searching: Searching is a process of finding a particular element in a given list.
Types:
1. Linear search
2. Binary search
Linear Search
- It is a process of finding an element in the list from the beginning and continues
till the end of the list.
Concept of linear Search:
i. To search an element we want, we start with the first element in the list. If this is the
required element, our search is over.
ii. Else, we take up the second element and see if this is the element we search for.
68
CS3251- PROGRAMMING IN C
iii. If this is too not the element, we pick up the third element and compare.
iv. This process continues until the element we search for is found.
Advantages:

 The linear search is simple - It is very easy to understand and implement;


 It does not require the data in the array to be stored in any particular order.
Disadvantages:
The linear search is inefficient(takes more time) if the list has more number of elements.
C program to perform Linear Search:
#include<stdio.h> Output:
int main() Enter the number of
{ elements in array
int array[100], item, i, n, found=0; 4
printf("Enter the number of elements in array\n"); Enter the elements
scanf("%d",&n); 6
printf("Enter the elements \n", n); 12
for (i = 0; i < n; i++) 5
scanf("%d", &array[i]); 8
Enter the element to
printf("Enter the element to search\n"); search
scanf("%d", &item); 5
5 is present in array and
for (i = 0; i <=n-1; i++) position is 2
{
if (array[i] == item) // if required element found
{
found=1;
break;
}
}
if (found==1)
printf("%d is present in array and position is %d\n", item,i);
else
printf("%d is not present in array.\n", item);
return 0;
}
Binary Search:
 Binary search is an algorithm used to find an element in an sorted array by using the
divide and conquer concept.
 This method can be applied only if list is in sorted order.
 List is divided into two halves separated by middle element.
Left half Middle Right half

69
CS3251- PROGRAMMING IN C
Concept of Binary search:
i. Find the middle element
ii. Check the middle element with the element to be found
iii. If the middle element is equal to that element, then it will provide the output.
iv. If the value is not same, then it will check whether the middle element value is less
than or greater than the element to be found.
v. If the value is less than that element, then the search will start with the elements next
to the middle element.
vi. If the value is high than that element, then the search will start with the elements
before to the middle element.
vii. This process continues, until that particular element has been found.
Example: Consider the following set of elements in array where 31 is the element to be
searched.

Middle =(First+Last)/2 =>(0+9)/2 =4.5=>4

Now we compare the value stored at location 4, with the value being searched, i.e. 31. We
find that the value at location 4 is 27, which is not a match. As the value is greater than 27
and we have a sorted array, so we also know that the target value must be in the upper
portion of the array.

We change our low to mid + 1 and find the new mid value again.
Like this searching continues until we find the desired element.

Advantages:
 Faster than linear search.
Disadvantages :

70
CS3251- PROGRAMMING IN C
 Binary search algorithm can work only with the sorted array (either ascending or
descending order).
 It is time consuming and waste of memory allocation.
If the element to be identified occurs more than once, then it will show the occurrence of
the first one.
Program for Binary search: Output:
#include <stdio.h>
int main() enter size of array
{ 6
int i, first, last, middle, n, item, arr[50]; enter the elements
printf("enter size of array"); 5
scanf("%d",&n); 12
printf("enter the elements\n"); 4
for (i = 0; i <=n-1; i++) 7
{ 18
scanf("%d",&arr[i]); 240
} Enter element to find
printf("Enter element to find\n"); 18
scanf("%d", &item); 18 found at location 4
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last)
{
if (arr[middle] < item)
{
first = middle + 1;
}
else if (arr[middle] == item)
{
printf("%d found at location %d.\n", item, middle);
break;
}
else
{
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("%d is not present in the list\n", item);
return (0);
}
Selection Sort:
71
CS3251- PROGRAMMING IN C
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning.
The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order)
from the unsorted subarray is picked and moved to the sorted subarray.
Consider the following example:

Program to perform selection sorting (ascending order) Output:


#include <stdio.h> Enter the size of array: 5
int main() Enter the elements of array:
{ 1
int arr[50],n,i,j; 6
int temp; 4
printf("Enter the size of array: "); 6
scanf("%d",&n); 1
printf("Enter the elements of array:\n"); Array elements after sorting:
for(i=0;i<=n-1;i++) 1
scanf("%d",&arr[i]); 1
4
for(i=0;i<=n-1;i++) 6
{ 6
for(j=i+1;j<=n-1;j++)
{
if(arr[i]>arr[j]) //sort array
{
72
CS3251- PROGRAMMING IN C
temp =arr[i];
arr[i] =arr[j];
arr[j] =temp;
}
}
}
printf("\nArray elements after sorting:\n");
for(i=0;i<=n-1;i++)
{
printf("%d\n",arr[i]);
}
return (0);
}
Computing Mean, Median
Mean: The average of a set of numbers.
The mean is the usual average, so I'll add and then divide:
(13 + 18 + 13 + 14 + 13 + 16 + 14 + 21 + 13) ÷ 9 = 15
Median: The middlemost number in a set of number arranged in order.
The median is the middle value, so first I'll have to rewrite the list in numerical order:
13, 13, 13, 13, 14, 14, 16, 18, 21
There are nine numbers in the list, so the middle one will be the (9 + 1) ÷ 2 = 10 ÷ 2 = 5th
number:
13, 13, 13, 13, 14, 14, 16, 18, 21
So the median is 14.
Mode: Mode is the number that is repeated more often than any other, so 13 is the mode.

C program to create mean and median of array of Output:


elements enter size of array
#include <stdio.h> 5
int main() enter the elements
{ 6
int i,j,a[20], sum=0,n,temp,b[20]; 4
float mean=0.0, median=0.0; 3
printf("enter size of array\n"); 2
scanf("%d",&n); 4
printf("enter the elements\n"); mean value is
for (i = 0; i <=n-1; i++) 3.800000median is 4.000000
{
scanf("%d",&a[i]);
sum=sum+a[i]; //Calculating mean
}
mean=(float)sum/(float)n;
73
CS3251- PROGRAMMING IN C
printf("mean value is %f",mean);
for(i=0;i<=n-1;i++)
{
for(j=i+1;j<=n-1;j++) //calculating median
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
if(n%2==0)
median=(float)(a[n/2]+a[(n-1)/2])/2;
else
median=a[(n-1)/2];
printf("median is %f",median);
}

Two dimensional Arrays:( Multidimensional Arrays

- In 2-dimentional array, elements are arranged in row and column format.


- An array with two subscripts[ ][ ] is termed as two dimensional arrays.
- A two dimensional array enables us to store multiple rows of elements, in form of
matrix.
Array Declaration Syntax:
data_type arr_name
[num_of_rows][num_of_column];

Example:
int arr[2][2];
- this array can hold 2*2=4 elements totally.

Array Initialization:
(i) Compile time Initialization

74
CS3251- PROGRAMMING IN C
Array Initialization Syntax:
data_type arr_name[2][2] = {{0,0},{0,1},{1,0},{1,1}};
Example:
int arr[2][2] = {1,2, 3, 4};
int arr[2][3] = { {0,0,0}, {1,1,1} };
int arr[2][3] = { 0,0,0, 1,1,1 };
Array accessing syntax:
arr_name[index];
Example:
int arr[2][2] = {1,2, 3, 4};
arr [0] [0] = 1;
arr [0] ]1] = 2;
arr [1][0] = 3;
arr [1] [1] = 4;
Invalid initializations:
Following initializations are wrong and invalid.
int arr[2][ ]={1,2,3,4}; // We need to mention the column size.
Otherwise compiler do not know where the first row size ends.
ii) Run Time initialization:
Syntax:
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,a[i][j]);
}
}
Programs on two dimensional arrays:
C Program To read and display 2 dimensional matrix Output:
#include <stdio.h> enter the size of row and
int main() column
{ 3
int a[10][10]; 3
int i,j,m,n; enter the elements of
printf("enter the size of row and column\n"); matrix
scanf("%d%d",&m,&n); 5
printf("enter the elements of matrix\n"); 2
for(i=0;i<=m-1;i++) 5
{ 2
for(j=0;j<=n-1;j++) 5
{ 2
scanf("%d",&a[i][j]); 5
75
CS3251- PROGRAMMING IN C
} 2
} 5
printf("the elements are\n"); the elements are
for(i=0;i<=m-1;i++) 5 2 5
{ 2 5 2
for(j=0;j<=n-1;j++) 5 2 5
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
return(0);
}
Program for Matrix Addition: Output:
#include <stdio.h> Enter the size of row and
int main() column
{ 2
int a[10][10], b[10][10]; // array declaration for matrix a&b 2
int c[10][10]={0}; // c matrix initialized to 0 Enter the elements of A
int i,j,m,n; matrix
printf("Enter the size of row and column\n"); 1
scanf("%d%d",&m,&n); //reading size or row and column 3
printf("Enter the elements of A matrix\n"); 2
for(i=0;i<=m-1;i++) 5
{ Enter the elements of B
for(j=0;j<=n-1;j++) matrix
{ 1
scanf("%d",&a[i][j]); //getting the elements of A matrix 5
} 5
} 6
printf("Enter the elements of B matrix\n"); Sum of two matrices:-
for(i=0;i<=m-1;i++) 2 8
{ 7 11
for(j=0;j<=n-1;j++)
{
scanf("%d", &b[i][j]); //getting the elements of B matrix
}
}
printf("Sum of two matrices:-\n");
for(i = 0;i<=m-1;i++)
{
for(j=0;j<=n-1;j++)
{
76
CS3251- PROGRAMMING IN C
c[i][j] = a[i][j] + b[i][j]; // addition of A and B matrix
printf("%d\t", c[i][j]);
}
printf("\n");
}
return(0);
}
Same program can be written for matrix subtraction with - sign c[i][j] = a[i][j] - b[i][j];

Matrix multiplication: Output:


#include<stdio.h> enter the size
int main() 2
{ 2
int i, j, k,m,n; Enter A matrix
int a[10][10], b[10][10]; 2
int c[10][10]={0}; 2
printf("enter the size"); 2
scanf("%d%d",&m,&n); 2
printf("Enter A matrix\n"); Enter B matrix
for (i = 0; i <=m-1; i++) 2
{ 2
for (j = 0; j <=n-1; j++) 2
{ 2
scanf("%d", &a[i][j]); The product of matrix is
} 8 8
} 8 8
printf("Enter B matrix\n");
for (i = 0; i <= m-1; i++)
{
for (j = 0; j <=n-1; j++)
{
scanf("%d", &b[i][j]);
}
}
printf("The product of matrix is\n");
for (i = 0; i <=m-1; i++)
{
for (j = 0; j <=n-1; j++)
{
for (k = 0; k <=m-1; k++)
{
c[i][j] = c[i][j] + a[i][k]*b[k][j];
}
77
CS3251- PROGRAMMING IN C
printf("%d\t", c[i][j]);
}
printf("\n");
}
return(0);
}
C Program to perform scalar multiplication: Enter Rows and Columns of
#include <stdio.h> Matrix
int main() 2
{ 2
int a[50][50]; enter the elements of matrix
int m, n, i, j, scalar; 2
printf("Enter Rows and Columns of Matrix\n"); 1
scanf("%d %d", &m, &n); 3
5
printf("enter the elements of matrix\n"); Enter a scalar number to
for(i = 0; i <=m-1; i++) multiply with matrix
for(j = 0; j <=n-1; j++) 5
scanf("%d", &a[i][j]); Product Matrix is
10 5
printf("Enter a scalar number to multiply with matrix 15 25
\n");
scanf("%d", &scalar);
/* Multiply each element of matrix with scalar*/
for(i = 0; i <= m-1; i++)
{
for(j = 0; j <=n-1; j++)
{
a[i][j] = a[i][j]*scalar;
}
}

printf("Product Matrix is\n");


for(i= 0; i <=m-1; i++)
{
for(j = 0; j<=n-1; j++)
printf("%d ", a[i][j]);
}
printf("\n");
return(0);
}
C Program to TRANSPOSE a matrix: Output:
#include <stdio.h> Enter the SIZE of the matrix
78
CS3251- PROGRAMMING IN C
int main() 2
{ 3
int a[10][10], i, j, m, n; Enter the ELEMENTS of the
printf("Enter the SIZE of the matrix \n"); matrix
scanf("%d %d", &m, &n); 2
printf("Enter the ELEMENTS of the matrix\n"); 1
for (i = 0; i <= m-1; i++) 5
{ 3
for (j = 0; j<= n-1; j++) 7
{ 8
scanf("%d", &a[i][j]); The given matrix is
} 215
} 378
printf("The given matrix is \n"); Transpose of matrix is
for (i = 0; i <=m-1; ++i) 23
{ 17
for (j = 0; j <= n-1; ++j) 58
{
printf(" %d", a[i][j]);
}
printf("\n");
}
printf("Transpose of matrix is \n");
for (j = 0; j <=n-1; j++) //interchanging rows and
columns
{
for (i = 0; i <=m-1; i++)
{
printf(" %d", a[i][j]);
}
printf("\n");
} return(0);
}
C program to find determinant of 2*2 Matrix :
#include<stdio.h>
int main()
{ Example:
int a[2][2],i,j; Output:
long determinant;
printf("Enter the elements of matrix:\n "); Enter the elements of matrix:
for(i=0;i<2;i++) 8
for(j=0;j<2;j++) 3
scanf("%d",&a[i][j]); 2
79
CS3251- PROGRAMMING IN C
1
printf("\nThe matrix is\n"); The matrix is
for(i=0;i<2;i++) 8 3
{ 2 1
printf("\n"); Determinant is :2
for(j=0;j<2;j++)
printf("%d\t",a[i][j]);
}
determinant = a[0][0]*a[1][1] - a[1][0]*a[0][1];
printf("\nDeterminant is :%ld",determinant);
return(0);
}
Determinant of 3*3 matrix Enter the elements of
#include<stdio.h> matrix: 1
int main() 5
{ 4
int a[3][3],i,j; 2
int determinant=0; 1
printf("Enter the elements of matrix: "); 2
for(i=0;i<3;i++) 1
for(j=0;j<3;j++) 2
scanf("%d",&a[i][j]); 1
printf("\nThe First matrix is\n");
for(i=0;i<3;i++) The First matrix is
{
printf("\n"); 1 5 4
for(j=0;j<3;j++) 2 1 2
printf("%d\t",a[i][j]); 1 2 1
} Determinant of matrix is: 9
for(i=0;i<3;i++)
determinant = determinant +
(a[0][i]*(a[1][(i+1)%3]*a[2][(i+2)%3] -
a[1][(i+2)%3]*a[2][(i+1)%3]));
printf("\nDeterminant of matrix is: %d",determinant);
return(0);
}
Three Dimensional array:
Total number of elements that can be stored in a multidimensional array can be calculated
by multiplying the size of all the dimensions.
Example:
int arr[5][10][20] can store total (5*10*20) = 1000 elements totally.

80
CS3251- PROGRAMMING IN C
Disadvantages of an array:
 The elements in an array must be same data type.
 The size of an array is fixed. we can’t expand the size in run time.
 The insertion and deletion operations in an array require shifting of elements
which takes more time.

CS8251 PROGRAMMING IN C

UNIT III FUNCTIONS AND POINTERS

Introduction to functions: Function prototype, function definition, function call, Built-in


functions (string functions, math functions) – Recursion – Example Program: Computation of
Sine series, Scientific calculator using built-in functions, Binary Search using recursive
functions .
Pointers – Pointer operators – Pointer arithmetic – Arrays and pointers – Array of pointers –
Example Program: Sorting of names – Parameter passing: Pass by value, Pass by reference –
Example Program: Swapping of two numbers and changing the value of a variable using
pass by reference.

FUNCTIONS:

o A function is a block of code or set of statements that are used to perform a


particular task which repeatedly occurs in the main program.
o By using functions, we can divide complex problem into small components that
makes program easy to understand and use.
o A function is often executed several times, from several different places(sub
function) during the execution of the program.
o After executing the subprogram, the program control return back to main function.

Functions are Classified into two types:

81
CS3251- PROGRAMMING IN C

(i)User defined functions:


 User-defined functions are those functions which are defined(written) by the user
according to their requirements.
 Users have full scope to implement their own ideas in the function.
 Examples: add (), sub (), mul()
How function works?
1. Once the function is called from
main function, it takes some data to
the sub function(called function)
2. When the program control is passed
to sub function, working of main
function is temporarily stopped.
3. Once the execution of sub function is
completed, again program control
returns back to main function(calling
function).
Elements of user defined function:( Components)
1. Function declaration or prototype
2. Function definition
3. Function call
(i)Function Declaration:
- Like variable and an array, a function must also be declared before it is called.
- A function declaration tells the compiler about a function name and how to call
the function.
Syntax Example
return-type function-name (parameter-list) ; int add(int x, int y);

Return type: int, char, float, void


Function name: specifies the name of the function.

82
CS3251- PROGRAMMING IN C

Parameter list: list of variables with data type separated by comma


(ii)Function Definition (function-body)
The function body contains following 3 parts.
Body is enclosed within curly braces { }.
 Local variable declaration.
 Execution statement that performs specific task.
 return statement that return the value evaluated by the function.

Syntax Example

return-type function-name (parameter-list) int add(int x,int y)

{ {

body of function; int z;

} z=x+y;

return(z);

}
return Statement:
return type specifies the type of value(int, float, char, double) that function is expected to return to
the program calling the function.
It may or may not present send back result to calling function.
Syntax Example
return; return;
return(); return();
return(value); return(1);
return(variable); return(c);
Note:
 Default data type is int.
 Only one value can be returned to a function. Pointers are used to return more
values.
 If return (a,b,c) is used, only c value is returned to the function
Example:
int add(int x, int y) // function definition

83
CS3251- PROGRAMMING IN C

{
int z; //local declaration
z=x +y //execution statement
return(z); // return statement
}
Note:
If a function does not return any value, then keyword void must be used as return type while
declaring function definition.

(iii)Function Call:

Calling the function by simply specifying the function name, return value and parameters if
present.
Syntax Example
return_variable= function_name(arg1, arg2, ….arg n); c=add(x,y);

Simple Program to add two numbers using function: Output:


#include<stdio.h> enter two numbers
int add(int,int); 5
int main() 6
{ The sum is 11
int a,b,c;
printf("enter two numbers\n");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("The sum is %d",c);
return(0);
}
int add(int x,int y)
{
int z;
z=x+y;
return(z);
}

Types of Arguments/Parameters:

Actual parameter – Parameters transferred from calling function(main function) to called


function(function definition)

84
CS3251- PROGRAMMING IN C

Formal Parameters - Parameters transferred to calling function(main function) from called


function(function definition)
Example:

Global And Local Variable:


Local Variables: Global Variable:
 Defined within the body of the  Defined outside the main function.
function.  These variables can be used throughout
 Other functions cannot access these the program.
variables.

Program using global and local variable:


#include<stdio.h>
void test();
int m = 10, n =10 ; // global variable
int main()
{
printf("globally declared values: m=%d n=%d\n", m,n);
test();
}
void test()
{
int m=20,n=20; // local variable
printf("locally declared values: m=%d n=%d\n:",m,n);

85
CS3251- PROGRAMMING IN C

Output:
globally declared values: m=10 n=10
locally declared values: m=20 n=20

FUNCTION PROTOTYPES: ( CATEGORIES OF FUNCTION)

1. Without arguments and without return type


2. Without arguments and with return type
3. With arguments and without return type
4. With arguments and with return type

1. Without arguments and without return type


o There is no data transfer between calling and the called function.
o The called function is used to perform any operation. They work independently.
o They read the data values and print the results in same block.
2. Without arguments and with return type
o In this type of function ,no argument are passed through the main() function. But the
called function returns the values to the main function.
o The called function is independent.
3.With argument and without return type:
o In this type the arguments are passed through the function call.
oThe called function operates on the values. But no result is sent back.
4.With argument and with return type( fruitful function)
o In this type the arguments are passed through the function call.

o The result is sent back to the main function.

without arguments and without return type without argument and with return type
/* Addition of two numbers */ /* Addition of two numbers */
#include<stdio.h> #include<stdio.h>
void my_add(); int my_add();
int main()
int main() {
{ int c;
int c; c=my_add();
c=my_add(); printf("sum is %d",c);
return(0); return(0);

86
CS3251- PROGRAMMING IN C

} }

void my_add(int x,int y) int my_add(int x,int y)


{ {
int z; int z;
printf("enter the values "); printf("enter the values ");
scanf("%d\n%d",&x,&y); scanf("%d%d",&x,&y);
z=x+y; z=x+y;
printf("sum is %d",z); return(z);
} }

Output: Output:
enter the values enter the values
5 5
6 6
sum is 11 sum is 11

With argument and without return type With argument and with return type
/* Addition of two numbers */ /* Addition of two numbers */
#include<stdio.h> #include<stdio.h>
void my_add(int a,int b); int my_add(int a, int b);

int main() int main()


{ {
int a,b; int a,b,c;
printf("enter the values "); printf("enter the values ");
scanf("%d%d",&a,&b); scanf("%d%d",&a,&b);
my_add(a,b); c=my_add(a,b);
return(0); printf("sum is %d",c);
} return(0);
}
void my_add(int x,int y) int my_add(int x,int y)
{ {
int z; int z;
z=x+y; z=x+y;
printf("sum is %d",z); return(z);
} }

Output: Output:

87
CS3251- PROGRAMMING IN C

enter the values enter the values


5 5
6 6
sum is 11 sum is 11

Calculator Program: ( with argument and with return


type) Output:
#include<stdio.h> enter a,b values
int my_add(int a,int b); 4
int my_sub(int a,int b); 3
int my_mul(int a,int b); the sum is: 7
float my_div(int a,int b); the dif is: 1
the product is: 12
int main() the division is: 1.000000
{
int a,b,c;
float d;
printf("enter a,b values\n");
scanf("%d%d",&a,&b);
c=my_add(a,b);
printf("the sum is: %d\n",c);
c=my_sub(a,b);
printf("the dif is: %d\n",c);
c=my_mul(a,b);
printf("the product is: %d\n",c);
d=my_div(a,b);
printf("the division is: %f\n",d);
return(0);
}

int my_add(int x,int y)

88
CS3251- PROGRAMMING IN C

{
int z;
z=x+y;
return(z);
}
int my_sub(int x,int y)
{
int z;
z=x-y;
return(z);
}
int my_mul(int x,int y)
{
int z;
z=x*y;
return(z);
}
float my_div(int x,int y)
{
float z;
z=x/y;
return(z);
}

Benefits of Using Functions


 Reduction in code redundancy
 Enabling code reuse
 Better readability
 Information hiding
 Easy to debug and test
 Improved maintainability
 Powerful programming tool

BUILT-IN FUNCTIONS ( STANDARD LIBRARY FUNCTIONS)


Built-in functions are nothing but predefined functions or library functions.
These functions are defined by C library.

89
CS3251- PROGRAMMING IN C

Example printf(), scanf(), strcat() etc.

Various standard library functions and a macro defined under:


- math.h to perform mathematical operations
- String.h Perfoms All String Operations

String Built-In Functions:


String.h header file supports all the string functions in C language.
Some of the string library functions are given below.

Function Purpose Syntax


strlen Calculates the length of the string s. strlen(str1);
strcmp Compares two strings. strcmp(str1, str2);
strcmpi Compares two strings without case sensitive. Strcmpi(str1,str2);
strcat Appends the copy of the string src to the end of the string dest. strcat(str1, str2);
strcpy Copies the source string src to the destination string strcpy(str1,str2);
dest.
strrev Reverse the content of the string s. strrev(str1);
strlwr Converts the string to lowercase. strlwr(str1);
strupr Converts the string to uppercase. strupr(str1);
strset Set all character in a string s to the character ch. strset(str1,ch);
strnset Set the first n character in a string s to the character ch. Strnset(str1,ch,n);
strchr Scans a string for the first occurrence of the given character. strchr(str1,ch);
strrchr Scans a string for the last occurrence of the given character. strrchr(str1,ch);
strstr Scans a string for the first occurrence of the substring in another strstr(str1,ch);
string.

Return Type:

S.no Result type Function


1 Integer strlen, strcmp, strcmpi
2 String strcat, strcpy, strrev, strupr, strlwr, strset, strnset
3 Address strchr, strnchr, strstr

Math Built-In Functions:

90
CS3251- PROGRAMMING IN C

This function returns the nearest integer which is less than or equal to
floor ( ) the argument passed to this function.

This function returns the nearest integer value that passed to this
function. If decimal value is from “.1 to .5”, it returns integer value less
than the argument. If decimal value is from “.6 to .9”, it returns the
round() integer value greater than the argument.

This function returns nearest integer value which is greater than or


ceil() equal to the argument passed to this function.

sin() This function is used to calculate sine value.

cos() This function is used to calculate cosine.

cosh() This function is used to calculate hyperbolic cosine.

exp() This function is used to calculate the exponential “e” to the xth power.

tan() This function is used to calculate tangent.

tanh() This function is used to calculate hyperbolic tangent.

sinh() This function is used to calculate hyperbolic sine.

log() This function is used to calculates natural logarithm.

log10() This function is used to calculates base 10 logarithm.

This function is used to find square root of the argument passed to this
sqrt() function.

pow() This is used to find the power of the given number.

This function truncates the decimal value from floating point value and
trunk() returns integer value.

Program using different math built-in functions: Output:

#include<stdio.h> floor of 5.4 is 5.000000

#include<math.h> round of 5.4 is 5.000000

ceil of 5.4 is 6.000000

91
CS3251- PROGRAMMING IN C

int main() The value of sin(3.014) : 0.127247

{ The value of cos(3.014) : -0.991871

printf("floor of 5.4 is %f\n", floor(5.4)); The value of tan(3.014) : -0.128290

printf("round of 5.4 is %f\n", round(5.4)); The value of sinh(0.25) : 0.252612

printf("ceil of 5.4 is %f\n", ceil(5.4)); The value of cosh(0.25) : 1.031413

The value of tanh(0.25) : 0.244919


printf("The value of sin(3.014) : %f \n", sin(3.014));
The value of log(6.25) : 1.832581
printf("The value of cos(3.014) : %f \n", cos(3.014));
The value of log10(6.25) : 0.795880
printf("The value of tan(3.014) : %f \n", tan(3.014));
The value of exp(6.25) : 6.250000
printf("The value of sinh(0.25) : %f \n", sinh(0.25));
sqrt of 16 = 4.000000
printf("The value of cosh(0.25) : %f \n", cosh(0.25));
5 5 power 3 = 125.000000
printf("The value of tanh(0.25) : %f \n", tanh(0.25));

printf("The value of log(6.25) : %f \n", log(6.25));

printf("The value of log10(6.25) : %f \n",log10(6.25));

printf("The value of exp(6.25) : %f \n",6.25);

printf ("sqrt of 16 = %f\n", sqrt (16) );

printf ("5 power 3 = %f\n", pow (5, 3) );

return(0);

RECURSION FUNCTION:
 A function that calls itself is known as a recursive function. And, this technique is
known as recursion.
 But while using recursion, programmers need to be careful to define an exit condition
from the function, otherwise it will go into an infinite loop.
 Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.
How Recursion Function Works?

92
CS3251- PROGRAMMING IN C

The recursion continues until some condition is met .i,e it must have at least one if statement
to terminate the recursion.

A Recursion Function must have the following statements:


- A statement to test whether function is calling itself again.
- A statement that calls the function itself must be an argument
- A conditional statement( if-else)
- A return statement
Advantages of recursion:
- Recursion makes program simple and ease
- All algorithms can be defined recursively which makes it easier to visualize and prove.
Disadvantages of recursion:
- Recursions use more memory and are generally slow. Instead, you can use loop.
Program Output

Program to find factorial of a given number: enter a number 5


#include<stdio.h> Factorial of a given number
int fact(int n); is 120
int main()
{
int f,n;
printf(" enter a number");
scanf("%d",&n);
f=fact(n);
printf("Factorial of a given number is %d",f);
return(0);
}
int fact(int n)
{
if(n==1)
return 1;

93
CS3251- PROGRAMMING IN C

else
return (n*fact(n-1));
}
Program to compute GCD of two given numbers enter two integers
#include<stdio.h> 6
int gcd(int x,int y); 12
int main() gcd of two numbers is :6
{
int a,b;
printf("enter two integers\n");
scanf("%d%d",&a,&b);
printf("gcd of two numbers is :%d %d\n",gcd(a,b));
return(0);
}
int gcd(int x,int y)
{
if(y!=0)
return gcd(y,x%y);
else
return(x);
}
To find Sum of n numbers using recursion function : Enter a positive integer: 3
#include <stdio.h> sum=6
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum=%d", result);
}
int sum(int num)
{
if (num!=0)
return num + sum(num-1); // sum() function calls
itself
else
return num;

94
CS3251- PROGRAMMING IN C

}
Sum of N numbers –How Recursive Function works.

Illustrative Program:
i) Computation of Sine series
ii) Scientific calculator using built-in functions (refer book page no 5.33)
iii) Binary Search using recursive functions .

Conputation of Sine Series:


Sine Series is a series which is used to find the value of Sin(x).
where, x is the angle in degree which is converted to Radian.

95
CS3251- PROGRAMMING IN C

The formula used to express the Sin(x) as Sine Series is

Expanding the above notation, the formula of Sine Series is

For example,

Let the value of x be 30.

So, Radian value for 30 degree is 0.52359.

So, the value of Sin(30) is 0.5.

Computation of Sine Series Output

#include<stdio.h> Enter the value for x : 30

int main() Enter the value for n : 5

{ The value of Sin(0.523598) =


0.5000
int i, n;

float x, sum, t;

printf(" Enter the value for x : ");

scanf("%f",&x);

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

scanf("%d",&n);

96
CS3251- PROGRAMMING IN C

x=x*3.14159/180;

t=x;

sum=x;

/* Loop to calculate the value of Sine */

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

t=(t*(-1)*x*x)/(2*i*(2*i+1));

sum=sum+t;

printf(" The value of Sin(%f) = %.4f",x,sum);

Binary Search Using Recursion Output:

#include <stdio.h> enter the element to search

int binarySearch(int arr[], int left, int right, int x) 75

{ Element is present at index 3

if (right >= left)

int mid = left + (right - left)/2;

if (arr[mid] == x)

return mid;

if (arr[mid] > x)

97
CS3251- PROGRAMMING IN C

return binarySearch(arr, left, mid-1, x);

return binarySearch(arr, mid+1, right, x);

return -1;

int main(void)

int arr[]= {25,35,50,75,100};

int x, result;

int n = sizeof(arr)/ sizeof(arr[0]);

printf("enter the element to search");

scanf("%d",&x);

result = binarySearch(arr, 0, n-1, x);

if (result ==-1)

printf("Element is not present in array");

else

printf("Element is present at index %d",result);

return 0;

98
CS3251- PROGRAMMING IN C

Pointers – Pointer operators – Pointer arithmetic – Arrays and pointers – Array of pointers –
Example Program: Sorting of names – Parameter passing: Pass by value, Pass by reference –
Example Program: Swapping of two numbers and changing the value of a variable using
pass by reference.

POINTERS:

 A pointer is a variable that holds the address of a variable or a function.


 It is a derived data type in c language.
 Only address can be assigned to a pointer variable
 Pointer variable is declared with * symbol.
Advantages:
 Pointer reduces the code and improves the performance, because it direct access the
address of variable.
 Pointers can be used to return multiple values from a function via arguments.
 It allows dynamic memory allocation.

Declaration of a variable:

For pointer declaration, we use * (asterisk symbol).


Syntax Example
datatype *pointer_variable; int *p; // pointer to integer
char *b; // pointer to character
double *p;// pointer to double
float *p;//pointer to float
Initialization of a pointer:
Syntax Example
Pointer_variable=&variable_name; p=&a;

Function Output
printf(“%d”,a); 50
printf(“%u”,&a); 1001

99
CS3251- PROGRAMMING IN C

printf(“%u”,p); 1001
printf(“%u”,&p); 2047
printf(“%d”,*p); 50

Pointer Operators:

Simply, To create pointer to a variable we use “*” operator and to find the address of variable
we use “&” operator. Eg,

Referencing: Assigning a address to a pointer variable is called referencing.


& is a unary operator and should appear on the left side of its operand.
Example:
int a = 50;
int *p=&a;

Dereferencing: Extraction a value via pointer variable is called dereferencing.


Example:
printf(“%d”,*p);
printf(“%d”,**pptr);

Program using Referencing and Dereferencing Operator Output

#include<stdio.h> Address of a is: 37814052


int main()

100
CS3251- PROGRAMMING IN C

{ Value of a is: 50
int a=50;
int *p;
p=&a;
printf("Address of a is: %u\n",&a);
printf("Value of a is: %d",*p);
return(0); }
POINTER ARITHMETIC:
We can perform arithmetic operations on a pointer just like we can on numeric value.
There are four arithmetic operators that can be used on pointers:
++,
--,
+,
-
Arithmetic operations that can be performed on value and address are given below.
Example:

Note:
All the arithmetic operations can be performed on values. But only subtraction,
increment and decrement can be performed on address.

Addition:
 We cannot add two pointers.
 This is because pointers contain addresses, adding two addresses makes no sense,
because you have no idea what address would address it would point to. It may go
beyond the limit also. Eg, p1+p2

Subtraction:
 We can subtract two pointers.
 This is because difference between two pointers gives the number of elements of its
data type that can be stored between the two pointers. Eg, p2-p1

101
CS3251- PROGRAMMING IN C

Increment:
 If the pointer p1 points to an integer whose address is 1000 , after this increment
operation, p1 will point to the location 1002 because each time p1 is incremented, it will
point to the next integer location which is 2 bytes next to the current location for integer
data type.
 If p1 points to a character whose address is 1000, then the above operation will point to
the location 1001 because the next character will be available at 1001. Eg, p1++;

Decrement:
 Similarly, depending upon the size of data type, the position is decremented Eg, p1--;
Operators Arithmetic operators on value Arithmetic operators on
Example address
Subtraction(-) *p1-*p2 p2-p1(legal)
5-6=-1 1002-1000=1(2 bytes of data)

Increment(++) *p1++ p1++(legal)


p1+1=1002
Decrement(--) *p1-- P2--(legal)
1002-1=1000
Addition(+) *p1+*p2 p1+p2(illegal)
5+6=11 1000+1002=2002
(illegal)
Multiplication(*) (*p1)*(*p2) p1*p2(illegal)
5*6=30 1000*1002=1002000
(illegal)
/(division) (*p1)/(*p2) p1/p2(illegal)
5/6=0

102
CS3251- PROGRAMMING IN C

Program for pointer arithmetic Output:


#include <stdio.h> p1 = 2680014
int main() p2 = 2680012
{ *p1+*p2 = 15
int a = 5, b = 10, c = 0; p1-p2 = 1
int *p1; // pointer declaration p1++ = 2680018
int *p2; p2-- = 26800010
int *p3;
p1 = &a; // pointer initialization
p2 = &b;
printf("p1 = %u\n", p1); //printing the address of a
printf("p2 = %u\n", p2);//printing the address of b

c = *p1+*p2;
printf("*p1+*p2 = %d\n", c);

p3 = p1-p2;
printf("p1 - p2 = %u\n", p3);

p1++;
printf("p1++ = %u\n", p1);

p2--;
printf("p2-- = %u\n", p2);

//Below line will give ERROR


printf("p1+p2 = %d\n", p1+p2);
return 0;
}

POINTERS AND ARRAYS


- Pointer to an Array
- Array of Pointers
1.Pointer to an array
Elements in an array can be accessed using 2 methods:
(i) Standard array
(ii) Array using pointers

103
CS3251- PROGRAMMING IN C

In array, the elements are stored in consecutive memory locations. So, it can be effectively
accessed using pointers.
Example:
int a[5]={10,20,30,40,50}

- Pointer to array simply points to base address of an array


- Base address is nothing but starting address ( address of 0th element).
- The address (memory location) of next element is dependent on size of data types( 2
bytes or 4 bytes for integer depending on the compiler ).

Pointer initialization:
int a[5]={10,20,30,40,50};
int *p;
p=a;
here, pointer variable ‘p’ points only to the base address(starting address) of array.
So, p=a ;
is same as p=&a[0];

Program to print address and value of array using pointers: Output:


int main() 37814024
{ 37814024
int a[5]={10,20,30,40,50},i; 37814024
int *p; 37814028
p=a; 10
printf("%u\n",a); 20
printf("%u\n",p); 50
printf("%u\n",&a);
printf("%u\n",a+1);
printf("%d\n",*p);
printf("%d\n",*(a+1));
printf("%d\n",*(a+4));
}
Note:

104
CS3251- PROGRAMMING IN C

Increment operator in pointer always increments based on the


size of datatype.
Eg, if base address of a is 2000, the next address is 2002 or
2004 based on datatype size( 2 bytes or 4 bytes)
Program to access elements in an array using pointers: Output:
#include<stdio.h> address of a[0]is: 37814008
int main() value of a[0]is:10
{ address of a[1]is: 37814012
int a[10]={10,20,30,40,50},i; value of a[1]is:20
int *p; address of a[2]is: 37814016
p=a; // pointer variable points to base address value of a[2]is:30
for(i=0;i<5;i++) address of a[3]is: 37814020
{ value of a[3]is:40
printf("address of a[%d]is: %u\n",i,a+i); address of a[4]is: 37814024
printf("value of a[%d]is:%d\n",i,*(a+i)); value of a[4]is:50
}
}

(ii)Array of Pointers:
- Array of pointers is the Collection of pointers to hold different addresses
Syntax:
datatype *array_name[size];
Example:
int *a[5] ;
Here, a is an array of 5 integer pointers. (i,e), this array can hold the address of 5 integer
variables.
In other words we can assign 5 pointer variables of type pointer to int to the elements of this
array.
Program to print elements using array of Description:
pointers:
#include<stdio.h>
int main()
{
int *arr[3];
int a = 10, b = 20, c = 30, i;
arr[0] = &a; // address of variable a to the 0th arr[i] gives the address of ith element of
element of the of the array the array.
arr[1] = &b; So arr[0] returns address of
arr[2] = &c; variable a, arr[1]returns address of b and

105
CS3251- PROGRAMMING IN C

for(i = 0; i < 3; i++) so on.


{ To get the value at address use indirection
printf("Address = %d\t Value = %d\n", arr[i], operator (*).
*arr[i]); So *arr[0] gives value at address[0],
} Similarly *arr[1] gives the value at
return 0; address arr[1] and so on.
}
Output:
Address = 37814036 Value = 10
Address = 37814032 Value = 20
Address = 37814028 Value = 30

Difference between array of pointers and pointer to an array:


Array of pointers Pointer to an array
Each element of an array is an address to the It is the base address of the array
memory location which holds the data
Eg, Eg,
int *a[10]; int(*a)[10];
Each element must be accessed Array must be dereferenced to access the
individually(dereferenced) value of each element.
Illustrative Program:

Sorting of names using Array of pointer:


#include<stdlib.h> Output:
#include<stdio.h> given array is
#include<string.h> ravi
int mycomp( void *a, void *b); anand
int main() chitra
{ ziya
char *arr[]={"ravi","anand","chitra","ziya"}; sorted array is
int n=sizeof(arr)/sizeof(arr[0]); anand
int i; chitra
printf("given array is\n"); ravi
for(i=0;i<n;i++) ziya
printf("%s\n",arr[i]);
sort(arr,n);
printf("sorted array is\n");
for(i=0;i<n;i++)
printf("%s\n",arr[i]);

106
CS3251- PROGRAMMING IN C

return(0);
}
int mycomp(void *a, void *b)
{
return strcmp(*(char **)a,*( char **)b); // type casting to char
}
void sort( char *arr[],int n)
{
qsort(arr,n,sizeof( char *),mycomp); // using QuickSort algorithm to
sort the given array.
}

TYPES OF POINTERS:
NULL pointer:
A NULL pointer is a special pointer that does not point anywhere.
 It does not hold any address.
 It has a numeric value 0.
Declaring NULL pointer:
Syntax Example
datatype* variable_name=0; (Or) int* a=0; (Or)
datatype* variable_name=NULL; int* a=NULL;
#define NULL 0

Points to remember about null pointer:

1. When a null pointer is compared with a pointer to any object the result of
comparison is always false.
2. Two null pointers always compares equal.
3. Dereferencing null pointer leads to error.

Program to print NULL value: Output:


#include <stdio.h> Value of ptr is 0
int main()
{
// Null Pointer
int *ptr = NULL;

107
CS3251- PROGRAMMING IN C

printf("The value of ptr is %u", ptr);


return 0;
}

Void pointer:
 Void pointer is a general purpose pointer that can point to any data type
 The pointer used to point different data types is called void data type.
 If we assign address of char data type to void pointer it will become char Pointer,
if int data type then int pointer and so on. Any pointer type is convertible to a
void pointer hence it can point to any value.

Declaring void pointer:


Syntax Example

void* variable_name; void* a;

Note: Typecasting is required to change void pointer to specific data type.


1. void pointers cannot be dereferenced. It can however be done using typecasting the
void pointer
2. Pointer arithmetic is not possible on pointers of void due to lack of concrete value and
thus size.
Program using void pointer:
Output:
#include<stdlib.h>
Integer variable is = 4
int main()
Float variable is=
{
5.500000
int x = 4;
float y = 5.5;
void *ptr;
ptr = &x;
printf("Integer variable is = %d", *((int*) ptr));
ptr = &y;
printf("\nFloat variable is= %f", *((float*) ptr));
return 0;
}
Note:
(int*)ptr - does type casting of void
*((int*)ptr) dereferences(accessing the value) of the typecasted
variable

NULL vs Void Pointer – Null pointer is a value, while void pointer is a type

108
CS3251- PROGRAMMING IN C

Pointer – Pointer(Double/Chained Pointer):

- Declaring Pointer to Pointer is similar to declaring pointer in C.


- The difference is we have to place an additional ‘*’ before the name of pointer.
- When we define a pointer to a pointer, the first pointer contains the address of the
second pointer, which points to the location that contains the actual value as shown
below.

Declaration:
int **ptr; // declaring double pointers
Initialization:
int a= 78;
int *ptr2; // pointer for variable a
int **ptr1; // double pointer for ptr2
ptr2 = &a; // storing address of a in ptr2
ptr1 = &ptr2;

Program for pointer - pointer Output:


int main() Value of var
{ 78
int a= 78; Value of var using
int *ptr2; // pointer for variable a single pointer 78
int **ptr1; // double pointer for ptr2 Value of var using
ptr2 = &a; // storing address of a in ptr2 double 78
ptr1 = &ptr2; // Storing address of ptr2 in ptr1
printf("Value of var = %d\n", a );
printf("Value of var using single pointer = %d\n", *ptr2 );
printf("Value of var using double pointer = %d\n", **ptr1);
return 0;
}

POINTERS AND FUNCTIONS:

PARAMETER PASSING METHODS:


There are two ways to pass value or data to function in C language:

109
CS3251- PROGRAMMING IN C

i) call by value and


ii) call by reference.
Original value is not modified in call by value but it is modified in call by reference.

Call by Value:

- In call by value, original value is not modified.


- In call by value, value being passed to the function is locally stored by the function
parameter.
- So, If you change the value of function parameter, it is changed for the current function
only. It will not change the value of variable inside main().

Passing the value (Call by Value): Output:


#include<stdio.h> Before function call x=10
void my_change(int num); changed value is x=15
int main() After function call x=10
{
int a=10; Note: Value is not modified in
printf("Before function call x=%d \n", a); main function.
my_change(a); //passing value in function
printf("After function call x=%d \n",a);
return 0;
}
void my_change(int num)
{
num=num+5;
printf("changed value is x=%d \n",num);
}

Call by Reference(Pass by reference):

110
CS3251- PROGRAMMING IN C

 In call by reference, original value is modified because we pass reference (address).


 Here, address of the value is passed in the function, so actual and formal arguments
shares the same address space.
 Hence, value changed inside the function, is reflected inside as well as outside the
function.

Passing the address( Call by Reference): Output:


#include<stdio.h> Before function call x=10
void my_change(int *num); changed value is x=20
int main() After function call x=20
{
int a=10; Note: Value is modified in
printf("Before function call x=%d \n", a); main function.
my_change(&a); //passing value in function
printf("After function call x=%d \n",a);
return(0);
}
void my_change(int *num)
{
*num=*num+10;
printf("changed value is x=%d \n",*num);
}

Difference between call by value and call by reference:


Call by value Call by reference
A copy of value is passed to the function An address of value is passed to the function
Changes made inside the function is not Changes made inside the function is reflected
reflected on other functions outside the function.

Actual and formal arguments will be Actual and formal arguments will be created in
created in different memory location same memory location

Slow processing because new address Fast because existing address are used.
are created.

Illustrative Program( Swapping of two numbers and changing the value of a variable
using pass by value and reference)

Swapping of 2 vaues(Exchanging) using call Swapping of 2 values(Exchanging)

111
CS3251- PROGRAMMING IN C

by reference: using call by Reference:

#include<stdio.h> #include<stdio.h>
void swap(int, int); void swap(int *x, int*y);
int main() int main()
{ {
int a=5,b=10; int a=5,b=10;
printf("Before Swap values of a and b is %d printf("Before Swap values of a and b is
%d\n", a, b); %d %d\n", a, b);
swap(a, b); swap(&a, &b);
return(0); printf("After Swap values of a and b is
} %d %d\n", a, b);
return(0);
void swap(int x, int y) }
{
int temp; void swap(int *x, int *y)
temp = x; {
x = y; int temp;
y = temp; temp = *x;
printf("after Swap values of a and b is %d *x = *y;
%d\n", x, y); *y = temp;
} return;
Output: }
before swap,value of an and b is 5 10
after swap,value of a and b is 10 5 Output:
Before Swap values of a and b is 5 10
After Swap values of a and b is 10 5

112
CS3251- PROGRAMMING IN C

UNIT IV STRUCTURES
Structure - Nested structures – Pointer and Structures – Array of structures –
Example Program using structures and pointers – Self referential structures –
Dynamic memory allocation - Singly linked list - typedef.

STRUCTURES:
- Structure is a collection of various data types shares a common name.
- It is a user defined data type.
- Each element in a C structure is called member.
Example:
Student: name, roll no, mark, avg
Book: author, title, price, year
Address: door no, street name, place, state, pin
Arrays Structures
Collection of similar data types. Collection of different data types.
Static memory allocation is done in arrays Dynamic memoryallocation is done in structures.
It uses index or subscript to access It uses (.) dot operator and ->(pointer) operator to
an array element. access members of structures
Array is a pointer to its first element. Structure is not a pointer.
Array is a derived data type. Structure is a user defined data type.
Accessing array element takes less time Accessing structure member takes more time.
It has no keywords. It uses keyword “struct”
Steps :
1. Declaring structure
2. Declaring structure variable
3. Initializing the members of the structure
4. Accessing the members of structure
1. Declaring structure:
Syntax: Example:
struct tag_name struct student
{ {
datatype member 1; char name[10];
datatype member 2; int roll_no;
float percentage;

datatype member n; };

113
CS3251- PROGRAMMING IN C

};
Keyword struct is used for creating a structure. Note: semicolon }; in the ending line is must.

2. Declaring structure variable


Syntax: Example:
struct tag_name
{ struct student
datatype member 1; {
datatype member 2; char name[10];
datatype member 3; int roll_no;
‘ float percentage;
‘ }
struct book s1,s2;
datatype member n;
} variable1, variable2,……. variable n; Note:
Structure variable can be declared within the
structure definition or in the main function.

3.Initializing the members of structure:


Initialization can be done in 2 ways.
 Compile time initialization:
- uses assignment operator(=) to initialize values to the members of structure.
Example:
struct student s1={“ramya”,1001,45.8};
struct student s2={“anitha”,1002,89.6};
 Run time initialization:
- uses scanf function to read the input from the user.
Example:
printf("enter s1 student details");
scanf("%s%d%f",s1.name,&s1.roll_no,&s1.percentage);
printf("enter s2 student details");
scanf("%s%d%f",s2.name,&s2.roll_no,&s2.percentage);

4. Accessing the members of the structure:


- Members can be accessed using .operator (dot). Also pointer operator is used(->)
Syntax:
structure_variable_name . member_name;
Example:
s1.name // to access name of s1

114
CS3251- PROGRAMMING IN C

s2.percentage // to access percentage of s2


Program to print student details( accessing member Output:
using .dot operator): Enter rollno, name , percentage
#include<stdio.h> 1001
struct student ramya
{ 96.8
int roll; Student details are:
char name[10]; ROLL_NO=1001
float percentage; NAME=ramya
}s1; PERCENTAGE=96.80000
int main()
{
printf("Enter rollno, name , percentage\n");
scanf("%d%s%f", &s1.roll, s1.name, &s1.percentage);
printf("Student details are:\n");
printf ("ROLL_NO=%d\n NAME=%s\n
PERCENTAGE=%f\n", s1.roll, s1.name, s1.percentage);
return(0);
}

NESTED STRUCTURE:
A structure with in a structure is called nested structure.
The elements of nested structure are accessed using dot (.) operator.

Syntax:
Example:
structure tagname_1
struct Employee
{
{
data_type member1;
char ename[20];
data_type member2;
int empid;
data_type member3;
int salary;
..
struct date
member n;
{
structure tagname_2
int day;
{
int month;
data_type member_1;
int year;
data_type member_2;
}doj;
data_type member_3;
}emp;
...
member_n;
} var1;
} var2;

115
CS3251- PROGRAMMING IN C

Syntax:

outrstructurevariable . innerstructure variable . innerstructuremember

To Access the Nested members,

Accessing month Field : emp1.doj.month


Accessing day Field : emp1.doj.day

Accessing year Field : emp1.doj.year

Program to display employee details using nested Output:


structure:
#include <stdio.h> Employee Name : ramya
struct Employee
{ Employee ID : 1001
char ename[20];
int empid; Employee Salary : 25000
int salary;
Employee DOJ : 25/9/1988
struct date
{
int day;
int month;
int year;
}doj;
}emp;
int main()
{
struct Employee
emp={"ramya",1001,25000,{25,9,1988}};
printf("\nEmployee Name : %s",emp.ename);
printf("\nEmployee ID : %d",emp.empid);
printf("\nEmployee Salary : %d",emp.salary);
printf("\nEmployee DOJ : %d/%d/%d", emp.doj.day,
emp.doj.month, emp.doj.year);
return 0;
}

116
CS3251- PROGRAMMING IN C

ARRAY OF STRUCTURES:

- Array of structures is nothing but collection of structures.


- Declaring an array of structure is same as declaring an array of fundamental types.
- This is also called as structure array in c.

- Here s is an array of 5 elements where each element is of type struct student.


- We can use s to store 5 structure variables of type struct student.
- To access individual elements we will use subscript notation ([]) and to access the
members of each element we will use dot (.) operator as usual.

Accessing members of array structure:


s[0] : points to the 0th element of the array.
s[1] : points to the 1st element of the array.

s[0].name : refers to the name member of the 0th element of the array.
s[0].roll_no : refers to the roll_no member of the 0th element of the array.
s[0].marks : refers to the marks member of the 0th element of the array.

Program to print 5 student details using array of Output:


structures:
#include<stdio.h> Enter details of student 1
#define MAX 5 Enter name: ravi
struct student Enter roll no: 1005
{ Enter marks: 89.6
char name[20];
int roll_no, i; Enter details of student 2
float marks; Enter name: priya

117
CS3251- PROGRAMMING IN C

}; Enter roll no: 1002


int main() Enter marks: 89.6
{
struct student s[5]; Enter details of student 3
int i; Enter name: mahesh
for(i = 0; i < MAX; i++) Enter roll no: 1003
{ Enter marks: 56.9
printf("\n Enter details of student %d\n\n", i+1);
Enter details of student 4
printf("Enter name: "); Enter name: rini
scanf("%s", s[i].name); Enter roll no: 1004
Enter marks: 96
printf("Enter roll no: ");
scanf("%d", &s[i].roll_no); Enter details of student 5
Enter name: ram
printf("Enter marks: "); Enter roll no: 1005
scanf("%f", &s[i].marks); Enter marks: 36.9
}

printf("\n");
printf("Name\tRoll no\tMarks\n");
for(i = 0; i < MAX; i++ )
{
printf("%s\t%d\t%.2f\n",
s[i].name, s[i].roll_no, s[i].marks);
}
return 0;
}
Note:
Here, array of size 5 to store information of 5 students.

How To Find the Size of Structure?


- sizeof() function is used to find the size of structure.
- sizeof can be applied to any data-type, including primitive types such as integer and floating-point types,
pointer types, or compound datatypes such as Structure, union etc.Syntax:
Example: (Sizeof() for structure)
#include <stdio.h>
struct book
{
int bookid;
char bookname[50];
char author[30];

118
CS3251- PROGRAMMING IN C

};
int main()
{
printf("Size of book structure is :%d",sizeof(b1.bookname));
}
Output:
Size of book structure is :84

POINTER AND STRUCTURE:


C structure can be accessed in 2 ways in a C program. They are,
(i) Using normal structure variable
(ii) Using pointer variable
Dot(.) operator is used to access the data using normal structure variable and
Arrow (->) is used to access the data using pointer variable.
Syntax: Example:
struct name struct product
{ {
member1; int prod_id;
member2; char prod_name[20];
. float price;
}; };
struct name *ptr; struct product *p1;

Difference between normal structure variable and pointer variable:

119
CS3251- PROGRAMMING IN C

Example:
Displaying book details using pointer to a structure:
#include <stdio.h>
struct book
{
int bookid;
char bookname[50];
char author[30];
float price;
};
int main()
{
struct book b1; // structure variable declaration

120
CS3251- PROGRAMMING IN C

struct book *ptr; // pointer variable declaration


ptr=&b1; // pointer variable initialization
printf("enter the bookid\n");
scanf("%d",&ptr->bookid);
printf("enter the book name\n");
scanf("%s",ptr->bookname);
printf("enter author\n");
scanf("%s",&ptr->author);
printf("Enter price");
scanf("%f",&ptr->price);
printf("book details are\n: %d\t %s\t %s\t %f\n\n",ptr->bookid,ptr->bookname,ptr-
>author,ptr->price);
}
Output:
enter the bookid
1001
enter the book name
python
enter author
Rossum
Enter price 450
book details are
1001 python Rossum 450.000000

DYNAMIC MEMORY ALLOCATION:


Why do we need to go for Dynamic Memory Allocation?
 We know, an array is uses static memory allocation technique because, the size of the
array is fixed. So we cannot increase or decrease the size of the array once size is
declared.
 Hence, the array we declared may be insufficient or sometimes size may be more than
what we required.
 To solve this issue, we can allocate memory dynamically.
Dynamic Memory Allocation:
 The process of allocating memory during program execution is called dynamic memory
allocation.
 It allows us to manually handle memory space for our program.
There are 4 library functions defined under <stdlib.h> which can be used for dynamic memory
allocation.
They are,

121
CS3251- PROGRAMMING IN C

malloc()
calloc()
realloc()
free()

(i)malloc() function:
- malloc() stands for "memory allocation".
- malloc () function is used to allocate space in memory during the execution of the
program.
- This function reserves a block of memory of the given size and returns a pointer of
type void (that is to be typecasted)

Syntax:
Pointer_variable= (type_cast*) malloc(Size_in _bytes)
Example:
int *x;
x = (int*)malloc(50 * sizeof(int)); //memory space allocated to variable x
Here, 50 represents the total size to be allocated depending upon 16 bit or 32 bit processor.
Hence given, sizeof() function irrespective of 2 byte or 4 byte integer
- If it fails to allocate enough space as specified, it returns a NULLpointer.
- malloc () does not initialize the memory allocated during execution. It carries garbage
value.
Program (to copy a string to allocated memory using malloc()):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *ptr;
ptr = (char*)malloc( 20 * sizeof(char) ); // memory is allocated dynamically
if( ptr== NULL )
{
printf("Couldn't able to allocate requested memory\n");

122
CS3251- PROGRAMMING IN C

}
else
{
strcpy( ptr,"good morning");
}
printf("Dynamically allocated memory content is : " \"%s\n", ptr);
free(ptr);
return(0);
}
Output:
Dynamically allocated memory content is : good morning

(ii)calloc() function:
 The name calloc() stands for "contiguous allocation".(continues)
 calloc() is another memory allocation function that is used for allocating memory at
runtime.
 This statement will allocate contiguous space in memory for an array of n elements.
 The only difference between malloc() and calloc() is that, malloc() allocates single block
of memory whereas calloc() allocates multiple blocks of memory each of same size
 calloc () initializes the allocated memory to zero. But, malloc() does not.
 If it fails to allocate enough space as specified, it returns a NULL pointer.

Syntax:
Pointer_variable= (type_cast*) calloc(n, element_size)
Example:
float *y;
y= (float*) calloc(25, sizeof(float));
Note:
This statement allocates contiguous space in memory to store 25 elements each of size of float(
i.e, 4 bytes)

Program: (To copy a string to allocated memory using calloc() ):


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *ptr;
ptr = (char*)calloc( 20,sizeof(char) ); // memory is allocated dynamically

123
CS3251- PROGRAMMING IN C

if( ptr== NULL)


{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( ptr,"good morning");
}
printf("Dynamically allocated memory content is : " \"%s\n", ptr);
free(ptr);
return(0);
}
Output:
Dynamically allocated memory content is : good morning

(iii) realloc():
- realloc() used to change the memory size that is already allocated using malloc() and
calloc() functions.

Syntax:
ptr = realloc(ptr, newsize); //ptr is reallocated with size of newsize.
Example:
int *x;
x = (int*)malloc(50 * sizeof(int));
x = (int*)realloc(x,100); //allocated a new memory to variable x

Difference between malloc() and calloc():

free()

124
CS3251- PROGRAMMING IN C

- free() to release the space that are allocated using memory by malloc (), calloc (),
realloc () functions .
- It returns the memory to the system.
Syntax:
free(pointer_variable);
Example:
int *x;
x = (int*)malloc(50 * sizeof(int)); //memory space allocated to variable x
free(x); //releases the memory allocated to variable x

Program: ( To copy a string to allocated memory using realloc())


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *ptr;
ptr = (char *)malloc( 20 * sizeof(char) ); //memory is allocated dynamically
if( ptr == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( ptr,"good morning");
}
printf("Dynamically allocated memory content : %s\n", ptr );
ptr=realloc(ptr,100*sizeof(char));
strcpy( ptr,"can store 100 characters");
printf("Resized memory : %s\n", ptr);
free(ptr);
}

Output:
Dynamically allocated memory content : good morning
Resized memory : can store 100 characters

C Program to generate Salary Slip of employee( Dynamic memory allocation for


Structure using pointers):

125
CS3251- PROGRAMMING IN C

#include <stdio.h> Output:


#include<stdlib.h> enter the number of employee2
struct employee enter the nameravi
{ Enter Basic Salary (RS): 12000
char name[10];
int basic, da, hra, ta, others; Enter Hra1000
int pf,it,t;
int net_salary; Enter da500
}e[10];
int main() Enter TA500
{
int i,n; Enter Others1000
struct employee *ptr;
printf("enter the number of employee"); Enter pf500
scanf("%d",&n);
ptr=(struct employee*)malloc(n * sizeof(struct Enter IT1000
employee)); enter the nameraja
for(i=0;i<n;i++) Enter Basic Salary (RS): 25000
{
printf("enter the name"); Enter Hra1000
scanf("%s",(ptr+i)->name);
printf("Enter Basic Salary (RS): "); Enter da1000
scanf("%d",&(ptr+i)->basic);
printf("\nEnter Hra"); Enter TA1000
scanf("%d",&(ptr+i)->hra);
printf("\nEnter da"); Enter Others500
scanf("%d",&(ptr+i)->da);
printf("\n Enter TA"); Enter pf1000
scanf("%d",&(ptr+i)->ta);
printf("\nEnter Others"); Enter IT1500
scanf("%d",&(ptr+i)->others);
printf("\nEnter pf"); Name is ravi Net Salary
scanf("%d",&(ptr+i)->pf); is:RS 13500
printf("\nEnter IT");
scanf("%d",&(ptr+i)->it); Name is raja Net Salary
is:RS 26000
//calculate net salary
(ptr+i)->net_salary = (ptr+i)->basic + (ptr+i)->da +
(ptr+i)->hra + (ptr+i)->ta + (ptr+i)->others - ((ptr+i)-

126
CS3251- PROGRAMMING IN C

>pf+(ptr+i)->it);
}
//printing Net salary
for(i=0;i<n;i++)
{
printf("\n Name is %s",(ptr+i)->name);
printf("\t Net Salary is:RS %d\n",(ptr+i)-
>net_salary);
}
return(0);
}

SELF REFERENTIAL STRUCTURES:

A structure that contains at least one pointers to a structure as its member along with other
members is known as self-referential structure.

Pointer variable declaration in structure Self-referential structure declaration


struct name { struct name {
member 1; member 1;
member 2; member 2;
... ...
member n; struct name *pointer;
}; };
struct name *pointer;

The above illustrated self referential structure prototype describes one node that comprises of
two logical segments.
One segment stores data and the other segment is a pointer indicating where the next element is
present.
Several such inter-connected nodes create a chain of structures(Linked List).

 A self-referential structure can dynamically be expanded or contracted.


 Operations like insertion or deletion of nodes in a self- referential structure involve
simple and straight forward alteration of pointers.
Singly Linked List(Linear List):

127
CS3251- PROGRAMMING IN C

In linked list, elements are not stored at contiguous location; the elements are linked
using pointers.
A linked list is represented by a pointer to the first node of the linked list.
The first node is called head. If the linked list is empty, then value of head is NULL.
Each node in a list consists of at least two parts:
1) data
2) pointer to the next node
In C, we can represent a node using structures.
Below is an example of a linked list node with an integer data.
Operations on Linked List:
1. Inserting a node in linked list:
A node can be added in three ways
1) At the front of the linked list
2) After a given node.
3) At the end of the linked list.
i) Insertion at the front of linked list:
When a new node is added at the front, it becomes the header of the list. Here, Node E is
added at the front. Hence E becomes the header node and not A.

ii) Inserting node at a given position

iii) Inserting at the End

2. Deleting a node:

128
CS3251- PROGRAMMING IN C

If node to be deleted is root, simply delete it.


To delete a middle node, we must have pointer to the node previous to the node to be
deleted. So if positions is not zero, we run a loop position-1 times and get pointer to the
previous node.
Advantages of linked list over arrays:
1) list uses Dynamic size whereas, array uses static size.
2) Easy to insert/delete element in list where as array requires shifting of elements.
Drawbacks:
1) Random access is not allowed. We have to access elements sequentially starting from the
first node. So we cannot do binary search with linked lists.
2) Extra memory space for a pointer is required with each element of the list.

Program to insert, delete and display the elements in Output:


singly linked list
Program : enter the number of nodes
#include<stdio.h> 4
#include<stdlib.h> Enter the element
#define NULL 0 10
typedef struct list enter the element20
{ enter the element30
int no; enter the element40
struct list *next; enter ur option=
}LIST; 1.insert 2.delete
LIST *p,*t,*h,*y,*ptr,*pt; 3.display 4.exit
void create(void); 3
void insert(void); List elements are:
void delet(void); 10 20 30 40
void display(void); Enter your option
int j,pos,k=1;count; 1
void main() enter the element to be
{ inserted
int n,i=1,opt; 35
printf("%d",sizeof(LIST)); enter the position to insert
printf("enter the number of nodes\n"); 4
scanf("%d",&n);
count=n; Enter your option
while(i<=n) 3
{ List elements are:
create(); 10 20 30 35

129
CS3251- PROGRAMMING IN C

i++; 40
} Enter your option
printf("enter ur option=\n"); 2
printf("1.insert\t 2.delete \t 3.display\t 4.exit\n"); enter the position to delete:
do 2
{
scanf("%d",&opt); Enter your option
switch(opt) 3
{ List elements are:
case 1: 10 30 35 40
insert(); Enter your option
count++; 4
break;
case 2:
delet();
count--;
if(count==0)
{
printf("\n List empty\n");
}
break;
case 3:
printf("List elements are:\n");
display();
break;
}
printf("\nEnter your option\n");
}while(opt!=4);
}
void create()
{
if(p==NULL)
{
p=(LIST*)malloc(sizeof(LIST));
printf("Enter the element\n");
scanf("%d",&p->no);
p->next=NULL;
h=p;
}

130
CS3251- PROGRAMMING IN C

else
{
t=(LIST*)malloc(sizeof(LIST));
printf("enter the element");
scanf("%d",&t->no);
t->next=NULL;
p->next=t;
p=t;
}
}

void insert()
{
t=h;
p=(LIST*)malloc(sizeof(LIST));
printf("enter the element to be inserted\n");
scanf("%d",&p->no);
printf("enter the position to insert\n");
scanf("%d",&pos);
if(pos==1)
{
h=p;
h->next=t;
}
else
{
for(j=1;j<(pos-1);j++)
t=t->next;
p->next=t->next;
t->next=p;
t=p;
}
}
void delet()
{
printf("enter the position to delete:\n");
scanf("%d",&pos);
if(pos==1)
{

131
CS3251- PROGRAMMING IN C

h=h->next;
}
else
{
t=h;
for(j=1;j<(pos-1);j++)
t=t->next;
pt=t->next->next;
free(t->next);
t->next=pt;
}
}
void display()
{
t=h;
while(t->next!=NULL)
{
printf("\t%d",t->no);
t=t->next;
}
printf("\t %d\t",t->no);
}

TYPEDEF:
- Typedef keyword is used to create a user defined name for existing data type.
- Generally typedef are use to create an alias name (nickname).
Syntax:
typedef datatype alias_name;
typedef int intdata;

Example: (Use of typedef on integer data type)


 - In this program, Intdata is
Program:
#include<stdio.h> an user defined name or alias
typedef int Intdata; // Intdata is alias name name for an integer data type.
of int
 - All properties of the integer
int main()
will be applied on Intdata also.
{
int a=10;  - Integerdata is an alias name
Intdata b=20; to existing user defined name

132
CS3251- PROGRAMMING IN C

typedef Intdata Integerdata; // Integerdata is again called Intdata.


alias name of Intdata
Integerdata s;
s=a+b;
printf("\n Sum:= %d",s);
return(0);
}
Output:
Sum:=30

Use of typedef on structure datatype:


 Output:
Program:
#include<stdio.h>  enter the name
typedef struct telephone
 anitha
{
char name[20];  enter the telephone number
int tel_no;  3216546531
}t1;
 Name:anitha
int main()
{  telephone number :909193779
t1 t11;
printf("enter the name");
scanf("%s",t11.name);
printf("enter the telephone number");
scanf("%s",&t11.tel_no);
printf("Name:%s\n",t11.name);
printf("telephone number is:%d",t11.tel_no);
return(0);
}

Example Programs Using Pointer and Structure:

1. C program to read, display, add, and subtract two Output


distances. Distance must bedefined using kms and
meters using structures.(typedef)
Program:
#include <stdio.h> ***MAIN MENU***
typedef struct distance 1. Read the distances
2. Display the distances
{
3. Add the distances

133
CS3251- PROGRAMMING IN C

int kms; 4. Subtract the distances


int metres; 5. EXIT
} DISTANCE; // structure variable Enter your option: 1
DISTANCE add_distance (DISTANCE, DISTANCE);
Enter the first distance in kms
DISTANCE subtract_distance(DISTANCE,DISTANCE); and metres:
DISTANCE dl, d2, d3, d4; 3
320
int main()
{ Enter the second distancekms
int option; and metres:
5
do
100
{
printf("\n ***MAIN MENU***"); ***MAIN MENU***
printf ("\n 1. Read the distances "); 1. Read the distances
printf ("\n 2. Display the distances"); 2. Display the distances
printf ("\n 3. Add the distances "); 3. Add the distances
printf ("\n 4. Subtract the distances"); 4. Subtract the distances
5. EXIT
printf ("\n 5. EXIT");
Enter your option: 2
printf ("\n Enter your option: ");
scanf("%d", &option); The first distance is: 3 kms
switch(option) 320 metres
{ The second distance is: 5 kms
case 1: 100 metres
***MAIN MENU***
printf("\n Enter the first distance in kms and metres:
1. Read the distances
"); 2. Display the distances
scanf ("%d %d", &dl .kms, &dl .metres); 3. Add the distances
printf("\n Enter the second distancekms and metres: 4. Subtract the distances
"); 5. EXIT
scanf ("%d %d" , &d2 .kms, &d2 .metres); Enter your option: 3
break;
The sum of two distances is: 8
case 2:
kms 420 metres
printf("\n The first distance is: %d kms %d metres " ***MAIN MENU***
, dl.kms, dl.metres); 1. Read the distances
printf("\n The second distance is: %d kms %d 2. Display the distances
metres " , d2 .kms, d2 .metres); 3. Add the distances
break; 4. Subtract the distances
case 3: 5. EXIT
Enter your option: 4
d3 = add_distance(dl, d2);
printf("\n The sum of two distances is: %d kms %d The difference between two

134
CS3251- PROGRAMMING IN C

metres", d3.kms, d3.metres); distances is: 1 kms 780 metres


break; ***MAIN MENU***
case 4: 1. Read the distances
2. Display the distances
d4 = subtract_distance(dl, d2);
3. Add the distances
printf("\n The difference between two distances is: 4. Subtract the distances
%d kms %d metres ", d4.kms, d4 .metres); 5. EXIT
break; Enter your option: 5
}
}
while(option != 5);
{
return 0;
}
}
DISTANCE add_distance(DISTANCE dl, DISTANCE d2)
{
DISTANCE sum;
sum.metres = dl.metres + d2. metres;
sum.kms = dl.kms + d2.kms;
if(sum.metres >= 1000)
{
sum.metres = sum.metres%1000;
sum.kms += 1;
}
return sum;
}
DISTANCE subtract_distance(DISTANCE dl,DISTANCE
d2)
{
DISTANCE sub;
if(dl.kms > d2.kms)
{
sub.metres = dl.metres - d2. metres;
sub.kms = dl.kms - d2.kms;
}
else
{
sub.metres = d2.metres - dl. metres;
sub.kms = d2.kms - dl.kms;

135
CS3251- PROGRAMMING IN C

}
if(sub.metres < 0)
{
sub.kms = sub.kms - 1;
sub.metres = sub.metres + 1000;
}
return sub;
}

2.C program to add, subtract two complex numbers using


Output
structure.
Program: Press 1 to add two complex
#include <stdio.h> numbers
#include <stdlib.h> Press 2 to subtract two complex
struct complex numbers
{ Press 3 to exit
int real, img; Enter your choice
}a,b,c; // Structure Variable 1
int main() Enter a and b where a + ib is the
{ first complex number.
int choice; a=3
while(1) b=5
{ Enter c and d where c + id is the
printf("Press 1 to add two complex numbers\n"); second complex number.
printf("Press 2 to subtract two complex numbers\n"); c=2
printf("Press 3 to exit\n"); d=6
printf("Enter your choice\n"); Sum of two complex numbers = 5 +
scanf("%d",&choice); 11i
if( choice == 3) Press any key to enter choice
{ again...
exit(0);
} Press 1 to add two complex
if(choice >= 1 && choice <= 2) numbers
{ Press 2 to subtract two complex
printf("Enter a and b where a + ib is the 1st complex number."); numbers
printf("\na = "); Press 3 to exit
scanf("%d", &a.real); Enter your choice
printf("b = "); 2
scanf("%d", &a.img); Enter a and b where a + ib is the
printf("Enter c and d where c + id is the 2nd complex number."); first complex number.
printf("\nc = "); a=1
scanf("%d", &b.real); b=1
printf("d = "); Enter c and d where c + id is the
scanf("%d", &b.img); second complex number.
} c=2
if ( choice == 1 ) d=1
{ Difference of two complex

136
CS3251- PROGRAMMING IN C

c.real = a.real + b.real; numbers = -1 + 0i


c.img = a.img + b.img; Press any key to enter choice
again...
if ( c.img >= 0 ) Press 1 to add two complex
printf("Sum of two complex numbers = %d + %di", c.real, c.img); numbers
else Press 2 to subtract two complex
printf("Sum of two complex numbers = %d %di",c.real,c.img); numbers
} Press 3 to exit
else if ( choice == 2 ) Enter your choice
{ 3
c.real = a.real - b.real;
c.img = a.img - b.img;

if ( c.img >= 0 )
printf("Difference of two complx no = %d + %di",c.real, c.img);
else
printf("Difference of two complex no = %d %di", c.real, c.img);
}
printf("\nPress any key to enter choice again...\n");
}
}

3.Define a structure called student that would contain name, regno and marks of five
subjects and percentage. Write a C program to read the details of name, regno and marks of
five subjects for 30 students and calculate the percentage and display the name, regno,
marks of 30 subjects and percentage of each student.( AssignmentQuestion)

Storage Classes in C

Storage classes in C are used to determine the lifetime, visibility, memory location, and
initial value of a variable. There are four types of storage classes in C

o Automatic
o External
o Static
o Register

Storage Storage Default Scope Lifetime


Classes Place Value

auto RAM Garbage Local Within function

137
CS3251- PROGRAMMING IN C

Value

extern RAM Zero Global Till the end of the main


program Maybe
declared anywhere in
the program

static RAM Zero Local Till the end of the main


program, Retains value
between multiple
functions call

register Register Garbage Local Within the function


Value

Automatic
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they are
defined.

The scope of the automatic variables is limited to the block in which they are defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.

Example 1

1. #include <stdio.h>
2. int main()
3. {
4. int a; //auto
5. char b;
6. float c;
7. printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b,
and c.

138
CS3251- PROGRAMMING IN C

8. return 0;
9. }

Output:

garbage garbage garbage

Static
o The variables defined as static specifier can hold their value between the multiple
function calls.
o Static local variables are visible only to the function or the block in which they are
defined.
o A same static variable can be declared many times but can be assigned at only one
time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has
declared.
o The keyword used to define static variable is static.

Example 1

1. #include<stdio.h>
2. static char c;
3. static int i;
4. static float f;
5. static char s[100];
6. void main ()
7. {
8. printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
9. }

Output:

0 0 0.000000 (null)

Register
o The variables defined as the register is allocated the memory into the CPU registers
depending upon the size of the memory remaining in the CPU.

139
CS3251- PROGRAMMING IN C

o We can not dereference the register variables, i.e., we can not use &operator for the
register variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the CPU
register. However, it is compiler?s choice whether or not; the variables can be stored
in the register.
o We can store pointers into the register, i.e., a register can store the address of a
variable.
o Static variables can not be stored into the register since we can not use more than one
storage specifier for the same variable.

Example 1
#include <stdio.h>

int main()
1. {
2. register int a; // variable a is allocated memory in the CPU register. The initial default v
alue of a is 0.
3. printf("%d",a);
4. }

Output: 0

External
o The external storage class is used to tell the compiler that the variable defined as
extern is declared with an external linkage elsewhere in the program.
o The variables declared as extern are not allocated any memory. It is only declaration
and intended to specify that the variable is declared elsewhere in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the
external variable within any block or method.
o An external variable can be declared many times but can be initialized at only once.
o If a variable is declared as external then the compiler searches for that variable to be
initialized somewhere in the program which may be extern or static. If it is not, then
the compiler will show an error.

Example 1

1. #include <stdio.h>

140
CS3251- PROGRAMMING IN C

2. int main()
3. {
4. extern int a;
5. printf("%d",a);
6. }

Output

main.c:(.text+0x6): undefined reference to `a'


collect2: error: ld returned 1 exit status

UNIT –V

141
CS3251- PROGRAMMING IN C

File Handling in C Language

A file represents a sequence of bytes on the disk where a group of related data is stored. File
is created for permanent storage of data. It is a readymade structure.

In C language, we use a structure pointer of file type to declare a file.

FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following are
the functions:

Function Description Prototype

create a new file or


fopen() FILE *fp =fopen (“filename”, ”‘mode”);
open a existing file

fclose() closes a file int fclose(FILE *fp);


fgets() get a string from file char *fgets( char *str, int count, FILE *stream );
reads a character
getc() int getc( FILE *stream );
from a file
writes a character to
putc() int putc( int ch, FILE *stream );
a file
reads a set of data
fscanf() int fscanf( FILE *stream, const char *format, ... );
from a file
writes a set of data
fprintf() int fprintf(FILE *fp, const char *format, …)
to a file
reads a integer from
getw() int getw(FILE *fp);
a file
writes a integer to a
putw() int putw(int w, FILE *stream); (deprecated, legacy)
file
set the position to
fseek() int fseek( FILE *stream, long offset, int origin );
desire point
gives current
ftell() long ftell( FILE *stream );
position in the file
set the position to
rewind() void rewind( FILE *stream );
the beginning point

142
CS3251- PROGRAMMING IN C

Function Description Prototype

reads specific
size_t fread( void
fread() number of bytes
*buffer, size_t size, size_t count, FILE *stream);
from binary file
writes specific
size_t fwrite( const void
fwrite() number of bytes to
*buffer, size_t size, size_t count, FILE *stream);
binary files
Opening a File or Creating a File

The fopen() function is used to create a new file or to open an existing file.
General Syntax :

FILE *fp = fopen(const char *filename , const char *mode );

Here filename is the name of the file to be opened and mode specifies the purpose of
opening the file. Mode can be of following types,

*fp is the FILE pointer (*FILE fp ), which will hold the reference to the opened (or created)
file.

Closing a File

The fclose() function is used to close an already opened file.

General Syntax :

int fclose ( FILE *fp ); Here fclose() function closes the file and returns zero on success,
or EOF if there is an error in closing the file. This EOF is a constant defined in the header
file stdio.h.

Input/Output operation on File


In the above table we have discussed about various file I/O functions to perform reading
and writing on file. getc() and putc() are simplest functions used to read and write
individual characters to a file.

#include <stdio.h>
#include <conio.h>
main() {
FILE *fp;
char ch;
// open a text file for writing into it
fp = fopen ("one.txt", "w");
printf("Enter data");

143
CS3251- PROGRAMMING IN C

while( (ch = getchar()) != EOF) {


putc(ch, fp);
}
fclose(fp);
// open a text file for reading from it
fp = fopen("one.txt", "r");
while( (ch = getc(fp)) != EOF)
printf("%c", ch);
fclose(fp);
}

Sample Output

Reading and Writing from File using fprintf() and fscanf()

#include<stdio.h>
#include<conio.h>
struct employee
{
char name[10];
int age;
};

void main(){
struct employee e;
FILE *p, *q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
printf("Enter Name and Age");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);
fclose(p);
do
{
fscanf(q,"%s %d", e.name, &e.age);
printf("%s %d", e.name, e.age);

144
CS3251- PROGRAMMING IN C

} while(!feof(q));
getch();
}

Sample Output

In this program, we have create two FILE pointers and both are referring to the same file
but in different modes. fprintf() function directly writes into the file, while fscanf() reads
from the file, which can then be printed on console using standard printf() function.

Difference between Append and Write Mode

Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are
used to write in a file. In both the modes, new file is created if it doesn't exists already.

The only difference they have is, when you open a file in the write mode, the file is reset,
resulting in deletion of any data already present in the file. While in append mode this will
not happen. Append mode is used to append or add data to the existing data of file (if any).
Hence, when you open a file in Append(a) mode, the cursor is positioned at the end of the
present data in the file.

Reading and Writing in a Binary File

A Binary file is similar to the text file, but it contains only large numerical data. The
Opening modes are mentioned in the table for opening modes above.

fread() and fwrite() functions are used to read and write is a binary file.

fwrite(data_element_to_be_written, size_of_element,number_of_elements, pointer_to_file);


fread() is also used in the same way, with the same arguments like fwrite() function. Below
mentioned is a simple example of writing into a binary file

const char mytext = "The quick brown fox jumps over the lazy dog";
FILE *bfp = fopen("test.txt", "wb");
if (bfp) {
fwrite(mytext , sizeof(char) , strlen(mytext) , bfp);

145
CS3251- PROGRAMMING IN C

fclose(bfp) ;
}
fseek(), ftell() and rewind() functions

 fseek() - It is used to move the reading control to different positions in file.


 ftell() - It tells the byte location of current position of cursor in file pointer.
 rewind() - It moves the control to beginning of the file.

Files

What are files? A file is sequential stream of bytes ending with an end-of-file marker.

As we know, at the time of execution, every program is executed in the main memory.
Main memory is volatile and the data would be lost once the program is terminated. If we
need the same data again, we have to store the data in a file on the disk. A file is sequential
stream of bytes ending with an end-of-file marker.

Storage of data in variables and arrays is temporary—such data is lost when a program
terminates. Files are used for permanent retention of data. Computers store files on
secondary storage devices, such as hard drives, CDs, DVDs and flash drives. In this
chapter, we explain how data files are created, updated and processed by C programs. We
consider both sequential-access and random-access file processing.

File Extensions

File extensions We can usually tell if a file is binary or text based on its file extension. This
is because by convention the extension reflects the file format, but ultimately it is the file
format that dictates whether the file data is binary or text.

Common extensions that are binary file formats:

Images: jpg, png, gif, bmp, tiff, psd, ...


Videos: mp4, mkv, avi, mov, mpg, vob, ...
Audio: mp3, aac, wav, flac, ogg, mka, wma, ...
Documents: pdf, doc, xls, ppt, docx, odt, ...
Archive: zip, rar, 7z, tar, iso, ...
Database: mdb, accde, frm, sqlite, ...
Executable: exe, dll, so, class, ...
Common extensions that are text file formats:

Web standards: html, xml, css, svg, json, ...

146
CS3251- PROGRAMMING IN C

Source code: c, cpp, h, cs, js, py, java, rb, pl, php, sh, ...
Documents: txt, tex, markdown, asciidoc, rtf, ps, ...
Configuration: ini, cfg, rc, reg, ...
Tabular data: csv, tsv, ...

Text File Characteristics

By convention, the data in every text file obeys a number of rules:

 The text looks readable to a human or at least moderately sane. Even if it contains a
heavy proportion of punctuation symbols (like HTML, RTF, and other markup
formats), there is some visible structure and it’s not seemingly random garbage.
 The data format is usually line-oriented. Each line could be a separate command, or a
list of values could put each item on a different line, etc. The maximum number of
characters in each line is usually a reasonable value like 100, not like 1000.
 The text looks readable to a human or at least moderately sane. Even if it contains a
heavy proportion of punctuation symbols (like HTML, RTF, and other markup
formats), there is some visible structure and it’s not seemingly random garbage.

Binary File Characteristics

 For most software that people use in their daily lives, the software consumes and
produces binary files. Examples of such software include Microsoft Office, Adobe
Photoshop, and various audio/video/media players. A typical computer user works
with mostly binary files and very few text files.
 A binary file always needs a matching software to read or write it. For example, an
MP3 file can be produced by a sound recorder or audio editor, and it can be played in
a music player or audio editor. But an MP3 file cannot be played in an image viewer
or a database software.
 Some binary formats are popular enough that a wide variety of programs can produce
or consume it. Image formats like JPEG are the best example – not only can they be
used in image viewers and editors, they can be viewed in web browsers, audio
players (for album art), and document software (such as adding a picture into a Word
doc).

Files and Streams

C views each file simply as a sequential stream of bytes (Fig. 11.1). Each file ends either
with an end-of-file (EOF) marker or at a specific byte number recorded in a system-
maintained, administrative data structure. When a file is opened, a stream is associated with
it.

147
CS3251- PROGRAMMING IN C

 Three files and their associated streams are automatically opened when program
execution begins — the standard input, the standard output and the standard error.
Streams provide communication channels between files and programs.

o For example, the standard input stream enables a program to read data from the
keyboard, and the standard output stream enables a program to print data on
the screen.
o The standard input, standard output and standard error are manipulated using
file pointers stdin, stdout and stderr.
 Opening a file returns a pointer to a FILE structure (defined in <stdio.h>) that
contains information used to process the file.
o In some operating systems, this structure includes a file descriptor, i.e., an
index into an operating system array called the open file table. Each array
element contains a file control block (FCB)—information that the operating
system uses to administer a particular file.
 The standard library provides many functions for reading data from files and for
writing data to files. Function fgetc, like getchar, reads one character from a file.
Function fgetc receives as an argument a FILE pointer for the file from which a
character will be read. The call fgetc(stdin) reads one character from stdin—the
standard input. This call is equivalent to the call getchar().
o Function fputc, like putchar, writes one character to a file.
Function fputc receives as arguments a character to be written and a pointer for
the file to which the character will be written. The function call fputc('a',
stdout) writes the character 'a' to stdout— the standard output. This call is
equivalent to putchar('a').
o Several other functions used to read data from standard input and write data to
standard output have similarly named file-processing functions. The fgets and
fputs functions, for example, can be used to read a line from a file and write a
line to a file, respectively. In the next several sections, we introduce the file-
processing equivalents of functions scanf and printf— fscanf and fprintf.

Function Description

fopen open a file for either sequential or random access

fclose close a file that has been opened for access

fprintf Write to sequential (or text) file

fscanf Read from sequential (or text) file

148
CS3251- PROGRAMMING IN C

Function Description

fread Read from random (or binary) file

rwrite Write to random (or binary) file

Types of file processing

 There are two types of files - text and binary files


 There are two techniques for processing files - sequential and random

Every open file has an associated file position indicator, which describes where read and
write operations take place in the file. The position is always specified in bytes from the
beginning of the file. When a new file is opened, the position indicator is always at the
beginning of the file, i.e., at position 0.
 Writing and reading operations occur at the location of the position indicator and
update the position indicator as well. Thus, if one wishes to read all the data in a file
sequentially or write data to a file sequentially, it is not necessary to be concerned
about the position indicator because the stream I/O functions take care of it
automatically.
 When more control is required, the C library functions that help determine and
change the value of the file position indicator, have to be used. By controlling the
position indicator, random access of a file can be made possible. Here, random means
that data can be read from, or written to, any position in a file without reading or
writing all the preceding data.

Creating a Sequential Access file

C imposes no structure on a file. Thus, notions such as a record of a file do not exist as part
of the C language. The following example shows how you can impose your own record
structure on a file.

Figure 11.2 creates a simple sequential-access file that might be used in an accounts
receivable system to keep track of the amounts owed by a company’s credit clients.

149
CS3251- PROGRAMMING IN C

 For each client, the program obtains an account number, the client’s name and the
client’s balance (i.e., the amount the client owes the company for goods and services
received in the past). The data obtained for each client constitutes a “record” for that
client.
 The account number is used as the record key in this application—the file will be
created and maintained in account-number order. This program assumes the user
enters the records in account number order.

// Fig. 11.2: fig11_02.c


// Creating a sequential file
#include <stdio.h>
#include <stdlib.h>

#define DATAFILE "clients.dat"

int main(void) {
unsigned int account; // account number
char name[30]; // account name
double balance; // account balance

FILE* cfPtr; // cfPtr = clients.dat file pointer

// fopen opens file. Exit program if unable to create file


if ((cfPtr = fopen(DATAFILE, "w")) == NULL) {
puts("File could not be opened");
exit(0);
} // end if

puts("Enter the account, name, and balance.");


puts("Enter EOF to end input.");
printf("%s", "? ");
scanf("%d%29s%lf", &account, name, &balance);

// write account, name and balance into file with fprintf


while (!feof(stdin)) {
fprintf(cfPtr, "%3d %-10s %.2f\n", account, name, balance);
printf("%s", "? ");
scanf("%d%29s%lf", &account, name, &balance);
} // end while
puts("Done");
fclose(cfPtr); // fclose closes file
} // end main

150
CS3251- PROGRAMMING IN C

Demo

Run prog13 in the http://bit.ly/replUnit5


OUTPUT

Enter the account, name, and balance.


Enter EOF to end input.
? 100 Jones 24.98
? 200 Doe 345.67
? 300 White 0.00
? 400 Stone -42.16
? 500 Rich 224.62
? ^D (or ^Z)
Sample clients.dat file contents
100 Jones 24.98
200 Doe 345.67
300 White 0.00
400 Stone -42.16
500 Rich 224.62
Now let’s examine this program.

 cfPtr is a pointer to a FILE structure. A C program administers each file with a


separate FILE structure.
 Each open file must have a separately declared pointer of type FILE that’s used to
refer to the file. The file name — "clients.dat" — will be used by the program and
establishes a “line of communication” with the file. The file pointer cfPtr is assigned
a pointer to the FILE structure for the file opened with fopen.
 Function fopen takes two arguments: a filename (which can include path information
leading to the file’s location) and a file open mode.
o The file open mode "w" indicates that the file is to be opened for writing. If a
file does not exist and it’s opened for writing, fopen creates the file.
o If an existing file is opened for writing, the contents of the file are discarded
without warning.
o In the program, the if statement is used to determine whether the file pointer
cfPtr is NULL (i.e., the file is not opened). If it’s NULL, the program prints an
error message and terminates.
o Otherwise, the program processes the input and writes it to the file.
o The program prompts the user to enter the various fields for each record or to
enter end-of-file when data entry is complete. The tabulation below lists the
key combinations for entering end-of-file (EOF) for various computer
systems.

151
CS3251- PROGRAMMING IN C

Operating system Key combination

Linux/ Mac OS X <Ctrl> d

Windows <Ctrl> z

 The function feof is used to determine whether the end-of-file indicator is set for the
file to which stdin refers. The end-of-file indicator informs the program that there’s
no more data to be processed.

o In Fig. 11.2, the end-of-file indicator is set for the standard input when the user
enters the end-of-file key combination. The argument to function feof is a
pointer to the file being tested for the end-of-file indicator (stdin in this case).
o The function returns a nonzero (true) value when the end-of-file indicator has
been set; otherwise, the function returns zero. The while statement that
includes the feof call in this program continues executing while the end-of-file
indicator is not set.
 Now, data is written to the file clients.dat. The data may be retrieved later by a
program designed to read the file (see Section 11.4). Function fprintf is equivalent to
printf except that fprintf also receives as an argument a file pointer for the file to
which the data will be written. Function fprintf can output data to the standard output
by using stdout as the file pointer, as in:
fprintf( stdout, "%d %s %.2f\n", account, name, balance );

 Finally, the program closes the clients.dat file with fclose and terminates.
Function fclose also receives the file pointer (rather than the filename) as an
argument. If function fclose is not called explicitly, the operating system normally
will close the file when program execution terminates. This is an example of
operating system “housekeeping.”

File Access Modes

Programs may process no files, one file or several files. Each file used in a program will
have a different file pointer returned by fopen. All subsequent file-processing functions
after the file is opened must refer to the file with the appropriate file pointer. Files may be
opened in one of several modes (Fig. 11.5). The binary modes are used when we have to
manage random-access files.

If an error occurs while opening a file in any mode, fopen returns NULL.

Text Mode Description

152
CS3251- PROGRAMMING IN C

Text Mode Description

r Open an existing file for reading.

Create a file for writing. If the file already exists, discard the current
w
contents.

a, a+ Append: open or create a file for writing at the end of the file.

r+ Open an existing file for update (reading and writing).

Create a file for update. If the file already exists, discard the current
w+
contents.

Binary
Description
Mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
ab, ab+ opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode
wb+ opens a binary file in both reading and writing mode

Reading Sequential Access file

Data is stored in files so that the data can be retrieved for processing when needed. The
previous section demonstrated how to create a file for sequential access. This section shows
how to read data sequentially from a file.

// Fig. 11.6: fig11_06.c


// Reading and printing a sequential file
#include <stdio.h>
#include <stdlib.h>

int main(void) {
unsigned int account; // account number
char name[30]; // account name
double balance; // account balance

FILE *cfPtr; // cfPtr = clients.dat file pointer

153
CS3251- PROGRAMMING IN C

// fopen opens file; exits program if file cannot be opened


if ((cfPtr = fopen("clients.dat", "r")) == NULL) {
puts("File could not be opened");
exit(0);
}

printf("%-10s%-13s%s\n", "Account", "Name", "Balance");


fscanf(cfPtr, "%d%29s%lf", &account, name, &balance);

// while not end of file


while (!feof(cfPtr)) {
printf("%-10d%-13s%7.2f\n", account, name, balance);
fscanf(cfPtr, "%d%29s%lf", &account, name, &balance);
} // end while

fclose(cfPtr); // fclose closes the file


} // end main

Sample Output

Account Name Balance


100 Jones 9023.00
200 Frank 234.00
300 Mano 29023.00
400 Bala 2344.00
Sample clients.dat file contents
100 Jones 9023.00
200 Frank 234.00
300 Mano 29023.00
400 Bala 2344.00
Resetting the File Position Pointer To retrieve data sequentially from a file, a program
normally starts reading from the beginning of the file and reads all data consecutively until
the desired data is found. It may be desirable to process the data sequentially in a file
several times (from the beginning of the file) during the execution of a program. The
statement

rewind( cfPtr );
causes a program’s file position pointer—which indicates the number of the next byte in the
file to be read or written—to be repositioned to the beginning of the file (i.e., byte 0)
pointed to by cfPtr. The file position pointer is not really a pointer. Rather it’s an integer
value that specifies the byte in the file at which the next read or write is to occur. This is

154
CS3251- PROGRAMMING IN C

sometimes referred to as the file offset. The file position pointer is a member of
the FILE structure associated with each file.

Read numbers from file and calculate Average


The next program reads five (or more) integer values from the data file num.dat. In this
program end-of-file marker EOF is used to exit the loop.
/* Program to read from the num.dat file
* and find the average of the numbers
*/

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

#define DATAFILE "prog15.dat"

int main() {
FILE* fp;
int n[50], i = 0;
float sum = 0;
if ((fp = fopen(DATAFILE, "r")) == NULL) {
printf("Unable to open %s...\n", DATAFILE);
exit(0);
}
puts("Reading numbers from num.dat");
while (!feof(fp)) {
fscanf(fp, "%d ", &n[i]);
printf("%d %d\n", i, n[i]);
sum += n[i];
i++;
}
fclose(fp);

// if no data is available in the file


if (i == 0)
printf("No data available in %s", DATAFILE);

float average = sum / i;


printf("The average is %.3f for %d numbers\n", average, i);

return 0;
}

155
CS3251- PROGRAMMING IN C

Sample Output

Random access file

As we stated previously, records in a file created with the formatted output


function fprintf are not necessarily the same length. However, individual records of a
random access file are normally fixed in length and may be accessed directly (and thus
quickly) without searching through other records. This makes random-access files
appropriate for airline reservation systems, banking systems, point-of-sale systems, and
other kinds of transaction-processing systems that require rapid access to specific data.
There are other ways of implementing random-access files, but we’ll limit our discussion to
this straightforward approach using fixed-length records.

 Because every record in a random-access file normally has the same length, the exact
location of a record relative to the beginning of the file can be calculated as a
function of the record key. We’ll soon see how this facilitates immediate access to
specific records, even in large files.
 Figure below illustrates one way to implement a random-access file. Such a file is
like a freight train with many cars—some empty and some with cargo. Each car in
the train has the same length.

Fixed-length records enable data to be inserted in a random-access file without destroying


other data in the file. Data stored previously can also be updated or deleted without

156
CS3251- PROGRAMMING IN C

rewriting the entire file. In the following sections we explain how to create a random-access
file, enter data, read the data both sequentially and randomly, update the data, and delete
data no longer needed.

Creating Random Access File


Function fwrite transfers a specified number of bytes beginning at a specified location in
memory to a file. The data is written beginning at the location in the file indicated by the
file position pointer. Function fread transfers a specified number of bytes from the location
in the file specified by the file position pointer to an area in memory beginning with a
specified address. Now, when writing an integer, instead of using

fprintf(fPtr, "%d", number);


which could print a single digit or as many as 11 digits (10 digits plus a sign, each of which
requires 1 byte of storage) for a four-byte integer, we can use

fwrite(&number, sizeof(int), 1, fPtr);


which always writes four bytes on a system with four-byte integers from a variable number
to the file represented by fPtr (we’ll explain the 1 argument shortly). Later, fread can be
used to read those four bytes into an integer variable number. Although fread and fwrite
read and write data, such as integers, in fixed-size rather than variable-size format, the data
they handle are processed in computer “raw data” format (i.e., bytes of data) rather than
in printf’s and scanf’s human-readable text format. Because the “raw” representation of
data is system dependent, “raw data” may not be readable on other systems, or by programs
produced by other compilers or with other compiler options.
Functions fwrite and fread are capable of reading and writing arrays of data to and from
disk. The third argument of both fread and fwrite is the number of elements in the array that
should be read from or written to disk. The preceding fwrite function call writes a single
integer to disk, so the third argument is 1 (as if one element of an array is being written).
File-processing programs rarely write a single field to a file. Normally, they write one struct
at a time, as we show in the following examples.

Consider the following problem statement:

Create a credit-processing system capable of storing up to 100 fixed-length records. Each


record should consist of an account number that will be used as the record key, a last name,
a first name and a balance. The resulting program should be able to update an account,
insert a new account record, delete an account and list all the account records in a formatted
text file for printing. Use a random-access file.
The next several sections introduce the techniques necessary to create the credit-processing
program. Figure 11.10 shows how to open a random-access file, define a record format
using a struct, write data to the disk and close the file. This program initializes all 100
records of the file "credit.dat" with empty structs using the function fwrite. Each empty

157
CS3251- PROGRAMMING IN C

struct contains 0 for the account number, "" (the empty string) for the last name, "" for the
first name and 0.0 for the balance. The file is initialized in this manner to create space on
disk in which the file will be stored and to make it possible to determine whether a record
contains data.
// Fig. 11.10: fig11_10.c
// Creating a random-access file sequentially
#include <stdio.h>

// clientData structure definition


struct clientData {
unsigned int acctNum; // account number
char lastName[15]; // account last name
char firstName[10]; // account first name
double balance; // account balance
}; // end structure clientData

int main(void) {
unsigned int i; // counter used to count from 1-100
// create clientData with default information
struct clientData blankClient = {0, "", "", 0.0};
FILE *cfPtr; // credit.dat file pointer

// fopen opens the file; exits if file cannot be opened


if ((cfPtr = fopen("credit.dat", "wb")) == NULL) {
puts("File could not be opened.");
} // end if
else {
// output 100 blank records to file
for (i = 1; i <= 100; ++i) {
fwrite(&blankClient, sizeof(struct clientData), 1, cfPtr);
}

fclose(cfPtr); // fclose closes the file


} // end else
} // end main
Function fwrite writes a block of bytes to a file. The structure blankClient of
size sizeof(struct clientData) is written to the file pointed to by cfPtr. The
operator sizeof returns the size in bytes of its operand in parentheses (in this case struct
clientData). Function fwrite can actually be used to write several elements of an array of
objects. To do so, supply in the call to fwrite a pointer to an array as the first argument and
the number of elements to be written as the third argument. In the preceding
statement, fwrite was used to write a single object that was not an array element. Writing a
single object is equivalent to writing one element of an array, hence the 1 in the fwrite call.

158
CS3251- PROGRAMMING IN C

Writing Random Access Data

Figure 11.11 writes data to the file "credit.dat". It uses the combination
of fseek and fwrite to store data at specific locations in the file. Function fseek sets the file
position pointer to a specific position in the file, then fwrite writes the data.

// Fig. 11.11: fig11_11.c


// Writing data randomly to a random-access file
#include <stdio.h>
#include <stdlib.h>

// clientData structure definition


struct clientData {
unsigned int acctNum; // account number
char lastName[15]; // account last name
char firstName[10]; // account first name
double balance; // account balance
}; // end structure clientData

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


FILE *cfPtr; // credit.dat file pointer

// create clientData with default information


struct clientData client = {0, "", "", 0.0};

// fopen opens the file; exits if file cannot be opened


if ((cfPtr = fopen("credit.dat", "rb+")) == NULL) {
printf("%s: File could not be opened.\n", argv[0]);
exit(-1);
} // end if
// require user to specify account number
printf("%s", "Enter account number"
"(1 to 100, 0 to end input)\n?");
scanf("%d", &client.acctNum);

// user enters information, which is copied into file


while (client.acctNum != 0) {
// user enters last name, first name and balance
printf("%s", "Enter lastname, firstname, balance\n? ");

// set record lastName, firstName and balance value


fscanf(stdin, "%14s%9s%lf", client.lastName, client.firstName,
&client.balance);

159
CS3251- PROGRAMMING IN C

// seek position in file to user-specified record


fseek(cfPtr, (client.acctNum - 1) * sizeof(struct clientData), SEEK_SET);

// write user-specified information in file


fwrite(&client, sizeof(struct clientData), 1, cfPtr);

// enable user to input another account number


printf("%s", "Enter account number\n? ");
scanf("%d", &client.acctNum);
} // end while

fclose(cfPtr); // fclose closes the file


} // end main
We position the file position pointer for the file referenced by cfPtr to the byte location
calculated by

`(client.accountNum - 1) * sizeof(struct clientData)`.


The value of this expression is called the offset or the displacement. Because the account
number is between 1 and 100 but the byte positions in the file start with 0, 1 is subtracted
from the account number when calculating the byte location of the record. Thus, for record
1, the file position pointer is set to byte 0 of the file. The symbolic
constant SEEK_SET indicates that the file position pointer is positioned relative to the
beginning of the file by the amount of the offset. As the above statement indicates, a seek
for account number 1 in the file sets the file position pointer to the beginning of the file
because the byte location calculated is 0.
int fseek( FILE *stream, long int offset, int whence );
The function prototype for fseek is where offset is the number of bytes to seek from whence
in the file pointed to by stream—a positive offset seeks forward and a negative one seeks
backward. Argument whence is one of the
values SEEK_SET, SEEK_CUR or SEEK_END (all defined in <stdio.h>), which indicate
the location from which the seek begins.
SEEK_SET - the seek starts at the beginning of the file
SEEK_CUR - the seek starts at the current location in the file and
SEEK_END - the seek starts at the end of the file

Return values

 Function fscanf returns the number of data items successfully read or the
value EOF if a problem occurs while reading data.
 Function fseek returns a nonzero value if the seek operation cannot be performed.

160
CS3251- PROGRAMMING IN C

 Function fwrite returns the number of items it successfully output. If this number is
less than the third argument in the function call, then a write error occurred.

A sample execution is shown below the code.

Sample Output

Reading Random Access Data


Function fread reads a specified number of bytes from a file into memory. For example,

fread(&client, sizeof(struct clientData), 1, cfPtr);


reads the number of bytes determined by sizeof(struct clientData) from the file referenced
by cfPtr, stores the data in client and returns the number of bytes read. The bytes are read
from the location specified by the file position pointer. Function fread can read several
fixed-size array elements by providing a pointer to the array in which the elements will be
stored and by indicating the number of elements to be read. The preceding statement reads
one element.
To read more than one, specify the number of elements as fread’s third argument. Function
fread returns the number of items it successfully input. If this number is less than the third
argument in the function call, then a read error occurred.

Figure 11.14 reads sequentially every record in the "credit.dat" file, determines whether
each record contains data and displays the formatted data for records containing data.
Function feof determines when the end of the file is reached, and the fread function
transfers data from the file to the clientData structure client.
// Fig. 11.14: fig11_14.c
// Reading a random-access file sequentially
#include <stdio.h>

// clientData structure definition


struct clientData {
unsigned int acctNum; // account number
char lastName[15]; // account last name
char firstName[10]; // account first name

161
CS3251- PROGRAMMING IN C

double balance; // account balance


}; // end structure clientData

int main(void) {
FILE *cfPtr; // credit.dat file pointer
int result; // used to test whether fread read any bytes

// create clientData with default information


struct clientData client = {0, "", "", 0.0};

// fopen opens the file; exits if file cannot be opened


if ((cfPtr = fopen("credit.dat", "rb")) == NULL) {
puts("File could not be opened.");
} // end if
else {
printf("%-6s%-16s%-11s%10s\n", "Acct", "Last Name", "First Name",
"Balance");

// read all records from file (until eof)


while (!feof(cfPtr)) {
result = fread(&client, sizeof(struct clientData), 1, cfPtr);

// display record
if (result != 0 && client.acctNum != 0) {
printf("%-6d%-16s%-11s%10.2f\n", client.acctNum, client.lastName,
client.firstName, client.balance);
} // end if
} // end while

fclose(cfPtr); // fclose closes the file


} // end else
} // end main
Sample Output

Fig. 11.14 | Reading a random-access file sequentially. (Part 2 of 2)

162
CS3251- PROGRAMMING IN C

Command line arguments

Command line arguments are simply arguments that are specified after the name of the
program in the system's command line, and these argument values are passed on to your
program during program execution.

On many UNIX systems, it is possible to pass arguments to main from the command line
by including the parameters int argc and char *argv[] in the parameter list of main().
 Parameter argc receives the number of command-line arguments
 Parameter argv is an array of strings in which the actual command-line arguments
are stored

 Common uses of command-line arguments include passing options to a program and


passing filenames to a program.

It is possible to pass arguments to C programs when they are executed. The brackets which
follow main() are used for this purpose. argc refers to the number of arguments passed,
and argv[] is a pointer array which points to each argument which is passed to main.

Simple example

A simple example follows, which checks to see if a single argument is supplied on the
command line when the program is invoked. The program is called by the command line,

> myprog argument1


The actual C code for the program is presented below:
#include <stdio.h>

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


printf("%s: ", argv[0]);
if(argc == 2)
printf("The argument supplied is %s\n", argv[1]);
else if(argc > 2)
printf("Too many arguments supplied.\n");

163
CS3251- PROGRAMMING IN C

else
printf("One argument expected.\n");

printf("%s: '%s' is the last argument!\n",


argv[0], argv[argc-1]);
return 0;
}
Note that argv[0] is the name of the program invoked, which means that argv[1] is a pointer
to the first argument supplied, and argv[argc-1] is a pointer to the last argument. If no
arguments are supplied, argc will be 1. Thus for n arguments, argc will be equal to n + 1.

Sample Output

/* Program to copy contents from one file to


* another using command line arguments
*
* Usage: mycopy file1.dat file2.dat
*
*/

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

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


FILE *inFilePtr; // input file pointer
FILE *outFilePtr; // output file pointer
int c; // to hold chars read from the source file

// check number of command-line arguments


if (argc != 3) {
puts("Usage: mycopy infile outfile");
exit(-1);
}

164
CS3251- PROGRAMMING IN C

// if input file cannot be opened


if ((inFilePtr = fopen(argv[1], "r")) == NULL) {
printf("File \"%s\" could not be opened\n", argv[1]);
exit(-1);
}
// if output file can be opened
if ((outFilePtr = fopen(argv[2], "w")) == NULL) {
printf("File \"%s\" could not be opened\n", argv[2]);
exit(-1);
}
// read and output characters
while ((c = fgetc(inFilePtr)) != EOF)
fputc(c, outFilePtr);

fclose(outFilePtr); // close the output file


fclose(inFilePtr); // close the input file
return 0;
} // end of main

Sample Output

FAQ

1. What is file?
A file is a collection of bytes stored on a secondary storage device, which is generally a disk
of some kind. It is identified by a name, which is given at the time of its creation. It may be
amended, moved from one storage device to another or removed completely when desired.

2. What is a stream?
In C, the stream is a common, logical interface to the various devices that form the
computer. When the program executes, each stream is tied together to a specific device that
is source or destination of data. The stream provides a consistent interface and to the
programmer one hardware device will look much like another. In its most common form, a

165
CS3251- PROGRAMMING IN C

stream is a logical interface to a file. Stream I/O uses some temporary storage area, called
buffer, for reading from or writing data to a file. A stream is linked to a file by using an
open operation. A stream is disassociated from a file using a close operation. The C
language provides three “standard” streams that are always available to a C program. These
are

Name Description Example


stdin Standard Input Keyboard
stdout Standard Output Screen
stderr Standard Error Screen
3. What is buffer? What’s its purpose?
Buffer is a temporary storage area that holds data while they are being transferred to and
from memory. Buffering is a scheme that prevents excessive access to a physical I/O device
like a disk or a terminal. Its purpose is to synchronize the physical devices that the program
needs. The buffer collects output data until there are enough to write efficiently. The
buffering activities are taken care of by software called device drivers or access methods
provided by the operating system.

4. Why have buffers?


It speeds up input/output which can be a major bottleneck in execution times. That is, it is
less time-consuming to transmit several characters as a block than to send them one by one.

5. What is FILE?
FILE is a structure declared in stdio.h. The members of the FILE structure are used by the
program in the various file access operations. For each file that is to be opened, a pointer to
type FILE must be declared. When the function fopen() is called, that function creates an
instance of the FILE structure and returns a pointer to that structure. This pointer is used in
all subsequent operations on the file. But programmers don’t need to be concerned about
the members of the structure FILE.
Because one may use a number of different files in the program, he or she must specify
when reading or writing which file one wishes to use. This is accomplished by using a
variable called a file pointer, a pointer variable that points to a structure FILE.

6. How many files can I open at once?


The number of files that can be opened at once will be determined by the value of the
constant FOPEN_MAX that is defined in <stdio.h>. FOPEN_MAX is an integer that
specifies the maximum number of streams that can be open at one time. The C language
standard requires that the value of FOPEN_MAX be at least 8, including the standard
streams stdin, stdout and stderr. Thus, as a minimum, it’s possible to work with up to 5 files
simultaneously.
7. What is the advantage of text files over binary files?
Due to differences in binary data representations across platforms, files written in binary
format often are not portable. For more portable file representations, consider using text
files

166
CS3251- PROGRAMMING IN C

167

You might also like