0% found this document useful (0 votes)
20 views20 pages

UNIT 3cp

good

Uploaded by

madhu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views20 pages

UNIT 3cp

good

Uploaded by

madhu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

MVRCOET/NVR/CP

UNIT: III: ARRAYS &STRINGS


Array in C is one of the most used data structures in C programming. It is a
simple and fast way of storing multiple values under a single name.
What is Array in C?(Array indexing)
An array in C is a fixed-size collection of similar data items stored in
contiguous memory locations. It can be used to store the collection of primitive
data types such as int, char, float, etc., and also derived and user-defined data
types such as pointers, structures, etc.

C Array Declaration
In C, we have to declare the array like any other variable before using it. We
can declare an array by specifying its name, the type of its elements, and the
size of its dimensions. When we declare an array in C, the compiler allocates
the memory block of the specified size to the array name.
Syntax of Array Declaration
data_type array_name [size];
or
data_type array_name [size1] [size2]...[sizeN];
where N is the number of dimensions.
MVRCOET/NVR/CP

The C arrays are static in nature, i.e., they are allocated memory at the compile
time.
C Array Initialization
Initialization in C is the process to assign some initial value to the variable.
When the array is declared or allocated memory, the elements of the array
contain some garbage value. So, we need to initialize the array to some
meaningful value. There are multiple ways in which we can initialize an array in
C.
1. Array Initialization with Declaration
In this method, we initialize the array along with its declaration. We use an
initializer list to initialize multiple elements of the array. An initializer list is the
list of values enclosed within braces { } separated b a comma.
data_type array_name [size] = {value1, value2, ... valueN};
MVRCOET/NVR/CP
2. Array Initialization with Declaration without Size
If we initialize an array using an initializer list, we can skip declaring the size of
the array as the compiler can automatically deduce the size of the array in these
cases. The size of the array in these cases is equal to the number of elements
present in the initializer list as the compiler can automatically deduce the size of
the array.
data_type array_name[] = {1,2,3,4,5};
The size of the above arrays is 5 which is automatically deduced by the
compiler.
3. Array Initialization after Declaration (Using Loops)
We initialize the array after the declaration by assigning the initial value to each
element individually. We can use for loop, while loop, or do-while loop to
assign the value to each element of the array.
for (int i = 0; i < N; i++) {
array_name[i] = valuei;
}
Example of Array Initialization in C
// C Program to demonstrate array initialization
#include <stdio.h>
int main()
{
// array initialization using initialier list
int arr[5] = { 10, 20, 30, 40, 50 };
// array initialization using initializer list without
// specifying size
int arr1[] = { 1, 2, 3, 4, 5 };
// array initialization using for loop
float arr2[5];
for (int i = 0; i < 5; i++) {
arr2[i] = (float)i * 2.1;
}
return 0; }
MVRCOET/NVR/CP
Access Array Elements
We can access any element of an array in C using the array subscript
operator [ ] and the index value i of the element.
array_name [index];
One thing to note is that the indexing in the array always starts with 0, i.e.,
the first element is at index 0 and the last element is at N – 1 where N is the
number of elements in the array.

Example of Accessing Array Elements using Array Subscript Operator


// C Program to illustrate element access using array
// subscript
#include <stdio.h>
int main()
{
// array declaration and initialization
int arr[5] = { 15, 25, 35, 45, 55 };
// accessing element at index 2 i.e 3rd element
printf("Element at arr[2]: %d\n", arr[2]);
// accessing element at index 4 i.e last element
printf("Element at arr[4]: %d\n", arr[4]);
// accessing element at index 0 i.e first element
printf("Element at arr[0]: %d", arr[0]);
MVRCOET/NVR/CP
return 0;
}

Output
Element at arr[2]: 35
Element at arr[4]: 55
Element at arr[0]: 15
Update Array Element
We can update the value of an element at the given index i in a similar way to
accessing an element by using the array subscript operator [ ] and assignment
operator =.
array_name[i] = new_value;
C Array Traversal
Traversal is the process in which we visit every element of the data structure.
For C array traversal, we use loops to iterate through each element of the array.
Array Traversal using for Loop
for (int i = 0; i < N; i++) {
array_name[i];
}
MVRCOET/NVR/CP
How to use Array in C?
The following program demonstrates how to use an array in the C programming
language:
// C Program to demonstrate the use of array
#include <stdio.h>
int main()
{
// array declaration and initialization
int arr[5] = { 10, 20, 30, 40, 50 };
// modifying element at index 2
arr[2] = 100;
// traversing array using for loop
printf("Elements in Array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}

Output
Elements in Array: 10 20 100 40 50
Types of Array in C
There are two types of arrays based on the number of dimensions it has. They
are as follows:
1. One Dimensional Arrays (1D Array)
2. Multidimensional Arrays
1. One Dimensional Array in C
The One-dimensional arrays, also known as 1-D arrays in C are those arrays
that have only one dimension.
MVRCOET/NVR/CP
Syntax of 1D Array in C
array_name [size];

Example of 1D Array in C
// C Program to illustrate the use of 1D array
#include <stdio.h>
int main()
{
// 1d array declaration
int arr[5];
// 1d array initialization using for loop
for (int i = 0; i < 5; i++) {
arr[i] = i * i - 2 * i + 1;
}
printf("Elements of Array: ");
// printing 1d array by traversing using for loop
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}

Output
Elements of Array: 1 0 1 4 9
MVRCOET/NVR/CP
Array of Characters (Strings)
In C, we store the words, i.e., a sequence of characters in the form of an array of
characters terminated by a NULL character. These are called strings in C
language.
// C Program to illustrate strings
#include <stdio.h>
int main()
{
// creating array of character
char arr[6] = { 'G', 'e', 'e', 'k', 's', '\0' };
// printing string
int i = 0;
while (arr[i]) {
printf("%c", arr[i++]);
}
return 0;
}

Output
2. Multidimensional Array in C
Multi-dimensional Arrays in C are those arrays that have more than one
dimension. Some of the popular multidimensional arrays are 2D arrays and 3D
arrays. We can declare arrays with more dimensions than 3d arrays but they are
avoided as they get very complex and occupy a large amount of space.
A. Two-Dimensional Array in C
A Two-Dimensional array or 2D array in C is an array that has exactly two
dimensions. They can be visualized in the form of rows and columns organized
in a two-dimensional plane.
Syntax of 2D Array in C
array_name[size1] [size2];
Here,
 size1: Size of the first dimension.
MVRCOET/NVR/CP
 size2: Size of the second dimension.

Example of 2D Array in C
// C Program to illustrate 2d array
#include <stdio.h>
int main()
{

// declaring and initializing 2d array


int arr[2][3] = { 10, 20, 30, 40, 50, 60 };

printf("2D Array:\n");
// printing 2d array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ",arr[i][j]);
}
printf("\n");
}
return 0;
}
MVRCOET/NVR/CP

Output
2D Array:
10 20 30
40 50 60
B. Three-Dimensional Array in C
Another popular form of a multi-dimensional array is Three Dimensional Array
or 3D Array. A 3D array has exactly three dimensions. It can be visualized as a
collection of 2D arrays stacked on top of each other to create the third
dimension.
Syntax of 3D Array in C
array_name [size1] [size2] [size3];

Example of 3D Array
// C Program to illustrate the 3d array
#include <stdio.h>
int main()
{
// 3D array declaration
int arr[2][2][2] = { 10, 20, 30, 40, 50, 60 };
// printing elements
for (int i = 0; i < 2; i++) {
MVRCOET/NVR/CP
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
printf("%d ", arr[i][j][k]);
}
printf("\n");
}
printf("\n \n");
}
return 0;
}

Output
10 20
30 40
50 60
00
MEMORY MODLE
Dynamic Memory Allocation in C: In C, dynamic memory allocation allows
you to allocate memory at runtime, rather than at compile time. This flexibility
is essential when dealing with varying data sizes or when you need to manage
memory efficiently.
Let’s explore the key concepts and functions related to dynamic memory
allocation:
1. malloc() (Memory Allocation):
 The malloc() function (short for “memory allocation”) dynamically
allocates a block of memory from the heap.
 It returns a pointer to the first byte of the allocated memory.
 Syntax:  ptr = (cast-type*) malloc(byte-size);
 Example:  int* arr = (int*) malloc(5 * sizeof(int));
// Allocating memory for 5 integers  Remember to check if malloc()
returns a NULL pointer (indicating insufficient memory).

2. calloc() (Contiguous Allocation):


 The calloc() function allocates memory for an array of elements,
initializes them to zero, and returns a pointer.
MVRCOET/NVR/CP
 Syntax: ptr = (cast-type*) calloc(n, element-size);
Example: float* floatArr = (float*) calloc(10, sizeof(float));
// Allocating memory for 10 floats

3. realloc() (Resizing Array):


 The realloc() function changes the size of an existing dynamically
allocated memory block.
 It can expand or shrink the memory block.
Syntax: ptr = (cast-type*) realloc(ptr, new-size);
Example: arr = realloc(arr, 10 * sizeof(int)); // Resizing memory to
hold 10 integers

4. free() (Memory Deallocation):


 The free() function releases the memory previously allocated by
malloc(), calloc(), or realloc().
 Always free memory to prevent memory leaks.
 Example:  free(arr);
// Release the allocated memory Dynamic memory allocation empowers
you to optimize memory usage and adapt to changing requirements
during program execution. Remember to use these functions wisely and
release memory when it’s no longer needed!

Example of malloc() in C

#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;

// Get the number of elements for the array


printf("Enter number of elements:");
scanf("%d",&n);
MVRCOET/NVR/CP
printf("Entered number of elements: %d\n", n);

// Dynamically allocate memory using malloc()


ptr = (int*)malloc(n * sizeof(int));

// Check if the memory has been successfully


// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {

// Memory has been successfully allocated


printf("Memory successfully allocated using malloc.\n");

// Get the elements of the array


for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}

// Print the elements of the array


printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}

return 0;
MVRCOET/NVR/CP
}
Output
Enter number of elements:7
Entered number of elements: 7
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7,

Strings
A String in C programming is a sequence of characters terminated with a null
character ‘\0’. The C String is stored as an array of characters. The difference
between a character array and a C string is that the string in C is terminated
with a unique character ‘\0’.

C String Declaration Syntax


Declaring a string in C is as simple as declaring a one-dimensional array.
Below is the basic syntax for declaring a string.

char string_name[size];

In the above syntax string_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.

There is an extra terminating character which is the Null character (‘\0’) used
to indicate the termination of a string that differs strings from normal
character arrays. To get a deeper understanding of how strings are used
alongside various data structures, the C Programming Course Online with
Data Structures provides a complete guide to managing and manipulating
strings efficiently in C.

C String Initialization
A string in C can be initialized in different ways. We will explain this with the
help of an example. Below are the examples to declare a string with the name
str and initialize it with “GeeksforGeeks”.

We can initialize a C string in 4 different ways which are as follows:


MVRCOET/NVR/CP
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[] = "GeeksforGeeks";

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.
char str[50] = "GeeksforGeeks";

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.
char str[14] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};

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.
char str[] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
Note: When a Sequence of characters enclosed in the double quotation marks
is encountered by the compiler, a null character ‘\0’ is appended at the end of
the string by default.
// C program to illustrate strings

#include <stdio.h>
#include <string.h>

int main()
{
// declare and initialize string
char str[] = "Geeks";

// print string
printf("%s\n", str);
MVRCOET/NVR/CP
int length = 0;
length = strlen(str);

// displaying the length of string


printf("Length of string str is %d", length);

return 0;
}
Output
Geeks
Length of string str is 5

// C program to read string from user


#include<stdio.h>

int main()
{
// declaring string
char str[50];

// reading string
scanf("%s",str);

// print string
printf("%s",str);

return 0;
}
MVRCOET/NVR/CP
Input
GeeksforGeeks
Output
GeeksforGeeks

String Functions in C
Some of the commonly used string functions in C are as follows:
1. strcat() Function
The strcat() function in C is used for string concatenation. It will append a
copy of the source string to the end of the destination string.
Syntax
char* strcat(char* dest, const char* src);

// C Program to illustrate the strcat function


#include <stdio.h>

int main()
{
char dest[50] = "This is an";
char src[50] = " example";

printf("dest Before: %s\n", dest);

// concatenating src at the end of dest


strcat(dest, src);

printf("dest After: %s", dest);

return 0;
}
Output
dest Before: This is an
dest After: This is an example
MVRCOET/NVR/CP

3. strcmp() Function
The strcmp() is a built-in library function in C. This function takes two
strings as arguments and compares these two strings lexicographically.
Syntax
int strcmp(const char *str1, const char *str2);
// C program to demonstrate the strcmp() function
#include <stdio.h>
#include <string.h>

int main()
{
// Define a string 'str1' and initialize it with "Geeks"
char str1[] = "Geeks";
// Define a string 'str2' and initialize it with "For"
char str2[] = "For";
// Define a string 'str3' and initialize it with "Geeks"
char str3[] = "Geeks";

// Compare 'str1' and 'str2' using strcmp() function and


// store the result in 'result1'
int result1 = strcmp(str1, str2);
// Compare 'str2' and 'str3' using strcmp() function and
// store the result in 'result2'
int result2 = strcmp(str2, str3);
// Compare 'str1' and 'str1' using strcmp() function and
// store the result in 'result3'
int result3 = strcmp(str1, str1);

// Print the result of the comparison between 'str1' and


// 'str2'
MVRCOET/NVR/CP
printf("Comparison of str1 and str2: %d\n", result1);
// Print the result of the comparison between 'str2' and
// 'str3'
printf("Comparison of str2 and str3: %d\n", result2);
// Print the result of the comparison between 'str1' and
// 'str1'
printf("Comparison of str1 and str1: %d\n", result3);

return 0;
}
Output
Comparison of str1 and str2: 1
Comparison of str2 and str3: -1
Comparison of str1 and str1: 0

Program to Reverse a String in C


In C, strings are nothing but character arrays. So, we can use two
indexes: one to the start and other to the end of the string. We move
these indexes towards each other swap the characters at these pointers
while moving the indexes towards each other. When these indexes meet
each other, the string will be reversed. This method is called two pointer
method as we use two pointers to the first and last.

// C Program to Reverse a String using Two-Pointer Technique


#include <stdio.h>
#include <string.h>

void reverse(char* str) {

// Initialize first and last pointers


int first = 0;
int last = strlen(str) - 1;
MVRCOET/NVR/CP
char temp;

// Swap characters till first and last meet


while (first < last) {

// Swap characters
temp = str[first];
str[first] = str[last];
str[last] = temp;

// Move pointers towards each other


first++;
last--;
}
}

int main() {
char str[100] = "Hello World";

// Reversing str
reverse(str);

printf("%s\n", str);
return 0;
}
Output
dlroW olleH

You might also like