Вы находитесь на странице: 1из 11

Arrays in C

In C language, arrays are reffered to as structured data types. An array is defined as finite ordered collection of
homogenous data, stored in contiguous memory locations.
Here the words,
 finite means data range must be defined.
 ordered means data must be stored in continuous memory addresses.
 homogenous means data must be of similar data type.

Example where arrays are used,


 to store list of Employee or Student names,
 to store marks of students,
 or to store list of numbers or characters etc.
Since arrays provide an easy way to represent data, it is classified amongst the data structures in C. Other data
structures in c are structure, lists, queues, trees etc. Array can be used to represent not only simple list of data but
also table of data in two or three dimensions.

Declaring an Array
Like any other variable, arrays must be declared before they are used. General form of array declaration is,
data-type variable-name[size];
/* Example of array declaration */
int arr[10];

Here int is the data type, arr is the name of the array and 10 is the size of array. It means array arr can only contain 10
elements of int type.
Index of an array starts from 0 to size-1 i.e first element of arr array will be stored at arr[0]address and the last
element will occupy arr[9].

Initialization of an Array
After an array is declared it must be initialized. Otherwise, it will contain garbage value(any random value). An array
can be initialized at either compile time or at runtime.
Compile time Array initialization
Compile time initialization of array elements is same as ordinary variable initialization. The general form of
initialization of array is,
data-type array-name[size] = { list of values };
/* Here are a few examples */
int marks[4]={ 67, 87, 56, 77 }; // integer array initialization
float area[5]={ 23.4, 6.8, 5.5 }; // float array initialization
int marks[4]={ 67, 87, 56, 77, 59 }; // Compile time error
One important thing to remember is that when you will give more initializer(array elements) than the declared array
size than the compiler will give an error.
#include<stdio.h>
void main()
{
int i;
int arr[] = {2, 3, 4}; // Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d\t",arr[i]);
}
}

234
Runtime Array initialization
An array can also be initialized at runtime using scanf() function. This approach is usually used for initializing large
arrays, or to initialize arrays with user specified values. Example,
#include<stdio.h>
void main()
{
int arr[4];
int i, j;
printf("Enter array element");
for(i = 0; i < 4; i++)
{
scanf("%d", &arr[i]); //Run time array initialization
}
for(j = 0; j < 4; j++)
{
printf("%d\n", arr[j]);
}
}

Two dimensional Arrays


C language supports multidimensional arrays also. The simplest form of a multidimensional array is the two-
dimensional array. Both the row's and column's index begins from 0.
Two-dimensional arrays are declared as follows,
data-type array-name[row-size][column-size]
/* Example */
int a[3][4];

An array can also be declared and initialized together. For example,


int arr[][3] = {
{0,0,0},
{1,1,1}
};
Note: We have not assigned any row value to our array in the above example. It means we can initialize any number
of rows. But, we must always specify number of columns, else it will give a compile time error. Here, a 2*3 multi-
dimensional matrix is created.
Runtime initialization of a two dimensional Array
#include<stdio.h>
void main()
{
int arr[3][4];
int i, j, k;
printf("Enter array element");
for(i = 0; i < 3;i++)
{
for(j = 0; j < 4; j++)
{
scanf("%d", &arr[i][j]);
}
}
for(i = 0; i < 3; i++)
{ for(j = 0; j < 4; j++)
{
printf("%d", arr[i][j]);
} }
}
Linear search in C programming: The following code implements linear search (Searching algorithm) which is used to
find whether a given number is present in an array and if it is present then at what location it occurs. It is also known
as sequential search. It is straightforward and works as follows: We keep on comparing each element with the element
to search until it is found or the list ends.
Linear search C program
1. #include <stdio.h>
2.
3. int main()
4. {
5. int array[100], search, c, n;
6.
7. printf("Enter number of elements in array\n");
8. scanf("%d", &n);
9.
10. printf("Enter %d integer(s)\n", n);
11.
12. for (c = 0; c < n; c++)
13. scanf("%d", &array[c]);
14.
15. printf("Enter a number to search\n");
16. scanf("%d", &search);
17.
18. for (c = 0; c < n; c++)
19. {
20. if (array[c] == search) /* If required element is found */
21. {
22. printf("%d is present at location %d.\n", search, c+1);
23. break;
24. }
25. }
26. if (c == n)
27. printf("%d isn't present in the array.\n", search);
28.
29. return 0;
30. }
Output of program:

C program for binary search: This code implements binary search in C language. It can only be used for sorted arrays,
but it's fast as compared to linear search. If you wish to use binary search on an array which isn't sorted, then you must
sort it using some sorting technique say merge sort and then use the binary search algorithm to find the desired
element in the list. If the element to be searched is found then its position is printed. The code below assumes that the
input numbers are in ascending order.
C programming code for binary search
1. #include <stdio.h>
2.
3. int main()
4. {
5. int c, first, last, middle, n, search, array[100];
6.
7. printf("Enter number of elements\n");
8. scanf("%d",&n);
9.
10. printf("Enter %d integers\n", n);
11.
12. for (c = 0; c < n; c++)
13. scanf("%d",&array[c]);
14.
15. printf("Enter value to find\n");
16. scanf("%d", &search);
17.
18. first = 0;
19. last = n - 1;
20. middle = (first+last)/2;
21.
22. while (first <= last) {
23. if (array[middle] < search)
24. first = middle + 1;
25. else if (array[middle] == search) {
26. printf("%d found at location %d.\n", search, middle+1);
27. break;
28. }
29. else
30. last = middle - 1;
31.
32. middle = (first + last)/2;
33. }
34. if (first > last)
35. printf("Not found! %d isn't present in the list.\n", search);
36.
37. return 0;
38. }
Output of program:
Transpose of a matrix
#include <stdio.h>

int main()
{
int m, n, c, d, matrix[10][10], transpose[10][10];

printf("Enter the number of rows and columns of matrix\n");


scanf("%d%d", &m, &n);

printf("Enter elements of the matrix\n");

for (c = 0; c < m; c++)


for(d = 0; d < n; d++)
scanf("%d", &matrix[c][d]);

for (c = 0; c < m; c++)


for( d = 0 ; d < n ; d++ )
transpose[d][c] = matrix[c][d];

printf("Transpose of the matrix:\n");

for (c = 0; c < n; c++) {


for (d = 0; d < m; d++)
printf("%d\t", transpose[c][d]);
printf("\n");
}

return 0;
}
Output of program:

Matrix Addition:
#include <stdio.h>
int main()
{ int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);
printf("Sum of entered matrices:-\n");
for (c = 0; c < m; c++) {
for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
return 0;
}

Example: Program to Multiply Two Matrices


#include <stdio.h>
int main()
{
int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k;
printf("Enter rows and column for first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d %d",&r2, &c2);
// Column of first matrix should be equal to column of second matrix and
while (c1 != r2)
{
printf("Error! column of first matrix not equal to row of second.\n\n");
printf("Enter rows and column for first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d %d",&r2, &c2);
}
// Storing elements of first matrix.
printf("\nEnter elements of matrix 1:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c1; ++j)
{
printf("Enter elements a%d%d: ",i+1, j+1);
scanf("%d", &a[i][j]);
}
// Storing elements of second matrix.
printf("\nEnter elements of matrix 2:\n");
for(i=0; i<r2; ++i)
for(j=0; j<c2; ++j)
{
printf("Enter elements b%d%d: ",i+1, j+1);
scanf("%d",&b[i][j]);
}
// Initializing all elements of result matrix to 0
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
result[i][j] = 0;
}
// Multiplying matrices a and b and
// storing result in result matrix
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
{
result[i][j]+=a[i][k]*b[k][j];
}
// Displaying the result
printf("\nOutput Matrix:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
printf("%d ", result[i][j]);
if(j == c2-1)
printf("\n\n");
}
return 0;
}

Bubble Sort:
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in
wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs
one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < n - 1; c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c < n; c++)
printf("%d\n", array[c]);
return 0;
}

Merge Sort

Merge sort is a sorting technique based on divide and conquer technique.


#include <stdio.h>
#define max 10
int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };
int b[10];
void merging(int low, int mid, int high) {
int l1, l2, i;
for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {
if(a[l1] <= a[l2])
b[i] = a[l1++];
else
b[i] = a[l2++];
}
while(l1 <= mid)
b[i++] = a[l1++];
while(l2 <= high)
b[i++] = a[l2++];
for(i = low; i <= high; i++)
a[i] = b[i];
}
void sort(int low, int high) {
int mid;
if(low < high) {
mid = (low + high) / 2;
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
} else {
return;
}
}

int main() {
int i;
printf("List before sorting\n");
for(i = 0; i <= max; i++)
printf("%d ", a[i]);
sort(0, max);
printf("\nList after sorting\n");
for(i = 0; i <= max; i++)
printf("%d ", a[i]);
}

Algorithm Analysis
The term "analysis of algorithms" was coined by Donald Knuth. Algorithm analysis is an important part
of computational complexity theory, which provides theoretical estimation for the required resources of an
algorithm to solve a specific computational problem.

Efficiency of an algorithm can be analyzed at two different stages, before implementation and after
implementation. They are the following

 A Priori Analysis − This is a theoretical analysis of an algorithm. Efficiency of an algorithm is


measured by assuming that all other factors, for example, processor speed, are constant and have no
effect on the implementation.
 A Posterior Analysis − This is an empirical analysis of an algorithm. The selected algorithm is
implemented using programming language. This is then executed on target computer machine. In
this analysis, actual statistics like running time and space required are collected.

Algorithm analysis deals with the execution or running time of various operations involved. The running
time of an operation can be defined as the number of computer instructions executed per operation.

Algorithm Complexity

Suppose X is an algorithm and n is the size of input data, the time and space used by the algorithm X are
the two main factors, which decide the efficiency of X.
 Time Factor − Time is measured by counting the number of key operations such as comparisons in
the sorting algorithm.
 Space Factor − Space is measured by counting the maximum memory space required by the
algorithm.

Asymptotic analysis

Asymptotic analysis of an algorithm refers to defining the mathematical boundation/framing of its run-time
performance. Using asymptotic analysis, we can very well conclude the best case, average case, and worst
case scenario of an algorithm.

Asymptotic analysis is input bound i.e., if there's no input to the algorithm, it is concluded to work in a
constant time. Other than the "input" all other factors are considered constant.

Asymptotic analysis refers to computing the running time of any operation in mathematical units of
computation. For example, the running time of one operation is computed as f(n) and may be for another
operation it is computed as g(n2). This means the first operation running time will increase linearly with the
increase in n and the running time of the second operation will increase exponentially when n increases.
Similarly, the running time of both operations will be nearly the same if n is significantly small.

Usually, the time required by an algorithm falls under three types


 Best Case − Minimum time required for program execution.
 Average Case − Average time required for program execution.
 Worst Case − Maximum time required for program execution.
Asymptotic Notations
Following are the commonly used asymptotic notations to calculate the running time complexity of an
algorithm.

 Ο Notation
 Ω Notation
 θ Notation
Big Oh Notation, Ο
The notation Ο(n) is the formal way to express the upper bound of an algorithm's running time. It measures
the worst case time complexity or the longest amount of time an algorithm can possibly take to complete.

For example, for a function f(n)


Ο(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) ≤ c.g(n) for all n > n0. }

Omega Notation, Ω
The notation Ω(n) is the formal way to express the lower bound of an algorithm's running time. It measures
the best case time complexity or the best amount of time an algorithm can possibly take to complete.

For example, for a function f(n)


Ω(f(n)) ≥ { g(n) : there exists c > 0 and n0 such that g(n) ≤ c.f(n) for all n > n0. }

Theta Notation, θ
The notation θ(n) is the formal way to express both the lower bound and the upper bound of an algorithm's
running time. It is represented as follows −

θ(f(n)) = { g(n) if and only if g(n) = Ο(f(n)) and g(n) = Ω(f(n)) for all n > n0. }
Common Asymptotic Notations

Following is a list of some common asymptotic notations


constant − Ο(1)

logarithmic − Ο(log n)

linear − Ο(n)

n log n − Ο(n log n)

quadratic − Ο(n2)

cubic − Ο(n3)

polynomial − nΟ(1)

exponential − 2Ο(n)

Вам также может понравиться