0% found this document useful (0 votes)
22 views25 pages

C Arrays: Types, Usage, and Examples

The document provides a comprehensive overview of arrays in C, including their definition, characteristics, advantages, and limitations. It covers one-dimensional and multi-dimensional arrays, their declaration, initialization, and methods for accessing and manipulating their elements. Additionally, it discusses searching techniques such as linear and binary search, along with examples for better understanding.

Uploaded by

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

C Arrays: Types, Usage, and Examples

The document provides a comprehensive overview of arrays in C, including their definition, characteristics, advantages, and limitations. It covers one-dimensional and multi-dimensional arrays, their declaration, initialization, and methods for accessing and manipulating their elements. Additionally, it discusses searching techniques such as linear and binary search, along with examples for better understanding.

Uploaded by

Princeton
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT-III

Arrays in C
 An array is a collection of elements of the same data type stored in contiguous memory locations.
 It allows storing multiple values under a single variable name.
 Each element in the group is referred by its position called index.
 Each element is accessed using an index (subscript).
 The first element in the array is numbered 0, so the last element is one less than the size of the
array.
 Before using an array its type and dimension must be declared, so that the compiler will know what
kind of an array and how large an array.

Example:

int marks[5] = {10, 20, 30, 40, 50};

Characteristics
1. All elements are of the same data type.
2. Stored in continuous (contiguous) memory.
3. Indexing starts from 0 in C.
4. The array name represents the base address of the first element.
5. Array size must be a constant value (known at compile time).

Advantages
 Easy to access elements using index.
 Efficient memory usage.
 Helps manage large amounts of data easily.
 Supports iteration with loops.

Limitations
 Fixed size (cannot grow/shrink at runtime).
 All elements must be of the same type.
 Wastage of memory if not fully used.

One – Dimensional arrays:-


A list of items can be given one variable name using only one subscript and such a variable is called one-dimensional
array or single-dimensional variable.

1
Syntax: The general form of array declaration is:

datatype array-name[size];

The data-type specifies the type of elements such as int, float or char. And the size indicates the maximum number of
elements that can be stored in that array.

Eg:
int a[5] ; here a is an array containing 5 integer elements.
float height[10]; here height is array containing 10 real elements.
char name[20]; here name is an array containing 20 characters.

Example:

#include <stdio.h>
int main() {
int arr[] = {2, 4, 8, 12, 16, 18};
int n = sizeof(arr)/sizeof(arr[0]);

// Printing array elements


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

return 0;
}
Output
2 4 8 12 16 18
The below image shows the array created in the above program.

2
To understand the key characteristics of arrays such as fixed size, contiguous memory
allocation, and random access. Refer to this article: Properties of Arrays
Creating an Array
The whole process of creating an array can be divided into two primary sub processes
i.e.
1. Array Declaration
Array declaration is the process of specifying the type, name, and size of the array. In
C, we have to declare the array like any other variable before using it.
When we declare an array in C, the compiler allocates the memory block of the
specified size to the array name.

2. Array Initialization
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 values.
 We can skip mentioning the size of the array if declaration and initialization are
done at the same time.
 We can also partially initialize while declaring. In this case, the remaining elements
will be assigned the value 0 (or equivalent according to the type).

3
Array Subscript in C:
Accessing Array Elements
Array in C provides random access to its elements, which means that we can access
any element of the array by providing the position of the element, called the index.

#include <stdio.h>
int main() {

// array declaration and initialization


int arr[5] = {2, 4, 8, 12, 16};
// accessing element at index 2 i.e 3rd element
printf("%d ", arr[2]);
// accessing element at index 4 i.e last element
printf("%d ", arr[4]);
// accessing element at index 0 i.e first element
printf("%d ", arr[0]);
return 0;
}

Output
8 16 2

//Example for One dimensional array – Sum of the elements of an array

// Initialize the array elements at compile time

4
#include<stdio.h>
#include<conio.h>
void main()
{
int i, sum=0;
int a [ 10 ] = { 12, 3, 5, 43, 21, 1, 6, 8, 9, 11 };
// Array a is initialized at compile time
clrscr();
/* finding the sum of array a */
for(i=0; i<10; i++)
sum = sum + a[ i ];
printf(“\n Sum of elements of array a is %d”, sum);
getch();
}
O/p: Sum of elements of array a is 119

//Example for One dimensional array – Sum of the elements of an array

// Initialize the array elements at run time


#include<stdio.h>
#include<conio.h>
void main()
{
int a[ 10], i, n, sum=0;
clrscr();
printf (“Enter [Link] elements :”);
scanf (“%d”, &n);
printf(“Enter %d elements :”,n);
for(i=0; i<n; i++)
scanf(“%d”,&a [ i ]); // run time initialization
/* finding the sum of array a */
for(i=0; i<n; i++)
sum = sum + a[ i ];
printf(“\n Sum of elements of array a is %d”, sum);
getch();
}
O/p:
Enter [Link] elements : 5
Enter 5 elements : 1 2 3 4 5
Sum of elements of array a is 15

5
Multidimensional Arrays:
A multi-dimensional array in C can be defined as an array that has more than one
dimension. Having more than one dimension means that it can grow in multiple
directions. Some popular multidimensional arrays include 2D arrays which grows in
two dimensions, and 3D arrays which grows in three dimensions.
We can create an array of arrays. These arrays are known as multidimensional arrays.

Types of Multidimensional Arrays


In C, there can be many types of arrays depending on their dimensions but two of
them are most commonly used:
1. 2D Array - Two Dimensional
2. 3D Array - Three Dimensional

Two - Dimensional Arrays:-


C allows us to define the data in the form of table of items by using two-dimensional arrays.

Syntax: syntax to declare two dimensional array

data-type array-name [ row size ] [ column size ];

Eg: int a [ 3] [ 4 ] ; Here a is two dimensional array with row size 3 and column size 4., and the total
elements we can store in this array a is 12 (i.e. 3 * 4 ).

For example,

float x[3][4];

Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think
the array as a table with 3 rows and each row has 4 columns.

6
Two dimensional Array

Initializing Two Dimensional Arrays:-


Like on-dimensional arrays, two-dimensional arrays can also be initialized at compile time and runtime.

Compile time initialization:-

Two-dimensional arrays may be initialized by following their declaration with a list of initial values enclosed in
braces. Until and unless we initialize the array explicitly it is having some garbage values initially.

Eg:- int a [2] [3] = {3, 5, 7, 12, 22, 32} ;

Here a[0][0] = 3 a[0][1] = 5 a[0][2] = 7

And a[1][0] = 12 a[1][1] = 22 a[1][2] = 32

The initialization can also be done in row by row as follows.

int a [2] [3] = { { 3, 5, 7 } , {12, 22, 32 } };

We can also initialize a two dimensional array in the form of a matrix as follows:

int a [2] [3] = {


{ 3, 5, 7 },
{12, 22, 32 }
};

7
Loop Through a 2D Array
To loop through a multi-dimensional array, you need one loop for each of the array's dimensions.

The following example outputs all elements in the matrix array:

#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("%d\n", matrix[i][j]);
}
}
return 0;
}
O/p:
1
4
2
3
6
8

3D Array in C
A Three-Dimensional Array or 3D array in C is a collection of two-dimensional arrays. It can be
visualized as multiple 2D arrays stacked on top of each other.
For example,

float y[2][4][3];

Here, the array y can hold 24 elements.


Example:
#include <stdio.h>
int main() {
// A 3D array with 2 blocks, each with 4 rows and 3 columns
int example[2][4][3] = {
{
{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}
},
8
{
{13, 14, 15}, {16, 17, 18}, {19, 20, 21}, {22, 23, 24}
}
};
// Print all elements using 3 nested loops
for (int i = 0; i < 2; i++) {
printf("Block %d:\n", i + 1);
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 3; k++) {
printf("%d ", example[i][j][k]);
}
printf("\n");
}
printf("\n");
}
return 0;
}
O/p:
Block 1:
1 2 3
4 5 6
7 8 9
10 11 12

Block 2:
13 14 15
16 17 18
19 20 21
22 23 24
Using for Loops for Sequential Access:
To access elements of an array sequentially in C using a for loop, you iterate through the array
using an index variable. This variable typically starts at 0 (the index of the first element) and
increments until it reaches one less than the total number of elements (the index of the last
element).
Here's how to implement this:

#include <stdio.h>

int main() {
// Declare and initialize an array
int numbers[] = {10, 20, 30, 40, 50};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the number of
elements

printf("Accessing array elements sequentially:\n");

9
// Use a for loop to iterate through the array
for (int i = 0; i < size; i++) {
// Access each element using the loop counter 'i' as the index
printf("Element at index %d: %d\n", i, numbers[i]);
}

return 0;
}

O/p:

Accessing array elements sequentially:


Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

Using Array Elements as Function Arguments:

Passing an array to a function allows the function to directly access and modify the
original array. In this article, we will learn how to pass arrays to functions in C.
In C, arrays are always passed to function as pointers. They cannot be passed by
value because of the array decay due to which, whenever array is passed to a
function, it decays into a pointer to its first element. However, there can be different
syntax of passing the arrays as pointers.
The easiest way to pass array to a function is by defining the parameter as
the undefined sized array. Let's take a look at an example:

#include <stdio.h>

// Array passed as an array without the size of its


// dimension
void printArr(int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
}

int main() {
int arr[] = {1, 2, 3, 4, 5};

// Pass array to function


printArr(arr, 5);

10
return 0;
}

Output
1 2 3 4 5
Explanation: In this example, we pass an integer array arr to the function printArr().
In the function prototype, we define the array as the array of integers with no size
information.
Array Arguments:
Example 1: Pass Individual Array Elements
#include <stdio.h>
void display(int age1, int age2) {
printf("%d\n", age1);
printf("%d\n", age2);
}

int main() {
int ageArray[] = {2, 8, 4, 12};

// pass second and third elements to display()


display(ageArray[1], ageArray[2]);
return 0;
}

Output

Here, we have passed array parameters to the display() function in the same way we
pass variables to a function.

// pass second and third elements to display()


display(ageArray[1], ageArray[2]);

11
We can see this in the function definition, where the function parameters are individual
variables:

void display(int age1, int age2) {


// code
}

Example 2: Pass Arrays to Functions


// Program to calculate the sum of array elements by passing to a function

#include <stdio.h>
float calculateSum(float num[]);

int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};

// num array is passed to calculateSum()


result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}

float calculateSum(float num[]) {


float sum = 0.0;

for (int i = 0; i < 6; ++i) {


sum += num[i];
}

return sum;
}

Output

Result = 162.50

12
Searching and Sorting an Array in C
1. Searching an Array

Definition:
Searching means finding the location of a particular element in an array.

There are two main types of searching techniques:

 Linear Search
 Binary Search

A) Linear Search

Definition:
In Linear Search, each element in the array is compared one by one with the target value until it is found or
the end of the array is reached.

Algorithm Steps:

1. Start from the first element.


2. Compare each element with the search value.
3. If match found, return the position.
4. If no match, print "Element not found".

Program:

#include <stdio.h>
int main()
{
int a[5] = {10, 20, 30, 40, 50};
int key, i, found = 0;

printf("Enter element to search: ");


scanf("%d", &key);

for(i = 0; i < 5; i++)


{
if(a[i] == key)
{
printf("Element found at position %d", i+1);
found = 1;
break;
}
}

if(found == 0)
13
printf("Element not found");

return 0;
}

Output:

Enter element to search: 30


Element found at position 3

B) Binary Search

Definition:
Binary Search works only on sorted arrays.
It repeatedly divides the array into halves to find the target element quickly.

Algorithm Steps:

1. Set low = 0, high = n-1.


2. Find mid = (low + high) / 2.
3. If key == a[mid], element found.
4. If key < a[mid], search in left half.
5. Else, search in right half.
6. Repeat until low > high.

2. Sorting an Array

Definition:
Sorting means arranging array elements in a particular order — ascending or descending.

Common sorting methods are:

 Bubble Sort
 Selection Sort

A) Bubble Sort

Definition:
Bubble Sort compares adjacent elements and swaps them if they are in the wrong order.
This process continues until the array is sorted.

Program:

#include <stdio.h>
14
int main()
{
int a[5] = {5, 2, 8, 1, 3};
int i, j, temp;

for(i = 0; i < 4; i++)


{
for(j = 0; j < 4 - i; j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}

printf("Sorted array: ");


for(i = 0; i < 5; i++)
printf("%d ", a[i]);

return 0;
}

Output:

Sorted array: 1 2 3 5 8

Parallel Arrays

Definition:
Parallel arrays are two or more arrays that store related data using the same index.
Each index position in the arrays represents information about the same item.

For example:

 One array stores student names.


 Another array stores their marks.
 The same index connects both pieces of information.

Example:
#include <stdio.h>
int main()
{
char name[3][20] = {"Asif", "Ravi", "John"};
int marks[3] = {85, 90, 78};

15
printf("Student Details:\n");
for(int i = 0; i < 3; i++)
{
printf("Name: %s\tMarks: %d\n", name[i], marks[i]);
}

return 0;
}

Output:

Student Details:
Name: Asif Marks: 85
Name: Ravi Marks: 90
Name: John Marks: 78

Explanation:

 name[i] and marks[i] together represent information about the same student.
 The arrays are parallel because their elements at the same index correspond to each other.

Advantages:

1. Easy to handle related data of same length.


2. Simple to implement and access.
3. Useful for tabular data (students, employees, products, etc.).

Disadvantages:

1. Difficult to manage when number of arrays increases.


2. Not suitable for complex data — structures are better for that.

2. Enumerated Types (enum)

Definition:
An enumerated type (keyword: enum) is a user-defined data type that consists of named integer
constants.
It improves code readability by using meaningful names instead of numbers.

16
Syntax:
enum enum_name { constant1, constant2, constant3, ... };

By default,

 The first constant has the value 0,


 The next has 1, and so on.
You can also assign custom values.

Example 1:
#include <stdio.h>
int main()
{
enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
enum week today;
today = Wednesday;

printf("Day number: %d", today);


return 0;
}

Output:

Day number: 3

Example 2 (With Custom Values):


#include <stdio.h>
int main()
{
enum month {Jan = 1, Feb, Mar, Apr};
enum month m = Mar;

printf("Month number: %d", m);


return 0;
}

Output:

Month number: 3

17
Advantages of enum:

1. Improves code clarity and readability.


2. Makes programs easy to debug and maintain.
3. Replaces magic numbers with meaningful names.

 Parallel arrays help in storing and processing related data using the same index.
 Enumerated types (enum) help in defining meaningful names for integer constants, improving the
readability and maintainability of programs.

STRINGS:

A string is an array of characters.(Or) A string is a one-dimensional array of characters terminated


by a null character (‘\0’).

Eg: “INDIA” “WELCOME”

Each character of the string occupies one-byte of memory. The characters of the string are stored in
contiguous memory locations.

Declaration and Initialization of Strings:-

Syntax: char string-


name[size]; Eg: char
city [20];

Character arrays (strings) may be initializing when they are declared(compiletime initialization).

Eg
:
 We can initialize a character array as element by element and last character should be the
null character.
char city [10] = { ‘H’, ‘Y’, ‘D’, ‘E’, ‘R’, ‘A’, ‘B’, ‘A’, ‘D’, ‘\0’ } ;

 We can initialize a character array as total string at a time.


char city [10] = “HYDERABAD”;

 We can initialize a character array without specifying the size; the compiler automatically
determines the size.
char city [] = “HYDERABAD”;

18
The memory representation of this character array is as follows:

0 1 2 3 4 5 6 7 8 9

H Y D E R A B A D \0

3010 3011 3012 3013 3014 3015 3016 3017 3018


3019

String Example in C

Let's see a simple example where a string is declared and being printed. The '%s'
isused as a format specifier for the string in c language.

1. #include<stdio.h>
2. #include <string.h>
3. intmain(){
4. charch[11]={'p’,’r’,’i’,’n’,’c’,’e’,’t’,’o’,’n’, '\0'};
5. charch2[11]="princeton";
6.
7. printf("Char Array Value is: %s\n", ch);
8. printf("String Literal Value is: %s\n", ch2);
9. return0;
10. }

Output

Char Array Value is: princeton


StringLiteralValueis:Princeton

19
C String Handling Functions

There are many important string functions defined in "string.h"library.

No. Function Description

1) strlen(string_name) returns the length of string name.

2) strcpy(destination, source) Copies the contents of source string to destination


string.

3) strcat(first_string,second_stri Concats or joins first string with second string. The


ng) result of the string is stored in first string.

4) strcmp(first_string,second_str Compares the first string with second string. If both


ing) strings are same, it returns 0.

5) strrev(string) returns reverse string.

6) strlwr(string) returns string characters in lowercase.

7) strupr(string) returns string characters in uppercase.

String Assignment:

In C, strings cannot be assigned directly using the assignment operator (=) because arrays do
not support direct assignment.

Invalid Example
char str1[10], str2[10] = "Hello";
str1 = str2; // ❌ Error: invalid assignment

Correct Way – Using strcpy() Function

 To assign one string to another, we use the strcpy() function from the <string.h>
library.

20
Example:

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

int main() {
char str1[20], str2[20] = "Hello";
strcpy(str1, str2); // Copy string
printf("String 1: %s\n", str1);
return 0;
}

Output:

String 1: Hello

strcpy(destination, source) copies all characters from source to destination,


including the null character.

Substrings in C:
 A substring is a part of a string, i.e., a smaller string extracted from a larger one.
 C does not provide a built-in function to get substrings directly, but we can extract
them manually using loops.

Example: Extracting a Substring


#include <stdio.h>

int main() {
char str[50] = "Programming";
char sub[20];
int i, start = 3, len = 5;

for (i = 0; i < len; i++) {


sub[i] = str[start + i];
}
sub[i] = '\0'; // End substring with null character

printf("Substring is: %s\n", sub);


return 0;
}

Output:

Substring is: gramm

21
String Concatenation
Definition:

String concatenation means joining two or more strings into one single string.

Invalid Method:
char s1[20] = "Hello", s2[20] = "World";
s1 = s1 + s2; // ❌ Not allowed

Correct Method – Using strcat() Function

 The strcat() function (from <string.h>) is used to concatenate strings.

Syntax:

strcat(destination, source);

Example:

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

int main() {
char s1[30] = "Hello ";
char s2[20] = "World";
strcat(s1, s2); // Join s2 at the end of s1
printf("Concatenated String: %s\n", s1);
return 0;
}

Output:

Concatenated String: Hello World

Explanation:
strcat() adds the content of s2 to the end of s1, including a null terminator at the end.

3. Whole-Line Input

Problem with scanf()

 The function scanf("%s", str) reads a word only up to the first space.
 Example:
 scanf("%s", str); // Input: Hello World
 // Output: "Hello" only

22
Solution – Using gets() or fgets()

 To read a whole line (including spaces), we use:


o gets() (deprecated, unsafe)
o fgets() (safe and recommended)
o Using fgets()

Syntax:

fgets(string_name, size, stdin);

Example:

#include <stdio.h>

int main() {
char line[100];
printf("Enter a line of text: ");
fgets(line, sizeof(line), stdin);
printf("You entered: %s", line);
return 0;
}

Output:

Enter a line of text: Welcome to C programming


You entered: Welcome to C programming

Explanation:
fgets() reads the entire line including spaces and stores it in the array.

String Comparison:
Definition:

String comparison means checking whether two strings are equal, or which one comes first in
lexicographical (dictionary) order.

Using strcmp() Function

 The strcmp() function (from <string.h>) is used to compare two strings.

Syntax:

strcmp(string1, string2);

23
Return Values:

Return Value Meaning

0 Strings are equal

>0 string1 is greater than string2

<0 string1 is smaller than string2

Example:

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

int main() {
char s1[20] = "Apple";
char s2[20] = "Mango";

int result = strcmp(s1, s2);

if (result == 0)
printf("Strings are equal\n");
else if (result > 0)
printf("s1 is greater than s2\n");
else
printf("s1 is smaller than s2\n");

return 0;
}

Output:

s1 is smaller than s2

Array of Pointers in C
Just like an integer array holds a collection of integer variables, an array of
pointers would hold variables of pointer type. It means each variable in an
array of pointers is a pointer that points to another address.
The name of an array can be used as a pointer because it holds the address to
the first element of the array. If we store the address of an array in another
pointer, then it is possible to manipulate the array using pointer arithmetic.
Create an Array of Pointers:
To create an array of pointers in C language, you need to declare an array of

24
pointers in the same way as a pointer declaration. Use the data type then an
asterisk sign followed by an identifier (array of pointers variable name) with a
subscript ([]) containing the size of the array.
In an array of pointers, each element contains the pointer to a specific type.
Example of Creating an Array of Pointers
The following example demonstrates how you can create and use an array of
pointers. Here, we are declaring three integer variables and to access and use
them, we are creating an array of pointers. With the help of an array of
pointers, we are printing the values of the variables.

#include <stdio.h>

int main() {
// Declaring integers
int var1 = 1;
int var2 = 2;
int var3 = 3;
// Declaring an array of pointers to integers
int *ptr[3];
// Initializing each element of
// array of pointers with the addresses of
// integer variables
ptr[0] = &var1;
ptr[1] = &var2;
ptr[2] = &var3;

// Accessing values
for (int i = 0; i < 3; i++) {
printf("Value at ptr[%d] = %d\n", i, *ptr[i]);
}

return 0;
}
Output:
Value of var[0] = 1
Value of var[1] = 2
Value of var[2] = 3

25

You might also like