logo

C Масив

Масив визначається як сукупність елементів даних подібного типу, що зберігаються в безперервних розташуваннях пам’яті. Масиви — це похідний тип даних мовою програмування C, який може зберігати простий тип даних, наприклад int, char, double, float тощо. Він також має можливість зберігати колекцію похідних типів даних, таких як покажчики, структура, тощо. Масив — це найпростіша структура даних, де до кожного елемента даних можна отримати довільний доступ за допомогою його номера індексу.

Масив C корисний, якщо вам потрібно зберігати схожі елементи. Наприклад, якщо ми хочемо зберегти оцінки студента з 6 предметів, тоді нам не потрібно визначати різні змінні для оцінок з різних предметів. Замість цього ми можемо визначити масив, який може зберігати позначки в кожному суб’єкті в безперервних місцях пам’яті.

Використовуючи масив, ми можемо легко отримати доступ до елементів. Для доступу до елементів масиву потрібно лише кілька рядків коду.

Властивості масиву

Масив містить такі властивості.

  • Кожен елемент масиву має однаковий тип даних і має однаковий розмір, тобто int = 4 байти.
  • Елементи масиву зберігаються в безперервних ділянках пам’яті, де перший елемент зберігається в найменшій ділянці пам’яті.
  • До елементів масиву можна отримати довільний доступ, оскільки ми можемо обчислити адресу кожного елемента масиву за заданою базовою адресою та розміром елемента даних.

Перевага C Array

1) Оптимізація коду : Менше коду для доступу до даних.

2) Легкість проходження : Використовуючи цикл for, ми можемо легко отримати елементи масиву.

3) Простота сортування : Щоб відсортувати елементи масиву, нам знадобиться лише кілька рядків коду.

4) Довільний доступ : Ми можемо отримати довільний доступ до будь-якого елемента за допомогою масиву.

Недолік C Array

1) Фіксований розмір : незалежно від розміру, який ми визначаємо під час оголошення масиву, ми не можемо перевищити обмеження. Отже, він не збільшує розмір динамічно, як LinkedList, про який ми дізнаємося пізніше.

Оголошення масиву C

Ми можемо оголосити масив мовою c наступним чином.

 data_type array_name[array_size]; 

Тепер давайте подивимося приклад оголошення масиву.

 int marks[5]; 

Тут int є тип даних , знаки є ім'я_масиву , а 5 – це розмір_масиву .

Ініціалізація масиву C

Найпростішим способом ініціалізації масиву є використання індексу кожного елемента. Ми можемо ініціалізувати кожен елемент масиву за допомогою індексу. Розглянемо наступний приклад.

зробити сценарій оболонки виконуваним
 marks[0]=80;//initialization of array marks[1]=60; marks[2]=70; marks[3]=85; marks[4]=75; 
ініціалізація масиву мовою c

Приклад масиву C

 #include 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 
',marks[i]); } end of for loop return 0; < pre> <p> <strong>Output</strong> </p> <pre> 80 60 70 85 75 </pre> <h2>C Array: Declaration with Initialization</h2> <p>We can initialize the c array at the time of declaration. Let&apos;s see the code.</p> <pre> int marks[5]={20,30,40,50,60}; </pre> <p>In such case, there is <strong>no requirement to define the size</strong> . So it may also be written as the following code.</p> <pre> int marks[]={20,30,40,50,60}; </pre> <p>Let&apos;s see the C program to declare and initialize the array in C.</p> <pre> #include int main(){ int i=0; int marks[5]={20,30,40,50,60};//declaration and initialization of array //traversal of array for(i=0;i<5;i++){ printf('%d 
',marks[i]); } return 0; < pre> <p> <strong>Output</strong> </p> <pre> 20 30 40 50 60 </pre> <h2>C Array Example: Sorting an array</h2> <p>In the following program, we are using bubble sort method to sort the array in ascending order.</p> <pre> #include 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 a[i]) temp="a[i];" a[i]="a[j];" a[j]="temp;" } printf('printing sorted element list ...
'); for(i="0;" i<10; printf('%d
',a[i]); < pre> <h2>Program to print the largest and second largest element of the array.</h2> <pre> #include void main () { int arr[100],i,n,largest,sec_largest; printf(&apos;Enter the size of the array?&apos;); scanf(&apos;%d&apos;,&amp;n); printf(&apos;Enter the elements of the array?&apos;); for(i = 0; i<n; i++) { scanf('%d',&arr[i]); } largest="arr[0];" sec_largest="arr[1];" for(i="0;ilargest)" else if (arr[i]>sec_largest &amp;&amp; arr[i]!=largest) { sec_largest=arr[i]; } } printf(&apos;largest = %d, second largest = %d&apos;,largest,sec_largest); } </n;></pre> <hr></10;></pre></5;i++){></pre></5;i++){>

Масив C: оголошення з ініціалізацією

Ми можемо ініціалізувати масив c під час оголошення. Давайте подивимось код.

 int marks[5]={20,30,40,50,60}; 

В такому випадку є відсутність вимоги щодо визначення розміру . Тому це також можна записати у вигляді наступного коду.

 int marks[]={20,30,40,50,60}; 

Давайте розглянемо програму C для оголошення та ініціалізації масиву в C.

 #include int main(){ int i=0; int marks[5]={20,30,40,50,60};//declaration and initialization of array //traversal of array for(i=0;i<5;i++){ printf(\'%d 
\',marks[i]); } return 0; < pre> <p> <strong>Output</strong> </p> <pre> 20 30 40 50 60 </pre> <h2>C Array Example: Sorting an array</h2> <p>In the following program, we are using bubble sort method to sort the array in ascending order.</p> <pre> #include 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 a[i]) temp="a[i];" a[i]="a[j];" a[j]="temp;" } printf(\'printing sorted element list ...
\'); for(i="0;" i<10; printf(\'%d
\',a[i]); < pre> <h2>Program to print the largest and second largest element of the array.</h2> <pre> #include void main () { int arr[100],i,n,largest,sec_largest; printf(&apos;Enter the size of the array?&apos;); scanf(&apos;%d&apos;,&amp;n); printf(&apos;Enter the elements of the array?&apos;); for(i = 0; i<n; i++) { scanf(\'%d\',&arr[i]); } largest="arr[0];" sec_largest="arr[1];" for(i="0;ilargest)" else if (arr[i]>sec_largest &amp;&amp; arr[i]!=largest) { sec_largest=arr[i]; } } printf(&apos;largest = %d, second largest = %d&apos;,largest,sec_largest); } </n;></pre> <hr></10;></pre></5;i++){>

Приклад масиву C: сортування масиву

У наступній програмі ми використовуємо метод бульбашкового сортування, щоб сортувати масив у порядку зростання.

 #include 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 a[i]) temp="a[i];" a[i]="a[j];" a[j]="temp;" } printf(\'printing sorted element list ...
\'); for(i="0;" i<10; printf(\'%d
\',a[i]); < pre> <h2>Program to print the largest and second largest element of the array.</h2> <pre> #include void main () { int arr[100],i,n,largest,sec_largest; printf(&apos;Enter the size of the array?&apos;); scanf(&apos;%d&apos;,&amp;n); printf(&apos;Enter the elements of the array?&apos;); for(i = 0; i<n; i++) { scanf(\'%d\',&arr[i]); } largest="arr[0];" sec_largest="arr[1];" for(i="0;ilargest)" else if (arr[i]>sec_largest &amp;&amp; arr[i]!=largest) { sec_largest=arr[i]; } } printf(&apos;largest = %d, second largest = %d&apos;,largest,sec_largest); } </n;></pre> <hr></10;>