Arrays in C++ Programming


An array is a collection of elements of the same type placed in contiguous memory locations that can be individually referenced by using an index to a unique identifier. An array is a variable that can store multiple values. For example, if you want to store 5 integers, you can create an array for it.

Syntax :
     datetype arrayName [ arraySize ] ;
Example :
     int arr [ 5 ] ;

This program demonstrates the use of arrays in C++ and prints out the elements of two different arrays:

  • Declare two integer arrays a and b.
  • Initialize a with the values 10 and 20. Since only the first two elements of a are explicitly initialized, the rest are set to 0 by default.
  • Initialize b with the values 1, 2, 3, 4, and 5.
  • Use a range-based for loop to iterate through each element x in a and print it to the console.
  • Print a separator line of dashes.
  • Use another range-based for loop to iterate through each element x in b and print it to the console.
  • Calculate and print the number of elements in a by dividing the total size of the array in bytes (sizeof(a)) by the size of a single integer in bytes (sizeof(int)).

Source Code

#include<iostream>
using namespace std;
 
int main()
{
    int a[5]={10,20};//10  20 0 0 0
    int b[]={1,2,3,4,5};
    for(int x:a)
        cout<<x<<endl;
    cout<<"------------"<<endl;
    for(int x:b)
        cout<<x<<endl;
    cout<<"Count :"<<sizeof(a)/sizeof(int);
    return 0;
}
 

Output

10
20
0
0
0
------------
1
2
3
4
5
Count :5
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples