Lec6
Lec6
Supriyo Mandal,
Ph.D. (IIT Patna)
Postdoc (ZBW, University of Kiel, Germany)
A scalar variable is a single variable whose stored value is an atomic data
type.
An array is a collection of individual data elements that is ordered, fixed in
size, and homogeneous.
An array is considered to be a derived data type.
Array enables the storing and manipulation of potentially huge quantities of
data.
Variables can be assigned values during declaration like the following example.
int x = 7;
Array initialization statements as shown.
(a) int A[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
9 8 7 6 5 4 3 2 1 0 ¨ values stored in array elements
0 1 2 3 4 5 6 7 8 9 ¨index values of array elements
(b) double a[5] = {3.67, 1.21, 5.87, 7.45, 9.12}
Automatic sizing While initializing, the size of a one dimensional array can be
omitted as shown.
int arr[] = {3,1,5,7,9};
Here, the C compiler will reduce the size of the array from the initialization
statement.
Integer array example:
int age [5];
int age[5]={0, 1, 2, 3, 4};
age[0]; /*0 is accessed*/
age[1]; /*1 is accessed*/
Array declaration syntax: age[2]; /*2 is accessed*/
data_type arr_name [arr_size];
Array initialization syntax: Character array example:
data_type arr_name [arr_size]=(value1, char str[10];
value2, value3,….); char str[10]={‘H’,‘a’,‘i’};
Array accessing syntax: (or)
arr_name[index]; char str[0] = ‘H’;
char str[1] = ‘a’;
char str[2] = ‘i;
str[0]; /*H is accessed*/
str[1]; /*a is accessed*/
str[2]; /*i is accessed*/
#include<stdio.h>
int main()
{
int i;
value of arr[0] is 10
int arr[5] = {10,20,30,40,50};
value of arr[1] is 20
for (i=0;i<5;i++)
value of arr[2] is 30
{ value of arr[3] is 40
// Accessing each variable value of arr[4] is 50
printf("value of arr[%d] is %d \n", i, arr[i]);
}
}
§ x and y are similar arrays (i.e., of the same data type, dimensionality, and size), then
assignment operations, comparison operations, etc., involving these two arrays must
be carried out on an element-by-element basis.
The C compiler automatically places the '\0' at the end of the string
when it initializes the array.
char test[100] = "Null terminator will follow me";
sprintf(test,"Null terminator will follow me");
§ Strings can be declared like one-dimensional arrays.
§ For example,
char str[30];
char text[80];