UNIT 3cp
UNIT 3cp
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.
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()
{
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).
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;
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’.
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”.
#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);
return 0;
}
Output
Geeks
Length of string str is 5
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);
int main()
{
char dest[50] = "This is an";
char src[50] = " example";
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";
return 0;
}
Output
Comparison of str1 and str2: 1
Comparison of str2 and str3: -1
Comparison of str1 and str1: 0
// Swap characters
temp = str[first];
str[first] = str[last];
str[last] = temp;
int main() {
char str[100] = "Hello World";
// Reversing str
reverse(str);
printf("%s\n", str);
return 0;
}
Output
dlroW olleH