Home  >  Article  >  Backend Development  >  Arrays in C/C++ programs

Arrays in C/C++ programs

WBOY
WBOYforward
2023-09-01 10:41:15848browse

Arrays in C/C++ programs

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

Each single element of a value can be accessed from its index value using square brackets "[]" and array names like a[4], a[3], etc.

Declaring arrays

In the c/c programming language, an array is declared by defining the type and length (number of elements) of the array. The following syntax shows the method of declaring an array in c/c −

data_tpye array_name[length];

For example, declare an array of float type named Percent with length 10.

float percentage[10]

Initializing Array Values

In C programming language, you have multiple ways to initialize values, i.e. initialize one by one or declare all the values ​​using a single statement.

Initialize one by one-

percentage[5] = 45.3;

Declare all values ​​at once-

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

0 1 2 3 4 5
78.06 56.78 99.20 12.22 87.66 34.44

Access Array Element

To access the value of an array, we will use the index value and the name of the array in curly braces. For example,

float anam’spercentage = percentage[4];

Example

Program that uses for loop to print all values ​​of array

Real-time demonstration

#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 array Specific value −

Example

Online demonstration

#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

Reinitialize the array value−

Example

Real-time demonstration

#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

The above is the detailed content of Arrays in C/C++ programs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete