As you can see in the code size=0 ; then how later code size-1 will lead to -1, can you explain me the code !!! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

As you can see in the code size=0 ; then how later code size-1 will lead to -1, can you explain me the code !!!

#include <iostream> using namespace std; class Queue { int size; int* queue; public: Queue() { size = 0; queue = new int[100]; } void remove() { if (size == 0) { cout << "Queue is empty"<<endl; return; } else { for (int i = 0; i < size - 1; i++) { queue[i] = queue[i + 1]; } size--; } } void print() { if (size == 0) { cout << "Queue is empty"<<endl; return; } for (int i = 0; i < size; i++) { cout<<queue[i]<<" <- "; } cout <<endl; } //your code goes here void add(int x){ size+=1; queue[size-1]=x; } }; int main() { Queue q; q.add(42); q.add(2); q.add(8); q.add(1); q.print(); q.remove(); q.add(128); q.print(); q.remove(); q.remove(); q.print(); return 0; }

18th Feb 2022, 3:45 PM
Sabnis Ashutosh
Sabnis Ashutosh - avatar
3 Answers
+ 1
Question is not clear..? do you mean about queue[size-1]=x?
18th Feb 2022, 3:58 PM
Jayakrishna 🇮🇳
+ 1
It's first incrementing , then using current position.. When size = 0 size+=1 causes size=1 but current position is 0 index so queue[1-1]=queue[0] = x It won't go to -1 But better way to write is : void add(int x) { queue[size] = x; size = size + 1; } //you can put overflow condition as well in add. Hope it helps..
18th Feb 2022, 4:05 PM
Jayakrishna 🇮🇳
0
Yes
18th Feb 2022, 4:00 PM
Sabnis Ashutosh
Sabnis Ashutosh - avatar