0% found this document useful (0 votes)
5 views11 pages

Data Structures Notes

The document provides an overview of data structures in C, focusing on arrays, pointers, and structures. It explains how arrays are used to store collections of similar data types, how to declare and access elements in arrays, and introduces pointers as variables that store memory addresses. Additionally, it covers the definition and usage of structures to combine different data types into a single entity, highlighting their importance in organizing complex data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views11 pages

Data Structures Notes

The document provides an overview of data structures in C, focusing on arrays, pointers, and structures. It explains how arrays are used to store collections of similar data types, how to declare and access elements in arrays, and introduces pointers as variables that store memory addresses. Additionally, it covers the definition and usage of structures to combine different data types into a single entity, highlighting their importance in organizing complex data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

DATA STRUCTURES

Data Structures in C are used to store data in an organised and efficient manner. The C Programming
language has many data structures like an array,pointers, stack, queue, linked list, tree, etc. A
programmer selects an appropriate data structure and uses it according to their convenience.

Let us look into some of these data structures:

ARRAY

An Array is a sequential collection of elements, of the same data type. They are stored sequentially in
memory. An Array is a data structure that holds a similar type of elements. The array elements are not
treated as objects in c like they are in java.

An array is a group (or collection) of same data types. For example an int array holds the elements of int
types while a float array holds the elements of float types.

Why we need Array in C Programming?

Consider a scenario where you need to find out the average of 100 integer numbers entered by user. In
C, you have two ways to do this: 1) Define 100 variables with int data type and then perform 100 scanf()
operations to store the entered values in the variables and then at last calculate the average of them. 2)
Have a single integer array to store all the values, loop the array to store all the entered values in array
and later calculate the average.
Which solution is better according to you? Obviously the second solution, it is convenient to store
same data types in one single variable and later access them using array index (we will discuss that later
in this tutorial).

How to declare Array in C


int num[35]; /* An integer array of 35 elements */
char ch[10]; /* An array of characters for 10 elements */
Similarly an array can be of any data type such as double, float, short etc.

How to access element of an array in C


You can use array subscript (or index) to access any element stored in array. Subscript starts with 0,
which means arr[0] represents the first element in the array arr.

In general arr[n-1] can be used to access nth element of an array. where n is any integer number.

For example:

int mydata[20];
mydata[0] /* first element of array mydata*/
mydata[19] /* last (20th) element of array mydata*/
Example of Array In C programming to find out the average of 4 integers
#include <stdio.h>
int main()
{
int avg = 0;
int sum =0;
int x=0;
/* Array- declaration – length 4*/
int num[4];

/* We are using a for loop to traverse through the array


* while storing the entered values in the array
*/
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
for (x=0; x<4;x++)
{
sum = sum+num[x];
}

avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}
Output:

Enter number 1
10
Enter number 2
10
Enter number 3
20
Enter number 4
40
Average of entered number is: 20
Lets discuss the important parts of the above program:

Input data into the array


Here we are iterating the array from 0 to 3 because the size of the array is 4. Inside the loop we are
displaying a message to the user to enter the values. All the input values are stored in the corresponding
array elements using scanf function.

for (x=0; x<4;x++)


{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
Reading out data from an array
Suppose, if we want to display the elements of the array then we can use the for loop in C like this.

for (x=0; x<4;x++)


{
printf("num[%d]\n", num[x]);
}
Various ways to initialize an array
In the above example, we have just declared the array and later we initialized it with the values input by
user. However you can also initialize the array during declaration like this:

int arr[5] = {1, 2, 3, 4 ,5};


OR (both are same)

int arr[] = {1, 2, 3, 4, 5};


Un-initialized array always contain garbage values.

Declaring Arrays

 Array variables are declared identically to variables of their data type, except that the variable
name is followed by one pair of square [ ] brackets for each dimension of the array.
 Uninitialized arrays must have the dimensions of their rows, columns, etc. listed within the
square brackets.
 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];
 Here balance is a variable array which is sufficient to hold up to 10 double numbers.

Initializing Arrays

 Arrays may be initialized when they are declared, just as any other variables.
 Place the initialization data in curly {} braces following the equals sign. Note the use of
commas in the examples below.
 An array may be partially initialized, by providing fewer data items than the size of the array.
The remaining array elements will be automatically initialized to zero.
 If an array is to be completely initialized, the dimension of the array is not required. The
compiler will automatically size the array to fit the initialized data. ( Variation:
Multidimensional arrays - see below. )
 Examples:

int i = 5, intArray[ 6 ] = { 1, 2, 3, 4, 5, 6 }, k;
float sum = 0.0f, floatArray[ 100 ] = { 1.0f, 5.0f, 20.0f };
double piFractions[ ] = { 3.141592654, 1.570796327, 0.785398163 };

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 the 10th element from the array and assign the value to salary variable.
The following example Shows how to use all the three above mentioned concepts viz. declaration,
assignment, and accessing arrays −
// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array
#include <stdio.h>

int main() {
int values[5];

printf("Enter 5 integers: ");

// taking input and storing it in an array


for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}

printf("Displaying integers: ");

// printing elements of an array


for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}

Output

Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3

// Program to find the average of n numbers using arrays

#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;

printf("Enter number of elements: ");


scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);

// adding integers entered by the user to the sum variable


sum += marks[i];
}

average = sum/n;
printf("Average = %d", average);

return 0;
}

Output

Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39

Multidimensional Arrays

 Multi-dimensional arrays are declared by providing more than one set of square [ ] brackets after
the variable name in the declaration statement.
 One dimensional arrays do not require the dimension to be given if the array is to be completely
initialized. By analogy, multi-dimensional arrays do not require the first dimension to be given
if the array is to be completely initialized. All dimensions after the first must be given in any
case.
 For two dimensional arrays, the first dimension is commonly considered to be the number of
rows, and the second dimension the number of columns. We will use this convention when
discussing two dimensional arrays.
 Two dimensional arrays are considered by C/C++ to be an array of ( single dimensional arrays ).
For example, "int numbers[ 5 ][ 6 ]" would refer to a single dimensional array of 5 elements,
wherein each element is a single dimensional array of 6 integers. By extension, "int numbers[ 12
][ 5 ][ 6 ]" would refer to an array of twelve elements, each of which is a two dimensional array,
and so on.
 Another way of looking at this is that C stores two dimensional arrays by rows, with all elements
of a row being stored together as a single unit. Knowing this can sometimes lead to more
efficient programs.
 Multidimensional arrays may be completely initialized by listing all data elements within a
single pair of curly {} braces, as with single dimensional arrays.
 It is better programming practice to enclose each row within a separate subset of curly {} braces,
to make the program more readable. This is required if any row other than the last is to be
partially initialized. When subsets of braces are used, the last item within braces is not followed
by a comma, but the subsets are themselves separated by commas.
 Multidimensional arrays may be partially initialized by not providing complete initialization
data. Individual rows of a multidimensional array may be partially initialized, provided that
subset braces are used.

Pointers

What are Pointers?

A pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location. Like any variable or constant, you must declare a pointer before using 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 * used to declare a pointer is the same asterisk used for multiplication.
However, in this statement the asterisk is being used to designate a variable as a pointer. Take a look at
some of the valid pointer declarations −
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.

C Pointers – Operators that are used with Pointers

Lets discuss the operators & and * that are used with Pointers in C.

“Address of”(&) Operator


We have already seen in the first example that we can display the address of a variable using ampersand
sign. I have used &num to access the address of variable num. The & operator is also known as
“Address of” Operator.

printf("Address of var is: %p", &num);


Point to note: %p is a format specifier which is used for displaying the address in hex format.
Now that you know how to get the address of a variable but how to store that address in some other
variable? That’s where pointers comes into picture. As mentioned in the beginning of this guide,
pointers in C programming are used for holding the address of another variables.

Pointer is just like another variable, the main difference is that it stores address of another
variable rather than a value.

“Value at Address”(*) Operator

The * Operator is also known as Value at address operator.


How to declare a pointer?

int *p1 /*Pointer to an integer variable*/


double *p2 /*Pointer to a variable of data type double*/
char *p3 /*Pointer to a character variable*/
float *p4 /*pointer to a float variable*/
The above are the few examples of pointer declarations. If you need a pointer to store the address of
integer variable then the data type of the pointer should be int. Same case is with the other data
types.

By using * operator we can access the value of a variable through a pointer.


For example:

double a = 10;
double *p;
p = &a;
*p would give us the value of the variable a. The following statement would display 10 as output.

printf("%d", *p);
Similarly if we assign a value to *pointer like this:

*p = 200;
It would change the value of variable a. The statement above will change the value of a from 10 to 200.

How to Use Pointers?

There are a few important operations, which we will do with the help of pointers very
frequently. (a) We define a pointer variable, (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.
The following example makes use of these operations −

#include <stdio.h>

int 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 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20

NULL Pointers

It is always a good practice to assign a NULL value to a pointer variable in case you do not have an
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 –

Benefits of using pointers

Below we have listed a few benefits of using pointers:

1. Pointers are more efficient in handling Arrays and Structures.

2. Pointers allow references to function and thereby helps in passing of function as arguments to
other functions.

3. It reduces length of the program and its execution time as well.

4. It allows C language to support Dynamic Memory management.

Structures

Arrays allow to define type of variables that can hold several data items of the same kind.
Similarly structure is another user defined data type available in C that allows 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 statement. The struct statement defines a new data type,
with more than one member. The format of the struct statement is as follows −
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 the keyword struct to define variables of structure type. The following
example shows how to use a structure in a program −
#include <stdio.h>
#include <string.h>

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;

Unions

A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can contain a
value at any given time. Unions provide an efficient way of using the same memory location for
multiple-purpose.

Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your program.
The format of the union statement is as follows −
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
The union 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 union's definition, before the final
semicolon, you can specify one or more union variables but it is optional. Here is the way you would
define a union type named Data having three members i, f, and str −
union Data {
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It
means a single variable, i.e., same memory location, can be used to store multiple types of data. You
can use any built-in or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the union. For
example, in the above example, Data type will occupy 20 bytes of memory space because this is
the maximum space which can be occupied by a character string. The following example displays
the total memory size occupied by the above union −
#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

printf( "Memory size occupied by data : %d\n", sizeof(data));

return 0;
}
When the above code is compiled and executed, it produces the following result −
Memory size occupied by data : 20

Accessing Union Members

To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we wish to
access. You would use the keyword union to define variables of union type. The following example
shows how to use unions in a program −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};

int main( ) {
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming

You might also like