Arrays in C/C++ program

CC++Server Side ProgrammingProgramming

The array is a collection of a fixed number of items of the same data type. These elements are stored in contiguous memory locations in the memory.

Every single element of the value can be accessed from its index value using the brackets “[]” and the array name like a[4], a[3], etc.

Declaring Arrays

In c/c++ programming languages, arrays are declared by defining the type and length (number of elements) of the array. The below syntax show declaration of an array in c/c++ −

data_tpye array_name[length];

For example, declaring an array of type float named the percentage of length 10.

float percentage[10]

Initializing array values

In c++ programming language, you have multiple ways to initialize values i.e. either one by one or using a single statement for declaring all values.

one by one −

percentage[5] = 45.3;

declaring all values at once −

float percentage[] = {56.4 , 99.0, 12.20, 67.2}


012345
78.0656.7899.2012.2287.6634.44

Accessing Array elements

To access array values, we will use index values in curly braces with the name of an array. Example,

float anam’spercentage = percentage[4];

Example

program to print all values of array using for loop

 Live Demo

#include <iostream>
using namespace std;
int main(){
   float percentage[] = {56.4 , 99.0, 12.20, 67.2};
   cout<<"printing all values of the array :\n";
   for(int i = 0; i<4 ; i++){
      cout<<"element "<<i+1<<" = "<<percentage[i]<<endl;
   }
   return 0;
}

Output

printing all values of the array :
element 1 = 56.4
element 2 = 99
element 3 = 12.2
element 4 = 67.2

print a specific value of the array −

Example

 Live Demo

#include <iostream>
using namespace std;
int main(){
   float percentage[4];
   percentage[0] = 56.3;
   percentage[1] = 99.12;
   percentage[2] = 78.32;
   percentage[3] = 61.3;
   cout<<"3rd element is "<<percentage[2];
   return 0;
}

Output

3rd element is 78.32

reinitializing array values −

Example

 Live Demo

#include <iostream>
using namespace std;
int main(){
   float percentage[4];
   percentage[0] = 56.3;
   percentage[1] = 99.12;
   percentage[2] = 78.32;
   percentage[3] = 61.3;
   cout<<"3rd element is "<<percentage[2];
   percentage[2] = 12.22;
   cout<<"\nafter change :\n";
   cout<<"3rd element is "<<percentage[2];
   return 0;
}

Output

3rd element is 78.32
after change :
3rd element is 12.22
raja
Published on 24-Oct-2019 08:44:50
Advertisements