How to use a Sentinel Value In C++
We can add a special value to the end of the array to indicate the end of the array, and then loop through the array until you find the sentinel value. This method is commonly used in string manipulation.
C++ program to Find the Size of an Array using a Sentinel Value
C++
// C++ program to find size of // an array using sentinel value #include <iostream> using namespace std; int main() { // maximum size of the array const int MAX_SIZE = 100; // declare the array int arr[MAX_SIZE]; // sentinel value to indicate the end // of the array int sentinel = -1; // read values into the array until the sentinel value // is entered int i = 0; // counter variable while (i < MAX_SIZE) { cout << "Enter a value for element " << i << " (or -1 to stop): " ; cin >> arr[i]; // exit the loop if the sentinel value is // entered if (arr[i] == sentinel) { break ; } i++; } // calculate the size of the array // the size of the array is the number of // elements entered int size = i; // print the size of the array cout << "Size of the array: " << size << endl; return 0; } // This code is contributed by Susobhan Akhuli |
Output
Enter a value for element 0 (or -1 to stop): Enter a value for element 1 (or -1 to stop): Enter a value for element 2 (or -1 to stop): Enter a value for element 3 (or -1 to stop): Enter a value for el...
Output
Enter a value for element 0 (or -1 to stop): 3 Enter a value for element 1 (or -1 to stop): 7 Enter a value for element 2 (or -1 to stop): 2 Enter a value for element 3 (or -1 to stop): 9 Enter a value for element 4 (or -1 to stop): 5 Enter a value for element 5 (or -1 to stop): -1 Size of the array: 5
Complexity Analysis
- Time complexity: O(n), where n is the number of elements in the array.
- Auxiliary space: O(1)
How to Find Size of an Array in C++ Without Using sizeof() Operator?
In C++, generally, we use the sizeof() operator to find the size of arrays. But there are also some other ways using which we can find the size of an array. In this article, we will discuss some methods to determine the array size in C++ without using sizeof() operator.
Contact Us