Chapter 4
Chapter 4
Chapter 4
P REPARED BY:
P ROF. A XIT K ACHHIA
CP D EPARTMENT
Concepts of Array:
➢So far we have used only the fundamental data types, namely char, int,
float, double and variations of int and double.
➢Although these types are very useful, they are constrained by the fact that a
variable of these types can store only one value at any given time.
2
Concepts of Array:
➢An array is a fixed-size sequenced collection of elements of the same data
type. It is simply a grouping of like-type data. In its simplest form, an array
can be used to represent a list of numbers, or a list of names.
➢Some examples where the concept of an array can be used:
➢∑ List of temperatures recorded every hour in a day, or a month, or a year.
➢∑ List of employees in an organization.
➢∑ List of products and their cost sold by a store.
➢∑ Test scores of a class of students.
➢∑ List of customers and their telephone numbers.
➢∑ Table of daily rainfall data.
3
Concepts of Array:
➢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.
➢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.
4
Concepts of Array:
➢Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
➢To create an array, define the data type (like int), and specify the name of
the array followed by square brackets [].
➢To insert values to it, use a comma-separated list, inside curly braces:
int myNumbers[] = {25, 50, 75, 100};
➢Example:
➢int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);
5
Continue
ARRAY:
➢int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d", myNumbers[0]);
6
Advantage of Array:
7
Declaration of Array:
➢We can declare an array in the c language in the following way.
data_type array_name[array_size];
➢Here, int is the data_type, marks are the array_name, and 5 is the
array_size.
8
Initialization of Array:
➢The simplest way to initialize an array is by using the index of each element.
We can initialize each element of the array by using the index. Consider the
following example.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
9
Types of Array:
Arrays in C are classified into three types:
•One-dimensional arrays
•Two-dimensional arrays
•Multi-dimensional arrays
10
One-Dimensional Array:
➢We can visualize a one-dimensional array in C as a single row to store the
elements. All the elements are stored at contiguous memory locations.
➢A list of items can be given one variable name using only one subscript and
such a variable is called single-subscripted variable or a one-dimensional
array.
➢Syntax is as follows-
datatype array name [size]
11
Declaration of One-Dimensional Array
➢While declaring a one-dimensional array in C, the data type can be of any
type, and also, we can give any name to the array, just like naming a random
variable.
➢Array must be declared before they used so that the compiler can allocate
space for them in memory.
➢Syntax:
int arr[5]; //arr is the array name of type integer, and 5 is the size of the array
12
Declaration of One-Dimensional Array
➢The C language treats character strings simply as array of characters. The
size in a character string represents the maximum number of characters that
the string can hold.
➢For instance, char name[10];
➢Declares the name as a character array(string) variable that can hold a
maximum of 10 characters.
➢Example, “WELL DONE”
13
Rules for declaring One-Dimensional Array
•Before using and accessing, we must declare the array variable.
•In an array, indexing starts from 0 and ends at size-1. For example, if we have
arr[10] of size 10, then the indexing of elements ranges from 0 to 9.
•We must include data type and variable name while declaring one-
dimensional arrays in C.
•Each element of the array is stored at a contiguous memory location with a
unique index number for accessing.
14
Initialization of One-Dimensional Array
➢After declaration, we can initialize array elements or simply initialize them
explicitly at the time of declaration. One-Dimensional arrays in C are
initialized either at Compile Time or Run Time.
➢Compile-Time Initialization
➢Compile-Time initialization is also known as static-initialization. In this,
array elements are initialized when we declare the array implicitly.
<data_type> <array_name> [array_size]={list of elements};
➢For Example,
int nums[5] = {0, 1, 2, 3, 4};
15
Initialization of One-Dimensional Array
➢C Program to illustrate Compile-Time Initialization:
#include <stdio.h>
int main(){
int nums[3]={0,1,2};
printf(" Compile-Time Initialization Example:\n");
printf(" %d ",nums[0]);
printf("%d ",nums[1]);
printf("%d ",nums[2]);
}
16
Initialization of One-Dimensional Array
➢In this C program code, we have initialized an array nums of size 3 and
elements as 0,1 and 2 in the list.
➢This is compile-time initialization, and then at the end, we have printed all
its values by accessing index-wise.
17
Initialization of One-Dimensional Array
➢Run-Time Initialization
➢Runtime initialization is also known as dynamic-initialization. Array elements
are initialized at the runtime after successfully compiling the program.
➢Example:
scanf("%d", &nums[0]); //initializing 0th index element at runtime
dynamically
18
Two-Dimensional Array:
➢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.
➢An array of arrays is known as 2D array. The two dimensional (2D) array in C
programming is also known as matrix. A matrix can be represented as a table
of rows and columns.
19
Declaration of Two-Dimensional Array:
➢The syntax to declare the 2D array is given below:
data_type array_name[rows][columns];
➢int disp[2][3];
20
Simple Two-Dimensional Array Example:
➢This program demonstrates how to store the elements entered by user in a
2d array and how to display the elements of a two dimensional array.
O/P:
Enter value for disp[0][0]:1
22
Initialization of Two-Dimensional Array:
Things that you must consider while initializing a 2D array
➢We already know, when we initialize a normal array (or you can say one
dimensional array) during declaration, we need not to specify the size of it.
➢However that’s not the case with 2D array, you must always specify the
second dimension even if you are specifying elements during the declaration.
➢Let’s understand this with the help of few examples –
23
Initialization of Two-Dimensional Array:
24
Initialization of Two-Dimensional Array:
➢The two-dimensional array can be declared and defined in the following
way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
25
Character Array:
➢A Character array is a derived data type in C that is used to store a collection
of characters or strings.
➢Each character in a character array has an index that shows the position of
the character in the string.
➢The first character will be indexed 0 and the successive characters are
indexed 1,2,3 etc...
➢The null character \0 is used to find the end of characters in the array and is
always stored in the index after the last character or in the last index.
➢Consider a string "character", it is indexed as the following image in a
character array
26
Character Array:
27
Character Array:
➢Syntax:
➢There are many syntaxes for creating a character array in c. The most
basic syntax is,
char name[size];
➢The name depicts the name of the character array and size is the length of
the character array.
➢The size can be greater than the length of the string but can not be lesser. If
it is lesser then the full string can't be stored and if it is greater the remaining
spaces are just left unused.
28
Initialization of Character Array:
➢There are different ways to initialize a character array in c. Let us understand
them with examples.
➢Using {} Curly Braces
➢We can use {} brackets to initialize a character array by specifying the
characters in the array.
➢The advantage of using this method is we don't have to specify the length of
the array as the compiler can find it for us.
➢Let us see a example where we initialize an array using {} and print it.
29
Initialization of Character Array:
#include <stdio.h> #include<string.h>
int main(){
//initialization
char char_array[] = {'c', 'h', 'a', 'r', '$','*'};
int a=puts(char_array); //print array
if(a>0){
printf("printed successfully\n"); }
printf("length of character array = %d",strlen(char_array));
//prints length of the character array.
return 0;
} 30
Initialization of Character Array:
Output:
char$*
printed successfully
length of character array = 6
31
Initialization of Character Array:
Using String Assignment
•A easy way to initialize a character array is using string assignment.
•We don't need to specify the length of the array in this method too.
Consider the following example,
32
Initialization of Character Array:
#include <string.h>
#include <stdio.h>
int main(){
char char_array[] = "string of characters";
puts(char_array);
printf("length of character array = %d",strlen(char_array));
return 0;
} Output:
string of characters
length of character array = 20
33
Initialization of Character Array:
Using {{ }} Double Curly Braces(2D Char Array)
•This method is used to store two or more strings together in a single array.
•As a character array can only store characters, to store different strings we
use a 2-dimensional array with syntax arr[i][j].
•The i denotes the string and j denote the position of the character in the
string at position i.
•The i can be left empty as it is automatically computed by the compiler but
the value of j must be provided.
34
Initialization of Character Array:
#include <stdlib.h>
#include <stdio.h>
int main(){
Output:
char arr[][5] = { {"code"}, {"break"}};
code
for (int i = 0; i < 2; ++i) {
break
for (int j = 0; j < 5; j++) {
printf("%c ", arr[i][j]); }
printf("\n"); }
printf("\n");
return 0;
} 35
What is the use of Character Array in C
•A string is stored and represented using a character array.
We can individually access every character in an array using the character
array.
Writing and reading from files also use character arrays.
36
Importance of Char Array
➢Character array is used to store and manipulate characters.
➢File systems and text editors use character arrays to manipulate strings.
➢NoSQL(Not only SQL) databases that store data in JSON also use character
arrays.
➢Character array is used in language processing software and speech-to-text
software.
37
String:
➢String in C programming is a sequence of characters terminated with a null
character ‘\0’. Strings are defined as an array of characters.
➢Strings are used for storing text/characters.
➢The difference between a character array and a string is the string is
terminated with a unique character ‘\0’.
38
Declaration of String:
➢Declaring a string is as simple as declaring a one-dimensional array. Below is
the basic syntax for declaring a string.
char str_name[size];
➢In the above syntax str_name is any name given to the string variable and
size is used to define the length of the string, i.e the number of characters
strings will store.
39
Declaration of String:
➢There are two ways to declare strings in C:
➢1. The following example will create a string as "Scaler" where the last
character must always be a null character. The size mentioned within the
brackets is the maximum number of characters a string could hold, and it is
mandatory to give the size of a string if we are not initializing it at the time of
declaration.
40
Declaration of String:
➢There are two ways to declare strings in C:
2.In this method, we do not need to put the null character at the end of the
string constant. The compiler automatically inserts the null character at the
end of the string.
41
Initializing a String:
➢A string can be initialized in different ways.
➢Below are the examples to declare a string with the name str and initialize it
with “Students”.
➢4 Ways to Initialize a String in C
1. Assigning a string literal without size
2. Assigning a string literal with a predefined size
3. Assigning character by character with size
4. Assigning character by character without size
42
Initializing a String:
1. Assigning a string literal without size
➢String literals can be assigned without size. Here, the name of the string str
acts as a pointer because it is an array.
➢char str[] = “Students";
43
Initializing a String:
2. Assigning a string literal with a predefined 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.
44
Initializing a String:
3. Assigning character by character with size
➢We can also assign a string character by character. But we should remember
to set the end character as ‘\0’ which is a null character.
45
Initializing a String:
4. Assigning character by character without size
➢ We can assign character by character without size with the NULL character
at the end. The size of the string is determined by the compiler automatically.
46
Initializing a String:
// C program to illustrate strings
int main()
{ char str[] = "Geeks"; // declare and initialize string
// print string
printf("%s\n", str);
int length = 0;
length = strlen(str);
// displaying the length of string
printf("Length of string str is %d", length);
return 0;
} 47
String Functions:
➢strlen() -> It returns the string's length.
➢strcmp() -> It compares two strings and returns 0 if the strings are the same.
➢Strncmp() -> It compares two strings only to n characters.
➢strcpy() -> It copies one string into another.
➢strncpy() -> It copies the first n characters of one string into another.
➢strchr() -> It finds out the first occurrence of a given character in a string.
➢strrchr() -> It finds out the last occurrence of a given character in a string.
48
Example of String Functions:
➢strlen():
➢#include <stdio.h>
➢#include <string.h>
➢int main() {
➢ char string1[20] = “HelloADIT";
➢ printf("Length of string string1: %ld", strlen(string1));
➢ return 0;
➢}
➢O/P: Length of string string1: 09
49
Example of String Functions:
➢Strcmp() :
➢Syntax:
50
Example of String Functions:
➢#include <stdio.h>
➢#include <string.h>
➢int main() {
➢ char s1[20] = "ScalerAcademy"; // string1
➢ char s2[20] = "ScalerAcademy.COM"; // string2
➢ if (strcmp(s1, s2) == 0) { // comparing both the strings
➢ printf("string 1 and string 2 are equal");
➢ } else {
➢ printf("string 1 and 2 are different");
➢ }
➢} 51
Example of String Functions:
➢O/P:
string 1 and 2 are different
52
Example of String Functions:
➢strncmp()
➢Syntax:
int strncmp(const char *str1, const char *str2, size_t n)
53
Example of String Functions:
➢#include <stdio.h>
➢#include <string.h>
➢int main() {
➢ char s1[20] = “HelloADIT";
➢ char s2[20] = “HelloGCET";
➢ if (strncmp(s1, s2, 5) == 0) { /*compares first 5 characters */
➢ printf("string 1 and string 2 are equal");
➢ } else {
➢ printf("string 1 and 2 are different");
➢ }
➢} 54
Example of String Functions:
strcat()
➢Syntax:
char *strcat(char *str1, char *str2)
➢It takes two strings as input and concatenates the second string to the first
string, which means it will attach the second string to the end of the first
string and save the concatenated string to the first string.
➢The size of the first string should be large enough to save the result.
55
Example of String Functions:
#include <stdio.h>
#include <string.h>
int main()
{
char string1[10] = "Hello";
char string2[10] = "World";
strcat(string1, string2);
printf("Output string after concatenation: %s", string1);
}
➢O/P: Output string after concatenation: HelloWorld
56
Example of String Functions:
strncat()
➢Syntax: char *strncat(char *str1, char *str2, int n)
➢It takes two strings as input and attaches only the first n characters of the
second string to the end of the first string.
57
Example of String Functions:
#include <stdio.h>
#include <string.h>
int main () {
char string1[10] = "Hello";
char string2[10] = "World";
strncat(string1,string2, 3);
printf("Concatenation using strncat: %s", string1);
}
➢O/P: Concatenation using strncat: HelloWor
58
Example of String Functions:
strcpy()
➢Syntax: char *strcpy( char *str1, char *str2)
➢It takes two strings as input and overwrites the data of the second string
into the first string, i.e., it copies the data of the second string to the first
string.
59
Example of String Functions:
#include <stdio.h>
#include <string.h>
int main() {
char s1[35] = "string 1"; // string1
char s2[35] = "I'll be copied to string 1."; // string2
strcpy(s1, s2); // copying string2 to string1
printf("String s1 is: %s", s1); // printing string1
}
O/P: String s1 is: I'll be copied to string 1.
60
Example of String Functions:
strncpy()
➢Syntax: char *strncpy( char *str1, char *str2, size_t n)
It takes two strings as input and overwrites the data of the first string by the
second string based on specific conditions:
If the length of string2 is greater than n, it copies only the first n characters of
string2 to string1; otherwise, it copies the entire string2 to string1.
61
Example of String Functions:
#include <stdio.h>
#include <string.h>
int main() {
char string1[30] = "string 1";
char string2[40] = "Only 12 characters will be copied.";
strncpy(string1, string2, 12);
printf("String s1 is: %s", string1);
}
➢O/P: String s1 is: Only 12 char
62