0% found this document useful (0 votes)
43 views10 pages

Understanding Arrays in C Language

Array in c details notes

Uploaded by

mauryaanjalivns
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)
43 views10 pages

Understanding Arrays in C Language

Array in c details notes

Uploaded by

mauryaanjalivns
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

Arrays in C Language

Introduc on

Managing large amounts of related data efficiently in any language is a common challenge, and
C is no excep on. This is where arrays in C programming come into play. They provide a
powerful way to group and handle mul ple values of the same type under one name.

What is Array in C Language?

An array in C is a collec on of mul ple values of the same data type stored together under a
single variable name. Instead of crea ng separate variables for each value, you can use an array
to store and manage them efficiently using index numbers.

These index numbers start from 0, allowing easy access to each element. Arrays are especially
useful when you need to work with lists, such as marks of students, temperatures, or items in a
menu.

Syntax of Array in C

The basic syntax for declaring an array in C is:

data_type array_name[array_size];

data_type: Type of data (e.g., int, float, char)

 array_name: Any valid iden fier

 array_size: Number of elements (must be a constant or macro)

Example:

Here’s how you declare different types of arrays:

int numbers[5]; // array of 5 integers

float scores[10]; // array of 10 floats

char le ers[26]; // array of 26 characters

Note: When you declare an array, memory is allocated for the specified number of elements.

Types of Arrays in C Language

There are three types of arrays in C programming:

1. One-Dimensional Array
A one-dimensional array in C is the simplest form of an array. It stores a list of elements of the
same data type in a single row (linear structure), accessed using a single index.

Declara on:

int numbers[5];

Ini aliza on:

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

Accessing Elements:

prin ("%d", numbers[2]); // Output: 30

Example:

#include <stdio.h>

int main() {

int marks[3] = {85, 90, 95};

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

prin ("marks[%d] = %d\n", i, marks[i]);

return 0;

2. Two-Dimensional Array

A two-dimensional array in C stores data in a table-like structure using rows and columns. It’s
o en used to represent matrices.

Declara on:

int matrix[2][3]; // 2 rows, 3 columns

Ini aliza on:

int matrix[2][3] = {

{1, 2, 3},

{4, 5, 6}

};
Accessing Elements:

prin ("%d", matrix[1][2]); // Output: 6

Example:

#include <stdio.h>

int main() {

int matrix[2][2] = {{10, 20}, {30, 40}};

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

for (int j = 0; j < 2; j++) {

prin ("matrix[%d][%d] = %d\n", i, j, matrix[i][j]);

return 0;

3. Mul -Dimensional Array

A mul -dimensional array in C contains more than two dimensions (like 3D or 4D arrays). These
are rarely used but helpful in special cases like 3D games or image processing.

Declara on:

int cube[2][2][2];

Ini aliza on:

int cube[2][2][2] = {

{{1, 2}, {3, 4}},

{{5, 6}, {7, 8}}

};

Accessing Elements:

prin ("%d", cube[1][0][1]); // Output: 6


Array Ini aliza on Techniques in C

When you declare an array in C, you can also assign values to it using different ini aliza on
methods. Let’s explore the common techniques:

1. Compile-Time Ini aliza on

You assign values to the array at the me of declara on.

Example:

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

 Values are stored in order.

 If fewer values are provided than the size, remaining elements are set to 0.

2. Ini aliza on Without Specifying Size

The compiler automa cally determines the size based on the number of elements.

Example:

int marks[] = {50, 60, 70}; // Array of size 3

 Useful for shorter code when you know the values.

3. Par al Ini aliza on

Only the first few elements are ini alized, rest are automa cally set to 0.

Example:

int data[4] = {9}; // {9, 0, 0, 0}

4. Zero Ini aliza on

You can explicitly ini alize all values to 0 using {0}.

Example:

int arr[5] = {0}; // All 5 elements set to 0

5. Run-Time Ini aliza on (Using Loops)

You can assign values to each element using a loop, especially when taking input from the user.

Example:

int n[3];
for (int i = 0; i < 3; i++) {

scanf("%d", &n[i]);

Examples of Arrays in C Language

1. Program to Print Elements of an Array

#include <stdio.h>

int main() {

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

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

prin ("Element %d: %d\n", i, numbers[i]);

return 0;

Explana on:

A simple loop is used to access and print each array element.

2. Program to Take Input in an Array and Print Sum

#include <stdio.h>

int main() {

int arr[5], sum = 0;

prin ("Enter 5 numbers:\n");

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

scanf("%d", &arr[i]);

sum += arr[i];

prin ("Sum = %d", sum);

return 0;
}

Explana on:

Takes user input into an array and calculates the total sum.

3. Program to Find Maximum Element in an Array

#include <stdio.h>

int main() {

int arr[5] = {11, 25, 9, 43, 31};

int max = arr[0];

for (int i = 1; i < 5; i++) {

if (arr[i] > max) {

max = arr[i];

prin ("Maximum element = %d", max);

return 0;

Explana on:

Iterates through the array and tracks the highest value.

4. Program to Reverse an Array

#include <stdio.h>

int main() {

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

prin ("Reversed array: ");

for (int i = 4; i >= 0; i--) {

prin ("%d ", arr[i]);

}
return 0;

Explana on:

Prints array elements in reverse order using a loop.

5. Program to Copy One Array to Another

#include <stdio.h>

int main() {

int original[5] = {3, 6, 9, 12, 15};

int copy[5];

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

copy[i] = original[i];

prin ("Copied array: ");

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

prin ("%d ", copy[i]);

return 0;

Explana on:

Uses a loop to copy elements from one array to another.

Character Arrays and Strings in C

A character array is a sequence of characters stored in con guous memory loca ons. In C,
strings are represented using character arrays terminated with a null character \0, which tells
the compiler where the string ends.

Declaring a Character Array (String)

Method 1: Using Character List: Must include \0 at the end to make it a valid string. Size must
be 1 more than the number of characters to accommodate the null terminator.
char name[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

Method 2: Using String Literal (Recommended): Automa cally adds \0 at the end. It has easier
and cleaner syntax.

char name[] = "Hello";

Ini alizing and Prin ng Strings

#include <stdio.h>

int main() {

char city[] = "Delhi";

prin ("City: %s", city); // Output: City: Delhi

return 0;

Reading Strings from User

Using scanf() (Stops at space)

char name[20];

scanf("%s", name);

Using fgets() (Reads full line including spaces)

fgets(name, 20, stdin);

Accessing Individual Characters

char str[] = "C Language";

prin ("%c", str[2]); // Output: L

Advantages of Arrays in C

 Efficient Data Storage: Arrays allow storing mul ple values of the same data type using a
single variable name.

 Indexed Access: Elements can be easily accessed, modified, or iterated using index
numbers (0-based indexing).

 Reduced Code Complexity: You don’t need to declare mul ple variables — one array
can hold hundreds of values.
 Easy Looping and Traversal: Arrays can be easily processed using loops (for, while),
making opera ons like prin ng, summing, or searching simpler.

 Improved Memory Management: Arrays use con guous memory, which helps in faster
data access and be er memory locality.

 Useful in Algorithms: Arrays are widely used in sor ng, searching, matrix opera ons,
and many algorithms.

 Founda on for Advanced Structures: Arrays form the basis of more advanced data
structures like strings, matrices, stacks, queues, and linked lists.

 Cleaner and Organized Code: Helps organize related data under a single name,
improving readability and maintainability.

Disadvantages of Arrays in C

 Fixed Size: Once declared, the size of an array cannot be changed during program
execu on.

 Sta c Memory Alloca on: Memory is allocated at compile me, which may lead to
inefficient memory usage if the size is too large or too small.

 No Bound Checking: C does not check whether an index is within array limits, which can
cause unexpected behavior or segmenta on faults.

 Only Homogeneous Data Types: Arrays can store elements of the same data type only
(e.g., all int or all char).

 No Built-in Dynamic Resizing: You cannot grow or shrink an array at run me without
using dynamic memory (malloc, realloc, etc.).

 No Built-in Inser on or Dele on: Inser ng or dele ng elements requires manual shi ing
of elements, unlike in higher-level data structures like lists.

 Wastage of Memory: If the allocated size is larger than needed, the unused memory is
wasted.

Uses and Applica ons of Arrays in C

 Storing Mul ple Values: To store a collec on of values (like marks, prices, or scores)
using a single variable name.

 Handling Tabular Data (2D Arrays): Arrays are used to represent matrices, tables, and
grids in a structured format.
 String Handling (Character Arrays): Arrays of characters (char[]) are used to store and
manipulate strings.

 Sor ng and Searching Algorithms: Arrays are essen al in implemen ng algorithms like
bubble sort, binary search, merge sort, etc.

 Loop-Based Opera ons: Arrays make it easy to perform repe ve opera ons on data
using loops.

 Storing Input Data: Arrays are commonly used to take mul ple inputs from the user and
store them temporarily.

 Mathema cal Computa ons: Arrays are used in vector and matrix calcula ons,
sta s cal analysis, and numeric simula ons.

 Buffer Handling: Arrays can be used as buffers for reading/wri ng data in file handling
and input/output opera ons.

 Simula ng Real-World Collec ons: Like storing student names, temperatures of the
week, scores in a game, etc.

 Implemen ng Data Structures: Arrays are the founda on of stacks, queues, heaps, and
hash tables.

 Storing Command Line Arguments: In main(int argc, char *argv[]), argv is an array of
strings passed from the command line.

You might also like