C ++ masīvi (ar piemēriem)

Šajā apmācībā mēs iemācīsimies strādāt ar masīviem. Mēs iemācīsimies deklarēt, inicializēt un piekļūt masīva elementiem C ++ programmēšanā, izmantojot piemērus.

C ++ masīvs ir mainīgais, kas var saglabāt vairākas viena veida vērtības. Piemēram,

Pieņemsim, ka klasē mācās 27 skolēni, un mums visiem ir jāsaglabā atzīmes. Tā vietā, lai izveidotu 27 atsevišķus mainīgos, mēs varam vienkārši izveidot masīvu:

 double grade(27);

Šeit pakāpe ir masīvs, kurā var ievietot ne vairāk kā 27 doubletipa elementus .

C ++ masīvu izmēru un veidu pēc tā deklarēšanas nevar mainīt.

C ++ masīva deklarācija

 dataType arrayName(arraySize);

Piemēram,

 int x(6);

Šeit,

  • int - glabājamā elementa tips
  • x - masīva nosaukums
  • 6 - masīva lielums

Piekļuves elementi C ++ masīvā

Programmā C ++ katrs masīva elements ir saistīts ar skaitli. Numurs ir pazīstams kā masīva indekss. Izmantojot šos indeksus, mēs varam piekļūt masīva elementiem.

 // syntax to access array elements array(index);

Apsveriet masīvu x, kuru mēs esam redzējuši iepriekš.

Masīva elementi C ++

Dažas lietas, kas jāatceras:

  • Masīvu indeksi sākas ar 0. Nozīme x (0) ir pirmais indeksā saglabātais elements 0.
  • Ja masīva lielums ir n, pēdējais elements tiek saglabāts indeksā (n-1). Šajā piemērā x (5) ir pēdējais elements.
  • Masīva elementiem ir secīgas adreses. Piemēram, pieņemsim, ka sākuma adrese x(0)ir 2120d. Tad nākamā elementa adrese x(1)būs 2124d, adrese x(2)būs 2128d un tā tālāk.
    Šeit katra elementa lielums tiek palielināts par 4. Tas ir tāpēc, ka lielums intir 4 baiti.

C ++ masīva inicializēšana

Programmā C ++ deklarācijas laikā ir iespējams inicializēt masīvu. Piemēram,

 // declare and initialize and array int x(6) = (19, 10, 8, 17, 9, 15);
C ++ masīva elementi un to dati

Cita metode masīva inicializēšanai deklarēšanas laikā:

 // declare and initialize an array int x() = (19, 10, 8, 17, 9, 15);

Šeit mēs neesam minējuši masīva lielumu. Šādos gadījumos kompilators automātiski aprēķina izmēru.

C ++ masīvs ar tukšiem dalībniekiem

Ja masīvā ir izmērs n, C ++ masīvā mēs varam saglabāt līdz n elementu skaitu masīvā. Tomēr, kas notiks, ja uzglabāsim mazāk nekā n elementu skaitu.

Piemēram,

 // store only 3 elements in the array int x(6) = (19, 10, 8);

Šeit masīva x izmērs ir 6. Tomēr mēs to esam inicializējuši tikai ar 3 elementiem.

Šādos gadījumos sastādītājs piešķir nejaušās vērtības atlikušajām vietām. Bieži vien šī nejaušā vērtība ir vienkārši 0.

Tukšajiem masīva dalībniekiem automātiski tiek piešķirta vērtība 0

Kā ievietot un izdrukāt masīva elementus?

 int mark(5) = (19, 10, 8, 17, 9) // change 4th element to 9 mark(3) = 9; // take input from the user // store the value at third position cin>> mark(2); // take input from the user // insert at ith position cin>> mark(i-1); // print first element of the array cout <> mark(i-1);

1. piemērs: masīva elementu parādīšana

 #include using namespace std; int main() ( int numbers(5) = (7, 5, 6, 12, 35); cout << "The numbers are: "; // Printing array elements // using range based for loop for (const int &n : numbers) ( cout << n << " "; ) cout << "The numbers are: "; // Printing array elements // using traditional for loop for (int i = 0; i < 5; ++i) ( cout << numbers(i) << " "; ) return 0; )

Rezultāts

 Skaitļi ir: 7 5 6 12 35. Skaitļi ir: 7 5 6 12 35

Šeit mēs esam izmantojuši forcilpu, lai atkārtotu no i = 0līdz i = 4. Katrā atkārtojumā mēs esam drukājuši numbers(i).

We again used a range based for loop to print out the elements of the array. To learn more about this loop, check C++ Ranged for Loop.

Note: In our range based loop, we have used the code const int &n instead of int n as the range declaration. However, the const int &n is more preferred because:

  1. Using int n simply copies the array elements to the variable n during each iteration. This is not memory-efficient.
    &n, however, uses the memory address of the array elements to access their data without copying them to a new variable. This is memory-efficient.
  2. We are simply printing the array elements, not modifying them. Therefore, we use const so as not to accidentally change the values of the array.

Example 2: Take Inputs from User and Store Them in an Array

 #include using namespace std; int main() ( int numbers(5); cout << "Enter 5 numbers: " << endl; // store input from user to array for (int i = 0; i > numbers(i); ) cout << "The numbers are: "; // print array elements for (int n = 0; n < 5; ++n) ( cout << numbers(n) << " "; ) return 0; )

Output

 Enter 5 numbers: 11 12 13 14 15 The numbers are: 11 12 13 14 15

Once again, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we took an input from the user and stored it in numbers(i).

Then, we used another for loop to print all the array elements.

Example 3: Display Sum and Average of Array Elements Using for Loop

 #include using namespace std; int main() ( // initialize an array without specifying size double numbers() = (7, 5, 6, 12, 35, 27); double sum = 0; double count = 0; double average; cout << "The numbers are: "; // print array elements // use of range-based for loop for (const double &n : numbers) ( cout << n << " "; // calculate the sum sum += n; // count the no. of array elements ++count; ) // print the sum cout << "Their Sum = " << sum << endl; // find the average average = sum / count; cout << "Their Average = " << average << endl; return 0; )

Output

 The numbers are: 7 5 6 12 35 27 Their Sum = 92 Their Average = 15.3333

In this program:

  1. We have initialized a double array named numbers but without specifying its size. We also declared three double variables sum, count, and average.
    Here, sum =0 and count = 0.
  2. Then we used a range based for loop to print the array elements. In each iteration of the loop, we add the current array element to sum.
  3. 1Katrā atkārtojumā mēs arī palielinām skaitīšanas vērtību , lai līdz for cilpas beigām mēs varētu iegūt masīva lielumu.
  4. Pēc visu elementu izdrukāšanas mēs izdrukājam visu skaitļu summu un vidējo vērtību. Skaitļu vidējo lielumu izsakaaverage = sum / count;

Piezīme: mēs izmantojām diapazona forcilpu, nevis parasto forcilpu.

Normālai forcilpai mums ir jānorāda atkārtojumu skaits, ko nosaka masīva lielums.

Bet diapazona forcilpa neprasa šādas specifikācijas.

C ++ masīvs ārpus robežas

Ja mēs pasludināsim masīvu ar 10 izmēru, tad masīvā būs elementi no 0 līdz 9 indeksa.

Tomēr, ja mēs mēģinām piekļūt elementam indeksā 10 vai vairāk nekā 10, tas radīs nedefinētu uzvedību.

Interesanti raksti...