Lesson 7 Arrays - 1D
Lesson 7 Arrays - 1D
main()
main()
{
{
float sal1,sal2,sal3;
int sal[3], i=0;
scanf (“%f”,&sal1); while (i < 3)
{
scanf (“%f”,&sal2);
scanf (“%f”,&sal[i];
scanf (“%f”,&sal3); }
} }
Example
Total size in bytes for a 1 D array:
total bytes = sizeof( data type) * size of array
int a [ 7 ] ;
total_bytes = 4 * 7
= 28 bytes in memory
Exercise
int main( ) {
float f1[10] ;
char c1[10] ;
printf(“%d”, sizeof(f1));
printf(“%d”, sizeof(c1));
return(0);
}
Output:
40
10
Example 1
Write a program to read 10 integers from the
user and display them.
2 2
Input the emp_id for which salary is
to be displayed.
…. ….
Search the above id in array
emp_id[ ] and get the index if match
found
id[0]=1234;
id[2]=2883;
id[3]=2322;
id[4]=8888;
id[5]=8237;
Run time initialization
Explicitly initializing an array at run time
Normally used for large array size
Example:
for(i=0; i<100; i++)
{
if(i<50)
sum[i] = 0;
else
sum[i] = 1;
}
Basics of character array
If you are required to store a group of character
like your name, city , or your college name, or
any word or text you need to define a array of
characters.
For example
Schin Tendulkar
It will scan only “ Sachin ”.
It will IGNORE any space or tab space
For example
char str [ 20 ] ;
gets( str ) ;
puts( )
puts( argument string ):
It displays the string of characters from
argument string to standard output till
NULL character and appends a new line
character at the end.
For example
puts ( str ) ;
EXAMPLE: Input ten numbers into an array,
using values of 0 to 99, and print out all numbers
except for the largest number..
/* to accept 10 values in the range 0 to 99 */
int size=10;
int value[size], i;
for (i=0; i< size; ++i)
{ scanf (“%d”,&value[i]);
if (value[i] > 99 || value[i] <0)
{ printf (“ enter only values within 0 -99 ”);
i--; }
}
/* to find the greatest among the list */
int maximum= 0;
for (i=0; i< size; i++)
{
if (maximum < value[i] )
maximum = value[i];
}
/* to print all the values other than the greatest */
for (i=0; i< size; i++)
{
if (value[i] != maximum )
printf (“%d”, value[i];
}
Home Assignment