In this section, you will learn how to declare an array in C.
To declare an array in C, you have to specify the name of the data type and the number of elements inside the square brackets.
Syntax for creating an array
data_type [int size] varname;
If the the size is not defined a default size of the array is taken by the compiler which is sufficient for most purposes.
In the above declaration, the arr is the array of integer type. The values inside this array arr or any array can be accessed with the array indexes.
Syntax for accessing array value
With the above syntax value an array at index 2 will be accessed.
Similarly, you can declare the array of float type and char type. At the time of allocating values to arrays, the index reference always starts from 0 and counts till the n -1 th index. Here n is the size of the array.
In the example an array arr is created that has capacity of 5 elements to store from index 0 to 4. The maximum size of the above array is 5. The values of this array can be stored and accessed in the following way:
arr = 10;
arr = 20;
arr = 30;
arr = 40;
arr = 50;
Now for printing the array values, printf() function is used.
<stdio.h>- This is the header file which includes standard input/output functions to be used in your program. It is necessary to include a header file as it has some inbuilt functions like printf(), scanf() etc. The angle brackets are used to indicate system include files.
<conio.h>- Its a non standard header file which is used for clrscr(), getch() functions.
void main() - This is the main function which should be coded first. Compiler will look for the program stuff to compile inside this function first. main function has default return type as integer therefore in the program code an integer return statement needs to coded at the end of the program. But after writing void its return type becomes void. This means method will not return any value.
clrscr()- It is used to clear the console screen. Use of this function is optional.
getch()- This function reads each character. It holds the console screen and program output on it. Without this output on the screen will generate in flash and vanishes.
Here is the code:
Output will be displayed as:
We have 1000s of tutorials on our website. Search Tutorials tutorials on our website.
Posted on: February 5, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles