An array is a variable that holds a fixed number of elements with the same data type. Imagine simple variables as boxes and arrays as shelves.

Do you remember when we talked about variables?

I said that a variable is like a box, but instead of objects, it contains a value of a certain type.

As well, arraysalso called vectors, but I personally don’t like that name, because it creates confusion with vectors in game engines and 3D graphycsare similar to shelves.

arrays are shelves

 

As a shelf, an array holds multiple values, but all of them are of the same type.

OK, maybe a shelf doesn’t hold values, but books and stuff… D-D-Don’t mind… just… don’t

When you go to IKEA, or a carpenter if you don’t have any IKEA store near to you – I’m sorry if it’s that the case -, you can choose a shelf of specific size, where you can fit a limited amount of objects.

Obviously, a shelf that gets automatically bigger when you can’t fit other things on it doesn’t exist. That would be amazing.

All this was to explain that arrays have fixed size.

Defining an Array

To define an array, write this:

And to initialise it:

  • type of the array – and so of the values that it contains
  • name of the array
  • its size ( also called length ), inside square brackets

Do you remember when you were in school and you studied mathematical sets?

One of the ways to list the elements inside a set is to write them inside curly brackets, as it’s explained here.

Since arrays are just sets in maths, they follow the same rule.

It’s NOT:

Or:

But:

Because the first is a single value, the second one doesn’t have any sense – it’s just syntactically wrong – while the third is an assignment of a set to another – therefore it’s correct.

Do you know what’s really important to know about arrays?

You start counting elements from 0.

Zephyro, you wrote 4 inside the square brackets and you put 4 elements in it, why do you say that?

Inside an array

See? The array size is still 4, even if the major index is 3.

Said so, let’s move on to: how to access elements of an array.

Access Array Elements

You can access an element of an array using its index.

Basically the index of an element is its position in the array, counted starting form 0: if it’s the first element, its index is 0; for the second one, it’s 1 and so on and so forth.

Here’s the magic formula to access the first element:

It’s like accessing the value of a simple variable, but you also have to specify the element’s index inside square brackets.

At this point, you can do every operation with it: an array element is treated as a simple variable.

Assign values to elements

You can only assign values to elements, once the array is initialised.

In order to assign a value to an array element, access it as you’ve read previously, put the assignment sign and the new value after it and you get:

Syntax

To sum up, the syntax for defining and initialising an array is:

The syntax for accessing an element is:

Basic algorithms with arrays

There are 5 basic algorithms often used with arrays:

  • Traverse: prints all the elements of an array;
  • Insertion: adds a new element at a given index;
  • Deletion: removes an element from the array;
  • Copy: copies all the elements from an array to another;
  • Search: searches an element by its value;

Traverse

This is the most basic algorithm of the five.

In order to print all the elements of an array, the best strategy is to use a for loop, which goes through each index and prints the corresponding value.

Example:

Insertion

Since an array has a fixed length, to insert a new value without deleting the others we need two arrays – unless we use pointers and dynamic memory, but they aren’t topics for today.

  • array1: the initial array
  • array2: the final array
  • n: the initial length
  • item: the new element
  • pos: the new element’s position

Example:

This code copies every array1’s element after pos ( included ) in array2 in the next position – first for loop.

Then it copies all the others elements in the same indices – second for loop.

Finally it adds the new item at the given index – array2[pos] = item;

Some sites, such as TutorialsPoint, show algorithms that use just one array, but it just works with their online compiler, because:

  1. You can’t change the length of an array in C so easily
  2. I’ve tried it on Code::Blocks and it doesn’t work

Since their tutorial are usually good, at first I thought I had just discovered a hidden feature of C, but then it was just a delusion – such a thing would make C programming even simpler… now I’m sad.

Deletion

Since an array has a fixed length, to delete an element without leaving blank spaces we need two arrays – unless we use pointers and dynamic memory.

  • array1: the initial array
  • array2: the final array
  • n: the initial length
  • pos: the position of the element to remove

Example:

This code copies every array1’s element after pos ( included ) in array2 in the previous position – first for loop.

Then it copies all the others elements in the same indices – second for loop.

Copy

This is the second most basic algorithm of the five.

Since we can’t assign an array to another, we have to write a simple algorithm, which puts every elements from the first set to the second one

Example:

Search

There are a lot of ways to search a value in an array, but in this post we’re going to see only one of them.

If you want to know others, make sure to subscribe to our main newsletter at the home page: we’ll send you useful algorithms and other cool programming stuff directly into your inbox.

Example:

If i==n it means that the for loop has naturally exited, so the searched value wasn’t found.

Do you want to know more about linear search in C? Check this!

Tips and Tricks

  • If you don’t specify the size of an array, but you initialise it, the compiler will set the right size for you.
  • It isn’t necessary to set all the elements during the initialisation.

Let’s analyse the for loop in today’s program

Today’s program is pretty simple after you’ve read the rest of the article.

It just creates an array of 5 elements, it initialises it with some prime numbers of our ( my, until you don’t edit it. *whispers* Edit the examples ) choice and it prints them using the traverse algorithm.

int some_prime_numbers[5] = {2, 3, 5, 7, 11};

It defines ( int some_prime_numbers[5] ) an array called some_prime_numbers containing 5 elements of integer type.

Then it initialises it with a collection of 5 numbers ( 2, 3, 5, 7, 11 ), which have to be put between curly brackets, because they make up a set.

printf(“Some prime numbers:\n”);

It prints “Some prime numbers:” on the terminal and it moves the cursor to a new line.

If you want a deeper explanation check Make Your First C Program (+ Step-by-step explanation)

for(int i=0; i

It’s a loop goes through all the elements of the array, from 0 to 4.

The value of i is incremented at the end of each cycle.

When i reaches the value of 5, the program leaves the loop.

Check the previous post to learn more about for.

printf(“%d\t”, some_prime_numbers[i]);

It essentially prints the value of the element contained in some_prime_numbers at the index indicated by the current value of i in the loop.

For example, at the first cycle, the value of i is 0, so the first element of the array is printed – because the first element has index equals to 0, the second one has index equals to 1 and so on and so forth.

Code’s translation

Computer, this program uses the Standard IO library

Here’s the main body of the program

Create an array of 5 integer elements and set its initial values to 2, 3, 5, 7, 11

Print “Some prime numbers:” and go to a new line

Create a variable called i and set it to 0

Repeat the following instruction until i is less than 5 and increment the value of i at the end of each cycle

Print the value of the array element with index equal to the current value of i. Then move the cursor to the next tab stop.

Conclusion

To sum up: arrays are an important feature, not only of C, but of all high-level programming languages.

They allows you to simplify your program, removing all useless repetition.

In fact, without using them, a simple program 7 lines long would have become a giant piece of code, made up of 5 variable (instead of 1) and multiple printfs (instead of a single loop containing a single instruction).

Nevertheless, using arrays you can make your code modular.

For example, to print more values using today’s example program, you don’t have to write or copy/paste more lines of code, but just change two numbers: the 5 in the array definition and the other one in the loop.

If you haven’t yet, notice that arrays and for loops are best friends.

BUT HEY! Why don’t you write a comment below to let me know if there’s anything you want me to explain better?

Or perhaps share this to your friends, uncle or dog: they might want to learn programming with you! You find three sharing buttons below that’ll make your life easier… otherwise copy the link and send it to someone.

Anyway, the post is finished, have a good day and we will see next week!

From Zephyro it’s all, Bye!


Learn C programming: Strings and Characters | with Examples - Zephyro · 20 October 2018 at 5:10 PM

[…] → If you missed the previous article about arrays, click here […]

Leave a Reply

%d bloggers like this: