Array in C | Properties of Array | Declaration of Array | Initialization of Array

 

Array in C

An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number.

Array in C


An array is a collection of elements of the same data type, stored in contiguous memory locations. Each element in an array is accessed using an index, with the first element typically having an index of 0.

Here's an example of using a C array to store and display a list of integers:
c
#include <stdio.h> int main() { // Declare an integer array to store 5 numbers int numbers[5]; // Initialize the array with some values numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50; // Calculate the sum of the numbers in the array int sum = 0; for (int i = 0; i < 5; i++) { sum += numbers[i]; } // Display the elements and the sum printf("Array Elements: "); for (int i = 0; i < 5; i++) { printf("%d ", numbers[i]); } printf("\n"); printf("Sum of Array Elements: %d\n", sum); return 0; }
In this example:

1. We include the stdio.h header for input and output functions.

2. We declare an integer array named numbers that can hold 5 integers.

3. We initialize the array with values from 10 to 50.

4. We calculate the sum of the numbers in the array using a for loop.

5. We display the elements of the array and the sum using printf.

Output:

mathematica
Array Elements: 10 20 30 40 50 Sum of Array Elements: 150

Properties of Array in C
Arrays in C have several important properties:
  1. Fixed SizeOnce you declare an array in C, its size is fixed and cannot be changed during runtime. You must specify the size of the array when declaring it.

  2. Homogeneous ElementsAn array can hold elements of the same data type. For example, you can have an array of integers, characters, or any other data type, but all elements in the array must be of that type.

  3. Contiguous Memory AllocationArray elements are stored in contiguous memory locations. This means that the elements are stored one after the other in memory, which allows for efficient access and traversal.

  4. Zero-Based IndexingArray indices start from 0. The first element is at index 0, the second at index 1, and so on. The last element is at index size - 1, where size is the number of elements in the array.

  5. Compile-Time Sizing:In C, the size of the array is determined at compile time. This means that the size of the array must be known when you write your program, and it cannot be determined dynamically at runtime.

  6. Accessing ElementsYou can access array elements using square brackets and their indices. For example, myArray[0] accesses the first element of the array.

  7. Efficient for Random AccessArrays are efficient for random access to elements, meaning you can quickly access any element in the array by its index.

  8. Memory EfficiencyArrays are memory-efficient because they allocate a fixed block of memory for all elements. However, you should be careful about the array size, as it can lead to memory wastage if you allocate more memory than you need.

  9. Not Self-SizingArrays do not keep track of their size, so you need to manage the size separately. It's a common practice to store the size of the array in a separate variable.

  10. InitializationArrays can be initialized at the time of declaration or by assigning values to individual elements.

    Declaration of Array in C

    We can declare an array in the c language in the following way.

    Here's the basic syntax for declaring an array:
    c
    data_type array_name[array_size];

    Here are some examples of array declarations in C:

    c
    int numbers[5]; // Declares an integer array named "numbers" with 5 elements. char name[20]; // Declares a character array named "name" with space for 20 characters. double prices[10]; // Declares a double-precision floating-point array with 10 elements.
    You can also declare an array and initialize it with values at the same time. Here's an example:
    c
    int scores[3] = {85, 92, 78}; // Declares an integer array and initializes it with values.


    In this example, we've declared an integer array named "scores" with a size of 3 and initialized it with the specified values.

    It's important to note that you can omit the array size when initializing an array. The compiler will automatically determine the size based on the number of elements you provide in the initialization. For example:
    c
    int values[] = {10, 20, 30, 40, 50}; // The array size is determined automatically.


    In this case, the "values" array will have a size of 5 because there are five elements in the initialization list.

    Initialization of Array in C

    The simplest way to initialize an array is by using the index of each element. We can initialize each element of the array by using the index.

    Here are the two common ways to initialize a C array:

    1. Initialization during Declaration:

    You can provide the initial values for the array elements when you declare the array. This is done by enclosing the initial values within curly braces {} and specifying them in a comma-separated list. Here's an example:
    1. c
      int numbers[] = {1, 2, 3, 4, 5};


      In this example, an integer array named "numbers" is declared, and its elements are initialized with the values 1, 2, 3, 4, and 5. The size of the array is determined automatically based on the number of elements in the initialization list.

      If you want to explicitly specify the size, you can do it like this:
      c
      int numbers[5] = {1, 2, 3, 4, 5};
    2. Initialization after Declaration:You can also initialize array elements individually after declaring the array. Use the array name followed by square brackets [] and the index to specify the element you want to initialize. Here's an example:

    3. c
      int scores[3]; // Declare an integer array with space for 3 elements. scores[0] = 85; // Initialize the first element with the value 85. scores[1] = 92; // Initialize the second element with the value 92. scores[2] = 78; // Initialize the third element with the value 78.


      This approach is useful when you need to set values for array elements based on user input or dynamic calculations.C

      Array in C: Declaration with Initialization

      Here's how to declare an array with initialization:
      c
      data_type array_name[array_size];

      Here's an example:

      c
      #include <stdio.h> int main() { // Declare and initialize an integer array with values. int numbers[] = {10, 20, 30, 40, 50}; // Display the elements of the array. for (int i = 0; i < 5; i++) { printf("Element at index %d: %d\n", i, numbers[i]); } return 0; }
      In this example, we declare and initialize an integer array named "numbers" with 5 elements. We provide the initial values {10, 20, 30, 40, 50} during the declaration. Then, we use a for loop to display the elements of the array.

      Output:

      c
      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


      This demonstrates how to declare an array with initialization in C, making it easy to set initial values for the elements when you create the array.

      Array in C Example: Sorting an array

      In the following program, we are using bubble sort method to sort the array in ascending order.

      Here's an example of how to sort an array of integers in C using the bubble sort algorithm:
      c
      #include <stdio.h> void bubbleSort(int arr[], int size) { int temp; int swapped; do { swapped = 0; // Initialize the flag // Iterate through the array for (int i = 0; i < size - 1; i++) { // Compare adjacent elements if (arr[i] > arr[i + 1]) { // Swap elements if they are in the wrong order temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; swapped = 1; // Set the flag to indicate a swap occurred } } } while (swapped); // Continue until no more swaps are needed } int main() { int numbers[] = {64, 34, 25, 12, 22, 11, 90}; int size = sizeof(numbers) / sizeof(numbers[0]); printf("Original array: "); for (int i = 0; i < size; i++) { printf("%d ", numbers[i]); } printf("\n"); // Sort the array bubbleSort(numbers, size); printf("Sorted array: "); for (int i = 0; i < size; i++) { printf("%d ", numbers[i]); } printf("\n"); return 0; }


      In this example:

      1. We include the stdio.h header for input and output functions.

      2, The bubbleSort function takes an array of integers and its size as parameters and sorts the array in ascending order using the bubble sort algorithm.

      3. The main function declares an array of integers named "numbers" and calculates the size of the array.

      4. We display the original array.

      5. We call the bubbleSort function to sort the array.

      6. We display the sorted array.

      Output:

      c
      Original array: 64 34 25 12 22 11 90 Sorted array: 11 12 22 25 34 64 90


      This demonstrates how to sort an array of integers in ascending order using the bubble sort algorithm.

      Program to print the largest and second largest element of the array.

      Here's an example of how to do that:
      c
      #include <stdio.h> int main() { int array[] = {10, 30, 15, 40, 25, 50, 5}; int size = sizeof(array) / sizeof(array[0]); if (size < 2) { printf("Array is too small to find the second largest element.\n"); return 1; } int largest = array[0]; int secondLargest = array[0]; for (int i = 0; i < size; i++) { if (array[i] > largest) { secondLargest = largest; largest = array[i]; } else if (array[i] > secondLargest && array[i] < largest) { secondLargest = array[i]; } } printf("Largest element: %d\n", largest); printf("Second largest element: %d\n", secondLargest); return 0; }


      In this program:

      1. We declare an integer array array and find its size.

      2. We check if the array has at least two elements. If not, we print an error message and exit, as we need at least two elements to find the second largest.


      3. We initialize largest and secondLargest both to the first element of the array.

      4. We iterate through the array and compare each element to largest and secondLargest. If we find a new largest element, we update largest, and if we find a new second-largest element (but not the largest), we update secondLargest.


      5. Finally, we print the largest and second-largest elements.

      Output:

      c
      Largest element: 50 Second largest element: 40
      This program finds the largest and second-largest elements in the array, and it works for arrays of various sizes.

Post a Comment

0 Comments