- 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
Initialization of a normal array with one default value in C++
The entire array can be initialized to zero very simply. This is shown below.
int arr[10] = {0};
However, it is not possible to initialize the entire array to a non-zero value using the above method. This is shown below.
int arr[10] = {5};
In the above example, only the first element will be initialized to 5. All others are initialized to 0.
A for loop can be used to initialize an array with one default value that is not zero. This is shown below.
for(i = 0; i<10; i++) { arr[i] = 5; }
In the above example, all the array elements are initialized to 5.
A program that demonstrates all the above examples is given as follows.
Example
#include <iostream> using namespace std; int main() { int a[10] = {0}; int b[10] = {5}; int c[10]; for(int i = 0; i<10; i++) { c[i] = 5; } cout<<"Elements of array a: "; for(int i = 0; i<10; i++) { cout<< a[i] <<" "; } cout<<"\n"; cout<<"Elements of array b: "; for(int i = 0; i<10; i++) { cout<< b[i] <<" "; } cout<<"\n"; cout<<"Elements of array c: "; for(int i = 0; i<10; i++) { cout<< c[i] <<" "; } cout<<"\n"; return 0; }
Output
The output of the above program is as follows.
Elements of array a: 0 0 0 0 0 0 0 0 0 0 Elements of array b: 5 0 0 0 0 0 0 0 0 0 Elements of array c: 5 5 5 5 5 5 5 5 5 5
Advertisements