R22 PPS Unit - 2 Notes
R22 PPS Unit - 2 Notes
R22 PPS Unit - 2 Notes
UNIT-2
Arrays: one and two dimensional arrays, creating, accessing and manipulating elements of arrays
Strings: Introduction to strings, handling strings as array of characters, basic string functions available in C (strlen, strcat,
strcpy, strstr etc.), arrays of strings
Structures: Defining structures, initializing structures, unions, Array of structures
Pointers: Idea of pointers, Defining pointers, Pointers to Arrays and Structures, Use of Pointers in self referential
structures, usage of self referential structures in linked list (no implementation) Enumeration data type
Arrays
An array in C is a collection of data items of similar data type. One or more values same data type, which may be
primary data types (int, float, char), or user-defined types such as struct or pointers can be stored in an array. In C,
the type of elements in the array should match with the data type of the array itself.
The size of the array, also called the length of the array, must be specified in the declaration itself. Once declared,
the size of a C array cannot be changed. When an array is declared, the compiler allocates a continuous block of
memory required to store the declared number of elements. Arrays are used to store and manipulate the similar
type of data.
Types of Arrays
1. One-Dimensional Array
2. Two-Dimensional Array
3. Multi-Dimensional Array
One-Dimensional Array
Suppose we want to store the marks of 10 students and find the average. We declare 10 different variables to store
10 different values as follows:
These variables will be scattered in the memory with no relation between them. Importantly, if we want to extend
the problem of finding the average of 100 (or more) students, then it becomes impractical to declare so many
individual variables. To go back to the problem of storing the marks of 10 students and find the average, the
solution with the use of array would be:
#include <stdio.h>
void main(){
int marks[10] = {50, 55, 67, 73, 45, 21, 39, 70, 49, 51};
int i, sum = 0;
float avg;
for (i = 0; i <= 9; i++){
sum += marks[i];
PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 1
}
avg = (float)sum / 10;
printf("Average: %f", avg);
}
Output
Average: 52.000000
Array elements are stored in contiguous memory locations. Each element is identified by an index starting with "0".
The lowest address corresponds to the first element and the highest address to the last element.
Declaration of an Array
To declare an array in C, you need to specify the type of the elements and the number of elements to be stored in
it.
The "size" must be an integer constant greater than zero and its "type" can be any valid C data type. There are
different ways in which an array is declared in C.
In the following example, we are declaring an array of 5 integers and printing the indexes and values of all array
elements:
#include <stdio.h>
void main(){
int arr[5];
int i;
for (i = 0; i <= 4; i++){
printf("a[%d]: %d\n", i, arr[i]);
}
}
Output
a[0]: -133071639
a[1]: 32767
a[2]: 100
a[3]: 0
a[4]: 4096
PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 2
Initialization of an Array:
At the time of declaring an array, you can initialize it by providing the set of comma-separated values enclosed
within the curly braces {}.
The compiler allocates a continuous block of memory. The size of the allocated memory depends on the data type
of the array.
PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 3
Example: Size of Integer Array
If an integer array of 5 elements is declared, the array size in number of bytes would be "sizeof(int) x 5"
#include <stdio.h>
int main(){
int arr[5] = {1, 2, 3, 4, 5};
printf("Size of array: %ld", sizeof(arr));
return 0;
}
Output
Size of array: 20
The sizeof operator returns the number of bytes occupied by the variable.
The size of each int is 4 bytes. The compiler allocates adjacent locations to each element.
#include <stdio.h>
int main(){
int a[] = {1, 2, 3, 4, 5};
int i;
PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 4
for (i=0; i<5; i++){
printf("a[%d]: %c address: %ld\n", i, a[i], &a[i]);
}
return 0;
}
Output
a[0]: H address: 6422038
a[1]: e address: 6422039
a[2]: l address: 6422040
a[3]: l address: 6422041
a[4]: o address: 6422042
Accessing Array Elements
Each element in an array is identified by a unique incrementing index, stating with "0". To access the element by its
index, this is done by placing the index of the element within square brackets after the name of the array.
double salary = balance[9];
The above statement will take the 10th element from the array and assign the value to the "salary".
Example to Access Array Elements in C
The following example shows how to use all the three above-mentioned concepts viz. declaration, assignment, and
accessing arrays.
#include <stdio.h>
int main(){
int n[5]; /* 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;
}
/* output each array element's value */
for(j = 0; j < 5; j++){
printf("n[%d] = %d\n", j, n[j]);
}
return 0;
}
Output
n[0] = 100
n[1] = 101
n[2] = 102
n[3] = 103
n[4] = 104
The index gives random access to the array elements. An array may consist of struct variables, pointers and even
other arrays as its elements.
PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 5
Two-Dimensional Array
Multidimensional arrays can be considered as an array of arrays or as a matrix consisting of rows and columns.
Syntax for Declaration of Two-Dimensional Array
data_type array_name[sizeof_1st_dimension][sizeof_2nd_dimension];
where,
data_type: is a type of data of each array block.
array_name: is the name of the array using which we can refer to it.
sizeof_dimension: is the number of blocks of memory array going to have in the corresponding dimension.
For Example
int nums[5][10];
int numbers[5][2] = {
{0, 2, 4, 6, 8},
{1, 3, 5, 7, 9}
};
Arrangement
PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 6
Output:
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
Three-dimensional array:
A 3-D Multidimensional array contains three dimensions, so it can be considered an array of two-dimensional
arrays.
data_type array_name[sizeof_1st_dimension][sizeof_2nd_dimension][sizeof_3rd_dimension];
where,
data_type: is a type of data of each array block.
array_name: is the name of the array using which we can refer to it.
sizeof_dimension: is the number of blocks of memory array going to have in the corresponding dimension.
For Example
int nums[5][10][2];
Three-dimensional arrays are also a specialized form of a multidimensional array, generally, they are used to
represent three-dimensional coordinates in programming. We could also say that three-dimensional arrays
are an array of two-dimensional arrays.
//Example
int array[5][10][15];
#include <stdio.h>
int main() {
int array[2][2][2];
int i, j, k;
printf("Enter Elements(8) of 3 Dimensional Array: \n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
for (k = 0; k < 2; k++) {
scanf("%d", & array[i][j][k]);
PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 7
}
}
}
printf("Print the Array\n");
Input:
Output:
12
34
56
78
Strings
String is a set of characters that are enclosed in double quotes. In the C programming language, strings are
created using one dimension array of character datatype. Every string in C programming language is enclosed
within double quotes and it is terminated with NULL (\0) character. Whenever c compiler encounters a string
value it automatically appends a NULL character (\0) at the end. The formal definition of string is as follows...
In C programming language, there are two methods to create strings and they are as follows...
1. Using one dimensional array of character datatype ( static memory allocation )
2. Using a pointer array of character datatype ( dynamic memory allocation )
Creating String
In C, strings are created as a one-dimensional array of character datatype. We can use both static and dynamic
memory allocation. When we create a string, the size of the array must be one more than the actual number
of characters to be stored. That extra memory block is used to store string termination character NULL (\0).
The following declaration stores a string of size 5 characters.
char str[6] ;
The following declaration creates a string variable of a specific size at the time of program execution.
char *str = (char *) malloc(15) ;
Assigning string value
String value is assigned using the following two methods...
1. At the time of declaration (initialization)
2. After declaraation
PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 8
Examples of assigning string value
void main()
{
char str1[6] = "Hello";
char str2[] = "Hello!";
char name1[] = {'j','n','t','u','h'};
char name2[6] = {'j','n','t','u','h'};
char title[20];
*title = "JNTUH HYD CAMPUS";
}
void main(){
char name[50];
printf("Please enter your name : ");
scanf("%s", name);
When we want to read multiple words or a line of text, we use a pre-defined method gets().
The gets() method terminates the reading of text with Enter character.
Examples of reading string value using gets() method
#include<stdio.h>
#include<conio.h>
void main(){
char name[50];
printf("Please enter your name : ");
gets(name);
printf("Hello! %s , welcome to btech smart class !!", name);
}
C Programming language provides a set of pre-definied functions called String Handling Functions to work
with string values. All the string handling functions are defined in a header file called string.h.
PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 9
String Handling Functions
C programming language provides a set of pre-defined functions called string handling functions to work with
string values. The string handling functions are defined in a header file called string.h. Whenever we want to
use any string handling function we must include the header file called string.h.
The following table provides most commonly used string handling function and their use...
Function Syntax (or) Example Description
strcmp() strcmp(string1, string2) Returns 0 if string1 and string2 are the same;
less than 0 if string1<string2; greater than 0 if string1>string2
strncmp() strncmp(string1, string2, 4) Compares first 4 characters of both string1 and string2
stricmp() stricmp(string1, string2) Compares two strings, string1 and string2 by ignoring case (similar
to strcmpi())
strchr() strchr(string1, 'b') Returns a pointer to the first occurrence of character 'b' in string1
strstr() strstr(string1, string2) Returns a pointer to the first occurrence of string2 in string1
Example:
#include <stdio.h>
#include <string.h>
void main() {
// Declaration and Initialization
char str1[] = "SCITSKNR cse";
char str2[20];
char search = 'o';
PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 10
printf("After copying, str2: %s\n", str2);
// strchr
char *found = strchr(str1, search);
// Check if the character is found
if (found != NULL) {
printf("'%c' found at position: %ld\n", search, found - str1 + 1);
} else {
printf("'%c' not found in the string.\n", search);
}
}
Output:
Length of str1: 12
After copying, str2: SCITSKNR cse
After concatenation, str2: SCITSKNR cse welcomes
str1 is less than str2
'o' not found in the string.
PPS Unit-2 Notes Prepared by Dr. P. KISHOR, HOD & Professor, CSE Dept, SCITS Page 11