Unit 3
Unit 3
Arrays indexing, memory model, programs with array of integers, two dimensional arrays, Introduction to
Strings.
ARRAYS
Def: - 1. An array is a special type of variable used to store multiple values of same data type at a
time.
2. An array is a collection of similar data items stored in continuous memory locations with single
name.
An array is defined as the collection of similar type of data items stored at contiguous memory
locations. Arrays are the derived data type in C programming language which can store the primitive type
of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data
types, such as pointers, structure, etc. The array is the simplest data structure where each data element can
be randomly accessed by using its index number.
C array is beneficial if you have to store similar elements. For example, if we want to store the marks of a
student in 6 subjects, then we don't need to define different variables for the marks in the different subject.
Instead of that, we can define an array which can store the marks in each subject at the contiguous memory
locations.
By using the array, we can access the elements easily. Only a few lines of code are required to access the
elements of the array.
When we work with a large number of data values, we need that any number of different variables.
As the number of variables increases, the complexity of the program also increases and so the programmers
get confused with the variable names. There may be situations where we need to work with a large number
of similar data values. To make this work easier, C programming language provides a concept called
"Array".
Properties of Array
➢ Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
➢ Elements of the array are stored at contiguous memory locations where the first element is stored at
the smallest memory location.
➢ Elements of the array can be randomly accessed since we can calculate the address of each element
of the array with the given base address and the size of the data element.
Advantage of Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
Array Terminologies:
1) Size : Number of elements to store in an array. It is always mentioned in square brackets [ ]
2) Type : Refers to data type. It decides which type of element is stored in the array. It is also
instructing the compiler to reserve memory according to the data type.
3) Base : The address of the first element is a base address. The array name itself stores address of
the first element.
4) Index : The array name is used to refer to the array element. For example int num[x], num is array
and x is index. The value of x begins from 0. The index value is always an integer value.
5) Range : Value of index of an array varies from lower bound to upper bound. For example, int
num[100]; the range of index is 0 to 99.
In the above memory allocation, all the three memory locations have a common name 'a'. So accessing
individual memory location is not possible directly. Hence compiler not only allocates the memory but also
assigns a numerical reference value to every individual memory location of an array. This reference number
is called "Index" or "subscript" or "indices".
ARRAY EXAMPLE
#include<stdio.h> OUTPUT
int main(){ 80
int i=0; 60
int marks[5]; //declaration of array 70
marks[0]=80; //initialization of array 85
marks[1]=60; 75
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}
1: Write a C program to Initialize and Print 1-D array 2: Write a C Program to Insert a new element at the
with 5 data elements. last position in an array.
Output:
Enter no of elements: 5
10 20 30 40 50
3: Write a C Program to Delete an element at the last 4: Write a C Program to delete / Remove the duplicate
position in an array. elements from an array.
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int arr[30], num, element, i; int arr[20], i, j, k, size;
char ch; printf("\nEnter array size: ");
printf("\nEnter no of elements: "); scanf("%d", &size);
scanf("%d", &num); printf("\nEnter array elements: ");
for (i = 0; i < num; i++) for (i = 0; i < size; i++)
{ scanf("%d", &arr[i]);
scanf("%d", &arr[i]); printf("\nArray with Unique list: ");
} for (i = 0; i < size; i++)
printf("\n Delete the last element (y/n): "); {
scanf("%c", &ch); for (j = i + 1; j < size;)
if(ch==’y’ || ch==’Y’) {
{ if (arr[j] == arr[i])
5: Write a C Program to Search an element in an array. 6: Write a C Program to Copy all elements of an array
into another array.
#include<stdio.h>
int main() #include<stdio.h>
{ int main()
int a[30], key, num, i, flag=0; {
printf("\n Enter array size: "); int arr1[30], arr2[30], i, num;
scanf("%d", &num); printf("\nEnter no of elements:");
printf("\n Enter array elements: "); scanf("%d", &num);
for (i = 0; i < num; i++) printf("\nEnter the values:");
scanf("%d", &a[i]); for (i = 0; i < num; i++) {
printf("\n Enter search key: "); scanf("%d", &arr1[i]); }
scanf("%d", &key); for (i = 0; i < num; i++) // Copying array 'a' to 'b’
for(i=0; i<num; i++) {
{ arr2[i] = arr1[i];
if (key == a[i]) }
{ printf("The copied array is: ");
flag=1; for (i = 0; i < num; i++)
break; printf("\n arr2[%d] = %d", i, arr2[i]);
} return (0);
} }
if (flag=1)
printf("Search key found at location = %d", i+1); Output:
else
printf("Search key not found"); Enter no of elements: 5
return (0); Enter the values: 11 22 33 44 55
} The copied array is:
arr2[0] = 11
Output: arr2[1] = 22
arr2[2] = 33
Enter array size: 10 arr2[3] = 44
Enter array elements: 10 20 30 40 50 60 70 80 90 99 arr2[4] = 55
7: Write a C Program to Merge two arrays into new. 8: Write a C Program to find Sum of all array
elements.
#include<stdio.h>
int main() #include<stdio.h>
{ int main()
int arr1[30], arr2[30], mrg[60]; {
int i, j, n1, n2, n3; int i, arr[50], sum, num;
printf("\nEnter no of elements in 1st array:"); printf("\nEnter no of elements: ");
scanf("%d", &n1); scanf("%d", &num);
for (i = 0; i < n1; i++) { printf("\nEnter the values: ");
scanf("%d", &arr1[i]); } for (i = 0; i < num; i++)
printf("\nEnter no of elements in 2nd array:"); scanf("%d", &arr[i]);
scanf("%d", &n2); for (i = 0; i < num; i++)
for (i = 0; i < n2; i++) sum = sum + arr[i];
{ for (i = 0; i < num; i++)
scanf("%d", &arr2[i]); printf("\na[%d]=%d", i, arr[i]);
} printf("\nSum=%d", sum);
for (i=0; i<n1; i++) // Merging starts return (0);
{ }
mrg[i] = arr1[i]; // copy arr1[ ] into mrg[ ]
j=i; Output:
}
for (i=0; i<n2; i++) Enter no of elements: 3
{ Enter the values: 11 22 33
j++; a[0]=11
mrg[j] = arr2[i]; // copy arr2[ ] into mrg[ ] a[1]=22
} a[2]=33
n3=n1+n2; Sum=66
printf("Merged array is: ");
for (i = 0; i < n3; i++) 8.1: Write a C Program to find Sum of all array
{ elements & average of them.
printf("%d", mrg[i]);
} #include<stdio.h>
return(0); int main()
} {
int i, n=10, sum; float avg=0.0;
Output: int arr[n] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 10 };
for (i = 0; i < n; i++)
Enter no of elements in 1st array: 5 sum = sum + arr[i];
11 22 33 44 55 avg = (float) sum / 10;
Enter no of elements in 2nd array: 5 printf("\nSum = %d", sum);
66 77 88 99 100 printf("\nAverage = %f", avg);
return(0);
Merged array is: 10 11 22 33 44 55 66 77 88 99 100 }
Output: Sum = 55
Avg = 5.5
11: Write a C program to reverse an array element in 11.1: Write a C program to reverse an array element
an array. in an array.
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int arr[30], i, j, num, temp; int arr[30], i, j, num, temp;
printf("\nEnter no of elements: "); printf("\nEnter no of elements: ");
scanf("%d", &num); scanf("%d", &num);
for (i = 0; i < num; i++) for (i = 0; i < num; i++)
{ scanf("%d", &arr[i]); } {
j = i - 1; // j will Point to last Element scanf("%d", &arr[i]);
i = 0; // i will be pointing to first element }
while (i < j) printf("\nResult after reversal : ");
{ for (i=num-1; i <= 0; i--)
temp = arr[i]; {
arr[i] = arr[j]; printf("%d \t", arr[i]);
arr[j] = temp; }
i++; // increment i return (0);
j--; // decrement j }
}
printf("\nResult after reversal : "); Output:
for (i = 0; i < num; i++) Enter no of elements: 5
{ printf("%d \t", arr[i]); } 11 22 33 44 55
return (0); Result after reversal: 55 44 33 22 11
MULTI-DIMENSIONAL ARRAY
An array of arrays is called as multi-dimensional array. In simple words, an array created with more
than one dimension (size) is called as multi-dimensional array. Multi-dimensional array can be of two-
dimensional array or three-dimensional array or four-dimensional array or more...
Most popular and commonly used multi-dimensional array is two-dimensional array. The 2-D
arrays are used to store data in the form of table. We also use 2-D arrays to create mathematical matrices.
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns. However, 2D arrays are created
to implement a relational database lookalike data structure. It provides ease of holding the bulk of data at
once which can be passed to any number of functions wherever required.
Declaration of two-dimensional Array
data_type array_name [rows] [columns];
int twodimen [4] [3];
Here, 4 is the number of rows, and 3 is the number of columns.
Initialization of 2D Array
In the 1D array, we don't need to specify the size of the array if the declaration and initialization are
being done simultaneously. However, this will not work with 2D arrays. We will have to define at least the
second dimension of the array.
datatype arrayName [rows][colmns] = {{r1c1value, r1c2value, ...},{r2c1, r2c2,...}...} ;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
(or)
int matrix_A [2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Example:
1. int a[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // initialize all array elements as list / comma separated values
2. int a[3][3] = { 1, , , , 1, , , , 1 }; // initialize some array elements as list / comma separated values
6. char grid[3][4] = { { 'a', 'b', 'c', 'd' },// 3 rows & 4 columns as single char comma separated value in row-wise
{ 'e', 'f', 'g', 'h' },
{ 'i', 'j', 'k', 'l' }
};
Ex: 2-D Array elements initialize by its subscripts / Ex: 2-D Array elements initialize by list / comma
index positions separated values
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int mat_a[3][3]; int mat_a[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
mat_a[0][0]=1; /* int mat_a[ ][ ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; */
mat_a[0][1]=2; printf(" %d ", mat_a[0][0] );
mat_a[0][2]=3; printf(" %d ", mat_a[0][1] );
mat_a[1][0]=4; printf(" %d ", mat_a[0][2] );
mat_a[1][1]=5; printf("\n");
mat_a[1][2]=6; printf(" %d ", mat_a[1][0] );
mat_a[2][0]=7; printf(" %d ", mat_a[1][1] );
mat_a[2][1]=8; printf(" %d ", mat_a[1][2] );
mat_a[2][2]=9; printf("\n");
return 0;
}
O/p: 1 2 3
4 5 6
7 8 9
= a[0][0]=1;
a[0][1]=2;
a[0][2]=3;
a[1][0]=4; = r0 1 2 3
a[1][1]=5; r1 4 5 6
a[1][2]=6; r2 7 8 9
a[2][0]=7;
a[2][1]=8;
a[2][2]=9;
= a[0][0]=1;
a[1][0]=4;
a[2][0]=7; c0 c1 c2
a[0][1]=2; = 1 2 3
a[1][1]=5; 4 5 6
a[2][1]=8; 7 8 9
a[0][2]=3;
a[1][2]=6;
a[2][2]=9;
Note 1: ‘C’ compiler represents 2-D array elements in memory default by Row representation or Row major
order. For example, int a[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; // row1, row2, row 3
Note 2: We can tell the ‘C’ compiler to represent 2-D array elements in memory by Column representation or
Column major order using the method of initializing individual subscripts only.
For example, int a[3][3];
a[0][0]=1; // column_0 & all row elements
a[1][0]=4;
a[2][0]=7;
a[0][1]=2; // column_1 & all row elements
a[1][1]=5;
a[2][1]=8;
a[0][2]=3; // column_2 & all row elements
a[1][2]=6;
a[2][2]=9;
2: Write a C program to Scan and Print 2-D array. 3: Write a C program to find Transpose of matrix
array.
#include <stdio.h>
int main() #include <stdio.h>
{ int main()
int a[3][3]; {
int i, j; int i, j, matrix[3][3], transpose[3][3];
for (i=0; i<3; i++) // scan i/p printf("Enter elements of the matrix: \n");
{ for (i= 0; i < 3; i++)
for (j=0; j<3; j++) {
{ for (j = 0; j < 3; j++)
printf(“Enter Element at a[%d][%d] : ”, i, j); {
4: Write a C program to perform addition of two matrix 5: Write a C program for Multiplication of two
matrix
#include <stdio.h>
int main() #include <stdio.h>
{ int main()
int i, j, a[3][3], b[3][3], c[3][3]; {
printf("Enter elements of the matrix a: \n"); int i, j, a[3][3], b[3][3], c[3][3];
for (i= 0; i < 3; i++) printf("Enter elements of the matrix a: \n");
{ for (i= 0; i < 3; i++)
for (j = 0; j < 3; j++) {
{ for (j = 0; j < 3; j++)
scanf("%d", &a[i][j]); {
} scanf("%d", &a[i][j]);
} }
printf("Enter elements of the matrix b: \n"); }
for (i= 0; i < 3; i++) printf("Enter elements of the matrix b: \n");
{ for (i= 0; i < 3; i++)
for (j = 0; j < 3; j++) {
{ for (j = 0; j < 3; j++)
scanf("%d", &b[i][j]); {
} scanf("%d", &b[i][j]);
} }
}
for (i = 0; i < 3; i++)
{ for (i = 0; i < 3; i++)
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.
Def:1 String is a set of characters enclosed in double quotation marks. In C programming, the string is a character
array of single dimension.
In C programming language, there are two methods to create strings and they are as follows...
➢ Using one dimensional array of character datatype ( static memory allocation )
➢ Using a pointer array of character datatype ( dynamic memory allocation )
Declaration of String:
Declaring a string in C is as simple as declaring a one-dimensional array.
syntax: char string_name[size];
string_name - is any name given to the string variable
size - is used to define the length of the string + ‘\0’.
Example: char str[35] = "Welcome to learn ‘C’ programming.";
Initialization of String:
String in C can be initialized in 4 different ways
1. Assigning a String Literal without Size:
It is possible to directly assign a string literal to a character array without any size. The size gets determined
automatically by the compiler at compile time. Here, the name of the string “str” acts as a pointer because it is an
array.
Example: char str[ ] = "Welcome to learn ‘C’ programming.";
2. Assigning a String Literal with Size:
String literals can be assigned with a predefined size. But we should always account for one extra space
which will be assigned to the null character. If we want to store a string of size n then we should always declare a
string with a size equal to or greater than n+1.
Example: char str[35] = "Welcome to learn ‘C’ programming.";
3. Assigning Character by Character without size:
Like assigning directly without size, we also assign character by character with the Null Character at the end.
The compiler will determine the size of the string automatically.
Example: char str[ ] = { ‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’, ‘\0’ };
4. Assigning Character by Character with size:
String can be assigned with a predefined size character by character with the Null Character at the end. Total
size / length of the string + one character for ‘\0’.
Example: char str[8] = { ‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’, ‘\0’ };
int main()
{
char str1[6] = "Hello";
char str2[] = "Hello!";
char name1[] = {'s','m','a','r','t'};
char name2[6] = {'s','m','a','r','t'};
char title[20];
title = "C Programming";
return 0;
}
Reading string value from user
We can read a string value from the user during the program execution. We use the following two methods...
1. Using scanf() method - reads single word
2. Using gets() method - reads a line of text
Using scanf() method we can read only one word of string. We use %s to represent string in scanf() and printf()
methods.
Examples of reading string value using scanf() method
#include<stdio.h>
#include<conio.h>
int main()
{
char name[50];
printf("Please enter your name : ");
scanf("%s", name);
printf("Hello! %s , welcome to btech smart class !!", name);
return 0;
}
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.
1. String program to Declare, Initialize and print. 2. String program to Declare, Initialize and print.
Output: Output:
5. String program to read str with gets() and puts(). 6. String program to read str with fgets() and fputs().
Output: Output:
2. strcpy(str1, str2) Used to copy one string to another. It copies the contents of str2 to str1.
Used for combining two strings together to form a single string. It Appends
3. strcat(str1, str2)
or concatenates str2 to the end of str1 and returns a pointer to str1.
Used to compare two strings with each other. It returns 0 if str1 is equal
4. strcmp(str1, str2)
to str2, less than 0 if str1 < str2, and greater than 0 if str1 > str2.
6. strlwr(str) Used to convert the given string into lower case one.
7. strupr(str) Used to convert the given string into upper case one.
Used to find the first occurrence of a specified character (ch) in the given
8. strchr(str1, ch)
string (str1).
Used to find the first occurrence of a specified string (str2) in the given
9. strstr(str1, str2)
string (str1).
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
int main() int main()
{ {
char str[25]; char str[25];
int strlength; int strlength;
printf(“Enter a String: “); printf(“Enter a String: “);
scanf(“%s”, str); gets(str);
strlength = strlen(str); strlength = strlen(str);
printf(“Given String Length is: %d”, strlength); printf(“Given String Length is: %d”, strlength);
return(0); return(0);
} }
Output: Output:
Enter a String: Welcome Enter a String: Welcome
Given String Length Is: 7 Given String Length Is: 7
2. Write a C program to Copy one string into another. 2.1. Write a C program to Copy one str. into another.
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
int main() int main()
{ {
char str1[25], str2[25]; char str1[25], str2[25];
printf(“Enter a First String: “); printf(“Enter a First String: “);
scanf(“%s”, str1); gets(str1);
printf(“Enter a Second String: “); printf(“Enter a Second String: “);
scanf(“%s”, str2); gets(str2);
printf(“First String is: %s”, str1); printf(“First String is: %s”, str1);
printf(“Second String is: %s”, str2); printf(“Second String is: %s”, str2);
strcpy(str1, str2); strcpy(str1, str2);
printf(“After strcpy(), First String is: %s”, str1); printf(“After strcpy(), First String is: %s”, str1);
return(0); return(0);
} }
Output: Output:
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
int main() int main()
{ {
char str1[25], str2[25]; char str1[25], str2[25];
printf(“Enter a First String: “); printf(“Enter a First String: “);
gets(str1); gets(str1);
printf(“Enter a Second String: “); printf(“Enter a Second String: “);
gets(str2); gets(str2);
printf(“First String is: %s”, str1); strcat(str1, str2);
printf(“Second String is: %s”, str2); printf(“After strcat(), First String is:”);
strcat(str1, str2); puts(str1);
printf(“After strcat(), First String is: %s”, str1); return(0);
return(0); }
}
Output:
Output:
Enter a First String: welcome
Enter a First String: Welcome Enter a Second String: to learn c.
Enter a Second String: to learn C.
First String is: welcome
First String is: Welcome Second String is: to learn c.
Second String is: to learn C. After strcat(), First String is: welcome to learn c.
After strcat(), First String is: Welcome to learn C.
4. Write C program to perform String Comparison. 5. Write a C program to Reverse the given String.
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
int main() int main()
{ {
char str1[25], str2[25]; char str1[25];
int result; printf(“Enter a String: “);
printf(“Enter a First String: “); gets(str1);
gets(str1); puts(strrev(str1);
printf(“Enter a Second String: “); return(0);
gets(str2); }
result = strcmp(str1, str2);
if(result==0) Output:
printf(“Both the strings are Equal.”);
else Enter a String: Welcome
printf(“Both the strings are Not Equal.”); emocleW
return(0);
}
5.1. Write a C program to find Palindrome or not. 6 & 7. C program to convert into lower & upper case.
#include<stdio.h>
#include<stdio.h> #include<string.h>
#include<string.h> int main()
int main() {
{ char str1[25];
char actual[25], reverse[25]; printf(“Enter a String: “);
int result; gets(str1);
printf("Enter a String: "); puts(“Actual String: ”);
gets(actual); puts(str1);
strcpy(reverse, actual);
strrev(reverse); puts(“After strlwr(): ”);
result=strcmp(actual, reverse); puts(strlwr(str1));
if(result == 0)
printf("Given string is a Palindrome."); puts(“After strupr(): ”);
else puts(strupr(str1));
printf("Given strings is Not a Palindrome"); return(0);
}
return(0);
} Output:
Output:
Enter a String: WelCome To Learn c
Enter a String: Malayalam After strlwr(): welcome to learn c
After strupr(): WELCOME TO LEARN C
Given string is a Palindrome.
Output: Output:
An efficient String handling concept in ‘C’ language is achieved by implementing two methods. They are,
1. Using character array. example: char str[25] = “Welcome to learn C.”;
2. Using pointer variable. example: char *ptr; ptr = str;
Definition:
In C, Pointers play a crucial role in handling strings efficiently. String is an array of characters terminated by
a null character ('\0'). Pointers can be used to manipulate strings more efficiently. Pointer that points to the beginning
of the string.
Pointer is used to store the String in a Variable. That variable is called as ‘pointer variable’. While using pointer,
no need to go for character data type array.
Pointer is a variable that stores the memory address of another variable. Pointers are widely used in languages
like C to facilitate dynamic memory allocation, array manipulation, and function parameter passing. a pointer is
declared using the * (asterisk) symbol. Dereferencing a pointer means accessing the value stored at the memory address
it points to. The * (asterisk) symbol is used for dereferencing.
1. ‘C’ String program using Pointer variable. 1.1. ‘C’ String program using Pointer variable.
#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
char myString[] = "Hello, World!"; char myString[ ];
[ C does not have Boolean data types, and normally uses integers for Boolean testing. Zero is used to
represent false, and One is used to represent true. For interpretation, zero is interpreted as false and
anything non-zero is interpreted as true.]