Professional Documents
Culture Documents
1
Lec 10-11: Array in C
PREPARED BY
SHAHRIAR RAHMAN KHAN
Lecturer, Department of CSE, MIST
Array Initialization
• Static array initialization - Initializes all elements of array during its declaration.
• Dynamic array initialization - The declared array is initialized some time later
during execution of program
int var[7];
var[0] = 14;
var[1] = 22;
var[2] = 31;
var[3] = 18;
var[4] = 19;
var[5] = 7;
var[6] = 23;
0 1 2 3 4 5 6
14 22 31 18 19 7 23
#include<stdio.h>
int main()
{
int ar[10];
int i;
for (i=0; i<10; i++) // for Initializing Array
{
ar[i]=i;
}
for (i=0; i<10; i++) // for displaying Array
{
printf("%d ", ar[i]);
}
}
11/20/2023 LEC SHAHRIAR RAHMAN KHAN 20
Array Initialization
int var[7] = {14, 22, 31, 18, 19, 7, 23}; #include<stdio.h>
int var[ ] = {14, 22, 31, 18, 19, 7, 23}; int main()
{
Size of array is optional when declaring
int i;
and initializing array at once. The C int ar[7] = {14, 22, 31, 18, 19, 7,
compiler automatically determines 23};
array size using number of array //int var[] = {14, 22, 31, 18, 19,
elements 7, 23};
for (i=0; i<7; i++)
0 1 2 3 4 5 6 {
14 22 31 18 19 7 23 printf("%d ", ar[i]);
}
int var[7] = {14, 22, 31}; }
C, unlike many languages, does NOT check array bounds subscripts during:
• Compilation
• Runtime (bounds are never checked)
If you access off the ends of any array, it will calculate the address it expects the
data to be at, and then attempts to use it anyways
• may get “something…”
• may get a memory exception (segmentation fault, bus error, core dump error)
It is the programmer’s responsibility to ensure that their programs are correctly
written and debugged!
Given a list of test scores, determine the max, min, average, sum
Array count (Ex: Given the height measurements of students in a class, output
the count of those students who are taller than average.)
Array reverse (temp array, in-place)
Frequency of digits in a number
Read in a list of student names and rearrange them in alphabetical order
(Bubble sorting).
Searching a particular item from a given list (Linear Search, Binary Search).
• First, it assumes that the smallest value is in num[0] and assigns it to the
variable Small.
• Then it compares Small with the rest of the values in num array, one at a time.
• When an element is smaller than the current value contained in Small, it is
assigned to Small. The process finally places the smallest array element in
Small.
int main()
{
int index;
float Small, num[]= {12.0,41.5,-31.2,-45.0,33.0,-21.2, 24.1,0.7,3.2,0.5};
Small = num[0];
for(index=0; index<10; index++)
{
printf("%.2f ",num[index]);
}
int main()
{
int index;
int Large, num[]= {12, 34, 21, 45, 9};
Large = num[0];
for(index=0; index<5; index++)
{
printf("%d",num[index]);
}