C Notes II-UNIT
C Notes II-UNIT
ARRAYS:
What is an array?
An array is a collection of similar datatype that are used to allocate memory in
a sequential manner.
Syntax : <data type> <array name>[<size of an array>]
Subscript or indexing: A subscript is property of an array that distinguishes
all its stored elements because all the elements in an array having the same
name (i.e. the array name). so to distinguish these, we use subscripting or
indexing option.
e.g. int ar[20];
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter n: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;
return 0;
}
Two Dimentional Arrays
In C programming, you can create array of an array known as
multidimensional array. For example,
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You
can think the array as table with 3 row and each row has 4 column.
Initialization of a two dimensional array
int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[2][3] = {1, 3, 0, -1, 5, 9};
Sum Of Matrix:
2.2 0.5
-0.9 25.0
STRINGS :
What is String?
· A string is a collection of characters.
· A string is also called as an array of characters.
· A String must access by %s access specifier in C.
· A string is always terminated with \0 (Null) character.
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";
C supports a wide range of functions that manipulate null-terminated strings −
Sr.No. Function & Purpose
strcpy(s1, s2);
1
Copies string s2 into string s1.
strcat(s1, s2);
2
Concatenates string s2 onto the end of string s1.
strlen(s1);
3
Returns the length of string s1.
strcmp(s1, s2);
4 Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0
if s1>s2.
strstr(s1, s2);
5
Returns a pointer to the first occurrence of string s2 in string s1.
1. strlen().
This string function is basically used for the purpose of computing the ength of
string.
Example: char str=”Gaurav Arora”;
int length= strlen(str);
printf(“The length of the string is =”,str);
2. strcmp ().
This string function is basically used for the purpose of comparing two string.
This string function compares two strings character by characters.
Thus it gives result in three cases:
Case 1: if first string > than second string then, result will be true.
Example:
char str1= “Gaurav”;
char str2= “Arora”;
char str3=strcmp(str1,str2);
printf(“%s”,str3);
3. strcat().
This string function is used for the purpose of concatenating two strings ie.
(merging two or more strings)
Example:
char str1 = “Gaurav”;
char str2 = “Arora”;
char str3[30];
str3=strcat(str1,str2);
printf(“%s”,str3);
4. strcpy()
This string function is basically used for the purpose of copying one string into
another string.
char str1= “Gaurav”;
char str2[20];
str2 = strcpy(str2,str1);
printf(“%s”,str2);
The following example uses some of the above-mentioned functions −
Live Demo
#include <stdio.h>
#include <string.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result
−
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
Array of Strings
A string is a 1-D array of characters, so an array of strings is a 2-D array of
characters.
Just like we can create a 2-D array of int, float etc; we can also create a 2-D
array of character or array of strings. Here is how we can declare a 2-D array of
characters.
char ch_arr[3][10] = {
{'s', 'p', 'i', 'k', 'e', '\0'},
{'t', 'o', 'm','\0'},
{'j', 'e', 'r', 'r', 'y','\0'}
};
It is important to end each 1-D array by the null character otherwise, it's just
an array of characters. We can't use them as strings.
Declaring an array of string this way is a tedious and error-prone process
that's why C provides a more compact way to it. This above initialization is
equivalent to:
char ch_arr[3][10] = {
"spike",
"tom",
"jerry"
};
The first subscript of the array i.e 3 denotes the number of strings in the array
and the second subscript denotes the maximum length of the string. Recall the
that in C, each character occupies 1 byte of data, so when the compiler sees
the above statement it allocates 30 bytes (3*10) of memory.
Structures:
Structure is a collection of variables of different data types under a single
name.
For example: We want to store information about a person: his/her name,
citizenship number and salary. You can create different variables name, citNo
and salary to store these information separately.
Defining a Structure
Keyword struct is used for creating a structure.
Syntax of structure
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};
Here is an example:
struct Person
{
char name[50];
int citNo;
float salary;
}var1;
int main()
{
struct Person person1, person2, p[20];
return 0;
}
Another way of creating a structure variable is:
struct Person
{
char name[50];
int citNo;
float salary;
} person1, person2, p[20];
How to Access members of a structure?
There are two types of operators used for accessing members of a structure.
1. Member operator(.)
2. Structure pointer operator(->) (will be discussed in structure and
pointers)
Example Porgram
#include <stdio.h>
struct student
{
char name[10];
int roll;
float marks;
};
int main()
{
Struct student s1,s2,s3;
printf("Enter information:\n");
printf("Enter name: ");
scanf("%s", s.name); //jpnce
printf("Enter roll number: ");
scanf("%d", &s.roll);
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;
}
Difference Between Structure and Union
POINTERS:
Pointers in C language is a variable that stores/points the address of another
variable.
A Pointer in C is used to allocate memory dynamically i.e. at run time.
The pointer variable might be belonging to any of the data type such as int,
float, char, double, short etc.
Pointer Syntax : data_type *var_name; Example : int *p; char *p;
Where, * is used to denote that “p” is pointer variable and not a normal
variable.
Key points to remember about pointers in C:
Normal variable stores the value whereas pointer variable stores the
address of the variable.
The content of the C pointer always be a whole number i.e. address.
Always C pointer is initialized to null, i.e. int *p = null.
The value of null pointer is 0.
& symbol is used to get the address of the variable.
* symbol is used to get the value of the variable that the pointer is
pointing to.
If a pointer in C is assigned to NULL, it means it is pointing to nothing.
Two pointers can be subtracted to know how many elements are
available between these two pointers.
But, Pointer addition, multiplication, division are not allowed.
The size of any pointer is 2 byte (for 16 bit compiler).
Declaration of Pointer variable
General syntax of pointer declaration is,
datatype *pointer_name;
Data type of a pointer must be same as the data type of the variable to which
the pointer variable is pointing. void type pointer works with all data types, but
is not often used.
Here are a few examples:
int *ip // pointer to integer variable
float *fp; // pointer to float variable
double *dp; // pointer to double variable
char *cp; // pointer to char variable
Initialization of Pointer variable
Pointer Initialization is the process of assigning address of a variable to a
pointer variable. Pointer variable can only contain address of a variable of the
same data type. In C language address operator & is used to determine the
address of a variable. The & (immediately preceding a variable name) returns
the address of the variable associated with it.
#include<stdio.h>
void main()
{
int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
}
Pointer variable always point to variables of same data type. Let's have an
example to showcase this:
#include<stdio.h>
void main()
{
float a;
int *ptr;
ptr = &a; // ERROR, type mismatch
}
If you are not sure about which variable's address to assign to a pointer
variable while declaration, it is recommended to assign a NULL value to your
pointer variable. A pointer which is assigned a NULL value is called a NULL
pointer.
Example Program
#include <stdio.h>
int main()
{
int a, *p; // declaring the variable and pointer
a = 10;
p = &a; // initializing the pointer
printf("%d", *p); //this will print the value of 'a' 10
printf("%d", *&a); //this will also print the value of 'a' 10
printf("%d", &a); //this will print the address of 'a' 1000
printf("%d", p); //this will also print the address of 'a' 1000
printf("%d", &p); //this will print the address of 'p' 2000
return 0;
}
Pointer to Arrays
When an array is declared, compiler allocates sufficient amount of memory to
contain all the elements of the array. Base address i.e address of the first
element of the array is also allocated by the compiler.
Suppose we declare an array arr,
int arr[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two
bytes, the five elements will be stored as follows:
Here variable arr will give the base address, which is a constant pointer
pointing to the first element of the array, arr[0]. Hence arr contains the address
of arr[0] i.e 1000. In short, arr has two purpose - it is the name of the array
and it acts as a pointer pointing towards the first element in the array.
arr is equal to &arr[0] by default
We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.
Now we can access every element of the array arr using p++ to move from one
element to another.
NOTE: You cannot decrement a pointer once incremented. p-- won't work.
Example Program
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
return 0;
}
In the above program, the pointer *p will print all the values stored in the array
one by one. We can also use the Base address (a in above case) to act as a
pointer and print all the values.
Pointer to Structure
Like we have array of integers, array of pointers etc, we can also have array of
structure variables. And to use the array of structure variables efficiently, we
use pointers of structure type. We can also have pointer to a single structure
variable, but it is mostly used when we are dealing with array of structure
variables.
#include <stdio.h>
struct Book
{
char name[10];
int price;
}
int main()
{
struct Book a; //Single structure variable
struct Book* ptr; //Pointer of Structure type
ptr = &a;
struct Book b[10]; //Array of structure variables
struct Book* p; //Pointer of Structure type
p = &b;
return 0;
}
Accessing Structure Members with Pointer
To access members of structure using the structure variable, we used the dot .
operator. But when we have a pointer of structure type, we use arrow -> to
access structure members.
#include <stdio.h>
struct my_structure {
char name[20];
int number;
int rank;
};
int main()
{
struct my_structure variable = {"StudyTonight", 35, 1};
struct my_structure *ptr;
ptr = &variable;
printf("NAME: %s\n", ptr->name);
printf("NUMBER: %d\n", ptr->number);
printf("RANK: %d", ptr->rank);
return 0;
}
Self Referential Structures in Linked Lists
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 Linked list : 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;
}
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
Enumerated Data Type
An enumeration is a user-defined data type that consists of integral constants.
To define an enumeration, keyword enum is used.
enum flag { const1, const2, ..., constN };
Here, name of the enumeration is flag.
And, const1, const2,...., constN are values of type flag.
int main()
{
enum week today;
today = wednesday;
printf("Day %d",today+1);
return 0;
}
Output
Day 4