C - Arrays
Arrays a kind of data structure that 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.
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]; - Here balance is a variable array which is sufficient
to hold up to 10 double numbers.
Initializing Arrays
You can initialize an array in C either one by one or using a single statement
as follows
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
he number of values between braces { } cannot be larger than the number
of elements that we declare for the array between square brackets [ ].
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, 7.0, 50.0};
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 10 th 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
#include <stdio.h>
#include <conio.h>
Void main () {
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
clrscr();
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
n[ i ] = i + 100; /* set element at location i to i + 100 */
/* output each array element's value */
for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
getch();
Multi-dimensional Arrays in C
C programming language allows multidimensional arrays. Here is the general
form of a multidimensional array declaration −
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional integer
array −
int threedim[5][10][4];
Two-dimensional Arrays
The simplest form of multidimensional array is the two-dimensional array. A
two-dimensional array is, in essence, a list of one-dimensional arrays. To
declare a two-dimensional integer array of size [x][y], you would write
something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C
identifier. A two-dimensional array can be considered as a table which will
have x number of rows and y number of columns. A two-dimensional array a,
which contains three rows and four columns can be shown as follows
Thus, every element in the array a is identified by an element name of
the form a[ i ][ j ], where 'a' is the name of the array, and 'i' and 'j' are
the subscripts that uniquely identify each element in 'a'.
Initializing Two-Dimensional Arrays
Multidimensional arrays may be initialized by specifying bracketed values for
each row. Following is an array with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The
following initialization is equivalent to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Accessing Two-Dimensional Array Elements
An element in a two-dimensional array is accessed by using the subscripts,
i.e., row index and column index of the array. For example −
int val = a[2][3];
The above statement will take the 4th element from the 3rd row of the array.
You can verify it in the above figure. Let us check the following program
where we have used a nested loop to handle a two-dimensional array
include <stdio.h>
void main ()
/* an array with 5 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 < 5; i++ )
for ( j = 0; j < 2; j++ )
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
Passing Arrays as Function Arguments in C
If you want to pass a single-dimension array as an argument in a function,
you would have to declare a formal parameter in one of following three
ways and all three declaration methods produce similar results because
each tells the compiler that an integer pointer is going to be received.
Similarly, you can pass multi-dimensional arrays as formal parameters.
Way-1
Formal parameters as a pointer −
void myFunction(int *param) {
Way-2
Formal parameters as a sized array −
void myFunction(int param[10]) {
Way-3
Formal parameters as an unsized array −
void myFunction(int param[]) {
}
Now, consider the following function, which takes an array as an
argument along with another argument and based on the passed
arguments, it returns the average of the numbers passed through the
array as follows
double getAverage(int arr[], int size) {
int i;
double avg;
double sum = 0;
for (i = 0; i < size; ++i)
sum += arr[i];
avg = sum / size;
return avg;
Now, let us call the above function as follows
#include <stdio.h>
/* function declaration */
double getAverage(int arr[], int size);
void main () {
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;
/* output the returned value */
printf( "Average value is: %f ", avg );
return 0;
Arrays & Strings
Strings are actually one-dimensional array of characters terminated by a null
character '\0'. Thus a null-terminated string contains the characters that
comprise the string followed by a null.
The following declaration and initialization create a string consisting of the
word "Hello". To hold the null character at the end of the array, the size of
the character array containing the string is one more than the number of
characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above
statement as follows −
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C
Actually, you do not place the null character at the end of a string constant.
The C compiler automatically places the '\0' at the end of the string when it
initializes the array. Let us try to print the above mentioned string
#include <stdio.h>
void main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
C supports a wide range of functions that manipulate null-terminated strings
Sr.No Function & Purpose
.
1
strcpy(s1, s2);
Copies string s2 into string s1.
2
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3
strlen(s1);
Returns the length of string s1.
4
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
s1>s2.
5
strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6
strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1
The following example uses some of the above-mentioned functions
#include <stdio.h>
#include <string.h>
void main () {
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
C - 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 −
Example
#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;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 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);
return 0;
When the above code is compiled and executed, it produces the following
result −
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
Structures as Function Arguments
You can pass a structure as a function argument in the same way as you
pass any other variable or pointer.
Example
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books book );
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;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printBook( Book1 );
/* Print Book2 info */
printBook( Book2 );
return 0;
void printBook( struct Books book ) {
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
When the above code is compiled and executed, it produces the following
result −
Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700
Self Referential Structures
Self Referential structures are those structures that have one or more
pointers which point to the same type of structure, as their member.
In other words, structures pointing to the same type of structures are self-
referential in nature.
Example:
struct node
int data1;
char data2;
struct node* link;
};
int main()
struct node ob;
return 0;
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence,
the structure ‘node’ is a self-referential structure with ‘link’ as the
referencing pointer.
An important point to consider is that the pointer should be initialized
properly before accessing, as by default it contains garbage value.
Types of Self Referential Structures
1) Self Referential Structure with Single Link
2) Self Referential Structure with Multiple Links
Self Referential Structure with Single Link: These structures can have only
one self-pointer as their member. The following example will show us how
to connect the objects of a self-referential structure with the single link
and access the corresponding data members. The connection formed is
shown in the following figure.
#include <stdio.h>
struct node {
int data1;
char data2;
struct node* link;
};
int main()
struct node ob1; // Node1
// Intialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
struct node ob2; // Node2
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
// Linking ob1 and ob2
ob1.link = &ob2;
// Accessing data members of ob2 using ob1
printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
return 0;
Output:
30
40
Self Referential Structure with Multiple Links: Self referential structures
with multiple links can have more than one self-pointers. Many complicated
data structures can be easily constructed using these structures. Such
structures can easily connect to more than one nodes at a time. The
following example shows one such structure with more than one links.
The connections made in the above example can be understood using the
following figure.
#include <stdio.h>
struct node {
int data;
struct node* prev_link;
struct node* next_link;
};
int main()
struct node ob1; // Node1
// Intialization
ob1.prev_link = NULL;
ob1.next_link = NULL;
ob1.data = 10;
struct node ob2; // Node2
// Intialization
ob2.prev_link = NULL;
ob2.next_link = NULL;
ob2.data = 20;
struct node ob3; // Node3
// Intialization
ob3.prev_link = NULL;
ob3.next_link = NULL;
ob3.data = 30;
// Forward links
ob1.next_link = &ob2;
ob2.next_link = &ob3;
// Backward links
ob2.prev_link = &ob1;
ob3.prev_link = &ob2;
// Accessing data of ob1, ob2 and ob3 by ob1
printf("%d\t", ob1.data);
printf("%d\t", ob1.next_link->data);
printf("%d\n", ob1.next_link->next_link->data);
// Accessing data of ob1, ob2 and ob3 by ob2
printf("%d\t", ob2.prev_link->data);
printf("%d\t", ob2.data);
printf("%d\n", ob2.next_link->data);
// Accessing data of ob1, ob2 and ob3 by ob3
printf("%d\t", ob3.prev_link->prev_link->data);
printf("%d\t", ob3.prev_link->data);
printf("%d", ob3.data);
return 0;
Output:
10 20 30
10 20 30
10 20 30
In the above example we can see that ‘ob1’, ‘ob2’ and ‘ob3’ are three
objects of the self referential structure ‘node’. And they are connected using
their links in such a way that any of them can easily access each other’s
data. This is the beauty of the self referential structures. The connections can
be manipulated according to the requirements of the programmer.
Applications:
Self referential structures are very useful in creation of other complex data
structures like:
Linked Lists
Stacks
Queues
Trees
Graphs etc
C - 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
Here, we can see that the values of i and f members of union got corrupted
because the final value assigned to the variable has occupied the memory
location and this is the reason that the value of str member is getting printed
very well.
Now let's look into the same example once again where we will use one
variable at a time which is the main purpose of having unions −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
When the above code is compiled and executed, it produces the following
result −
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is
being used at a time.
Bitwise Operators in C
In arithmetic-logic unit (which is within the CPU), mathematical operations
like: addition, subtraction, multiplication and division are done in bit-level. To
perform bit-level operations in C programming, bitwise operators are used.
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise complement
<< Shift left
>> Shift right
Bitwise AND operator &
The output of bitwise AND is 1 if the corresponding bits of two operands is 1.
If either bit of an operand is 0, the result of corresponding bit is evaluated to
0.
Let us suppose the bitwise AND operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100 & 00011001
________
00001000 = 8 (In decimal)
Example #1: Bitwise AND
#include <stdio.h>
int main()
int a = 12, b = 25;
printf("Output = %d", a&b);
return 0;
}
Output
Output = 8
Bitwise OR operator |
The output of bitwise OR is 1 if at least one corresponding bit of two
operands is 1. In C Programming, bitwise OR operator is denoted by |.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise OR Operation of 12 and 25
00001100 | 00011001
________
00011101 = 29 (In decimal)
Example #2: Bitwise OR
#include <stdio.h>
int main()
int a = 12, b = 25;
printf("Output = %d", a|b);
return 0;
}
Output
Output = 29
Bitwise XOR (exclusive OR) operator ^
The result of bitwise XOR operator is 1 if the corresponding bits of two
operands are opposite. It is denoted by ^.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise XOR Operation of 12 and 25
00001100 ^ 00011001
________
00010101 = 21 (In decimal)
Example #3: Bitwise XOR
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a^b);
return 0;
Output
Output = 21
Bitwise complement operator ~
Bitwise compliment operator is an unary operator (works on only one
operand). It changes 1 to 0 and 0 to 1. It is denoted by ~.
35 = 00100011 (In Binary)
Bitwise complement Operation of 35
~ 00100011
________
11011100 = 220 (In decimal)