Earn Online

Chapter - 3


Array:-

Array definition
Array by definition is a variable that hold multiple elements which has the same data type.

Declaring Arrays
We can declare an array by specify its data type, name and the number of elements the array holds between square brackets immediately following the array name. Here is the syntax:

data_type array_name[size];

For example, to declare an integer array which contains 100 elements we can do as follows.
int a[100];
There are some rules on array declaration. The data type can be any valid C data types including structure andunion. The array name has to follow the rule of variable and the size of array has to be a positive constant integer.
We can access array elements via indexes array_name[index]. Indexes of array starts from 0 not 1 so the highest elements of an array is array_name[size-1].

Initializing Arrays

It is like a variable, an array can be initialized. To initialize an array, you provide initializing values which are enclosed within curly braces in the declaration and placed following an equals sign after the array name. Here is an example of initializing an integer array.
int list[5] = {2,1,3,7,8};
= = = = = = = = = = = = = = = = = = = = = = = = = = = 
#include <stdio.h>
int main()
{
int n[10] = {32,27,64,18,95,14,90,70,60,37};
int i ;
printf("%s%13s\n","Element","Value");
for (i=0 ;  i<10 ; i++)
{
 printf("%7d%13d\n",1,n[i]);
}
return 0;
}

= = = = = = = = = = = = = = = = = = = = = = = = = = 
Calculate the average of 10 numbers:
#include<stdio.h>
#define MAX_NUM 10 /*if some thing is predefine like max or min then we can define
it like this MAX_NUM is variable name.*/
int main(void)
{
int num[MAX_NUM];
int ave, i;
int sum = 0;
Filling the Array 
printf("Please enter 10 numbers: \n");
for (i = 0; i < MAX_NUM; i++)
{
scanf("%d", &num[i]);
}
printf("Your numbers are: \n");
for(i = 0; i < MAX_NUM; i++)
{
printf("%4d",num[i]);
for(i = 0; i < MAX_NUM; i++)
{
sum += num[i];
}
ave = (sum / 10.0);
printf("\nThe average of the ten numbers are: %d\n", ave);
system("pause");
return 0;
}
= = = = = = = = = = = = = = = = = = = = = = = = = =