A simple Queue problem; please help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96

#include<iostream>
using namespace std;
class Queue{
    private:
        int *queue;
		int q;
        int front;
		int rear;
    public:
        Queue(int);
        void enqueue(int);
        void dequeue();
        int size();
        void display();
        bool isEmpty();
        bool isFull();
};

Queue::Queue(int x)
{
    q=x;
	queue=new int[q];
	rear=-1;
    front=0;
}

void Queue::enqueue(int x)
{
	if(size()==q)
		cout<<"Queue is full! ";
	else{
		queue[front]=x;
		++rear;
	}
}

void Queue::dequeue()
{
	if(front>rear)
		cout<<"Queue is empty! ";
	else{
		queue[rear++];
		cout<<"The data dequeued is :"<<queue[rear];;
	}
}

void Queue::display()
{
    for(int i=front; i<=rear; i++)
        cout<<queue[i]<<" ";
}

int Queue::size()
{
    return (rear-front+1);
}

int main()
{
    Queue q1(2);
    int ch, x;
    while(true){
        cout<<"\n1. Enqueue\n2. Dequeue\n3. Size\n4. Display all element\n5. Quit";
        cout<<"\nWhat do you want to do?\n";
		cout<<"Enter your choice: ";
        cin>>ch;
        switch(ch){
            case 1:
                cout<<"\nEnter data: ";
                cin>>x;
                q1.enqueue(x);
            break;

            case 2:         
                q1.dequeue();
            break;

            case 3:
                cout<<"Size of Queue is "<<q1.size();
            break;

            case 4:
                q1.display();
            break;

            case 5:
		exit(0);
            break;
		}
    }
    
    system ("Pause");
    return 0;
}


Question 1.
When I dequeue a value, it displays a garbage value. Whats wrong in the following function?
1
2
3
4
5
6
7
8
9
void Queue::dequeue()
{
	if(front>rear)
		cout<<"Queue is empty! ";
	else{
		queue[rear++];
		cout<<"The data dequeued is :"<<queue[rear];;
	}
}


Question 2.
Is there any other way to break the while loop(Line no. 61) in the program instead of using
exit(0)
(Line no. 87)?
Question 2: Probably break; will help.
Topic archived. No new replies allowed.