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

UNIT IV - C Programing

The document discusses arrays and pointers in C programming. It defines that an array is a collection of similar data items indexed with integers starting from 0. It describes how to declare, initialize and access single and multi-dimensional arrays. It also explains that a pointer is a variable that stores the address of another variable. It discusses how to declare and initialize pointer variables, dereference pointers to access the value of the variable being pointed to, and perform pointer arithmetic.

Uploaded by

AKANKSHA
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

UNIT IV - C Programing

The document discusses arrays and pointers in C programming. It defines that an array is a collection of similar data items indexed with integers starting from 0. It describes how to declare, initialize and access single and multi-dimensional arrays. It also explains that a pointer is a variable that stores the address of another variable. It discusses how to declare and initialize pointer variables, dereference pointers to access the value of the variable being pointed to, and perform pointer arithmetic.

Uploaded by

AKANKSHA
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 13

C Programming – UNIT IV

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.

Key Points : Array

 An array is a collection of similar data items and these data types may be all ints, floats or all chars.

 Each member of an array is identified by unique index assigned to it.

 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 general syntax of an array is:


Data type array_name[size];
Example: int marks[30];

 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:

type arrayName [ arraySize ];

This is called a single-dimensional array. The arraySize must be an integer constant greater than zero


and type can be any valid C data type. For example, to declare a 10-element array called balance of type
double, use this statement:

double balance[10];

Now balance is avariable array which is sufficient to hold upto 10 double numbers.

Content Designed By: Faiz Mohd Arif Khan | 1|


C Programming – UNIT IV

 Initializing Arrays
You can initialize array in C either one by one or using a single statement as follows:

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

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:

double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};

You will create exactly the same array as you did in the previous example.

 Accessing Array Elements


An element is accessed by indexing the array name. This is done by placing the index of the element within
square brackets after the name of the array. For example:

double salary = balance[9];

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;

/* initialize elements of array n to 0 */


for ( i = 0; i < 5; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}

/* output each array element's value */


for (j = 0; j < 5; j++ )
{
printf("Element[%d] = %d\n", j, n[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

Content Designed By: Faiz Mohd Arif Khan | 2|


C Programming – UNIT IV

In C there are mainly three types of array :-

Single dimensional array.

Ex: int x[3]={10,20,30};

Double dimensional array.

Ex:- int x[3][2]={ {10,20},{30,40},{50,60} };

Multi dimensional array.

Ex:- int x[2][3][2]={ {{10,20},{30,40},{50,60}},{{11,22},{33,44},{55,66}} };

Example of two dimensional array.

int a[3][4];

 Accessing Two -Dimensional Array Elements:


An element in 2-dimensional array is accessed by using the subscripts ie. row index and column index of the array.
For example:

int val = a[2][3];

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;

/* output each array element's value */


for ( i = 0; i < 4; i++ )
{
for ( j = 0; j < 2; j++ )
{
printf("a[%d][%d] = %d\n", i,j, a[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

Content Designed By: Faiz Mohd Arif Khan | 3|


C Programming – UNIT IV

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:

int *ip; /* pointer to an integer */


double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */

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.

 How to use Pointers?


There are few important operations which we will do with the help of pointers very frequently. 
(a) we define a pointer variables 
(b) assign the address of a variable to a pointer and 
(c) finally access the value at the address available in the pointer variable.
This is done by using unary operator * that returns the value of the variable located at the address specified
by its operand. Following example makes use of these operations:

#include <stdio.h>
void main ()
{
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */


printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */


printf("Value of *ip variable: %d\n", *ip );

When the above code is compiled and executed, it produces result something as follows:

Address of var variable: bffd8b3c


Address stored in ip variable: bffd8b3c
Value of *ip variable: 20

Content Designed By: Faiz Mohd Arif Khan | 4|


C Programming – UNIT IV

 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;

printf("The value of ptr is : %x\n", ptr );

return 0;
}

When the above code is compiled and executed, it produces following result:

The value of ptr is 0

 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:

int x = 30; //Suppose Address of X is 200


int *p = &x; //Suppose Address of P is 100
p++; //Increment the address of P by 2 i.e. 202 because size of int is 2 bytes

 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:

int x = 30; //Suppose Address of X is 200


int *p = &x; //Suppose Address of P is 100
p--; //Decrement the address of P by 2 i.e. 198 because size of int is 2 bytes

Content Designed By: Faiz Mohd Arif Khan | 5|


C Programming – UNIT IV

 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.

 Following arithmetic operations are valid with pointers:-


p1= p1+ 4;
p1= p1-2;
p3= p1-p2;
 Following other operations are valid with pointers:-
p1>p2
p1==p2
p1 != p2
p1++;
--p2;

 Following operations are not valid with pointers:-

p3=p1+p2;

p3=p1/p2;

p3=p1*p2;

p1=p1/3;

 Using Pointers as function argument : Call by reference


The call by reference method of passing arguments to a function copies the address of an argument
into the formal parameter. Inside the function, the address is used to access the actual argument used in
the call. This means that changes made to the parameter affect the passed argument.

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.

/* function definition to swap the values */


void swap(int *x, int *y)
{
int temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
}

Content Designed By: Faiz Mohd Arif Khan | 6|


C Programming – UNIT IV

#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:

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

 Difference between call by value & call by reference.

Cal by Value Call by Reference


This is the usual method to call a function in which only In this method, the address of the variable is passed as an
the value of the variable is passed as an argument argument
Any alternation in the value of the argument passed is Any alternation in the value of the argument passed is
local to the function and is not accepted in the calling accepted in the calling program(since alternation is made
program indirectly in the memory location using the pointer)
Memory location occupied by formal and actual Memory location occupied by formal and actual arguments is
arguments is different same and there is a saving of memory location
Since the existing memory location is used through its
Since a new location is created, this method is slow
address, this method is fast

Content Designed By: Faiz Mohd Arif Khan | 7|


C Programming – UNIT IV

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:

struct [structure tag]


{
member definition;
member definition;
...
member definition;
} [one or more structure variables];

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;

 Accessing Structure Members


To access any member of a structure, we use the member access operator (.). The member access operator
is coded as a period between the structure variable name and the structure member that we wish to access.
You would use struct keyword to define variables of structure type. Following is the example to explain usage
of structure:
#include <stdio.h>
#include <string.h>

struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};

Content Designed By: Faiz Mohd Arif Khan | 8|


C Programming – UNIT IV

void main( )
{

/* Declare Book1 of type Book */


struct Books Book1 = {"C Programming","Herbert","C Tutorial",6495407};

/* Declare Book2 of type Book */


struct Books Book2 = {"Telecom","Bertz","Tele Billing",6495700};

/* print Book1 info */


printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */


printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);

When the above code is compiled and executed, it produces following result:

Book 1 title : C Programming


Book 1 author : Herbert
Book 1 subject : C Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom
Book 2 author : Bertz
Book 2 subject : Tele Billing
Book 2 book_id : 6495700

Content Designed By: Faiz Mohd Arif Khan | 9|


C Programming – UNIT IV

Dynamic Memory Allocation :


The C programming language provides several functions for memory allocation and management. These
functions can be found in the <stdlib.h> header file.

S.N. Function and Description


void *calloc(int num, int size);
1.
This function allocates an array of num elements each of which size in bytes will be size.

void free(void *address); 


2.
This function release a block of memory block specified by address.

void *malloc(int num); 


3.
This function allocates an array of num bytes and leave them initialized.

void *realloc(void *address, int newsize); 


4.
This function re-allocates memory extending it upto newsize.

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.

Content Designed By: Faiz Mohd Arif Khan | 10 |


C Programming – UNIT IV

Example : Implementation of stack in C using integer array.

#include<stdio.h>
#include<conio.h>

int top = -1;


const int MAX = 5;
int stack_arr[5];

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()*/

Content Designed By: Faiz Mohd Arif Khan | 11 |


C Programming – UNIT IV

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");

while(1) Enter your choice : 1


{ Enter the item to pushed in stack : 11
printf("Enter your choice : ");
scanf("%d",&choice); Enter your choice : 1
Enter the item to pushed in stack : 22
switch(choice)
{
case 1 : Enter your choice : 1
push(); Enter the item to pushed in stack : 33
break;
Enter your choice : 3
case 2: Stack elements :
pop(); 33
break; 22
11
case 3:
display(); Enter your choice : 2
break;
Popped element is : 33
case 4:
printf("THANK YOU!!!"); Enter your choice : 6
exit(1); WRONG CHOICE!!!

default: Enter your choice : 4


printf("WRONG CHOICE!!!\n"); THANK YOU!!!
}/*End of switch*/
}/*End of while*/
}/*End of main()*/

Content Designed By: Faiz Mohd Arif Khan | 12 |


C Programming – UNIT IV

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.

 Linked List Operations :

We can perform various operations on such a list. The most common operations are:

 checking whether the list is empty;


 inserting or removing a specific element (e.g., the first one, the last one, or one with a
certain value);

 accessing a node to modify it or to obtain the information in it;

 traversing the list to access all elements (e.g., to print them, or to find some specific
element);

 determining the size (i.e., the number of elements) of the list;

Content Designed By: Faiz Mohd Arif Khan | 13 |

You might also like