Arrays is like a numbered list. It has an address, which is a whole number, and data that correspond with the address of the array. It is declared with variables.

Declarations:

int arr[size];
char arr[size][charlenght];

Basically you just put the size of the array in brackets after the name of the variable.

#include<stdio.h>
#include<conio.h>
#include<string.h>
#define max 5

char fruits[max][8];

void main()
{
clrscr();
strcpy(fruits[0], "Apple");
strcpy(fruits[1], "Orange");
strcpy(fruits[2], "Banana");
strcpy(fruits[3], "Grapes");
strcpy(fruits[4], "Mango");
for (int i=0; i<max; i++) printf("%s\n", fruits[i]);
getch();
}
Apple
Orange
Banana
Grapes
Mango
Fruits
AppleOrangeBananaGrapesMango
01234

Arrays and for loop go together like a list and counting numbers. Array of words is a bit complicated with C as you can see, since strings are treated like an array of character, and array of words would be like a two-dimensional array of strings, but it still works. Array of numbers are much easier.

Here's another example with arrays of numbers:

#include<stdio.h>
#include<conio.h>
#define max 5

int num[max], i, sum=0;

void main()
{
clrscr();
printf("Enter %d numbers: ", max);
for (i=0; i<max; i++) scanf("%d", &num[i]);
for (i=0; i<max; i++) sum+=num[i];
printf("%d\n", sum);
getch();
}

Now your turn. Edit the code above to include the average and the product of the numbers inputed. What do you do if you want to change how many numbers can be inputed, let say 10, instead of 5?

Click here to see what I did.

<<back<< >>Next>>