Last Updated : 10 Apr, 2024

The number of times while loop executes in the program given below:

#include <iostream>
#include <vector>
using namespace std;

int main() 
{
    vector <int> v = {1, 2, 3, 4, 5, 6};
    vector <int> :: iterator ptr = v.begin();
    advance(ptr, 3);
    int count = 0;
    while(ptr != v.end())
    {
        count++;
         ptr++;
    }
    cout << count;
    return 0;
}

(A) 4
(B) 3
(C) 2
(D) 1


Answer: (B)

Explanation:

advance(): The function is used to increment the iterator 
position till the specified number mentioned in its arguments.

Thus iterator starts from 4th element and value of count becomes 3.


Share your thoughts in the comments