Arrays in C Programming - ProgrammerTech
Language:

Search

Arrays in C Programming

  • Share this:
Arrays in C Programming

Arrays in C language

Arrays are a set of data that are similar in type, whether they are texts, integer numbers, decimal numbers, fractional numbers, and one letter, and they have a common name. We format our code and put a large number of variables in it without any complexity, and we can access any element in this array and distinguish it by calling it its index.

 

One-dimensional arrays in C

One dimensional array We talked about variables in the previous lessons and said that the variable carries the value of a number or a letter or other, but what about several values? Can multiple sequential values ​​be defined in one variable? Yes, Arrays are the best way to define a variable that holds several values, let's remember a project for calculating a student's average.

The thing that will be difficult for us to store and use the values, what if the number of items is 20 items, will we define 20 different variables? Of course not, that's why Arrays exist, which greatly facilitates such cases.

We have learned that a variable reserves a specific place in memory, and its capacity depends on the type of data in which it is defined. Since it is only one location, it can only contain one value of the same type as the variable. As for the array, it reserves more than one location in the memory, according to what the programmer specifies. If an array has a capacity of 3, for example.

It can hold three different values, if it were an array of type int with a capacity of 3 for example. It can accommodate three different int values ​​as well, and of course we can retrieve values ​​from them or modify the values ​​in them.

The general formula for defining an array

int myArray[size];

whereas :

The int is to define the type of the array and here its type is an integer, it is the same way we define variables.

The myArray is the name of the array, just as we work with variables with the same conditions.

The [size] is the capacity of the array, we write it as a positive integer, and this is the difference between it and the normal variable, and this number will represent the array's capacity and size, and in the end a semicolon must be placed;.

 

Determining the initial values ​​of an array Array in C

You can also specify the initial values ​​of the array by placing an equal sign before the semicolon and then opening the bracket {. Then we specify the initial values ​​so that they are separated by a comma and in the end we close the curly brace and put a semicolon.

int myArray[size] = {4, 3, 7, ....etc};

In this example, the first value of the array will be 4, the second 3, the third 7, and so on....etc, and in the case of specifying initial values ​​for the array. There is no need to specify its size, the compiler or interpreter will set it according to the initial values.

Example

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
    int x[] = {1, 2, 3, 4, 5};
    return 0;
}

It is worth noting that when determining the amplitude of the array, the number of values ​​must match the amplitude. array, if the number of values ​​is greater than the specified capacity, the compiler will throw an error.

 

Retrieve values ​​from an array in C

In this section, we will learn how to define the values ​​of an array or change the values ​​in it. After defining the matrix we can define any of the . The values ​​contained within it by writing the name of the array and then open a square bracket and specify the location of the value to be determined from the array. Note that the counting starts from 0, not 1, that is, by writing the number 0, we modify the first value of the matrix and then close the square bracket.

int myArray[3];
myArray[0]

Now the process is more like setting a regular variable so we write an equals symbol followed by the value we want and then the semicolon. For example 16 ie the first value is 16 and the second value we don't know what it is because we didn't specify it. It may contain any random value depending on what you find in the memory location.

int myArray[3];
myArray[0] = 23;

If we want to modify the value after that, we do the same

int myArray[3];
myArray[0] = 23;
myArray[0] = 27;

Here the first value has been modified from 23 to 27.

 

How to retrieve a value from an array in C

We first write the name of the array and open a square bracket, then we write the location of the value we want to read. of the matrix so that the count starts from zero, 0. If we set zero, we read the first value from the matrix and then close the square bracket.

int myArray[3];
myArray[0]=16;
myArray[0];

Of course, so far we have not benefited from the value that we have read, we put it in a variable in order to benefit from it

int myArray[3]; 
myArray[0]=16; 
int x =myArray[0];

Now the value 16 has been copied to the variable x so we can use the values ​​in the array in any way we want (printing them on the screen or reading the values ​​and storing them in it).

 

How to deal with one-dimensional arrays

Let's imagine the following form of a matrix

int myArray[7]  = {2, 27, -26, -24, 0, 15, 12};

Required:

  1. Read the following value int x =myArray[0] What is the value stored in x?
  2. What is the value stored in int x =myArray[4]?
  3. What is the value stored in int x =myArray[8]?
  4. What is the value in the following:
myArray[2]=60;
int x = myArray[2];

solve the previous question

1- Here the stored value will be 2.

2- The stored value is 0.

3- In this case, we will run into a problem with two expected results, both of which are bad, either a random value is returned from memory. Depending on where we tried to read from x=-342354236. Or the program will stop working when it is running, and an error message will appear to the user indicating that we tried to access memory incorrectly. This is because we tried to read from a place that we didn't reserve, so the array has a size of 7 and we try to get to the ninth value in it and it's not defined and won't be reserved.

4- Here the value will be 60 because we have modified the value after defining the matrix, which is x=60 .

 

Multidimensional arrays in C

Multidimensional arrays, Today we will talk about multidimensional arrays, which are Array arrays that can take values ​​in more than one dimension. For example, two-dimensional matrices consisting of rows and columns can be imagined as similar to a table, and it is the two-dimensional matrices that we will cover in this lesson.

Example

Let's define an array consisting of four arrays, each of these arrays has three char values ​​and access the elements of some of the values ​​from the arrays to print abcd.

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
    char characters[4][3] = {{'a', 'g', 'c'},
                            {-2, 200, 'z'},
                            {'G', 'd', 'K'},
                            {-90, -1, 'b'}};
    printf("%c", characters[0][0]);
    printf("%c", characters[3][2]);
    printf("%c", characters[0][2]);
    printf("%c", characters[2][1]);

    return 0;
}

We have created an array named characters that contains four arrays and each array contains three different values. And we put within these values ​​characters as char in order to print them, and then we wrote the printf command and specified that we want to print char via the symbol %c. And we wrote the name of the array and the location of the character we want to print via the index. And the number 0 means the first matrix and zero the other 0 means the first value of it, and with the same thing we went to the fourth matrix, which has the index 3.

We chose the value number 2 from it and the same thing on the remaining two matrices and when printing the result will be abcd as follows

abcd

 

Using the array in a function

In our functions lesson, we learned how to pass values ​​to a function via so-called parameters. Can we pass an entire array to a function? Yes we can, of course. Arrays are passed in the same way we pass a regular variable. But the difference here is that we put an empty square bracket after the parameter name in order to inform the function that we want to pass an entire array and not a normal value.

void function(int y[])
{
    printf("%d", y[0]);
}

The problem is that C is not like other programming languages ​​that pass the array's capacity with the array so we can't know the array's capacity inside the function.

void function(int y[], int arraySize)
{
for(int i = 0; i < arraySize; i++)
    printf("%d", y[i]);
}

If we want to print all the values ​​of the matrix, how can we know the number of these values ​​in the first place, then the values ​​of the matrix can be anything. To solve this problem, we must manually pass the array's capacity as an int type and use it inside the function.

Example

#include <stdio.h>
#include <stdlib.h>
void adder(int numbers[], int size)
{
    int sum = 0;
    for(int i = 0 ; i < size; i++)
    {
        sum = sum + numbers[i];
    }
    printf("The sum of the values of the matrix= %d", sum);
}
int main(int argc, char** argv)
{
    int array[4] = {10, 20, 30, 40};
    adder(array, 4);
}

We have defined a function of type void and called it adder and this function receives an array of type int and the name of the array we called numbers. And because it is a matrix, we put square brackets [] in the parameters. We have sent the size of the array and we have made the type of the function void because our function will not return any value. And we have defined a variable inside this function called sum and its beginning is 0, and this variable will contain all the values ​​of this array and its initial value is 0 so that the sum is true.

We create a for loop to pass all the values ​​of the array, and we set i=0 and i less than the size of the array so we pass them in the parameters. We sum the sum with itself and the value inside the array and print the output into this function via printf and into the main function. And we defined an int array with a size of 4 and put several values ​​in it, then we called the adder function and passed the array we created and passed its size without any square brackets.

And we set the size of the array, and when we run the code, its result will be 100 as follows

The sum of the values of the matrix=100

If we want to pass a two-dimensional array, we must determine the amplitude of the sub-array by writing it in square brackets and it is worth noting that this is mandatory in this case.

void function(int y[][3], unsigned int arrarSiz)
{
.
}

Tags:
Saja Alsadig

Saja Alsadig

من السودان مبرمجة مواقع ويب و تطبيقات أندرويد اتقن لغات "html, css, php, js" بالإضافة للتعامل مع اندرويد ستوديو و بناء التطبيقات, مهتمة بمجال التقنية منذ الصغر و كان لدي شقف كبير للدخول بالجامعه بقسم البرمجة و دخلته في عام 2013 و تعلمت كل شيئ ضمن الجامعة و خارجها من التعليم الذاتي و اتمنى أن أكون عند حسن ظن الجميع و إيصال الأمانة لكم, اعمل حاليا في إدارة موقع جامعة السودان.