0% found this document useful (0 votes)
72 views

Introduction To Arrays To File Handling (C)

Arrays are collections of elements of the same data type stored in contiguous memory locations. They can be accessed using an index and are useful for storing related data. Arrays allow random access of elements and can be single or multi-dimensional. Elements in an array are initialized by assigning values to them at declaration.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views

Introduction To Arrays To File Handling (C)

Arrays are collections of elements of the same data type stored in contiguous memory locations. They can be accessed using an index and are useful for storing related data. Arrays allow random access of elements and can be single or multi-dimensional. Elements in an array are initialized by assigning values to them at declaration.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

Introduction to Arrays || Arrays || CSIT Notes

Introduction to Arrays
As for the introduction to arrays, we say that they are the collection of elements of the same data type placed in
a consecutive memory location. We can access these individually using the index giving a unique name.
The individual data items in an array are called elements of the array and they all are of the same data type.
This makes it easier to calculate the position of each element by simply adding an offset to a base value. The
individual elements are characterized by array name and all of them are followed by one or more indices. We
enclose these indices or subscripts in the square brackets. We can store five types of value integers with a
single identifier. There is no need of declaring five different variables with a different identifier.
Arrays are very useful when store related data items. For instance, grades of students, marks of students,
matrix addition, subtraction, etc. These can be both single dimensional or multidimensional.
Types of indexing in an array
 zero-based indexing
In this type, there is the indexing of the first element of the array by the use of subscript of 0.
 one- based indexing
The subscript 1 indexes the second element of the array in this type.
 n -based indexing
We can freely choose the n- based index. Usually, programming languages that allow n- based indexing also
allow negative index values. It also allows other scalar data types like enumerations or characters that are used
in the array.
The most important property of an array is that it stores elements in contiguous memory locations.
Let us take an example:
Int num [5]

Here, the integer value is within the square bracket. We call it a subscript.
Advantages of Array

 They represent multiple data items of the same type in a single name.
 Arrays allow random access of elements which makes accessing elements by position faster.
 They have a better cache locality and can make a big difference in performance.
 These also implement matrices.
 We can use arrays for linking lists.
Types of Arrays
There are two types of arrays: Single dimensional Array and Multidimensional Arrays. We characterize these
types of arrays on the basis of dimensions. Dimension here means index.
 One Dimensional Array
One dimensional array is those arrays whose list of items can be given one variable name using only one
subscript or dimension or index. The value of the single subscript or index from 0 to n-1 refers to the individual
array elements. Here, n is the size of the array.
For a single-dimensional array, the size is specified by a positive integer expression which is enclosed in the
square brackets. We write the expression usually as a positive integer constant. In general terms, we define a
one- dimensional as:
Storage- class data- type array [expression];
Here, storage –class refers to the storage class of the array, data-type is the data type we use, the array is
the array name and, the expression is the positive-valued integer which indicates the number of array
elements. The storage-class is optional and, the default values are automatic for arrays. We define these within
a function or a block and external for arrays outside a function.

 
In the diagram above, x is an n-element, one-dimensional array.
 Multi-Dimensional Array
Multidimensional Arrays are as same as single-dimensional arrays. The only thing different in it is that it needs
a separate pair of square brackets for each of the subscript. A two-dimensional array will require two pairs of
square brackets, a three-dimensional array will require three pairs of square brackets. The pair of square
brackets increases as an increase in the number of dimensions.
In general terms, we define a multidimensional array as:
Storage- class data- type array [expression 1] [expression 2] [expression n];
Here storage class refers to the storage-class of arrays, the data-type is the data type we need, the array is the
array name, and expression 1, expression 2, …., expression n are the positive-valued integers expression.
These indicate the number of array elements related to each subscript. Here also, the storage class is optional.
 
 

Declaration and Memory Representation of Array


 
The declaration and Memory Representation of Array refers to the number of elements and to portray the
memory bits in the specific location respectively.
Declaration of One dimensional Array
The value of a single subscripted index from 0 to n-1 refers to the individual elements. Here, n is the size of the
array. For example, the declaration int a [4]; is a 1-Dimensional array of the integer data type. It has four
elements in it. They are: a [0], a [1], a [2], a [3]. But before using an array it is important that it should be
declared.
The general form of a single-dimensional array is:
Syntax:
storage_class   data_type   array_name [size]

 The storage_class is the storage class of the array.


 data_type is the data type of array. It may be like int, float, char,…, etc.
 array_name is the name of the array.
 size is the number of elements in the array. It is mentioned in the square bracket.

Examples:
int a [10]; a is the array of 10 integers.
float x [20]; x is an array of 20 float numbers.
char name [10]; the name is a character array of size 10. It can store 10 characters.
We should notice that the array name should not be separated from the square brackets having an index. The
number of array elements must remain constant while declaring an array.
Declaration of Multidimensional array
Syntax:
storage_class  data_type  array_name [dim 1] [dim 2] [dim 3]……..[dim N];
Here, storage_class, data_type, array_name are as same as in the single dimensional array. dim 1, dim 2, dim
3,….. dim N is the positive-valued integer expressions associated with each subscript.
Thus, the total no. of elements = dim 1*dim 2*dim 3*…..*dim N
E.g. int survey [3] [5] [12];
Here, the survey is a 3-D array that can contain 3*5*12 = 180 integer type data.
For Example:
int a [3] [4]; It is a two-dimensional array with 3-rows and 4-columns
int [4] [5] [3]; It is a three-dimensional array with dimensions 4, 5, and 3.
 
Memory Representation of Array
Arrays are represented with the diagrams that represent their memory use on the computer. These are
represented by the square boxes that represent every bit of the memory. We can write the value of the element
inside the box. Below is the figure that represents the memory representation in an array. Each box represents
the amount the memory needed to hold the one array of elements. The pointers in it hold the memory address
of the other data. They are represented by a black disk with an arrow to the referring data.
Let us write code and represent the memory of it.
int a [5];
.....
a[0] =1;
for (int i = 1; i< 5; i++)
{
a[i] = a[i-1]* 2;
}
In the example above, ‘a’ is the pointer to the memory for all of its elements. Now, in the computer memory,
there is an allocation of the data bit like follows:

Initialization of Array
Initialization of Array is defined as assigning the specific values to the individual array elements at the time of
array declaration. Since an array has multiple elements of the same data type, the braces we use are to denote
the entire array. And, there is the use of commas to separate the individual values assigned to the individual
elements in the array.
An array will not be initialized until it is declared. Therefore, its contents are undetermined unless we store
some of the values in it. The array elements contain the garbage values in an uninitialized array. That means
there is the only declaration.
One-Dimensional Array Initialization
Syntax:
storage_class data_type array_name [size] = [value 1, value 2, ….., value N];
Here in the syntax above, value 1 is the first element, value 2 is the second element, and so on.
For example:
int a[6] = [21, 13, 54, 5, 101, 77 ];
In the ‘For Example’ above, a is an integer type array having 5 elements.
Their values are initialized a[0] = 21, a [1] = 13, a [2] = 54, a[3] = 5 , a[4] = 101 and a[5] =77. There is toring of
these sequentially in separate memory locations.
For Instance,
int marks [5];
This is the array of 5 integers. We can initialize the elements in an array in two ways. The first one is, there is a
listing of the value of each element within two curly brackets { } and a comma (, ) to separate one value from
the other.
marks [5] = { 45, 3, 65, 88, 60 };
or
marks [ ] = { 45, 3, 65, 88, 60};
Now, the second one is, each element can be initialized one at a time. Then it will look like:
marks [0] = 45  marks [1] = 3  marks [2] = 65  marks [3] = 88  marks [4] = 60;
We can also show these in the memory cells. Marking of these in the memory cells will look like below:

Multidimensional Array
In the initialization of a multidimensional array, we can take the example of a two-dimensional array.
We can initialize two-dimensional arrays by separating each element by commas and each row by { }. Let us
take a two-dimensional array initialization.
For example:
int a [4] [2] = { { 12, 56}, {13, 33}, {14, 80}, {15, 78} };
We can also write it as:
int a [4] [2] = { 12, 56, 13, 33, 14, 80, 15, 78 };
We should remember that, while initializing a 2-Dimensional array, it is necessary to mention the second
dimension, whereas the first one is optional.
Thus the declaration will be,
int a[2] [3] = {12, 34, 23, 15, 32, 54};
int a [ ] [3] = {12, 34, 23,15, 32, 54};
The declarations like below does not work.
int a [2] [ ] = {12, 34, 23, 15, 32, 54};
int a [ ] [ ] = {12, 34, 23, 15, 32, 54};
 
Accessing Elements in an Array
Accessing Elements in an Array simply refers to the specifying of an offset or index of the desired element
within the square brackets after the array name. These subscripts as mentioned earlier are of the same data
type.
Once the array is declared, a single operation that involves an entire array is not permitted in C. Generally,
there is the use of a loop in accessing the elements of the array. Access here means input and output.
The nth element can be accessed as int [n].
We are using n as a subscript to refer to the various elements of the array. This can take different values and
refer to the different elements in the array.
For example:
int a [5], b[5], x;
x = a [0] + 10;
a[4] = a[1] + a[2];
b[3] = b[0] + a[3] + x;
 
Reading the elements of an array
For instance, let us take an example,
int i;
int marks [4];
for ( i = 0; i< = 3; i++ )
{
printf ( “/n Input marks of the given subject “);
scanf (“ %d &marks [i];
}
Here, the ‘for’ loop will cause the process to ask for and receive a student’s marks 4 times. The first time in the
loop, ‘i’ has 0 value. So, scanf () function will cause the value type storing in the array element marks[0]. This
loop will work until and unless the value of i is 3.
 
Accessing Data
We know that for reading data in the array, there is a use of loop for loading data.
Let us suppose, we need to find out the total marks of 5 subjects.
then the program for it will look like,
int marks [5] , i, sum = 0;
for ( i=0, i< 5; i++)
sum = sum + marks [i];
printf ( “/n Total marks  = %d”, sum );
The above program accepts the marks of five subjects from the user and stores them in an array named marks.
This is only known as the accessing of data. That is, the data input that the user provides is accessed using an
array.

Character Array and Strings


 
Character Array and Strings are the characters arranged one after the other inside the computer memory. The
character array is a string. The string is a sequence of characters that are treated as a single data item. There
is the termination of strings always by using a null character ‘\0’. We should remember that C language does
not support strings as a data type. It is actually a one-dimensional array of characters in C language. These are
often used to create meaningful and readable programs.
There are different operations on character strings and some of them include:

 Reading and Writing Strings


 Copying one string to the other
 Combining the strings
 Comparing Strings
 Extracting Portion of Strings

Declaring String Variables


Syntax:
char string_name[size];
Here, the size determines the number of characters of strings in the string_name.
For Example:
char marks [12];
When the compiler assigns a character string to the character array, it automatically gives it a null character i.e.
“\0” at the end of it. The size is equal to the number of characters of the strings. In addition to this, we give one
more size extra because of the null character.
 
Initializing String Variables
We can also initialize the strings in the following two forms like below:
char name [6] = { ‘N’, ‘O’, ‘T’, ‘E’, ‘S’, ‘\0’ };
char name [ ] = { ‘N’, ‘O’, ‘T’, ‘E’, ‘S’, ‘\0’ };  or char name [ 13 ] = {‘O’, ‘N’, ‘L’, ‘I’, ‘N’, ‘E’, ‘ ‘, ‘N’, ‘O’, ‘T’, ‘E’, ‘S’, ‘\
0’ };
Now, these will become,
char name [ ] = “NOTES”;
char name [13 ] = “ONLINE NOTES”;
 
When we initialize the character array by listing the elements, the null element should be provided correctly. Or,
the size of the array should be accurate.
For Instance, Let us write a program for initializing the string variables.
And. the output comes like below:
O N L I N E   N O T E S
 

Reading and Writing Strings


Reading and Writing Strings are one of the operations performed on the character strings. These are the input/
output characters.
We use an input function scanf with %s format specification to read in a string of characters.
For Example:
Char name [20];
Scanf (“%s”, name);
 There is no requirement of ‘&’ before the variable name or it is optional.
#include<stdio.h>
int main ()
{
char str [100];
Printf (“Enter a string :”);
Scanf (“%s”, &str);
printf (“String = %s”, str);
return 0;
}
For Output:
Enter String: Online
String: Online
 Due to using of scanf (), it terminates the input of the first which space in the text.
For Instance:
#include<stdio.h>
int main ()
{
char str [100];
printf (“Enter String: “);
scanf (“%s”, str);
printf (“String = %s”, str);
return 0;
}
If the input is Online Notes, then it will only read Online.
i.e.,
Output:
Enter String: Online Notes
String: Online
 There should be maximum space to read the string. If not, the program will be terminated.
For Example:
#include<stdio.h>
int main ()
{
char str [5];
printf (“Enter String: “);
scanf (“%s”, str);
printf (“String = %s”, str);
return 0;
}
Output:
Enter String: Online
Aborted (core dumped)
The size should be large to store all data. Otherwise, it will destroy anything that follows the array in the
memory. And, we must not exceed the length of the data.
We can use an alternative method for reading the data in a string variable. That is, to use scanf () with the %c
which has a count related to it. The %c conversion does not generate the NULL termination automatically like
%s and % [ ].
#include<stdio.h>
int main ()
{
char str [100];
printf (“Enter a string in lower case: “);
scanf (“% [a-z]”, str);
printf (“String = %s\n”, str);
return 0;
}
Output:
Enter a string in lower case: onlinenotes
string: onlinenotes
Enter a string in lower case: onlineNotes
string: online

String Library Functions


String Library Functions are those functions in C, which has some useful contribution for functioning and
working of the strings. Some of the string handling functions are strcpy ( ), strcmp ( ), strlen ( ), strcat ( ), etc.
Let us see the working of some of the string functions.

 Concatenating two strings: strcat


 String scanning Operation: strchr
 Copying strings: strcpy
 Getting string length: strlen
 Comparison between two strings: strcmp
 Concatenating the one part of a string with other: strncat
 Copying the two parts of strings: strncpy
 Comparison between two parts of strings: strncmp
We use these library functions to manipulate the string data. One can call these functions from the header file
namely string.h file.
Some of the string functions are briefly discussed below:
 Copying the string
We use strcpy ( ) function is used to copy the one string into another one. Another function strncpy ( ) is used
for the copying of one part of the string to the other.
The following given program can illustrate the use of the copying string.

Output:

 
 Finding the length of the string
The length of the string is the number of characters present in the string excluding the null character. To find
the length of the given string, we use strlen ( ) function.
Syntax: integer_variable = strlen (input_string);
Let us see a program for it:
Ouput:

 
 Concatenation of two Strings
We already know that there is the use of string function strcat ( ) for concatenating two strings. It links or joins
the two strings together.
For Instance, let us see a program below:
 
Output:

 
 
 Converting a string to uppercase
Like other functions, for the conversion of string from lower to upper case, there is a library function that is
strupr ( ). This converts the given lower case string to the upper case.
For Instance:
 
Output:

 
 Conversion of a Given string to lowercase
The process of conversion to lowercase is also the same method. But, the library function we use here is, strlwr
( ). It converts the uppercase string into the lower case.
For Example:

Output:

 
Functions
 
A functions declaration tells the compiler about a function’s name, return type, and parameters. Functions
definition provides the actual body of the function.
A function is a block of statements that performs a specific task. A function is a complete and independent
program that is used (or invoked) by the main program or other subprograms. A subprogram receives values
called arguments from a calling program, performs calculations, and returns the results to the calling program.
Advantages of using Functions

1. It facilitates top-down modular programming. In this programming style, the high-level logic of the
overall problem is solved first while the details of each lower-level function are addressed later.
2. The length of the source program can be reduced by using functions at appropriate places. This factor
is critical with microcomputers where memory space is limited.
3. It is easy to locate and isolate a faulty function for further investigation.
4.  A function may be used by many other programs this means that a c programmer can build on what
others have already done, instead of starting over from scratch.
5.  A program can be used to avoid rewriting the same sequence of code at two or more locations in a
program. This is especially useful if the code involved is long or complicated.
6.  Programming teams do a large percentage of programming. If the program is divided into
subprograms, each subprogram can be written by one or two team members of the team rather than
having the whole team to work on the complex program

We already know that C supports the use of library functions and user-defined functions. The library functions
are used to carry out a number of commonly used operations or calculations. The user-defined functions are
written by the programmer to carry out various individual tasks.
 
Two types of functions:

 Library functions (Built-in functions):


These functions are provided in the programming language and we can directly use them as required.
However, the functions name, return type, number of arguments, and types must be known in advance. For
e.g. printf(), scanf(), sqrt(), getch(),etc.

 User-defined functions:
These functions are written by the user. The user selects the name of the function, return type, number of
arguments, and types.

 Note: main() is a user-defined function. However, the name of the function is defined or fixed by the
programming language.
 
Function definition

 The collection of program statements that describes the specific task to be done by the function is
called a function definition.
 A function definition consists of function header (a function name, return type, and number and types
of arguments)and function body (block of code or statements enclosed in parentheses).

 Syntax:
return_type function_name(data_type variable1, …,data_type variableN)
{
…………………;
…………………;
statements;
}
return_type is optional. The default value is an integer.

 Whenever return_type is provided, a value must be returned using the return statement except for
the void case.

 function_name is a user-defined name given to the function. (Same as identifier naming)

 variable1, …,variableN are called formal arguments or formal parameters that are passed to the
function. Also these are local variables for the function
Example of the function definition:
#include <stdio.h>
int add(int c, int d)
{
int sum;
sum = c+d;
return sum;
}
void main()
{
………;
}
Calling a function through main()

 A function can be called by specifying the function name, followed by a list of arguments enclosed in
parentheses and separated by commas.

 For example, the function add() can be called with two arguments from main() function as:add(a, b);

 These arguments appearing in the function call are called actual arguments or actual parameters.

 In this case, main() is called calling function and add() iscalled called function.
Note:

 In a function call, there must be one actual argument for each formal argument. This is because the
value of the actual argument
is transferred into the function and assigned to the corresponding formal argument.

 If a function returns a value, the returned value can be assigned to a variable of data type same as
the return type of the function to
the calling function.

 When a function is called, the program control is passed to thefunction and once the function
completes its task, the program
control is transferred back to the calling function.
#include <stdio.h>
#include <conio.h>
int add(int c, int d)
{
int sum;
sum = c+d;
return sum;
}
void main()
{
int a=50,b=100, x;
x=add(a, b);
printf(“%d”, x);
getch();
void add(int c, int d)
{
int sum;
sum = c+d;
printf(“%d”, sum);
}
void main()
{
int a=50,b=100;
add(a, b);
getch();
}
Write functions to add, subtract, multiply and divide two numbers a and b.
// Combination Problem
#include <stdio.h>
#include <conio.h>
long factorial(int n)
{
long fact=1;
int i;
for(i=1;i<=n;i++)
fact *= i;
return fact;
}
void main()
{
long f1=1,f2=1,f3=1,comb;
int n, r;
clrscr();
printf(“\nEnter n and r:”);
scanf(“%d %d”,&n,&r);
f1=factorial(n);
f2=factorial(n-r);
f3=factorial(r);
comb=f1/(f2*f3);
printf(“\n The combination is: %ld”, comb);
getch();
}
 
Function Prototype or Declaration

 The function prototype is a model or blueprint of the function.

 The function prototype is necessary if a function is used before the function is defined.

 When a user-defined function is defined before the use,function prototype is not necessary (maybe
given though).

 Syntax:
return_type function_name(data_type1, …,data_typeN);

 E.g.
void add(int, int);
#include <stdio.h>
#include <conio.h>
int add(int, int); //Function Prototype
void main()
{
int a=12,b=5,x;
clrscr();
x=add(a,b);
printf(“%d”,x);
getch();
}
int add(int c, int d)
{
int sum;
sum=c+d;
return;
}
 
The return Statement
The return statement serves two purposes:
1. It immediately transfers the control back to the calling function (i.e. no statements within the function body
after the
the return statement is executed).
2. It returns the value to the calling function.
Syntax:
return (expression);
where expression, is optional and, if present, it must evaluate to a value of the data type specified in the
function header for
the return_type.
Note: When nothing is to be returned, the return_type in thefunction definition is specified
/*Program using function to find the greatest number among three numbers*/
#include <stdio.h>
#include <conio.h>
int greater(int, int);
void main()
{
int a, b, c, d, e;
clrscr();
printf(“\n Enter three numbers:”);
scanf(“%d %d %d”,&a,&b,&c);
d=greater(a, b);
e=greater(d, c);
printf(“\n The greatest number is:%d”, e);
getch();
}
int greater(int x, int y)
{
if(x>y)
return x;
else
return y;
}
Function parameters

 Function parameters are the means for communication between the calling and the called functions.

 Two types: formal parameters and actual parameters.

 Formal parameters are given in the function definition while actual parameters are given in the
function call.

 The name of formal and actual parameters need not be the same but data types and the number of
parameters must match.

Types of Functions
 
 
There are three different types of functions:

1.  Functions with no arguments and no return values.


2. Functions with arguments and no return values.
3. Functions with arguments and return values.

 
Functions with no arguments and no return values
Let us consider the following program
/* Program to illustrate a function with no argument and no return values*/ #include
main()
{
statement1();
starline();
statement2();
starline();
}
/*function to print a message*/
statement1()
{
printf(“\n Sample subprogram output”);
}
statement2()
{
printf(“\n Sample subprogram output two”);
}
starline()
{
int a;
for (a=1;a<60;a++)
printf(“%c”,‟*‟);
printf(“\n”);
}
In the above example, there is no data transfer between the calling function and the called function. When a
function has no arguments it does not receive any data from the calling function. Similarly, when it does not
return value the calling function does not receive any data from the called function. A function that does not
return any value cannot be used in an expression it can be used only as an independent statement.
Functions with arguments but no return values
The nature of data communication between the calling function and the arguments to the called function and
the called function does not return any values to the calling function this shown in the example below:
Consider the following:
Function calls containing appropriate arguments. For example the function call value (500,0.12,5)
Would send the values 500,0.12 and 5 to the function value (p, r, n) and assign values 500 to p, 0.12 to r, and 5
to n. the values 500,0.12 and 5 are the actual arguments that become the values of the formal arguments
inside the called function.
Both the arguments actual and formal should match in number type and order. The values of actual arguments
are assigned to formal arguments on a one to one basis starting with the first argument as shown below:
main()
{
function1(a1,a2,a3……an)
}
function1(f1,f2,f3….fn);
{
function body;
}
Here a1, a2, a3 are actual arguments and f1, f2, f3 are formal arguments.
The no of formal arguments and actual arguments must be matching to each other suppose if actual arguments
are more than the formal arguments, the extra actual arguments are discarded. If the numbers of actual
arguments are less than the formal arguments then the unmatched formal arguments are initialized to some
garbage values. In both cases, no error message will be generated.
The formal arguments may be valid variable names; the actual arguments may be variable names expressions
or constants. The values used in actual arguments must be assigned values before the function call is made.
When a function call is made only a copy of the values actual arguments are passed to the called function.
What occurs inside the functions will have no effect on the variables used in the actual argument list.
Let us consider the following program
/*Program to find the largest of two numbers using function*/ #include<stdio.h>
main()
{
int a,b;
printf(“Enter the two numbers”);
scanf(“%d%d”,&a,&b);
largest(a,b);
}
/*Function to find the largest of two numbers*/
largest(int a, int b)
{
if(a>b)
printf(“Largest element=%d”,a);
else
printf(“Largest element=%d”,b);
}
in the above program, we could make the calling function to read the data from the terminal and pass it on to
the called function. But function does not return any value.
Functions with arguments and return values
The function of the type Arguments with return values will send arguments from the calling function to the
called function and expects the result to be returned back from the called function back to the calling function.
To assure a high degree of portability between programs a function should generally be coded without involving
any input-output operations. For example, different programs may require different output formats for displaying
the results. These shortcomings can be overcome by handing over the result of a function to its calling function
where the returned value can be used as required by the program.
 
Call by Value and Call by reference
The arguments passed to function can be of two types namely

1. Values passed / Call by Value


2. The address passed / Call by reference

The first type refers to call by value and the second type refers to call by reference.
For instance, consider program 1:
main()
{
int x=50, y=70;
interchange(x,y);
printf(“x=%d y=%d”,x,y);
}
interchange(x1,y1);
int x1,y1;
{
int z1;
z1=x1;
x1=y1;
y1=z1;
printf(“x1=%d y1=%d”,x1,y1);
}
Here the value to function interchange is passed by value.
Consider program2
main()
{
int x=50, y=70;
interchange(&x,&y);
printf(“x=%d y=%d”,x,y);
}
interchange(x1,y1);
int *x1,*y1;
{
int z1;
z1=*x1;
*x1=*y1;
*y1=z1;
printf(“*x=%d *y=%d”,x1,y1);
}
Here the function is called by reference. In other words, the address is passed by using symbol & and the value
is accessed by using symbol *.
The main difference between them can be seen by analyzing the output of program1 and program2.
The output of program1 that is called by value is
x1=70 y1=50
x=50 y=70
But the output of program2 that is called by reference is
*x=70 *y=50
x=70 y=50
This is because in case of call by value the value is passed to function named as an interchange and there the
value got interchanged and got printed as
x1=70 y1=50
and again since no values are returned back and therefore original values of x and y as in the main function
namely
x=50 y=70 got printed.
 
Recursion
A recursive function is a function that calls itself. When a function calls another function and that second
function calls the third function then this kind of function is called nesting of functions. But a recursive function
is the function that calls itself repeatedly.
An example program to find out factorial of a given number using Recursion:
int fact(int);
void main()
{
int n, fac;
clrscr();
printf(“Enter the value of n”);
scanf(“%d”,&n);
fac=fact(n);
printf(“The factorial of %d is %d”,n,fac);
getch();
}
int fact(int n)
{
if(n= =1)
return(1);
else
return fact(n-1)*n;
}
 
Storage Class:

 Variables in C are categorized into four different storage classes according to the scope and lifetime
of variables:
1. Automatic variables
2. External variables
3. Static variables
4. Register variables
Note:

 The scope of a variable determines over what part(s) of the program a variable is actually available
for use (active).

 Lifetime refers to the period of time during which a variable retains a given value during the
execution of a program (alive).
 
Global and local variables
A local variable is one that is declared inside a function and can only be used by that function. If you declare a
variable outside all functions then it is a global variable and can be used by all functions in a program.
#include<stdio.h>
// Global variables
int a;
int b;
int Add()
{
return a + b;
}
int main()
{
answer;
// Local variable
a = 5;
b = 7;
answer = Add();
printf(“%d\n”,answer);
return 0;
}
Functions and arrays
We can pass an entire array of values into a function just as we pass individual variables. In this task, it is
essential to list the name of the array along with functions arguments without any subscripts and the size of the
array as arguments
For example:
Largest(a,n);
will pass all the elements contained in the array an of size n. the called function expecting this call must be
appropriately defined. The largest function header might look like:
float smallest(array,size);
float array[];
int size;
The function smallest is defined to take two arguments, the name of the array and the size of the array to
specify the number of elements in the array. The declaration of the formal argument array is made as follows:
float array[ ];
The above declaration indicates to the compiler that the argument array is an array of numbers. It is not
necessary to declare the size of the array here. While dealing with array arguments we should remember one
major distinction. If a function changes the value of array elements then these changes will be made to the
original array that passed to the function. When the entire array is passed as an argument, the contents of the
array are not copied into the formal parameter array instead information about the address of the array
elements is passed on to the function. Therefore any changes introduced to array elements are truly reflected
in the original array in the calling function.
 
Passing 2-D Array to a Function
Rules
1. The function must be called by passing only the array name.
2. In the function definition, we must indicate that the array has two dimensions by including two sets of
brackets.
3. The size of the second dimension must be specified.
4. The prototype declaration should be similar to the function header.
//Program to display a matrix
#include <stdio.h>
#include <conio.h>
void display(int rix[][2]);
void main()
{
int matrix[2][2], i, j;
clrscr();
printf(“Input matrix elements:\t”);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
scanf(“%d”, &matrix[i][j]);
}
display(matrix);
getch();
}
void display(int mat[][2])
{
int i, j;
printf(“\nThe matrix is:\n”);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf(” %d\t”, mat[i][j]);
printf(“\n”);
}
}
 
The thing to remember

 When an entire array is passed to a function and if that function changes the values of array
elements, then these changes are actually made to the original array that is passed to the function.
 This means that when an entire array is passed as an argument, the contents of the array are not
copied into the formal parameter; instead, information about the addresses of array elements is passed on to
the function.

 Thus, any changes made to the array elements by the function truly reflected in the original array in
the calling function.

 However, this does not apply when an individual element is passed as an argument.
 
Passing Strings to Functions

 Since strings are character arrays, the rules for passing strings to functions are similar to those for
passing arrays to functions.

 Rules
1. The string to be passed must be declared as a formal argument of the function definition in the function
header.
void display(char item_name[])
{
……………
}
2. The function prototype must show that the argument is a string.
void display(char str[]);
3. A call to the function must have a string name without subscripts as its actual argument.
display(name);
where the name is a properly declared string in the calling function.
Note: Like arrays, strings are passed by address.
 
What is a pointer???

 A pointer is a variable that stores the memory address of a variable

 Pointer naming is the same as variable naming and it is declared in the same way as other variables
but is always preceded by * (asterisk) operator.

 E.g. int b, *a; //pointer declarationa=&b; /* address of b is assigned to pointer variable a */


#include <stdio.h>
#include <conio.h>
void swap(int *, int *);
void main()
{
int a=50, b=100;
clrscr();
printf(“\n Before swap function call: a=%d and b=%d”, a, b);
swap(&a, &b);
printf(“\n After swap function call: a=%d and b=%d”, a, b);
getch();
}
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
printf(“\n Values within swap: x=%d and y=%d”, *x, *y);
}
 
One more type of function:
Functions that return multiple values

 A return statement can return only one value.

 When we need to return more than one value from a function

 We can achieve this by using the arguments not only to receive information but also to send back
information to the calling function.

 The arguments that are used to send out information are called output parameters.

 The mechanism of sending back information through arguments are achieved using what is known
as the address operator (&) and the indirection operator (*).
void fun(int, int, int *,int *);
void main()
{
int x=100,y=50,s,d;
clrscr();
fun(x, y, &s, &d);
printf(“s=%d \td=%d”, s, d);
getch();
}
void fun(int a, int b, int *sum, int *diff)
{
*sum=a + b;
*diff=a-b;
}
 

Structures
 
Introduction
Arrays are used to store large sets of data and manipulate them but the disadvantage is that all the elements
stored in an array are to be of the same data type. If we need to use a collection of different data type items it is
not possible using an array. When we require using a collection of different data items of different data types
we can use a structure. The structures is a method of grouping data of different types. Structures are a
convenient method of handling a group of related data items of different data types.
Example of Structure

struct Student
{
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender;
};

Here struct Student declares a structure to hold the details of a student which consists of 4 data fields,
namely name, age, branch and gender. These fields are called structure elements or members.
Each member can have different datatype, like in this case, name is an array of char type and age is of int type
etc. The student is the name of the structure and is called the structure tag.
Declaring Structure Pointers
Assuming the previously defined structure addr, the following declares addr_pointer as a pointer to data of that
type:
struct addr *addr_pointer;
 REFERENCING STRUCTURE ELEMENTS 
Individual elements of a structure are referenced using the dot operator. The pointer to a structure member
operator -> is used to access a member of a structure using a pointer variable.
Accessing Structure members using the dot operator
Individual elements of a structure are referenced using the dot operator, for example:
addr_info. postalcode = 1234;
printf (“%d”,addr_info. postalcode);
Example:
# include <stdio.h>
# include <string.h>
struct
{
char name[15]; /* childs name */
int age; /* childs age */
int grade; /* childs grade in school */
} boy, girl;
int main()
{
strcpy (boy.name, “Herbert”);
boy.age = 15;
boy.grade = 75;
girl.age = boy.age – 1; /* she is one year younger */
girl.grade = 82;
strcpy (girl.name, “Fousett”);
printf (“%s is %d years old and got a grade of %d\n”,
girl.name, girl.age, girl.grade);
printf (“%s is %d years old and got a grade of %d\n”,
boy.name, boy.age, boy.grade);
return 0;
}
Output:
Fausett is 14 years old and got a grade of 82
Herbert is 15 years old and got a grade of 75
Accessing Structure Pointers using -> operator
Structure pointers may be used to generate a call by reference to a function and to create linked
lists and other dynamic data structures. Call by reference can be used for structures to avoid
overheads occurred by the push and pop operations of all the structure elements of the stack. For
example if:
struct addr_info *ptr;
To access the elements of a structure using a pointer, the -> operator is used:
ptr -> postalcode
where ptr has been declared as a pointer to the type of structure and assigned the address of a
variable of that type and postalcode is a structural element within that variable.
This can also be expressed as:
(*ptr). postalcode
The parenthesis is necessary because the structure member operator “. “ takes higher precedence
than does the indirection operator.
Arrays of structure
It is possible to define an array of structures for example if we are maintaining information of all the students in
the college and if 100 students are studying in the college. We need to use an array than single variables. We
can define an array of structures as shown in the following example:
structure information
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}
student[100];
 
An array of structures can be assigned initial values just as any other array can. Remember that each element
is a structure that must be assigned corresponding initial values as illustrated below.
#include< stdio.h >
void main()
{
struct info
{
int id_no; char name[20];
char address[20];
char combination[3];
int age;
};
struct info std[100];
int i,n;
printf(“Enter the number of students”);
scanf(“%d”,&n);
for(i=0;i < n;i++)
{
printf(“ Enter Id_no,name address combination age\m”);
scanf(“%d%s%s%s%d”,&std[I].id_no,std[I].name,std[I].address,std[I].combination,&std[I].age);
}
printf(“\n Student information”);
for (I=0;I< n;I++)
{
printf(“%d%s%s%s%d\n”, std[I].id_no,std[I].name,std[I].address,std[I].combination,std[I].age);
}
}
 
Structure within a structure
A structure may be defined as a member of another structure. In such structures, the declaration of the
embedded structure must appear before the declarations of other structures.
struct date
{
int day;
int month;
int year;
};
 
struct student
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
structure date def;
structure date doa;
}oldstudent, newstudent; the structure student contains another structure date as its one of its members.
 
Functions and structures
We can pass structures as arguments to functions. Unlike array names, however, which always point to the
start of the array, structure names are not pointers. As a result, when we change the structure parameter inside
a function, we don‟t affect its corresponding argument.
 
Passing structure to elements to functions
A structure may be passed into a function as individual member or a separate variable. A program example to
display the contents of a structure passing the individual elements to a function is shown below.
#include<stdio.h>
#include<conio.h>
void fun(float,int);
void main()
{
struct student
{
float marks;
int id;
};
struct student s1={67.5,14};
fun(s1.marks,s1.id);
getch();
}
void fun(float marks,int id)
{
printf(“\nMarks:%f”,marks);
printf(“\nID:%d”,id);
}
It can be realized that to pass individual elements would become more tedious as the number of structure
elements go on increasing a better way would be to pass the entire structure variable at a time.
Passing entire structure to functions
In case of structures having to have numerous structure elements passing these individual elements would be
a tedious task. In such cases we may pass a whole structure to a function as shown below:
# include stdio.h>
{
int emp_id;
char name[25];
char department[10];
float salary;
};
void main()
{
static struct employee emp1= { 12, “sadanand”, “computer”, 7500.00 };
/*sending entire employee structure*/
display(emp1);
}
/*function to pass entire structure variable*/
display(empf)
struct employee empf
{
printf(“%d%s,%s,%f”, empf.empid,empf.name,empf.department,empf.salary);
}
Pointers to struct
Pointers can be used to refer to a struct by its address. This is useful for passing structs to a function. The
pointer can be dereferenced using the * operator. The -> operator dereferences the pointer to struct (left
operand) and then accesses the value of a member of the struct (right operand).

struct point {
int x;
int y;
};
struct point my_point = { 3, 7 };
struct point *p = &my_point; /* p is a pointer to my_point */
(*p).x = 8; /* set the first member of the struct */
p->x = 8; /* equivalent method to set the first member of the struct */

Union
 
Unions like structure contain members whose individual data types may differ from one another. However, the
members that compose a union all share the same storage area within the computer’s memory whereas each
member within a structure is assigned its own unique storage area. Thus unions are used to observe memory.
They are useful for application involving multiple members, where values need not be assigned to all the
members at any one time. Like structures union can be declared using the keyword union as follows:
union item
{
int m;
float p;
char c;
}
code;
This declares a variable code of type union item. It contains three members each with a different data type.
However, we can use only one of them at a time. This is because if only one location is allocated for union
variable irrespective of size. The compiler allocates a piece of storage that is large enough to access a union
member we can use the same syntax that we use to access structure members. That is
code.m
code.p
code.c
are all valid member variables. During accessing we should make sure that we are accessing the member
whose value is currently stored.
For example a statement such as
code.m=456;
code.p=456.78;
printf(“%d”,code.m);
More on Structure
TYPEDEF
typedef allows a new data type to be explicitly defined. Note that it does not actually create a new data class,
but simply defines a new name for an existing type. This process helps in making machine-dependent code
more portable since only the typedef statements need to changed. It can also aids in self-documenting a
program by allowing the use of more descriptive names for the standard data types.
The general form of defining a new data type is:
typedef data type identifier;
Where identifier refers to the name(s) given to the data type. User-defined types obey the same scope rules as
identifiers, so if one defined in a function, it is recognized only within that function. Few examples of type
definitions are
typedef int age;
typedef float average;
typedef char string;
Where age symbolizes int, average symbolizes float,and ring symbolizes char.
They can be later used to declare variables as:
age child, adult;
average mark1, mark2;
string name[20];
Where child and adult are declared as integer variables, mark1 and mark2 are declared as floating point
variables and name is declared as a character array variable. The typedef can also be used to define
structures. The main advantage of type definition is that, you can create meaningful data type names for
increasing the readability of the program. They also suggest the purpose of the data type names used in the
program.
 
Difference Between Structure and Union
1. Keyword
The keyword ‘struct’ is used to define a structure whereas ‘union’ keyword is used to define a union.
2. Memory Allocation
Separate memory space is allotted for the members within a structure and members have different addresses
that do not share memory. A union, on the other hand, shares the same memory space for all its members so
shared memory location is allocated.
3. Member Access
A union stores a single value at a time for all its members making accessibility to only one member at a time.
While multiple values can be stored in a structure so any member value can be accessed and retrieved at any
time.
4. Size
The size of a structure is equal to the sum of the size of all members or more, whereas the size of a union is
equal to the size of the largest size member.
5. Initialization
In a structure, several members can be initialized at once, while in a union, only the first member can be
initialized with the value of its type.
6. Value
A structure can store different values of all the members and change in the value of one member will not have
any effect on the values of other members. While a union stores the same value for all its members and
change of the value of one member will affect the value of other.
 

Pointers
A pointer is a variable that stores the address of another variable. Memory can be visualized as an ordered
sequence of consecutively numbered storage locations. A data item stored in memory in one or more adjacent
storage locations depends upon its type. That is the number of memory locations required depends upon the
type of variable. The address of a data item is the address of its first storage location. This address can be
stored in another data item and manipulated in a program. The address of a data item is a pointer to the data
item, and a variable that holds the address is called a pointer variable. Some uses of pointers are:

1.  Accessing array elements.


2.  Returning more than one value from a function.
3. Accessing dynamically allocated memory.
4. Implementing data structures like linked lists, trees, and graphs.

Address (&) Operator and indirection (*) operator


C provides an address operator “&”, which returns the address of a variable when placed before it. This
operator can be read as “the address of”, so &age means the address of age, similarly &sal means address of
sal. The following program prints the address of variables using the address operator. We can access a
variable indirectly using pointers. For this, we will use the indirection operator (*). By placing the indirection
operator before a pointer variable, we can access the variable whose address is stored in the pointer.
&: Address of
* : value at address of
Program to understand & and * operator.
#include<stdio.h>
#include<conio.h>
void main()
{
int age=25,*page;
float sal=50000,*psal;
page=&age;
psal=&sal;
printf(“\nAddress of age=%u and value of age=%d”,page,*page);
printf(“\nAddress of sal=%u and value of sal=%f”,psal,*psal);
getch();
}
Declaration of pointer
Like all other variables, it also has a name, has to be declared, and occupies some space in memory. It is
called pointer because it points to a particular location in memory by storing the address of that location.
Syntax: datatype *identifier
Example:
int age; //declaring a normal variable
int *ptr; //declaring a pointer variable
ptr=&age; //store the address of the variable age in the variable ptr.

 Now ptr points to age or ptr is a pointer to age.


 We’ve created a pointer ptr which becomes a variable that contains the address of another variable
age

 
Pointer arithmetic
All types of arithmetic operations are not possible with pointers. The only valid operations that can be
performed are as follow:

1. Addition of an integer to a pointer and increment operation.


2. Subtraction of an integer from a pointer and decrement operation.
3. Subtraction of a pointer from another pointer of the same type.

Pointer arithmetic is somewhat different from ordinary arithmetic. Here all arithmetic is performed relative to the
size of the base type of pointer. For example, if we have an integer pointer pi which contains address 1000
then on incrementing we get 1002 instead of 1001. This is because the size of the int data type is 2.Similarly,
on decrementing pi, we will get 998 instead of 999. The expression (pi + 3) will represent the address 1006.
Program to understand pointer arithmetic
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,*pi;
float b=7.3,*pf;
char c=’x’,*pc;
clrscr();
pi=&a;
pf=&b;
pc=&c;
printf(“\n Address of a=%u “,pi);
printf(“\n Address of b=%u “,pf);
printf(“\n Address of c=%u “,pc);
pi++;
pf++;
pc++;
printf(“\n\n Address of a=%u “,pi);
printf(“\n Address of b=%u “,pf);
printf(“\n Address of c=%u “,pc);
getch();
}
Output:
 
The arithmetic operations that can never be performed on pointers are:

1. Addition, multiplication, division of two pointers.


2. Multiplication between pointer and any number.
3. Division of a pointer by any number.
4. Addition of float or double values to pointers.

Pointer to pointer (double indirection)


The pointer variable itself might be another pointer so pointer which contains another pointer‟s address is
called pointers to pointers or multiple indirections.
Syntax: datatype **identifier;
Example:
int **pptr;
Program to understand pointer to pointer
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,*pa,**ppa;
clrscr();
pa=&a;
ppa=&pa;
printf(“\nValue of a=%d”,*pa);
printf(“\nValue of a=%d”,**ppa);
getch();
}

Output:
Value of a=5
Value of a=5

Arrays and Pointers


In C, there is a strong relationship between arrays and pointers. Any operations that can be achieved by array
subscripting can also be done with pointers. The pointer version will, in general, be faster but for the beginners
somewhat harder to understand.
An array name is itself is an address or pointer value, so any operation that can be achieved by array
subscripting can also be done with pointers as well. Pointers and arrays are almost synonymous in terms of
how they are used to access memory, but there are some important differences between them. A pointer is
fixed. An array name is a constant pointer to the first element of the array. The relation of pointer and array is
presented in the following tables:
 

Pointer and one-dimensional array


The elements of an array are stored in contiguous memory locations.
Suppose we have an array arr[5] of type int.
int arr[5]={6,9,12,4,8};
This is stored in memory as

Here 5000 is the address of the first element, and since each element (type int) takes 2 bytes so the address of
the next element is 5002, and so on. The address of the first element of the array is also known as the base
address of the array.
Program to print the value of array element using pointer
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[100],i,n;
printf(“How many elements are there: “);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“\n Enter element: “);
scanf(“%d”,(arr+i));
}
printf(“\n Printing array element:”);
for(i=0;i<n;i++)
{
printf(“\n %d”,*(arr+i));
}
getch();
}
Output:
Pointer with two-dimensional arrays
In a two dimensional array, we can access each element by using two subscripts, where the first subscript
represents row number and the second subscript represents the column number. The elements of the 2-D
array can be accessed with the help of pointer notation. Suppose arr is a 2-D array, then we can access any
element arr[i][j] of this array using the pointer expression *(*(arr+i)+j).
Example
1. Write a program to read any 2 by 3 matrix and display its element in appropriate format.
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[2][3],i,j;
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf(“\n Enter elements of matrix: “);
scanf(“%d”,&arr[i][j]);
}
}
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf(“%d\t”,*(*(arr+i)+j));
}
printf(“\n”);
}
getch();
}
Output:

Pointer and String


A string in C is merely an array of characters. The length of a string is determined by a terminating null
character: ‘\0’. We can take a char pointer and initialize it with a string constant.
For example:
char *ptr= “Programming”;
Here ptr is a char pointer that points to the first character of the string constant “Programming” i.e. ptr contains
the base address of this string constant.
Now let‟s compare the strings defined as arrays and strings defined as pointers.
char str[ ]=”Chitwan”;
char *ptr=”Nawalparasi”;
These two forms may look similar but there are some differences in them. The initialization itself has a different
meaning in both forms. In array form, initialization is a short form for
char str[ ]={„C‟,‟h‟,‟i‟,‟t‟,‟w‟,‟a‟,‟n‟,‟\0‟}
while in pointer form, the address of string constant is assigned to the pointer variable.
Now let us see how they are represented in memory.

Here string assignments are valid for pointers while they are invalid for strings defined as arrays.
str = “Narayangarh” //invalid
ptr = ”Butwal” //valid
Array of pointers with string
Array of pointers to strings is an array of char pointers in which each pointer points to the first character of a
string i.e. each element of this array contains the base address of a string.
char *arrp[ ]={“white”,”red”,”green”,”yellow”,”blue”};
Here arrp is an array of pointers to a string. We have not specified the size of the array, so the size is
determined by the number of initializers. The initializers are string constant. arrp[0] contains the base address
of string “white” similarly arrp[1] contains the base address of string “red”
 

Dynamic memory allocation


The memory allocation that we have done until now was static memory allocation. The memory that could be
used by the program was fixed i.e. we could not increase or decrease the size of memory during the execution
of the program. In many applications, it is not possible to predict how much memory would be needed by the
program at run time. For example, if we declare an array of integers.
int emp[100];
In an array, it is a must specify the size of the array while declaring, so the size of this array will be fixed during
runtime. Now two types of problems may occur.

1. The number of values to be stored is less than the size of the array then there will be the wastage of
memory.
2. If we want to store more values than the size of the array then we can‟t.

To overcome these problems we should be able to allocate memory at run time. The process of allocating
memory at the time of execution is called dynamic memory allocation. The allocation and release of this
memory space can be done with the help of some built-in-functions whose prototypes are found in alloc.h and
stdlib.h header files.
Pointers play an important role in dynamic memory allocation. It is because we can access the dynamically
allocated memory only through pointers.
malloc ( )
This function is used to allocate memory dynamically.
Syntax: pointer_variable=(datatype*) malloc(specified_size);
Here pointer_variable is a pointer of type datatype, and specified_size is the size in bytes required to be
reserved in memory.
calloc ( )
The calloc ( ) function is used to allocate multiple blocks of memory. It is somewhat similar to malloc ( ) function
except for two differences. The first one is that it takes two arguments. The first argument specifies the number
of blocks and the second one specifies the size of each block.
For example: ptr= (int *) calloc (5, sizeof(int));
The other difference between calloc( ) and malloc( ) is that the memory allocated by malloc( ) contains garbage
value while the memory allocated by calloc( ) is initialized to zero.
realloc( )
The function realloc( ) is used to change the size of the memory block. It alters the size of the memory block
without losing the old data. This is known as the reallocation of memory.
This function takes two arguments, first is a pointer to the block of memory that was previously allocated by
malloc( ) or calloc( ) and the second one is the new size for that block.
For example: ptr=(int*) realloc(ptr,newsize);
Program to understand dynamic allocation of memory
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *ptr,n,i;
printf(“How many numbers do you want to entered: “);
scanf(“%d”,&n);
ptr=(int *)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
printf(“\n Enter number: “);
scanf(“%d”,ptr+i);
}
printf(“\nDisplaying elements: “);
for(i=0;i<n;i++)
{
printf(“\n%d”,*(ptr+i));
}
getch();
}
Output:

The free( ) function


The free( ) function is opposite of malloc( ). Dynamically allocated memory is deallocated with the free function.
It returns previously allocated memory to the system.
Syntax: void free(void *p);

Concept of Files
Files are the collection of related data that a computer treats as a single unit. Computers store files to the
secondary storage device so that the contents of files remain intact when a computer shuts down and can be
obtained anytime we require those contents.
When a computer reads a file, it copies the file from the storage device to memory. When it writes to a file, it
transfers data from memory to the storage device. In order to use the file, we have to learn about File I/O i.e.
how to read from a file and how to write in a file with a C program.
C uses a structure called FILE (defined in stdio.h) to store the attributes of a file.
Steps to follow for File Processing

1. Create the File Pointer to access each file used. The file pointer is a pointer variable using the FILE
structure
as:
FILE *p;
where p is the name of the file pointer.
2.  Open the file, associating the pointer name with the file name.
3.  Read and/or write the data from the file.
4.  Close the file after use.

Why files are needed?

 When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if
the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter them all. However, if you
have a file containing all the data, you can easily access the contents of the file using a few commands
in C.
 You can easily move your data from one computer to another without any changes.

Opening and Closing a File


Opening a File

 Declare file pointer for opening or closing a file as FILE *fp.


 You can use multiple variables to access different files in a program by declaring as – FILE
*fp1,*fp2,*fp3 ;
  Function fopen() is used to open the file for reading or writing operation which requires filename to
open as the first argument and file mode as the second argument as – fp=fopen(“myfile.dat”,
“filemode”);
 File name is the name of the file that you need to open for read or write.
 File mode indicates for what purpose file is to be opened i.e. for read, write.

 Different modes of file open are: 


File opening
modes
File Open
The file open function fopen() serves two purposes:

 It makes the connection between the physical file and the stream.
 It creates “a program file structure to store the information” C needs to process the file.

Syntax:
filepointer=fopen(“filename”, “mode”);

 The file mode tells C how the program will use the file.
 The filename indicates the system name and location for the file.
 We assign the return value of fopen to our pointer variable:
spData = fopen(“MYFILE.TXT”, “w”);
spData = fopen(“A:\\MYFILE.TXT”, “w”);
Closing a File

 When we finish with a mode, we need to close the file before ending the program or
beginning another mode with that same file.
 After closing the file, the connection between file and program is broken. Hence, operations like read,
write can’t be done.
 On closing the file, all the buffers associated with it are written to the file.
 Although all the files are closed automatically when the program terminates, sometimes it may be
necessary to close the file using fclose() function.
 To close a file, we use fclose() and the pointer variable as :
fclose(spData);
– Here spData is pointer variable

File I/O Functions


Once a file is opened, reading out of or writing to it is accomplished using the standard I/O functions.
String I/O Functions
Using string I/O functions fgets() and fputs(), data can be read from a file or written to a file in the form of an
array of characters.
fgets()

  fgets() is used to read a string from the file.


 Syntax: fgets(string,int_value, ptr_var);

Here, int_value denotes the no. of characters in the string.


fputs()
 is used to write a string to file.
 Syntax: fputs(string, ptr_var);

Character I/O Functions


Using character I/O functions fgetc() and fputc(), data can be read from the file or written onto the file one
character at a time.
fgetc()

 is used to read a character from a file.


 Syntax: identifier = fgetc (file pointer);
 Example:
FILE *fp;
fp=fopen(“input.txt”,”r”);
char ch;
ch = fgetc (fp);

fputc()

 Write a single character to the output file, pointed to by fp.


 Syntax : fputc(‘character or character_variable’,fp);
 Example:
FILE *fp;
char ch;
fputc (ch,fp); /* writes character ch to a file pointed by file pointer fp*/

Note:

 The routine: getc(fp) is similar to getchar() and


 The routine putc(c,fp) is similar to putchar(c).

Formatted I/O Functions


USing formatted I/O functions, fprintf(), and fscanf(), numbers, characters, or string can be read from a file or
written onto a file according to our required format.
fprintf()

 fprintf() is a function used for formatted output in file a file same as printf() does in stardard I/O
 Syntax: fprintf (fp,“format_string”,variables);
 Example:
int i = 12;
float x = 2.356;
char ch = ‘s’;
FILE *fp;
fp=fopen(“out.txt”,”w”);
fprintf (fp, “%d %f %c”, i, x, ch);

fscanf()

  fscanf() is a function used for formatted input in file a file same as printf() does in stardard I/O
 Syntax: fscanf (fp,“format_string”,identifiers);
 Example:
FILE *fp;
Fp=fopen(“input.txt”,”r”);
int i;
fscanf (fp,“%d”,i);

Integer I/O Functions


putw()

 is used to write an integer value to the file pointed by file_pointer.


 Syntax: putw(integer,fp);

getw()

 returns the integer value from the file associated with file_pointer.
 Syntax: getw(fp);

/*Example program for using getw and putw functions*/


#include< stdio.h >
main()
{
FILE *f1,*f2,*f3;
int number I;
printf(“Contents of the data file\n\n”);
f1=fopen(“DATA”,”W”);
for(I=1;I< 30;I++)
{
scanf(“%d”,&number);
if(number==-1)
break;
putw(number,f1);
}
fclose(f1);
f1=fopen(“DATA”,”r”);
f2=fopen(“ODD”,”w”);
f3=fopen(“EVEN”,”w”);
while((number=getw(f1))!=EOF) /* Read from data file*/
{
if(number%2==0)
putw(number,f3); /*Write to even file*/
else
putw(number,f2); /*write to odd file*/
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen(“ODD”,”r”);
f3=fopen(“EVEN”,”r”);
printf(“\n\nContents of the odd file\n\n”);
while(number=getw(f2))!=EOF)
printf(“%d%d”,number);
printf(“\n\nContents of the even file”);
while(number=getw(f3))!=EOF)
printf(“%d”,number);
fclose(f2);
fclose(f3);
}
Block I/O Functions
fread ()

 is used to read an entire block from a given file.


 Declaration: size_t fread(void *ptr, size_t size, size_t n, FILE *stream);
 Remarks:
fread() reads a specified number of equal-sized data items from an input stream into a block.
ptr = Points to a block into which data is read
size = Length of each item read, in bytes
n = Number of items read
stream = file pointer
 Example:
#include<stdio.h>
int main()
{
FILE *fp;
char buffer[11];
if(fp=fopen(“file1.c”,”r”))
{
fread(buffer,1,10,fp);
buffer[10]=0;
fclose(fp);
printf(“First 10 characters of the file :\n%s\n”,buffer);
}
getch();
return 0;
}

fwrite()

 is used for writing an entire block to a given file.


 Declaration: size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);
 Remarks:
fwrite() appends a specified number of equal-sized data items to an output file.
ptr = Pointer to any object; the data written begins at ptr
size = Length of each item of data
n =Number of data items to be appended
stream = file pointer
 Example:
#include <stdio.h>
int main()
{
char a[10]={‘1′,’2′,’3′,’4′,’5′,’6′,’7′,’8′,’9′,’a’};
FILE *fp;
fp=fopen(“Project.txt”,”w”);
fwrite(a,1,10,fp);
fclose(fp);
return 0;
}

 
End of File(EOF)

 There are a number of ways to test for the end-of-file condition.


 Another way is to use the value returned by the fscanf function:
FILE *fptr1;
int istatus ;
istatus = fscanf (fptr1, “%d”, &var) ;
if ( istatus == feof(fptr1) )
{
printf (“End-of-file encountered.\n”) ;
}
  EOF is special constant used to check the End of file condition
if( getc(fp)== EOF )
{
printf(“End of file Reached.\n”);

Binary Files
Binary files are the one where data is stored on the disk in the same way as it is represented in the computer
memory. The binary data stored in the files cannot be read using any of the text editors.
For example; the data 2345 takes 2 bytes of memory. The number of characters written/read is the same as
the number of characters written/read on the external device. Therefore, there is a one-to-one relationship
between the characters written/read into the file and those stored on the external devices.
The binary files organize data into blocks containing contiguous bytes of information.
In binary file, the opening mode of a text file is appended by a character b i.e.

 “r” is replaced by “rb”


 “w” is replaced by “wb”
 “a” is replaced by “ab”
 “r+” is replaced by “r+b”
 “w+” is replaced by “r+b”
 “a+” is replaced by “a+b”

Differences between text files and binary files

S.N. Text File Binary File

1. They are in human-readable formats. They are not in human-readable format.

2. Bits represent character. Bits represent custom data.

3. Less prone to get corrupt as changes reflect Can easily get corrupted, even a single bit
as soon as the file is opened and can easily change may corrupt the file.
be undone.

4. Widely used file format and can be opened Developed especially for an application and
using any simple text editor. may not be understood by other applications.

5. Mostly .txt and .rtf are used as extensions to It can have any application-defined
text files. extension.

Random Access in File


Random access means you can move to any part of a file and read or write data from it without having to read
through the entire file. There is no need to read each record sequentially if we want to access a particular
record. C supports these functions for random access file processing.
Functions used for random access file are:
 fseek()
 ftell()
 rewind()

fseek()

 This function is used for seeking the pointer position in the file at the specified byte.
 Syntax:  fseek( file pointer, displacement, pointer position);
Where
->file pointer: It is the pointer that points to the file.
->displacement: It is positive or negative. This is the number of bytes that are skipped backward (if
negative) or forward (if positive) from the current position. This is attached to L because this is a long
integer.
 Pointer position: This sets the pointer position in the file.
SEEK_SET     Seeks from the beginning of the file
SEEK_CUR    Seeks from the current position
SEEK_END    Seeks from the end of file

Equivalently,

Value Pointer position

0 Beginning of file

1 Current position

2 End of file

1. fseek( p,10L,0) or fseek(fp,10L, SEEK_SET);


0 means pointer position is on the beginning of the file, from this statement pointer position is skipped
10 bytes from the beginning of the file.
2. fseek( p,5L,1) or fseek(fp,5L,SEEK_CUR);
1 means the current position of the pointer position. From this statement pointer position is skipped 5
bytes forward from the current position.
3. fseek(p,-5L,1) or fseek(fp,-5L,SEEK_CUR);
From this statement pointer position is skipped 5 bytes backward from the current position.

Example: fseek()
#include <stdio.h>
int main()
{
FILE * fp;
f = fopen(“myfile.txt”, “w”);
fputs(“Hello World”, fp);
fseek(fp, 6, SEEK_SET);
fputs(” Nepal”, fp);
fclose(fp);
return 0;
}
ftell()
 This function returns the value of the current pointer position in the file.
 The value is count from the beginning of the file.
 Syntax: ftell(fptr); Where fptr is a file pointer.

Example:
#include <stdio.h>
int main(void)
{
FILE *stream;
stream = fopen(“MYFILE.TXT”, “w”);
fprintf(stream, “This is a test”);
printf(“The file pointer is at byte %ld\n”, ftell(stream));
fclose(stream);
return 0;
}
rewind()

 This function is used to move the file pointer to the beginning of the given file.
 Syntax: rewind( fptr); Where fptr is a file pointer.

 
More Examples:
Writing character to file
For writing character to a file, the file must be opened in write mode.
Sytax: fp = fopen(filename,“w” );

  If the file does not exist already, it will be created.


  If the file does exist, it will be overwritten!
  So, be careful when opening files for writing, in case you destroy a file unintentionally!!!!
  Opening files for writing can also fail.
 If you try to create a file in another user’s directory where you do not have access you will not be
allowed and fopen() will fail.
  Also if there is not sufficient memory to create files, it also fails.
 So check whether file created or not after calling fopen().

 
Program:
#include <stdio.h>
int main()
{
char ch;
FILE *fpw;
fpw = fopen(“new.txt”,”w”);
if(fpw == NULL)
{
printf(“Error”);
exit(1);
}
printf(“Enter any character: “);
scanf(“%c”,&ch);
/* You can also use fputc(ch, fpw);*/
fprintf(fpw,”%c”,ch);
fclose(fpw);
return 0;
}
This program asks the user to enter a character and writes that character at the end of the file. If the file doesn’t
exist then this program will create a file with the specified name and writes the input character into the file.
Output:
Command-line arguments in main()
Accessing the command-line arguments is a very useful facility. It enables you to provide commands with
arguments that the command can use e.g. the command
file prog.c
where the file is the command name, takes the argument “prog.c” and opens a file with that name, which it then
displays.

 The command-line arguments include the command name itself so that in the above example, “file”
and “prog.c” are the command line arguments.
 The first argument i.e. “file” is argument number zero, the next argument, “prog.c”, is argument
number one, and so on.
 To access these arguments from within a C program, you pass parameters to the function main().
 The use of arguments to main is a key feature of many C programs. The declaration of main looks like
this:   int main (int argc, char *argv[])
 This declaration states that main returns an integer value (used to determine if the program terminates
successfully)
 argc is the number of command-line arguments including the command itself i.e argc must be at least
1
 argv is an array of the command line arguments
 The declaration of argv means that it is an array of pointers to strings (the command-line arguments).
 By the normal rules about arguments whose type is array, what actually gets passed to main is the
address of the first element of the array.
 As a result, an equivalent (and widely used) declaration is: int main (int argc, char **argv)

When the program starts, the following conditions hold true:

1. argc is greater than 0.


2. argv[argc] is a null pointer.
3. argv[0], argv[1], …, argv[argc-1] are pointers to strings with implementation-defined meanings.
4. The argv[0] is a string that contains the program’s name or is an empty string if the name isn’t
available.
5. Remaining members of argv are the program’s arguments.

Example: print_args echoes its arguments to the standard output : form of echo command
/* print_args.c– Echo command-line arguments */
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int i = 0 ;
int num_args ;
num_args=argc;
printf(“No of arguments: %d\n”,num_args);
while(num_args > 0)
{
printf(“%s\t”, argv[i]);
i++ ;
num_args–;
}
}
If the name of this program is print_args, an example of its execution is as follows:
Run as:
C:\Users\Acer\Desktop\Programs>print_args aaa bbb ccc
Output as:
No of arguments: 4
print_args aaa bbb ccc

Graphics
Graphics is an art of drawing pictures, lines, charts, etc. using computers with the help of
programming.Computer graphics are made up of number of pixels.
Pixels
A pixel is a single point in the screen. If all pictures are built by the concept of pixel then wondering how each
picture differ that is how some picture appear brighter while some others have a shady effect. All this is by the
concept or technical terminology called resolution.
Resolution
Resolution is the number of rows that appear from top to bottom of a screen and in turn the number of pixels or
pixel elements that appear from left to right on each scan line. Based on this resolution only the effect of the
picture appears on the screen. In other words, the greater the resolution greater will be the clarity of the picture.
This is because the greater the number of dots greater will be the sharpness of the picture. That is resolution
value is directly proportional to the clarity of the picture.
Graphic modes
There are generally two modes available namely text and graphics. In a graphics mode we have generally the
following adapters namely CGA called Color Graphics Adapter, EGA, and VGA. Each adapter differs in the way
of generating colors and also in the number of colors produced by each adapter. Pixel being a picture element
when we consider the graphics mode each pixel has a color associated with it. But the way these colors are
used depends on adapters because each adapter differs in the way they handle colors and also in the number
of colors supported.
Having known about adapters now let us start knowing how to start switching to graphics mode from text mode.
In other words how to start using pixel and resolution concepts.
This is done by a function called intigraph( ). This intigraph( ) takes in it 2 main arguments as input namely gd
and gm.
In this gd has the number of modes which has the best resolution. This is very vital for graphics since the best
resolution only gives a sharper picture as we have seen before. This value is obtained by using the function
called as getgraphmode ( ) in C graphics.
The other argument gm gives insight about the monitor used, the corresponding resolution of that, the colors
that are available since this varies based
on adapters supported. This value is obtained by using the function named getmodename ( ) in C graphics.
 

Graphics function in C
There are numerous graphics functions available in c. Let us see some graphics functions used in C to
understand how and where a pixel is placed in each when each of the graphics function gets invoked.
Plotting and getting points
Function: putpixel(x, y, color)
Purpose:
The functionality of this function is it put a pixel or in other words a dot at position x, y given in inputted
argument. Here one must understand that the whole screen is imagined as a graph. In other words the pixel at
the top left-hand corner of the screen represents the value (0, 0).
Here the color is the integer value associated with colors and when specified the picture element or the dot is
placed with the appropriate color associated with that integer value.
Function: getpixel(x, y)
Purpose:
This function when invoked gets the color of the pixel specified. The color got will be the integer value
associated with that color and hence the function gets an integer value as a return value. So the smallest
element on the graphics display screen is a pixel or a dot and the pixels are used in this way to place images in
graphics screen in C language.
Drawing lines
Function:Line(x1, y1, x2, y2)
Purpose: The functionality of this function is to draw a line from (x1,y1) to (x2,y2).Here also the coordinates
are passed taking the pixel (0,0) at the top left-hand corner of the screen as the origin. And also one must note
that the line formed is by using the number of pixels placed near each other.
Some Examples of C graphics:
// Drawing a Circle
#include<graphics.h>
void main()
{
int gd= DETECT, gm;
initgraph(&gd,&gm,”c:\\tc\\bgi”);
circle(200,100,10);
setcolor(WHITE);
getch();
closegraph();
}
//Drawing Lines
#include<graphics.h>
void main()
{
int gd= DETECT, gm;
initgraph(&gd,&gm,”c:\\tc\\bgi”);
line(90,70,60,100);
line(200,100,150,300);
setcolor(WHITE);
getch();
closegraph();
}
//Drawingrectangle
#include<graphics.h>
void main()
{
int gd= DETECT, gm;
initgraph(&gd,&gm,”c:\\tc\\bgi”);
rectangle(200,100,150,300);
setcolor(WHITE);
getch();
closegraph();
}
//Constructing triangle
#include<graphics.h>
void main()
{
int gd= DETECT, gm;
initgraph(&gd,&gm,”c:\\tc\\bgi”);
line(200,100,10,20);line(10,20,50,60);line(50,60,200,100);
setcolor(WHITE);
getch();
closegraph();
}

You might also like