One dimensional array in C++ program
Introduction
In this post, we will discuss one-dimensional array. Arrays allow us to define a group of objects. Arrays can be defined either with or without initialization.
int Numbers[5];
int Numbers[5] = {1,2,3,4,5};
int Numbers[] = {1,2,3,4,5};
We can refer to individual array elements using the index. The index of the array starts with 0. The first element
of an array can be accessed as
Numbers[0]
An array can also be passed as parameters to function as well. Let’s write a simple program in C++ to demo the usage of one-dimensional arrays.
C++ Program
/******************************* * C++ Program to demo * one dimensional array. *******************************/ #include<iostream> using namespace std; void GetNumbers(int A[]); int SumOfNumbers(int A[]); void printArray(int A[]); const int size=5; int main() { int Numbers[size]; cout << "Please enter the numbers:" << endl; GetNumbers(Numbers); printArray(Numbers); int sum = SumOfNumbers(Numbers); cout << "Sum of numbers in array =:" << sum << endl; return 0; } /****************************** * Method to get the numbers ******************************/ void GetNumbers(int A[]) { for(int i=0; i<size; i++) { cin >> A[i] ; } } /****************************** * Method to get the sum numbers ******************************/ int SumOfNumbers(int A[]) { int sum=0; for(int i=0; i<size; i++) { sum=sum+A[i]; } return sum; } /****************************** * Method to print the array ******************************/ void printArray(int A[]) { cout << "********************************" << endl; cout << "Array = " << endl; for(int i=0; i<size; i++) { cout << A[i] << endl; } cout << "********************************" << endl; }
Sample Output:
Please enter the numbers:
45
56
105
518
67
********************************
Array =
45
56
105
518
67
********************************
Sum of numbers in array =:791
Process returned 0 (0x0) execution time : 13.969 s
Press any key to continue.
The above program is simple C++ program to demo the usage of one dimensional array of five numbers, passing the array to a function and to process the array elements in a for loop.
The IDE used in the tutorial is Code:: Blocks. To download and install Code Blocks follow the link:
https://www.testingdocs.com/download-and-install-codeblocks/
For more information on Code Blocks IDE, visit the official website of Code blocks IDE:
http://www.codeblocks.org/