Professional Documents
Culture Documents
project
C Programming – Arrays
Declaration of arrays:
Like any other variable arrays must be declared before
they are used. The general form of declaration is:
type variable-name[50];
G = grade [50];
grades [100]=95;
values[0
]
values[1
]
values[2
]
values[3
]
values[4
]
values[5
]
values[6
]
values[7
]
values[8
]
values[9
]
Initialization of arrays:
We can initialize the elements in the array in the same
way as the ordinary variables when they are declared. The
general form of initialization off arrays is:
int number[3]={0,0,0};
int counter[]={1,1,1,1};
data_type array_name[row_size][column_size];
int m[10][20]
Example:
int table[2][3]={0,0,01,1,1};
date_type array_name[s1][s2][s3]…..[sn];
int survey[3][5][12];
float table[5][4][5][3];
TWO-DIMENSIONAL ARRAYS
Two-dimensional arrays are a little more complicated to
use than one-dimensional ones. This page presents two
methods of passing a pointer to a two-dimensional array
to a function for processing.
Subscript Notation
Consider an int array as declared below.
#define NUM_STUDENTS 5
#define NUM_TESTS 4
int grades[NUM_STUDENTS][NUM_TESTS];
Sample Program 1
This is a complete program which initializes part of an
array of integer grades at the time of its declaration with 6
values and then calls a function to find, return, and print
the highest grade. Note that the dimensions of the array
have been changed from those used in the discussion
above by altering the compiler directives.
#include <stdio.h>
#define NUM_STUDENTS 25
#define NUM_TESTS 10
int main()
{
int grades[NUM_STUDENTS][NUM_TESTS] = { {55, 60,
65},
{85, 90, 95} };
int num_students = 2;
int num_tests = 3;
int high_test;
Sample Program 2
This is a program which initializes parts of two arrays of
integer grades at the time of their declaration, each with 6
values. Then it calls a function to find, return, and print
the highest grade in each of the two arrays.
#include <stdio.h>
#define NUM_STUDENTS1 25
#define NUM_TESTS1 10
#define NUM_STUDENTS2 15
#define NUM_TESTS2 8
int main()
{
int grades1[NUM_STUDENTS1][NUM_TESTS1] = { {55,
60, 65},
{85, 90, 95} };
int num_students1 = 2;
int num_tests1 = 3;
int high_test1;
high_test1 =
get_highest( (int *)grades1, NUM_TESTS1,
num_students1, num_tests1);
printf("The highest score in the first class is %d.\n",
high_test1);
high_test2 =
get_highest( (int *)grades2, NUM_TESTS2,
num_students2, num_tests2);
printf("The highest score in the second class is %d.\n",
high_test2);
return 0;
}