Array in C-C++
Array in C-C++
Arrays
It is a group of variables of similar data types
referred by a single element.
Its elements are stored in a contiguous memory
location.
The size of the array should be mentioned while
declaring it.
Array elements are always counted from zero
(0) onward.
Array elements can be accessed using the
position of the element in the array.
The array can have one or more dimensions.
Array
Advantages:-
Random access of elements using the array index.
Use of fewer lines of code as it creates a single array of multiple elements.
Easy access to all the elements.
Traversal through the array becomes easy using a single loop.
Sorting becomes easy as it can be accomplished by writing fewer lines of
code.
Disadvantages:-
Size Limit: We can store only the fixed size of elements in the array.
It doesn’t grow its size at runtime.
Allows a fixed number of elements to be entered which is decided at
the time of declaration. Unlike a linked list, an array in C is not
dynamic.
Insertion and deletion of elements can be costly since the elements
are needed to be managed in accordance with the new memory
allocation.
Array declaration in C/C++:There are
various ways in which we can declare an array. It can be done by specifying its type and size, initializing it or both.
Declaration & Initialization of Array
Print marks of four students
#include <stdio.h>
int main()
{
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75; //traversal of array
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}
C Array Example: Sorting an array
#include<stdio.h>
void main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
}
}
Program to print the largest and second largest element of the
array.
#include<stdio.h> {
void main () if(arr[i]>largest)
{ {
sec_largest = larg
int arr[100],i,n,largest,sec_lar
gest; est;
largest = arr[i];
printf("Enter the size of the arr
}
ay?");
else if (arr[i]>sec_la
scanf("%d",&n); rgest && arr[i]!=largest)
printf("Enter the elements of t {
he array?"); sec_largest=arr[i];
for(i = 0; i<n; i++)
{ }
scanf("%d",&arr[i]); }
}
printf("largest = %d, se
cond largest = %d",larges
largest = arr[0];
t,sec_largest);
sec_largest = arr[1];
for(i=0;i<n;i++) }
Multidimensional Arrays in C / C++