Unit 1 Arrays
Unit 1 Arrays
Static arrays have their sizes declared from the start and the size
cannot be changed after declaration.
The first element in an array is numbered 0 (zero) so last element is 1 less than
size of an array
for(i=0;i<5;i++){
printf(“\n Enter marks”);
scanf(“%d”,&marks[i]);
}
for(i=0;i<5;i++)
sum+=marks[i];
avg=sum/5;
printf(“\n %f”,avg);
Ex : int marks[5]={1,2,3,4,5};
Ex : int marks[]={1,2,3,4,5};
ARRAYS Ex : main(){
int num[40],i;
for(i=0;i<100;i++)
num[i]=i;
}
int main() {
int arr[2] = {1, 2, 3, 4, 5};
printf("%d", arr[3]);
}
Here the size of an array is 2, but the value inside array is exceed 2.
Thus it prints garbage value for index more than 1
int main() {
int a, b, c;
int arr[5] = {1, 2, 3, 25, 7};
a = ++arr[1];
b = arr[1]++;
c = arr[a++];
printf(“\n %d %d %d", a, b, c);
}
Sol : 4 3 25
Searching :
1) Linear search
2) Binary search
Step 2) Repeat Step 1 with one less comparison. During which the second
largest element will occupy its proper position. i.e we stop after we
compare and finally rearrange A[N-2] with A[N-1]
Step N-1) Finally we compare A[1] with A[2] and arrange them in such a
way that A[1] < A[2].
25 48 57 37 12 92 86 33
25 48 37 12 57 92 86 33
25 48 37 12 57 92 86 33
25 48 37 12 57 86 92 33
25 48 37 12 57 86 92 33
25 48 37 12 57 86 33 92
25 48 37 12 57 86 33 92
Simple to understand
Easy to implement.
Disadvantages :
Now A[0] with A[2] i.e 12 with 10. 12 > 10 hence interchange.
We get:
10 20 12 15 2
This is the end of first pass. The lowest element is in first position.
Now A[1] with A[2] i.e 20 with 12. 20 > 12 - hence interchange.
We get:
2 12 20 15 10
Now A[1] with A[3] i.e 12 with 15. 12 < 15 - hence no interchange.
We have:
2 12 20 15 10
Now A[1] with A[4] i.e 12 with 10. 12 > 10 - hence interchange.
We get :
2 10 20 15 12
Abbreviations used :
6) Exit
11 22 30 33 40 44 55 60 66 77 80 88 99
Whereas
static int marks[5][]={11,12,13,…};
and
static int marks[][]={11,12,13,…}; would never work.
5 20
=
15 46
1 4 0 1 -5
= 4 2
-5 2 7 0 7
main() {
int n[3][3]={1,2,3,4,5,6,7,8,9};
printf(“\n %d”,n);
printf(“\n %d”,n[2]);
printf(“\n %d ”,n[2][2]);
}
Ex : 6*6 matrix
1 1 1 1 1 0
1 1 1 1 0 -1
1 1 1 0 -1 -1
1 1 0 -1 -1 -1
1 0 -1 -1 -1 -1
0 -1 -1 -1 -1 -1
NGP invented
10) Input : 5 digit
Output : 5 digit . . .
So you better know what you’re getting into because here you’re
on your own.