Problem solving through programming (18escs01)


INITIALIZATION OF ARRAYS (CONTD.)


Download 215.92 Kb.
bet2/4
Sana16.06.2023
Hajmi215.92 Kb.
#1502284
1   2   3   4
Bog'liq
Module 3 C program


INITIALIZATION OF ARRAYS (CONTD.)

  • Example for compile time:

  • #include void main( )
    {
    int i;

int arr[ ] = {2, 3, 4}; //Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d\t", arr[i]);
}
}
6
Output:
2 3 4

INITIALIZATION OF ARRAYS (CONTD.)


7
  • Example for run time:

  • #include void main( )

{
int arr[3]; int i, j; printf("Enter array element"); for(i = 0; i < 3; i++)
{
scanf("%d", &arr[i]);
}
for(j = 0; j < 3; j++)
{
printf("%d\n", arr[j]);
}
//Run time array initialization
}
Output:
2 3 4

EXAMPLE – 1: DISPLAY ELEMENTS ELEMENT’S


#include int main ( )
{
int n[ 10 ]; /* n is an array of 10 integers */ int i, j; /* initialize elements of array n to 0 */ for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
} /* output each array element's value */
for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
} return 0;
}
8
Output:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

DIFFERENT WAYS OF INITIALIZATION OF ARRAYS


9

(A) INITIALIZING ALL SPECIFIED MEMORY LOCATION

  • Arrays can be initialized at the time of declaration

  • when their initial values are known in advance.
  • Array elements can be initialized with data items of type int, char etc.
  • Ex:- int a[5] = {10, 15, 1, 3, 20};
  • During compilation, 5 contiguous memory locations are reserved by the compiler for the variable ‘a’ and all these locations a1r0e initialized as shown in figure.

a[0]

a[1]

a[2]

a[3]

a[4]

10

15

1

3

20

1000

1002

1004

1006

1008

(B) PARTIAL ARRAY INITIALIZATION

  • If the number of values to be initialized is less than the size of the array, then the elements will be initialized to zero automatically.
  • Ex:- int a[5] = {10, 15};
  • Eventhough compiler allocates 5 memory locations, using this declaration statement; the compiler initializes first two locations with 10 and 15, the next set of memory locations are automatically initialized to 0's by compiler as shown in figure.

MANJUNATH C R

a[0]

a[1]

a[2]

a[3]

a[4]


Download 215.92 Kb.

Do'stlaringiz bilan baham:
1   2   3   4




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling