Question
Download Solution PDFWhich of the following can be used to determine the number of elements present in an array Arn?
Answer (Detailed Solution Below)
Detailed Solution
Download Solution PDFThe correct answer is Option 2) sizeof(Arr) / sizeof(Arr[0]).
Key Points
- In C/C++,
sizeof
is used to determine the memory (in bytes) occupied by a data type or variable. - To find the number of elements in an array
Arr
, we use the formula:
sizeof(Arr) / sizeof(Arr[0])
- This divides the total size of the array (in bytes) by the size of one element, giving the total number of elements.
- Example:
Ifint Arr[5] = {10, 20, 30, 40, 50};
sizeof(Arr) = 20
bytes (5 integers × 4 bytes each)
sizeof(Arr[0]) = 4
bytes
So,20 / 4 = 5
elements.
Additional Information
- Option 1 – sizeof(Arr[0]): ❌ This only gives the size of the first element, not the total number of elements.
- Option 3 – sizeof(Arr): ❌ Gives total size in bytes, not the count of elements.
- Option 4 – sizeof(Arr[MAX]): ❌ Incorrect and may even lead to an error if MAX is not defined properly or goes out of bounds.
Conclusion: Use sizeof(Arr) / sizeof(Arr[0]) to correctly determine the number of elements in an array.
Last updated on Nov 25, 2024
-> BELTRON Programmer 2024 Notification has been released on the official website.
-> The Bihar State Electronics Development Corporation Limited (BELTRON) has announced a recruitment drive for Programmer positions on a contractual basis.
-> Specific vacancy details will be shared separately.
-> Interested candidates can apply online from November 11, 2024, to December 10, 2024.
-> The Minimum age of the candidates should be 21 years and maximum age should be 59 year of age.