27666 total geeks with 3538 solutions
Recent challengers:
 Welcome, you are an anonymous user! [register] [login] Get a yourname@osix.net email address 



User's box

Forgot password?
New account

<ul><li><str ong><a href="http:/ /www.tiffany blue.co/">ti ffany and co outlet</a></ strong> </li ><li><strong ><a href="http:/ /www.tiffany blue.co/">ti ffany blue</a></st rong> </li>< li><strong>< a href="http:/ /www.tiffany blue.co/">ti ffany outlet</a></ strong> </li >
<strong><a href="http:/ /www.pens74. ru/">montbla nc pen</a></str ong> | <strong><a href="http:/ /www.pens74. ru/">montbla nc pen</a></str ong> | <strong><a href="http:/ /www.pens74. ru/">mont blanc</a></s trong> <br> <title>Montb lanc Meisterstuck Carbon &amp; S
<strong><a href="http:/ /www.tiffany andcosilver. com/">tiffan y blue</a></st rong> <br> <strong><a href="http:/ /www.tiffany andcosilver. com/">tiffan y blue</a></st rong> <br> <strong><a href="http:/ /www.tiffany andcosilver. com/">tiffan y outlet</a></ strong> <br> <
<ul><li><str ong><a href="http:/ /www.yxypd.c om/">swiss Mechanical movement replica watches</a>< /strong> </l i><li><stron g><a href="http:/ /www.yxypd.c om/">watches price</a></s trong> </li> <li><strong> <a href="http:/ /www.yxypd.c om/">best replica watches</a>< /s
<strong><a href="http:/ /watches.wed dingdresstre nd.org/">hig h quality swiss replica watches</a>< /strong> | <strong><a href="http:/ /watches.wed dingdresstre nd.org/">wat ches</a></st rong> | <strong><a href="http:/ /watches.wed dingdresstre nd.org/">swi ss Mechan

Donate and help us fund new challenges
Due Date: Oct 31
October Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00

News Feeds
The Register
can hack
smartphones, says
Snowden. Again.
Potent OWA backdoor
scores 11,000
corporate creds
from single biz
used by PRINCESS
LEIA sold for just
Cisco reforms its
security disclosure
NoSQL pioneer Basho
stamps its mark on
time stamp data
with Riak TS
Linux kernel dev
who asked Linus
Torvalds to stop
verbal abuse quits
over verbal abuse
Quantum Pentium
appears on the
Google bugle sounds
patch release for
Android Stagefright
If you wanted
Windows 10, it
looks like you"ve
already installed
Fast, wireless
access to Tor? Just
EFF Joins Nameless
Coalition and
Demands Facebook
Kills Its Real
Names Policy
London Mayor Boris
Johnson Condemns
Random Uber
Space Travel For
the 1%: Virgin
Galactic"s $250,000
Tickets Haunt New
Mexico Town
What Effect Will
VW"s Scandal Have
On Robocars?
Study Finds Humans
Are Worse Than
Radiation For
Chernobyl Animals
DNA Vaccine
Sterilizes Mice,
Could Lead To
One-Shot Birth
Control For Cats,
What Non-Geeks Hate
About the Big Bang
Ask Slashdot: What
Is Your Most
Awesome Hardware
Linux Kernel Dev
Sarah Sharp Quits,
Citing "Brutal"
CodeWeavers To
Release CrossOver
For Android To Run
Windows Programs
Article viewer

Arrays in C: A simple example for beginners

Written by:dimport
Published by:Nightscript
Published on:2003-06-21 07:19:46
Search OSI about C.More articles by dimport.
 viewed 32639 times send this article printer friendly

Digg this!
    Rate this article :
A basic explanation of arrays in C.
Any comments, add-ons are more than awaited, as I am eager to get all the input from more experienced folks like you all.

I specifically want to mention, this is what I learn in C, (NOT C++, NOT C#).


Character Arrays: Lists of Characters

C is one of the few programming languages that does NOT HAVE STRING VARIABLES.
Although C doesn't have string variables, there is a way to store string data.
Despite the efficiency obtained by not supporting string
variables, programmers can't give up being able to store character string data. Therefore, C offers character arrays that hold several characters of data in string-like form.

"Character arrays" hold strings in memory.

An array is nothing more than a list of variables of the same data type.
Before you use a character array to hold a string, you must tell C that you need a character array in the same place you would tell C that you need any other kind of variable.

char month[10]; /* Defines a character array */

*** The String Terminator (null zero)***

C does the strangest things to strings: It adds a zero to the end of every string.
C marks the end of all strings with the string-terminating zero. The string terminator is sometimes called because you represent the null zero by enclosing in single quotes. Therefore, '0' is the character zero, and '' is the string terminator.

ex: c | r | a | z | y | |

As you can see, the string "crazy" takes 6 bytes to store the string, even though the string has only five letters. The null zero that is part of the string "Crazy" takes one of those six memory locations. The null zero is never counted when determining the length of a string.

Clue: All single characters of data have a length of one. Therefore, both 'X' and "X" have lenghts of one, but the "X" consumes two characters of memory because of its null zero. Any time you see a string literal enclosed in quotation marks, picture in your mind that terminating null zero at the end of that string in memory.


char month[10] = "January"

[0][1][2][3][4][5][6][7][8][9] --> subscripts

J a n u a r y ? ?

Each individual piece of an array is called "element".
The month array has 10 elements. You distinguish between them with subscripts.
Subscripts are numbers that you specify inside the brackets that refer to each of the array elements.

Each of the elements in a character array is a character.
The combination of characters -- the array or "list" of
characters -- holds the entire string. In a way, an character array is made of several character variables of the same type holding together, thus forming a string.

month[0] = 'M';

month[1] = 'a';

month[2] = 'r';

month[3] = 'c';

month[4] = 'h';

month[5] = '';

Printing strings in arrays is easy: use the %s conversion character:
printf(" The month is %s", month); If you define an array and initialize the array at the same time, you don't have to put the number in brackets.

Both of the following do exactly the same thing:

char month[8] = "January";


char month[] = "January";

In the SECOND example, C counts the number of characters
in January and adds one for the null zero. You won't be able to store a string larger than eight characters later, however. If you want to define a string's character array and initialize it but leave extra padding for a longer string later, you could do this:

char month[25] = "January"; /*Leaves room for longer strings */

final example:

/* Stores the days of the week in seven different character arrays */
char day1[7] = "Sunday";
char day2[7] = "Monday";
char day3[8] = "Tuesday";
char day4[10] = "Wednesday";
char day5[] = "Thursday";
char day6[] = "Friday";
char day7[] = "Saturday";
char myName[5];
strcpy(myName, "Azar");

**When you want to store string data, define character
arrays as shown here.

**You must add brackets after the variable names or C will
think you are defining single-character variables.

**Always reserve enough for the null zero that terminates
every string.

**If you assign a string to the array when you define
the array, you don't have to count the number of characters and add one for the null zero.

**The last three day variables do not include the total
number of characters because C is able to count the number needed to hold the data being assigned.

**Finally, if you want to define an array without
assigning data, as done in the "myName" array, you must
include the maximum number of elements when you define
the array. You then can use strcpy() to assign a string
value to the array.


Numbers in Arrays

As you have seen, an array of CHARACTERS is just a list of characters that has a name.
Similarly, an array of INTEGERS is just a list of integers that has a name, and an array of FLOATING-POINT values is just a list of floating-point values that has a name.
Instead of referring to each of the array elements by a different name, you only have to refer to them by the array name and distinguish them with a subscript enclosed in brackets.

To make a short review:

All arrays contain values called "elements".
An array can contain "only" elements that are of the
same type. In other words, you can't have an array that
has a floating-point value, a character value, and an
integer value. To define an array, you must add brackets ([ ]) after the name and specify the maximum number of elements that you will ever store in array:

int i[25]; /* Defines the array */

The following statement both defines an integer array and initializes it with five values:

int vals[5] = { 10, 40, 70, 90, 120};


No "null zero" is at the end of the array because null


10 | vals[0]
40 | vals[1]
70 | vals[2]
90 | vals[3]
120 | vals[4]

The first subscript of all C arrays begins at 0.

int nums[4] = {5, 1, 3, 0};

There is NOT a "null zero" at the end of nums!
Be careful, nums is not a character array, and a string
is not being stored there. The zero at the end of the array is a regular numeric zero.


Always specify the number of subscripts when you define
an array!(we are talking now about Numbers in Arrays)
There is one exception to this rule, however: If you
assign an initial value or set of values to the array AT
THE TIME YOU DEFINE THE ARRAY, you can leave the brackets empty:


int ages[5] = {5, 27, 40, 65, 92}; /* Correct */
int ages[]; /* Incorrect */
int ages[] = {5, 27, 40, 65, 92}; /* Correct */


( sizeof() returns the number of BYTES you reserved for
the array, NOT the number of ELEMENTS in which you have
stored a value.

For example, if floating-point values consume 4 bytes on
your computer, an 8-element floating-point array will
take a total of 32 bytes of memory, and 32 is the value
returned if you apply sizeof() to the array after you deifne the array ) If you don't initialize an array, C won't either. Until you put values into an array, you have no idea exactly what's in the array.

The only exception to this rule is that most C compilers zero out all elements of an array if you initialize at least one of the array's values when you define the array.
Clue: If you want to zero out every element of an array,
you can do so with a shortcut that C provides:

float amount[100] = {0.0}; /* Zeroes-out all of the
array */

..because one value was stored in amount's first element's position and C filled in the rest with zeros.

(Even if the first elements were initialized with 123.45, C would have filled the remaining elements with zeros.)

Putting Values in Arrays:

You don't allways know the contents of an array at the
time you define it. Often, array values come from a disk file, calculations,
or a user's input. CHARACTER arrays are easy to fill with strings because C
supplies the strcpy() function.

OTHER TYPES of arrays need to be filled a single element
at a time. There is no shortcut function, such as strcpy(), that puts lots of integers or floating-point values in an array.
The following code defines an array of integers and asks
the user for values that are stored in that array.
Array elements, unlike regular variables that all have
different names, are easy to work with because you can
use a loop to count the subscripts, as done here:

 int ages[3];
for (i = 0; i < 3; i++)
{ printf("What is the age of child #%d?", i+1);
scanf(" %d", &ages[i]); /* Gets next age from user */


Final review:

An array is nothing more than a bunch of variables.
Each variable has the same name (the array name).
You distinguish between the variables in the array (the array "elements") with a numeric "subscript". The first array element has a subscript of 0, and the rest count up from
there. Arrays are characterized by brackets that follow the
array names.

The array subscripts go inside the brackets when you need to refer to an individual array element.

code example:

 int i;
float grades[10]; /* Creates the array */
float avg = 0;
for (i = 0 ; i < 10; i++)
{ printf("What is student number %d's grade?", i+1);
scanf(" %f", &grades[i]); /* Gets each grade from
                                      teacher */
avg += grades[i]; /* Adds to total scores */
avg /= 10; /* Computes average */
printf("The average of all grades is %.2f.", avg);

This code first creates work variables that hold an integer counter for the "for" loop -- the grades array that will hold 10 grades -- and the floating-point variable "avg" that will hold the average of those grades. The program then asks the teacher for each of the 10 students' grades in the "for" loop.

The last statement in the loop adds each grade to a running total of the grades.
The total variable, named "avg", is finally divided by 10 at the end of the program to hold the average of the grades.


All the text and examples here were picked from the book
"Absolute beginner's Guide to C" by Greg Perry

This article was originally written by Azar

Did you like this article? There are hundreds more.

2007-06-12 21:38:20
How do I solve this, Using the term COLOR(1), distinguish between an array name, a sub-script, and a subscripted variable name.
2007-09-09 00:00:03
Why do array subscripts in C always begin with zero?
2009-07-21 12:17:01
Can you plz explain how do I solve this, Using the term COLOR(1), distinguish between an array name, a sub-script, and a subscripted variable name.i would like to know because i started learning programming as previously i was in the business of managed dedicated hosting and auction image hosting services in my area then i start streaming video web hosting services at affordable price but now i want to change my line and will learn from you.
2009-12-18 16:10:04
Both binary and decimal system start with symbol 0. That is, 0,1 are basic (atomic) symbols in binary arithmetic. {0,1,2...9} are ten basic symbols in decimal system. Unfortunately, we do not teach in your early childhood, so you expect number 1 to be the first element. C stores the address in binary encoded format thus always start with 0(zero). Also, maths subscript start from zero too.
2011-05-17 06:02:07
I am wondering if someone could look over this array I made, please help!

Input a list of employee names and salaries, and determine the mean (average) salary as well as the number of salaries above and below the mean.

Declare EmpNames[100], Salaries[100]
Set x=1
Set Sum=0
Set Mean =0
Display "Enter the number of Employees"
input EmployeesCount
FOR x = 1 to EmployeesCount DO

Display "Enter the Employee Name and salary"
input Name, salary
Set EmpNames[x]=Name
Set Salaries[x]=salary
Set Sum=Sum + salary

Set Mean=Sum/EmployeesCount
Set CntAbove =0
Set CntBelow=0
FOR x = 1 to EmployeesCount DO
If Salaries[x] > Mean Then
Set CntAbove = CntAbove + 1
End If
If Salaries[x] < Mean Then
Set CntBelow = CntBelow + 1
End If


Display "The Average Salary is: $"+Mean
Display "The number of Salaries Above the Average Salary is:"+CntAbove
Display "The number of Salaries Below the Average Salary is:"+CntBelow
Anonymously add a comment: (or register here)
(registration is really fast and we send you no spam)
BB Code is enabled.
Captcha Number:

Blogs: (People who have posted blogs on this subject..)
Creating a Lexical Analyzer in C on Tue 9th Dec 11am
#include<stdio.h> #include<string.h> #include<conio.h> #include<ctype.h> /*************************************** ************************* Functions prototype. **************************************** *************************/ void Open_File(
Controling digital circuit through computer on Tue 9th Dec 10am
this code access the lpt port.here only 4 of the total 8 pins are used but can be modified for full 8 pins.it has a complete GUI with mouse & keyboard interactive control panel.works well in win98, but not in winxp. #include<stdio.h> #include<conio.
/* Computerised Electrical Equipment Control */ /* PC BASED DEVICE CONTROLLER * on Tue 9th Dec 10am
#include<stdio.h> #include<conio.h> #include<dos.h> void main() { void tone(void); int p=0x0378; char ex={"Created By Mrc"}; int j; char ex1={"For Further Details & Improvements"}; int k; char ex2={"Contact : E-mail : anbudan
Calendar Program on Tue 9th Dec 10am
This program prints Weekdays of specified date. It even prints calendar of a given year too. /*Ccalendar library*/ #include<stdio.h> #include<string.h> #include<conio.h> int getNumberOfDays(int month,int year) { switch(month) { case
Calculator: on Tue 9th Dec 10am
#include"graphics.h" #include"dos.h" #include"stdio.h" #include"math.h" union REGS i,o; char text={ "7","8","9","*","4","5","6","/","1","2", "3","+","0","00",".","-","M","M+", "M-","+/-","MR","MC","x^2","sr","OFF","A C","CE","="}; int s=0,k=0,pass
This is a simple code that changes system time and date. It is written using c/c++ but can be easily converted to java. #include "stdio.h" #include "process.h" #include "dos.h" int main(void) { struct date new_date; struct date old_date; s
A C programme which can print the file name it is kept in on Tue 9th Dec 9am
BOOTSECTOR EDITOR: on Tue 9th Dec 9am
Code : /*program to save the partion table of your hard disk for future use. it will save your partition table in a file partition.dat */ #include<stdio.h> #include<bios.h> #include<conio.h> #include<stdlib.h> #include<ctype.h> void main () {
BLINKING STAR : on Tue 9th Dec 9am
#include<conio.h> #include<graphics.h> #include<stdlib.h> #include<dos.h> void main() { int gdriver=DETECT,gmode; int i,x,y; initgraph(&gdriver,&gmode,"e: cgi"); while(!kbhit()) { x=random(640); y=random(480); setcolor
// To print semicolons using C programming without using semicolons any where i on Tue 9th Dec 9am
// To print semicolons using C programming without using semicolons any where in the C code in program. // #include<stdio.h> #include<conio.h> void main() { char a; a=59; if(printf("%c",a)){} getch();

Test Yourself: (why not try testing your skill on this subject? Clicking the link will start the test.)
BSD sockets API by skrye

This is a test of your knowledge of the BSD socket interface
C Programming by keoki

This test is aimed at a C programmer that is at an intermediate level.

Your Ad Here
Copyright Open Source Institute, 2006