- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Initializing array with variable vs a real number in C++
An array is a collection of same type of elements at contiguous memory location. The lowest address in the array corresponds to the first element while highest address corresponds to the last element. The array index starts with zero(0) and ends with the size of array minus one(array size - 1).
An array can be initialized with variables as well as real numbers. A program that demonstrates this is given as follows.
Example
#include <iostream> using namespace std; int main() { int a = 5; int b = 3; int arr[4]; arr[0] = a; arr[1] = 8; arr[2] = b; arr[3] = 2; cout << "The elements of array are: "; for(int i = 0; i<4; i++) cout << arr[i] << " "; return 0; }
Output
The output of the above program is as follows.
The elements of array are: 5 8 3 2
Now let us understand the above program.
An array arr of size 4 is declared. Two int variables a and b are initialized with values 5 and 3 respectively. The first and third elements of the array are initialized with the variables a and b while the second and fourth elements of the array are initialized with the real numbers 8 and 2. The code snippet that shows this is as follows.
int a = 5; int b = 3; int arr[4]; arr[0] = a; arr[1] = 8; arr[2] = b; arr[3] = 2; cout << "The elements of array are: "; for(int i = 0; i<4; i++) cout << arr[i] << " ";