Advancing the counter in an "if" structure

Good morning. I'd ask for some hints about the following homework code, which is about printing limited tickets (5 for first class and 5 for second) for a plane company, in which someone has to choose between the class to book the seat in. The issue I have is the counter in the "if" structure, because I have to initialize it. This way, though, every time the corresponding class is selected,the counter is set to 1 again and it won't advance; how could I change the choice-iteration structure?

(I included only the function for the first class since the one for the second class is basically the same. The array is initialized to 0 and every time a seat is booked, one of his ten elements has to be set to 1).

#include <iostream>
using namespace std;

int main(){
int Class;
int seats[10]={0};
cout<<"The seats vector is:\n";
for (int t=0; t<10; t++)
cout<<seats[t]<<" ";
for (int i=1; i<=10;i++){
cout<<"\nEnter 1 for first class, 2 for second: \n";
cin>>Class;

if (Class==1){
int i=1;
while (i<=5){
cout<<"Printing plane ticket.\n";
cout<<"First class ticket, your seat is number: "<<i<<".\n";
seats[i]=1;
cout<<"The seats vector is:\n";
for (int j=1; j<=10; j++){
cout<<seats[j]<<" ";
}
i++;
break;
}
return i;
}
}
}
Last edited on
When you want to sell a seat, you have to search the array for an available seat. You can't assume the first seat is available.

Lines 21-22: You are going to have an out of bounds reference. j goes from 1 to 10, but the elements of your array are 0-9.

I can't tell if this is all your code. There are issues with what you posted. The break statement is going to exit the while loop on the first iteration. The return statement is going to exit the program after the first seat is sold.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.

You're missing the
[/code]
tag.


Many thanks. I just posted part of the code without the function used for the second class, because it was almost the same as the first class. I added the break statement because I wanted to exit the loop after printing a ticket, but the loop has to be there because the program should allow to book the seats until i=5. I used the return statement because I thought it would save the value of the counter after exiting the if statement, but it doesn't work.
Topic archived. No new replies allowed.