- 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
Why array index starts from zero in C/C++ ?
An array arr[i] is interpreted as *(arr+i). Here, arr denotes the address of the first array element or the 0 index element. So *(arr+i) means the element at i distance from the first element of the array. So array index starts from 0 as initially i is 0 which means the first element of the array.
A program that demonstrates this in C++ is as follows.
Example
#include <iostream> using namespace std; int main() { int arr[] = {5,8,9,3,5}; int i; for(i = 0; i<5; i++) cout<< arr[i] <<" "; cout<<"\n"; for(i = 0; i<5; i++) cout<< *(arr + i) <<" "; return 0; }
Output
The output of the above program is as follows.
5 8 9 3 5 5 8 9 3 5
Now let us understand the above program.
An array arr[] contains 5 elements. These elements are displayed using a for loop with array representations arr[i] and *(arr + i). The results obtained are identical in both cases. The code snippet that shows this is as follows.
int arr[] = {5,8,9,3,5}; int i; for(i = 0; i<5; i++) cout<< arr[i] <<" "; cout<<"\n"; for(i = 0; i<5; i++) cout<< *(arr + i) <<" ";
Advertisements