UNIT IV - C Programing
UNIT IV - C Programing
Arrays in C :
C programming language provides a data structure called the array, which can store a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array
variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual
variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and
the highest address to the last element.
An array is a collection of similar data items and these data types may be all ints, floats or all chars.
An index is a positive integer enclosed in [ ] placed immediately after the array name.
An index holds integer value starting with zero. Means the first element in the array is numbered 0,
so the last element is 1 less than the size of the array.
An array is defined in the same way as a variable defined except that array name is followed by one
or more expressions, enclosed within square brackets[ ], specifying the array dimension.
The data type specifies the type of elements that will be contained in the array.
The array name indicates the location of the first member of an array.
The array size indicates the maximum number of elements stored in the array.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of elements
required by an array as follows:
double balance[10];
Initializing Arrays
You can initialize array in C either one by one or using a single statement as follows:
The number of values between braces { } can not be larger than the number of elements that we declare for
the array between square brackets [ ]. Following is an example to assign a single element of the array:
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you
write:
You will create exactly the same array as you did in the previous example.
The above statement will take 10th element from the array and assign the value to salary variable. Following
is an example which will use all the above mentioned three concepts viz. declaration, assignment and
accessing arrays:
#include <stdio.h>
void main ()
{
int n[ 10 ]; /* n is an array of 5 integers */
int i,j;
When the above code is compiled and executed, it produces following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
int a[3][4];
The above statement will take 4th element from the 3rd row of the array. You can verify it in the above diagram.
Let us check below program where we have used nested loop to handle a two dimensional array:
#include <stdio.h>
void main ()
{
/* an array with 4 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
When the above code is compiled and executed, it produces following result:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
Pointers in C :
A pointer is a variable whose value is the address of another variable ie. direct address of the memory
location. Like any variable or constant, you must declare a pointer before you can use it to store any
variable address. The general form of a pointer variable declaration is:
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer
variable. The asterisk * you used to declare a pointer is the same asterisk that you use for multiplication.
However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the
valid pointer declaration:
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a
long hexadecimal number that represents a memory address. The only difference between pointers of
different data types is the data type of the variable or constant that the pointer points to.
#include <stdio.h>
void main ()
{
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
When the above code is compiled and executed, it produces result something as follows:
NULL Pointers in C
It is always a good practice to assign a NULL value to a pointer variable in case you do not have exact address
to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called
a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the
following program:
#include <stdio.h>
int main ()
{
int *ptr = NULL;
return 0;
}
When the above code is compiled and executed, it produces following result:
Pointer Arithmetic:
C pointer is an address which is a numeric value. Therefore, you can perform arithmetic operations on a pointer
just as you can a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, +, and –
Incrementing a Pointer
Incrementing a pointer, which increases its value by the number of bytes of its data type as shown below:
Decrementing a Pointer
The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes of
its data type as shown below:
Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to variables that
are related to each other, such as elements of the same array, then p1 and p2 can be meaningfully compared.
p3=p1+p2;
p3=p1/p2;
p3=p1*p2;
p1=p1/3;
To pass the value by reference, argument pointers are passed to the functions just like any other value.
So accordingly you need to declare the function parameters as pointer types as in the following function
swap(), which exchanges the values of the two integer variables pointed to by its arguments.
#include <stdio.h>
void swap(int *x, int *y); // function prototype
void main ()
{
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
swap(&a, &b); //calling swap by passing addresses of a and b
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
}
Let us put above code in a single C file, compile and execute it, it will produce following result:
Structures in C :
C arrays allow you to define type of variables that can hold several data items of the same kind but
structure is another user defined data type available in C programming, which allows you to combine data
items of different kinds.
Structures are used to represent a record, Suppose you want to keep track of your books in a library. You
might want to track the following attributes about each book:
Title
Author
Subject
Book ID
Defining a Structure
To define a structure, you must use the struct keyword. The struct statement defines a new data type, with
more than one member for your program. The format of the struct statement is this:
The structure tag is optional and each member definition is a normal variable definition, such as int i;
or float f; or any other valid variable definition. At the end of the structure's definition, before the final
semicolon, you can specify one or more structure variables but it is optional. Here is the way you would
declare the Book structure:
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
void main( )
{
When the above code is compiled and executed, it produces following result:
Stack :
Stack is a specialized data storage structure (Abstract data type). Unlike, arrays access of elements in a
stack is restricted. It has two main functions push and pop. Insertion in a stack is done using push function and
removal from a stack is done using pop function. Stack allows access to only the last element inserted hence, an
item can be inserted or removed from the stack from one end called the top of the stack. It is therefore, also
called Last-In-First-Out (LIFO) list. Stack has three properties: capacity stands for the maximum number of
elements stack can hold, size stands for the current size of the stack and elements is the array of elements.
#include<stdio.h>
#include<conio.h>
void push()
{
int pushed_item;
if(top == (MAX-1))
{
printf("Stack Overflow\n");
}
else
{
printf("Enter the item to be pushed in stack : ");
scanf("%d",&pushed_item);
top=top+1;
stack_arr[top] = pushed_item;
}
}/*End of push()*/
void pop()
{
if(top == -1)
{
printf("Stack Underflow\n");
}
else
{
printf("Popped element is : %d\n",stack_arr[top]);
top=top-1;
}
}/*End of pop()*/
void display()
{
int i;
if(top == -1)
printf("Stack is empty\n");
else
{
printf("Stack elements :\n");
for(i = top; i >=0; i--)
{
printf("%d\n", stack_arr[i] );
}
}
}/*End of display()*/
void main()
{ OUTPUT :
int choice; 1. Push
2. Pop
printf("1.Push\n");
printf("2.Pop\n"); 3. Display
printf("3.Display\n"); 4. Quit
printf("4.Quit\n");
Linked List :
A linked list is a data structure that consists of a sequence of data records such that in each record
there is a field that contains a reference (i.e., a link) to the next record in the sequence.
Linked lists are among the most common data structures, and are used to implement many
important data structures, such as stacks, queues.
Linked lists allow insertion and removal of nodes at any point in the list, with a constant number of
operations.
Linked lists contain nodes which have a data field as well as a next field, which points to the next
node in the linked list.
We can perform various operations on such a list. The most common operations are:
traversing the list to access all elements (e.g., to print them, or to find some specific
element);