Programming in C Unit Vise Lecture Notes
Programming in C Unit Vise Lecture Notes
The programming language „C‟ was developed in the early 1970s by Dennis Ritchie at Bell
Laboratories. Although C was initially developed for writing system software, today it has become
such a popular language that a variety of software programs are written using this language. The
greatest advantage of using C for programming is that it can be easily used on different types of
computers. Many other programming languages such as C++ and Java are also based on C which
means that you will be able to learn them easily in the future. Today, C is widely used with the
UNIX operating system.
Programming Languages
Computer programming languages are developed with the primary objectives of facilitating a large
number of people to use computer without the need to know the details of internal structure of the
computer.
Structure of C program
A C program contains one or more functions, where a function is defined as a group of statements
that perform a well-defined task. Figure 1.1 shows the structure of a C program.
The statements in a function are written in a logical sequence to perform a specific task. The main()
function is the most important function and is a part of every C program.
lOMoARcPSD|28529566
Rather, the execution of a C program begins with this function. From the structure given in Fig. 1.1, we can
conclude that a C program can have any number of functions depending on the tasks that have to be
performed, and each function can have any number of statements arranged according to specific
meaningful sequence.
Note that programmers can choose any name for functions. It is not mandatory to write Function1,
Function2, etc., with an exception that every program must contain one function that has its name
as main().
Fig 1.1 Structure of C program
lOMoARcPSD|28529566
Storage classes
Storage classes of a variable determine:
1. Storage area of the variable
2. Initial value of variable if not initialized
3. Lifetime of the variable
lOMoARcPSD|28529566
{
int b=20;
printf(“b=%d”,b);
}
printf(“Here b is not visible\n”);
printf(“a=%d”,a);
lOMoARcPSD|28529566
Output a=10
b=20
Here b is not
visible a=10
2. The register storage class
Register variables can be accessed faster than others
Variables are stored in CPU.
Variables have automatic (local) lifetime.
Register variables are not implicitly initialized.
Register variables have no linkage.
Register variables are used for loop counter to improve the performance of a program.
Example:
# include<stdio.h>
void main()
{
register int a=200;
printf(“a=%d”,a);
}
Output:
a=200
Ex:
# include<stdio.h>
void fun(int); void
main()
{
int i=0;
for(i=0;i<5;i++)
{
fun(i);
}
}
void fun(int i)
{
static int a=10; a+
+;
printf(“%d”,a);
}
Output:
11 12 13 14 15
4. The extern storage class
Variables that are available to all functions are called external or global variables.
External variables are stored in main memory.
External variables have static (global) lifetime.
External variables have external linkage.
External variables are implicitly initialized to 0.
Example: extern
int v=10; void
call1()
void main()
{
call1();
printf(“In main v=%d”,v);
}
void call1()
{
printf(“In call1() v=%d”,v);
}
Output:
In main v=10 In call1( )
v=10
Since v is a external variable it is visible and accessed in all functions.
Eg:
typedef char* cp;
cp c; // is same as char * c;
cp and (char *) can be used interchangeably.
Literal constants
Literal constant or just literal denotes a fixed value, which may be an integer, floating point
number, character or a string.
Literal constants are of the following types.
1. Integer Literal constant
2. Floating point Literal constant
3. Character Literal constant
4. String Literal constant
Qualified constants:
Qualified constants are created by using const qualifier.
E.g. const char a = „A‟
The usage of const qualifier places a lock on the variable after placing the value in it. So we can‟t
change the value of the variable a
Symbolic constants
Symbolic constants are created with the help of the define preprocessor directive. For ex #define
PI= 3.14 defines PI as a symbolic constant with the value 3.14. Each symbolic constant is replaced
by its actual value during the pre-processing stage.
Keywords
Keyword is a reserved word that has a particular meaning in the programming language. The
meaning of a keyword is predefined. It can‟t be used as an identifier.
Operators: Precedence and Associativity
Operands
An operand specifies an entity on which an operation is to be performed. It can be a variable
name, a constant, a function call.
E.g: a=2+3 Here a, 2 & 3 are operands
Operator
An operator is a symbol that is used to perform specific mathematical or logical manipulations.
For e.g, a=2+3 Here = & + are the operators
Precedence of operators
The precedence rule is used to determine the order of application of
operators in evaluating sub expressions.
Each operator in C has a precedence associated with it.
The operator with the highest precedence is operated first.
Associativity of operators
The associativity rule is applied when two or more operators are having same precedence in the
sub expression.
An operator can be left-to-right associative or right-to-left associative.
sub expression.
Expressions
An expression is a sequence of operators and operands that specifies computation of a value.
For e.g, a=2+3 is an expression with three operands a,2,3 and 2 operators = & +
Simple Expressions & Compound Expressions
An expression that has only one operator is known as a simple expression.
E.g: a+2
An expression that involves more than one operator is called a compound expression.
E.g: b=2+3*5
Classification of Operators
The operators in C are classified on the basis of
1) The number of operands on which an operator operates
2) The role of an operator
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modular
Division
&& Logical AND
3. Ternary Operator
A ternary operator operates on 3 operands. Conditional operator (i.e. ?:) is the ternary operator.
Classification based on role of operands
Based upon their role, operators are classified as,
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Miscellaneous Operators
1. Arithmetic Operators
They are used to perform arithmetic operations like addition, subtraction, multiplication, division
etc.
A=10 & B=20
Increment operator
The operator ++ adds one to its operand.
++a or a++ is equivalent to a=a+1
Prefix increment (++a) operator will increment the variable BEFORE
the expression is evaluated.
Postfix increment operator (a++) will increment AFTER the
expression evaluation.
E.g.
1. c=++a. Assume a=2 so c=3 because the value of a is incremented
and then it is assigned to c.
2. d=b++ Assume b=2 so d=2 because the value of b is assigned to d
before it is incremented.
Decrement operator
The operator – subtracts one from its operand.
--a or a-- is equivalent to a=a+1
Prefix decrement (--a) operator will decrement the variable BEFORE
the expression is evaluated.
Postfix decrement operator (a--) will decrement AFTER the
expression evaluation.
E.g.
1. c=--a. Assume a=2 so c=1 because the value of a is decremented
and then it is assigned to c.
2. d=b-- Assume b=2 so d=2 because the value of b is assigned to d
before it is decremented.
2. Relational Operators
Relational operators are used to compare two operands. There are 6
relational operators in C, they are
4. Bitwise Operators
C language provides 6 operators for bit manipulation. Bitwise operator operates on the
individual bits of the operands. They are used for bit manipulation.
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
Truth tables
5. Assignment Operators
To assign a value to the variable assignment operator is used.
6. Miscellaneous Operators
Other operators available in C are
a. Function Call Operator(i.e. ( ) )
b. Array subscript Operator(i.e [ ])
c. Member Select Operator
i. Direct member access operator (i.e. . dot operator)
ii. Indirect member access operator (i.e. -> arrow operator)
d. Conditional operator (?:)
e. Comma operator (,)
f. sizeof operator
g. Address-of operator (&)
a) Comma operator
It is used to join multiple expressions together.
E.g.
int i , j; i=(j=10,j+20
In the above declaration, right hand side consists of two expressions separated by comma. The first
expression is j=10 and second is j+20. These expressions are evaluated from left to right. ie first
the value 10 is assigned to j and then expression j+20 is evaluated so the final value of i will be 30.
b) sizeof Operator
The sizeof operator returns the size of its operand in bytes.
Example : size of (char) will give us 1.
sizeof(a), where a is integer, will return 2.
c) Conditional Operator
It is the only ternary operator available in C.
Conditional operator takes three operands and consists of two symbols ? and : .
Conditional operators are used for decision making in C.
Syntax :
(Condition? true_value: false_value);
For example:
c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
d) Address-of Operator
It is used to find the address of a data object.
Syntax
Input/Output statements
The I/O functions are classified into two types:
Formatted Functions
Unformatted functions
printf() getch()
getche()
getchar()
scanf()
gets()
putch()
putchar()
puts()
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 elements. These data elements have the same data type. The elements
of the array are stored in consecutive memory locations and are referenced by an index (also known as
subscript). Subscript indicates an ordinal number of the elements counted from the beginning of the array.
Definition:
An array is a data structure that is used to store data of the same type. The position of an element is specified
with an integer value known as index or subscript.
E.g.
a(integer array)
Characteristics:
i) All the elements of an array share a common name called as array name
ii) The individual elements of an array are referred based on their position.
Declarations of Arrays
Array has to be declared before using it in C Program. Declaring Array means specifying three things.
Data_type Data Type of Each Element of the array
Here the type can be either int, float, double, char or any oher valid data type. The number within the
brackets indicates the size of the array, i.e., the maximum number of elements that can be stored in the array.
ex: int marks[10]
Initialization of arrays
Elements of the array can also be initialized at the time of declaration as in the case of every other variable.
When an array is initialized, we need to provide a value for every element in the array. Arrays are initialized
by writing,
type array_name[size] = { list of values};
The values are written with curly brackets and every value is separated by a comma. It is a compiler error to
specify more number of values than the number of elements in the array.
ex: int marks[5] = {90, 92, 78, 82, 58};
1 3 5 2
a
[0] [1] [2] [3] subscripts or indices
E.g. int a[4]; // a is an array of 4 integers char b[6]; //b is an array of 6 characters
Rules
a) Elements of an array can be initialized by using an initialization list. An initialization list is a comma
separated list of initializers enclosed within braces.
Eg) int a[3]={1,3,4};
b) If the number of initializers in the list is less than array size, the leading array locations gets
initialized with the given values. The rest of the array locations gets initialized to
0 - for int array
0.0 - for float array
\0 - for character array Eg) int a[2]={1};
a char b[5]={‘A’.’r’,’r’};
b
Usage of single dimensional array
The elements of single dimensional array can be accessed by using a subscript operator([]) and a subscript.
Output:
Enter number of students 5
Enter marks of students 55
60
78
85
90
Average=73.6
Example Programs
C Program to Find Mean, Median, and Mode of Given Numbers.
#define SIZE 100 #include"stdio.h"
float mean_function(float[],int); float median_function(float[],int); float mode_function(float[],int); int
main()
{
int i,n,choice;
float array[SIZE],mean,median,mode; printf("Enter No of Elements\n"); scanf("%d",&n);
printf("Enter Elements\n"); for(i=0;i scanf("%f",&array[i]);
do
{
printf("\n\tEnter Choice\n\t1.Mean\n\t2.Median\n\t3.Mode\n4.Exit"); scanf("%d",&choice);
switch(choice)
{
case 1: mean=mean_function(array,n); printf("\n\tMean = %f\n",mean); break;
Introduction to functions
A function is a subprogram of one or more statements that performs a specific task when called.
Advantages of Functions:
1. Code reusability
2. Better readability
3. Reduction in code redundancy
4. Easy to debug & test.
Classification of functions:
• Based on who develops the function
• Based on the number of arguments a function accepts
1. Based on who develops the function
There are two types.
1. Library functions
2. User-defined functions
1. Library functions [Built-in functions]
Library functions are predefined functions. These functions are already developed by someone and are
available to the user for use. Ex. printf( ), scanf( ).
2. User-defined functions
User-defined functions are defined by the user at the time of writing a program. Ex. sum( ), square( )
Using Functions
A function can be compared to a black box that takes in inputs, processes it, and then outputs the
result. Terminologies using functions are:
A function f that uses another function g is known as the calling function,
and g is known as the called function.
The inputs that a function takes are known as arguments.
When a called function returns some result back to the calling function, it is said to return that result.
The calling function may or may not pass parameters to the called function. If the called function
accepts arguments, the calling function will pass parameters, else not.
Function declaration is a declaration statement that identifies a function’s
name, a list of arguments that it accepts, and the type of data it returns.
Function definition consists of a function header that identifies the function, followed by the body of
the function containing the executable code for that function.
Function Prototype
Before using a function, the compiler must know the number of parameters and the type of parameters that
the function expects to receive and the data type of
value that it will return to the calling program. Placing the function declaration statement prior to its use
enables the compiler to make a check on the arguments used while calling that function.
Syntax:
return_data_type function_name(data_type variable1, data_type variable2,..); Here, function_name is a valid
name for the function. Naming a function follows the same rules that are followed while naming variables. A
function should
have a meaningful name that must specify the task that the function will perform.
return_data_type specifies the data type of the value that will be returned to the calling function as a result of
the processing performed by the called function.
(data_type variable1, data_type variable2, ...) is a list of variables of specified data types.
These variables are passed from the calling function to the called function. They are also known as
arguments or parameters that the called function accepts to perform its task.
Function definition
When a function is defined, space is allocated for that function in the memory. A function definition
comprises of two parts:
Function header
Function body
The syntax of a function definition can be given as:
return_data_type function_name(data_type variable1, data_type variable2,..)
{
.............
statements
.............
return(variable);
}
Function Call
The function call statement invokes the function. When a function is invoked, the compiler jumps to the
called function to execute the statements that are a part of that function. Once the called function is executed,
the program control passes back to the calling function.
Syntax:
function_name(variable1, variable2, ...);
The following points are to be noted while calling a function:
Function name and the number and the type of arguments in the function call must be same as that
given in the function declaration and the function header of the function definition.
Names (and not the types) of variables in function declaration, function call, and header of function
definition may vary.
Arguments may be passed in the form of expressions to the called function. In such a case, arguments
are first evaluated and converted to the type of formal parameter and then the body of the function gets
executed.
If the return type of the function is not void, then the value returned by the called function may be
assigned to some variable as given below. variable_name = function_name(variable1, variable2, ...);
Working of a function
void main()
{
int x,y,z;
int abc(int, int, int) // Function declaration
…..
…..
abc(x,y,z) // Function Call
… Actual arguments
…
}
Calling function – The function that calls a function is known as a calling function.
Called function – The function that has been called is known as a called function.
Actual arguments – The arguments of the calling function are called as actual arguments.
Formal arguments – The arguments of called function are called as formal arguments.
Steps for function Execution:
1. After the execution of the function call statement, the program control is transferred to the called
function.
2. The execution of the calling function is suspended and the called function starts execution.
3. After the execution of the called function, the program control returns to the calling function
and the calling function resumes its execution.
4 double log(double x)
Returns the natural logarithm (base-e logarithm) of x.
5 double sqrt(double x) Returns the square root of x.
6 double pow(double x, double y) Returns x raised to the power of y.
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
Introduction
Using C language we can create new data types. These data types are known as User Defined data types &
can be created by using Structures, Unions & Enumerations.
Need for Structure
Arrays can store data of same data type. They can’t be used to store data of different data types. For this
Structures are used.
Structures
A structure is a collection of variables of different types under a single name. It is used for storing different
types of data.
3 aspects:
1. Defining a structure type
2. Declaring variables
3. Using & performing operations.
Structure Definition
The structure can be defined with the keyword struct followed by the name of structure and opening brace
with data elements of different type then closing brace with semicolon.
General Form
struct [structure tag name]
{
type membername1; type membername2;
……
}[variable name];
E.g.
struct book
{
char title[25]; int pages;
float price;
};
• Structure definition does not reserve any space in the memory.
• It is not possible to initialize the structure members during the structure definition.
• A structure definition must always be terminated with a semicolon.
Rules for Structure members
1. A structure can have data of different types
2. A structure can’t contain an instance of itself.
E.g.
struct box
{
struct box a; // not possible
};
3. A structure can contain members of other complete types.
E.g.
struct name
{
char firstname[20]; char lastname[20];
};
struct person
{
struct name personname; float salary;
}
Variables of structure type can be declared either at the time of structure definition or after the structure
definition.
General Form
struct structurename variablename[=initialization list]; E.g.
struct book b1,b2;
struct book b3={“CP”,500,385.00};
Accessing Members of Structure
There are two types of operators used for accessing members of a structure.
1. Direct member access operator (dot operator) (.)
2. Indirect member access operator (arrow operator) (->)
Using Dot operator General form:
structure variable name.member variable name E.g.
Suppose, we want to access title of structure variable b1, then, it can be accessed as:
b1.title
We can also directly assign values to members.
b1.title= “CP”;
Structures within a Structure (Nested Structures)
A structure can be nested within another structure. Structure within structure is known as nested structure
i.e.) one structure can be declared inside other.
1 70 58 68 AjithKesav
2 90 86 95 RishikKesav
nested structure
Pointer and Structures
It is possible to create a pointer to a structure. A Structure containing a member that is a pointer to the same
structure type is called self referential structure. A pointer variable for the structure can be declared by
placing an asterisk(*) in front of the structure pointer variable.
Syntax:
struct namedstructuretype
*identifiername;
Example:
struct struct_name
{
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
Introduction
A file is a semi-permanent, named collection of data. A File is usually stored on magnetic media, such as a
hard disk or magnetic tape. Semi-permanent means that data saved in files stays safe until it is deleted or
modified.
Named means that a particular collection of data on a disk has a name, like mydata.dat and access to the
collection is done by using its name.
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.
Types of Files
1. Text files
2. Binary files
1. Text Files
A text file consists of consecutive characters, which are interpreted by the library functions used to access
them and by format specifiers used in functions.
Text files are the normal .txt files that you can easily create using Notepad or any simple text editors.
They take minimum effort to maintain, are easily readable, and provide least security and takes bigger
storage space.
2. Binary files
A binary file consists of bytes of data arranged in continuous block. A separate set of library functions is
there to process such data files.
Binary files are mostly the .bin files in your computer. Instead of storing data in plain text, they store it in the
binary form (0's and 1's). They can hold higher amount of data, are not readable easily and provides a better
security than text files.
File Operations
In C, you can perform four major operations on the file, either text or binary:
1. Creating a new file
2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file
Function description
fopen() - create a new file or open a existing file fclose() - closes a file
getc() - reads a character from a file putc() - writes a character to a file fscanf() - reads a set of data from a
file fprintf() - writes a set of data to a file getw() - reads a integer from a file putw() - writes a integer to a file
fseek() - set the position to desire point ftell() - gives current position in the file
rewind() - sets the position to the beginning point
1. Opening a File or Creating a File
Opening a file means creating a new file with specified file name and with accessing mode.
The fopen() function is used to create a new file or to open an existing file.
Syntax:
*fp = FILE *fopen(const char *filename, const char *mode);
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created) file.
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:
Mode Description
Mode Purpose
r opens a text file in reading mode
w opens or create a text file in writing mode.
a opens a text file in append mode
r+ opens a text file in both reading and writing mode
w+ opens a text file in both reading and writing mode
a+ opens a text file in both reading and writing mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
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
ab+ opens a binary file in both reading and writing mode
2. Closing a File
A file must be closed after all the operation of the file have been completed. The fclose() function is used to
close an already opened file.
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.