Subscripted Variables : Arrays
Introduction:
An array is a sequence of data in memory, where all data are of same types .In this ,data is placed in physically adjacent locations , for example a sequence of 10 integers stored one after another in memory represent an array .Note that a string can be considered as a sequence of characters (an array of characters).
Example:
stu_age [5]
[14] [16] [18]
stu_age (0) stu_age(1) stu_age(2)
•Subscripted Variable:
A variable with a subscript is known as subscripted variable and it refers to one value in the array .e.g., stu_age[0], stu_age[1].,etc.
•Declaration of an array :
As you know that all variable in C must be declared before use, hence we must declare the array .It is done at the beginning of the function main() with data type and size.
Syntax-
data type name [size];
Example
int stu_age[5];
These statement state that stu_age is an array of 5 integer (Number of elements).
This statement reserves enough memory for stu_age to hold 5 integer . Once the declaration is made ,stu_age[0] refer to the first integer in the array ,stu_age [1] refer to the second integer in the array and so on.
•Accessing array elements:
To access particular element in an array specify the array name ,followed by square braces enclosing an integer ,Which is called the array index. The array index indicates the particular element of the array which we want to access.
Example: stu_age[3]
The subscripted variable allows us to access the element number 4 of the array stu_age.
By using loop
Example:
for(i=0;i<n;i++)
{
printf ("Enter age");
scanf("%d";&stu_age[i]);
}
Example-
for(i=0;i<n;i++)
sum=sum+stu_age[i]);
}
avg=sum/5;
printf ("Average age is %f",avg);
In exp 1 scanf() Function will accept the elements for the array stu_age with the help of control variable i (whose value will vary from (0) to (n-1) and in the second example different values are used to find the average age of students.
Initialization of array:
Arrays can be initialized once they are declared .The declaration of an array can be done in two ways.
•At the time of declaration
e.g.
int stu_age[5]={14,16,18,17,15};
The above declaration causes stu_age[0] to be initialized to 14,stu_age[1] to 16, stu_age[2] to 18, stu_age [3] to 17 and stu_age[4] to 15.
•By using loop
e.g.
for(i=0;i<5;i++)
{
scanf("%d",&stu_age[i]);
}
In this the system will take the values from keyboard (entered by user ) and assign them to their respective variables.
:::::::::::::::::::::::::: HARSHIT KUMAR:::::::::::::::::
input and output in C language




Comments
Post a Comment
DON'T COMMENT LINK.