0% found this document useful (0 votes)
13 views28 pages

Array in C

An array in C is a fixed-size collection of similar data types stored in contiguous memory locations, allowing for efficient data management. The document explains how to declare, initialize, access, and manipulate arrays, including their relationship with pointers and how to pass them to functions. It also covers important concepts such as array size, out-of-bounds access, and initialization behaviors.

Uploaded by

irfanazad18
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)
13 views28 pages

Array in C

An array in C is a fixed-size collection of similar data types stored in contiguous memory locations, allowing for efficient data management. The document explains how to declare, initialize, access, and manipulate arrays, including their relationship with pointers and how to pass them to functions. It also covers important concepts such as array size, out-of-bounds access, and initialization behaviors.

Uploaded by

irfanazad18
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
You are on page 1/ 28

ARRAY IN C

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., as well as derived and user-defined data types such as pointers, structures, etc

Creating an Array in C
The whole process of creating an array in C language 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.
data_type array_name[size];
The above statements create an array with the name array_name, and it can store a
specified number of elements of the same data type.
Example:
// Creates array arr to store 5 integer values.
int arr[5];
When we declare an array in C, the compiler allocates the memory block of the specified
size to the array name.

Linkedin@KeerthanaGaliveeti
2. 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 values.
Syntax:
int arr[5] = {2, 4, 8, 12, 16};
The above statement creates an array arr and assigns the values {2, 4, 8, 12, 16} at the time
of declaration.
We can skip mentioning the size of the array if declaration and initialisation are done at the
same time. This will create an array of size n where n is the number of elements defined
during array initialisation. We can also partially initialize the array. In this case, the
remaining elements will be assigned the value 0 (or equivalent according to the type).

//Skiping the size of the array.


int arr[] = {2, 4, 8, 12, 16};

Linkedin@KeerthanaGaliveeti
//Partial Initialisation
int arr[5] = {2, 4, 8};

1/3

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.
Syntax:
The index values start from 0 and goes up to array_size-1. We pass the index inside square
brackets [] with the name of the array.
Linkedin@KeerthanaGaliveeti
array_name [index];
where, index value lies into this range - (0 ≤ index ≤ size-1).

Example:

#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

//initialize an array with all elements set to 0.


int arr[5] = {0};

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

Linkedin@KeerthanaGaliveeti
Update Array Element
We can update the value of array elements at the given index i in a similar way to accessing
an element by using the array square brackets [] and assignment operator (=).
array_name[i] = new_value;
Example:

#include <stdio.h>

int main() {
int arr[5] = {2, 4, 8, 12, 16};

// Update the first value


// of the array
arr[0] = 1;
printf("%d", arr[0]);
return 0;
}

Output
1

C Array Traversal
Array Traversal is the process in which we visit every element of the array in a specific
order. For C array traversal, we use loops to iterate through each element of the array.

Traversing
An Array
Example:

Linkedin@KeerthanaGaliveeti
#include <stdio.h>

int main() {
int arr[5] = {2, 4, 8, 12, 16};

// Print each element of


// array using loop
printf("Printing Array Elements\n");
for(int i = 0; i < 5; i++){
printf("%d ", arr[i]);
}
printf("\n");
// Printing array element in reverse
printf("Printing Array Elements in Reverse\n");
for(int i = 4; i>=0; i--){
printf("%d ", arr[i]);
}
return 0;
}

Output
2 4 8 12 16

Size of Array
The size of the array refers to the number of elements that can be stored in the array. The
array does not contain the information about its size but we can extract the size using
sizeof() operator.
Example:

#include <stdio.h>

int main() {
int arr[5] = {2, 4, 8, 12, 16};

// Size of the array


int size = sizeof(arr)/sizeof(arr[0]);
printf("%d", size);
return 0;
}
The sizeof() operator returns the size in bytes. sizeof(arr) returns the total number of bytes
of the array. In an array, each element is of type int, which is 4 bytes. Therefore, we can
calculate the size of the array by dividing the total number of bytes by the byte size of one
element.
Note: This method only works in the scope in which the array is declared. Refer to this article
to know more - Length of Array in C

Arrays and Pointers


Linkedin@KeerthanaGaliveeti
Arrays and Pointers are closely related to each other such that we can use pointers to
perform all the possible operations of the array. The array name is a constant pointer to the
first element of the array and the array decays to the pointers when passed to the function.

#include <stdio.h>

int main() {

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


int* ptr = &arr[0];

// Address store inside


// name
printf("%p\n", arr);

// Print the address which


// is pointed by pointer ptr
printf("%p\n", ptr);
return 0;
}

Output
0x7ffde73e54b0
0x7ffde73e54b0
To know more about the relationship between an array and a pointer, refer to this article
- Pointer to an Arrays | Array Pointer.
Passing Array to Function
In C, arrays are passed to functions using pointers, as the array name decays to a pointer to
the first element. So, we also need to pass the size of the array to the function.
Example:

#include <stdio.h>S

// Functions that take array as argument


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

int main() {
int arr[] = {2, 4, 8, 12, 16};
int n = sizeof(arr) / sizeof(arr[0]);

Linkedin@KeerthanaGaliveeti
// Passing array
printArray(arr, n);
return 0;
}

Output
2 4 8 12 16
int arr[5]={1,2,4,8,7};

now we want to calculate the number of element present in that array

memory size of arr:- 5*4=20

each integer have 4 byte and we have 5 elements.

let n store number of element in a giver array or size of array.

so

sizeof(arr)=20

and

sizeof(arr[0])=4

nt n = sizeof(arr)/size of (arr o])

n=20/4

n=5

number of element present in array =5

1. What is an array in C?

✅ Answer:
An array in C is a collection of fixed-size elements of the same data type, stored in contiguous memory
locations.
It allows storing multiple values under one name and accessing them using indexing.

Example:

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

 marks is the name of the array.


 marks[0] is 10, marks[1] is 20, and so on.

📌 Internally:
If base address is 1000 (and size of int = 4 bytes), then:
Linkedin@KeerthanaGaliveeti
 marks[0] → 1000
 marks[1] → 1004
 marks[2] → 1008 ... and so on

2. How do you declare an integer array of size 5?

✅ Answer:

c
CopyEdit
int arr[5];

This declares an array named arr that can store 5 integers.

You can also write:

c
CopyEdit
int arr[] = {1, 2, 3, 4, 5}; // compiler infers size = 5

💡 Tip: Always ensure the size is a constant integer (except in C99+ where VLAs are allowed).

3. What is the index of the first element in an array?

✅ Answer:
In C, arrays are zero-indexed, meaning the first element starts at index 0.

So for int a[3] = {10, 20, 30};, we have:

 a[0] = 10
 a[1] = 20
 a[2] = 30

Trying to access a[3] is an out-of-bound access and causes undefined behavior.

4. Can you change the size of an array once declared?

✅ Answer:
No. In C, once you declare an array with a fixed size, you cannot change it at runtime.

c
CopyEdit
int arr[5]; // size is fixed at compile-time

If you need dynamic sizing, use dynamic memory allocation with malloc() or use Variable Length Arrays
(C99+):

c
Linkedin@KeerthanaGaliveeti
CopyEdit
int n;
scanf("%d", &n);
int arr[n]; // VLA - Valid in C99 or newer

5. How to initialize an array at the time of declaration?

✅ Answer:

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

You can also partially initialize:

c
CopyEdit
int arr[5] = {1, 2}; // remaining elements = 0

If you leave size empty:

c
CopyEdit
int arr[] = {1, 2, 3}; // compiler assigns size = 3

🛑 Note: Uninitialized arrays may contain garbage values.

6. What happens if you access an out-of-bound index?

✅ Answer:
Accessing beyond the defined size of an array leads to undefined behavior.
The program might:

 Crash (Segmentation fault)


 Print garbage values
 Overwrite adjacent memory

Example:

c
CopyEdit
int arr[3] = {1, 2, 3};
printf("%d", arr[5]); // Undefined behavior

👉 Compiler might not give an error, but it’s a logic error and dangerous.

7. What is the output of this?


c
CopyEdit
Linkedin@KeerthanaGaliveeti
int arr[5] = {1, 2};
printf("%d", arr[3]);

✅ Answer:
Output: 0

Explanation:

 arr[0] = 1
 arr[1] = 2
 arr[2], arr[3], arr[4] are auto-initialized to 0

This works only for global or static arrays.


For local arrays, uninitialized values may be garbage unless explicitly initialized.

8. Can array size be a variable in C?

✅ Answer:
Yes, in C99 and newer, you can declare Variable Length Arrays (VLAs).

c
CopyEdit
int n;
scanf("%d", &n);
int arr[n]; // valid in C99+

However, older C versions (C90) do not support VLAs. For dynamic sizes, use malloc():

c
CopyEdit
int *arr = (int *)malloc(n * sizeof(int));

9. How do you access the last element of a size 5 array?

✅ Answer:

c
CopyEdit
int arr[5] = {1, 2, 3, 4, 5};
printf("%d", arr[4]); // last element

You can also use:

c
CopyEdit
printf("%d", arr[sizeof(arr)/sizeof(arr[0]) - 1]);

sizeof(arr)/sizeof(arr[0]) gives total elements.

10. How do you input values into an array using a loop?


Linkedin@KeerthanaGaliveeti
✅ Answer:

c
CopyEdit
int arr[5];
for (int i = 0; i < 5; i++) {
scanf("%d", &arr[i]);
}

This is a standard input method. Ensure the loop doesn’t exceed the declared size of the array.

💡 Use functions like:

c
CopyEdit
void inputArray(int arr[], int size) {
for (int i = 0; i < size; i++)
scanf("%d", &arr[i]);
}

Arrays in C - 30 Questions with Detailed Answers

**1. What is an array in C?**


An array in C is a collection of fixed-size elements of the same data type, stored in contiguous memory
locations. It allows storing multiple values under one name and accessing them using indexing.

For example, if you want to store 5 integers like 10, 20, 30, 40, 50, instead of declaring 5 separate
variables, you can use:

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

This simplifies both storage and access. Internally, the array elements are laid out in consecutive
memory addresses. If `marks[0]` is at memory address 1000 and `int` takes 4 bytes, then `marks[1]` is at
1004, `marks[2]` at 1008, and so on.

**2. How do you declare an integer array of size 5?**


You can declare an array of 5 integers using:

```c
Linkedin@KeerthanaGaliveeti
int arr[5];
```

This creates space for 5 integers, each of 4 bytes (typically), totaling 20 bytes. You can also initialize
during declaration:

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

The compiler will count the elements and set the array size automatically.

**3. What is the index of the first element in an array?**


In C, array indexing starts at 0. So, the first element is accessed using index 0. For example:

```c
int arr[3] = {10, 20, 30};
printf("%d", arr[0]); // prints 10
```

This indexing scheme simplifies pointer arithmetic and is consistent with most C operations.

**4. Can you change the size of an array once declared?**


No, the size of an array is fixed at compile time in traditional C. You cannot change it during runtime.
For dynamic sizes, use pointers with dynamic memory allocation:

```c
int *arr = malloc(n * sizeof(int));
```

This allows flexibility, but you must manage memory manually using `free()`.

**5. How to initialize an array at the time of declaration?**


Linkedin@KeerthanaGaliveeti
Arrays can be fully or partially initialized:

```c
int arr[5] = {1, 2, 3, 4, 5}; // full initialization
int arr[5] = {1, 2}; // rest become 0
int arr[] = {1, 2, 3}; // compiler sets size = 3
```

Uninitialized local arrays contain garbage values; global or static arrays are zero-initialized by default.

**6. What happens if you access an out-of-bound index?**


Accessing an index outside the declared range is undefined behavior. The program might:

* Crash (segmentation fault)


* Return a garbage value
* Overwrite adjacent memory (corruption)

```c
int arr[3] = {1, 2, 3};
printf("%d", arr[5]); // undefined behavior
```

Always ensure loop boundaries are valid.

**7. What is the output of:**

```c
int arr[5] = {1, 2};
printf("%d", arr[3]);
```

Output: `0` (if global or static array)

Linkedin@KeerthanaGaliveeti
In local scope, this may return a garbage value since only `arr[0]` and `arr[1]` are initialized. In
global/static scope, the remaining elements default to 0.

**8. Can array size be a variable in C?**


Yes, in C99 and above, you can use Variable Length Arrays (VLAs):

```c
int n;
scanf("%d", &n);
int arr[n];
```

This is not allowed in C90. For portability or dynamic needs, use `malloc()`:

```c
int *arr = malloc(n * sizeof(int));
```

**9. How do you access the last element of a size 5 array?**


Use:

```c
arr[4];
```

or more generally:

```c
arr[size - 1];
```

To compute size at runtime:

Linkedin@KeerthanaGaliveeti
```c
int size = sizeof(arr) / sizeof(arr[0]);
```

**10. How do you input values into an array using a loop?**

```c
int arr[5];
for (int i = 0; i < 5; i++) {
scanf("%d", &arr[i]);
}
```

This is the standard way to read values into an array. The loop ensures each index receives input.

(Intermediate and Advanced sections to be similarly expanded...)

**11. How do you find the length of an array?**

In C, for statically declared arrays:

```c

int arr[10];

int length = sizeof(arr) / sizeof(arr[0]);

```

`sizeof(arr)` gives total size in bytes, and `sizeof(arr[0])` gives size of one element. This only works inside

the scope where the array is declared.

For dynamically allocated arrays, you must track the size separately since `sizeof` won't work.

Linkedin@KeerthanaGaliveeti
**12. Can arrays be passed to functions? How?**

Yes. Arrays decay into pointers when passed to functions.

```c

void printArray(int arr[], int size)

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

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

```

Inside the function, `arr` behaves like a pointer. It does not carry size info, so size must be passed

separately.

**13. What is the difference between arr[] and *arr in function parameters?**

Functionally, both are equivalent:

```c

void func(int arr[]);

void func(int *arr);

```

Inside the function, `arr[i]` is interpreted as `*(arr + i)`. The difference is mostly syntactic.

**14. Can you return an array from a function?**

Directly returning an array is not allowed. But you can:

1. Return a pointer to a dynamically allocated array

2. Pass an array to be modified inside the function

Example using dynamic allocation:

```c

Linkedin@KeerthanaGaliveeti
int* createArray(int size) {

int* arr = malloc(size * sizeof(int));

return arr;

}```

Be sure to free the memory after use.

Linkedin@KeerthanaGaliveeti
**15. How are arrays stored in memory?**

Arrays are stored in contiguous memory locations. For example:

```c

int arr[3] = {10, 20, 30};

```

If `arr[0]` is at address 1000 and `int` takes 4 bytes, then:

- `arr[1]` is at 1004

- `arr[2]` is at 1008

This layout enables pointer arithmetic like `*(arr + i)`.

**16. How do you reverse an array?**

```c

void reverse(int arr[], int size) {

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

int temp = arr[i];

arr[i] = arr[size - 1 - i];

arr[size - 1 - i] = temp;

```

This swaps elements from both ends moving inward.

**17. What is the difference between static and dynamic arrays?**

- **Static arrays**: Size fixed at compile-time.

```c
Linkedin@KeerthanaGaliveeti
int arr[10];

```

Linkedin@KeerthanaGaliveeti
- **Dynamic arrays**: Size decided at runtime using `malloc()` or `calloc()`.

```c

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

```

Static arrays are easier but less flexible. Dynamic arrays are flexible but need manual memory

management.

**18. How do you copy one array to another?**

Use a loop:

```c

for (int i = 0; i < size; i++)

dest[i] = src[i];

```

Or use `memcpy`:

```c

memcpy(dest, src, size * sizeof(int));

```

Make sure destination has enough space.

**19. How do you sort an array in C?**

Use the C standard library function `qsort()`:

```c

int compare(const void *a, const void *b) {

return (*(int*)a - *(int*)b);

}qsort(arr, size, sizeof(int), compare);

Linkedin@KeerthanaGaliveeti
This performs a quicksort based on your comparison logic.

**20. What is the use of `const` with arrays?**

Declaring an array parameter as `const` ensures it can't be modified inside the function:

```c

void print(const int arr[], int size);

```

This is good practice when the function is only meant to read the array.

**21. What are multi-dimensional arrays?**

These are arrays of arrays. Example:

```c

int matrix[3][4];

```

This declares a 2D array with 3 rows and 4 columns. Access using:

```c

matrix[0][2];

```

Internally stored in row-major order.

**22. How to pass a 2D array to a function?**

```c

void display(int arr[][COLS], int rows);

Linkedin@KeerthanaGaliveeti
```

Number of columns must be specified so the compiler knows the layout. Alternatively:

```c

void display(int (*arr)[4], int rows);

```

**23. What is the difference between array of pointers and pointer to an array?**

- Array of pointers:

```c

int *arr[5];

```

Each element is a pointer.

- Pointer to array:

```c

int (*ptr)[5];

```

Pointer to entire array of 5 integers.

**24. How can you use pointers to access array elements?**

```c

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

int *p = arr;

printf("%d", *(p + 2)); // 30

```

Linkedin@KeerthanaGaliveeti
This is equivalent to `arr[2]`. Arrays and pointers are closely related.

**25. What is array decay in C?**

Linkedin@KeerthanaGaliveeti
When passed to a function, arrays decay to pointers:

```c

void func(int arr[]); // actually int *arr

```

Size information is lost, so pass it explicitly.

**26. Can arrays be initialized at runtime?**

Not static arrays. For runtime initialization:

```c

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

```

Use loops or input functions to assign values.

**27. What are jagged arrays?**

C doesn't support jagged arrays natively (arrays with rows of different lengths). But you can simulate

them using an array of pointers:

```c

int *arr[3];

arr[0] = malloc(2 * sizeof(int));

arr[1] = malloc(3 * sizeof(int));

```

Each row can have different length.

**28. What is the role of `sizeof` in arrays?**

`sizeof` helps determine:

Linkedin@KeerthanaGaliveeti
- Total size: `sizeof(arr)`

- Element size: `sizeof(arr[0])`

Linkedin@KeerthanaGaliveeti
- Number of elements: `sizeof(arr) /

sizeof(arr[0])` Works only in scope

where array is declared.

**29. How to find the sum of array elements?**

```c

int sum = 0;

for (int i = 0; i

< size; i++)

sum +=

arr[i];

```

Can be extended to calculate average:

```c

double avg = (double)sum / size;

```

**30. How to find the maximum and minimum elements in an array?**

```c

int max = arr[0],

min = arr[0]; for

(int i = 1; i < size;

Linkedin@KeerthanaGaliveeti
i++) {

if (arr[i] >

max) max =

arr[i]; if

(arr[i] < min)

min = arr[i];

Linkedin@KeerthanaGaliveeti

You might also like