Please help with do..while Urgently

Can someone please tell me what I'm doing wrong , cause this loop will not terminate, even if I enter the sentinal character. I really can't figure out why I'm wrong.

Int main()
{
Int maxVal = 10;
Char characters[maxVal];
Int I = 0;

Do
{
Cout<<"enter character";
Cin<<characters[i];
I++;

}While(characters[i] != 'x');

Return 0;
}

[/code]
In the loop condition you are accessing an element that was not yet assigned a value. I would rewrite the loop the following way

1
2
3
4
5
do
{
   cout << "enter character: ";
   cin >> characters[i];
} while( characters[i++] != 'x' );
Last edited on
I'm not that good with programming either, but what does characters[i] refer to? You have capital and lower case I and i. You are also capitalizing a bunch of stuff that shouldn't be, your stream operators are wrong, so I'm not even sure how it runs. 'i' was never initialized, and you never change the value of characters[i], so the while is never satisfied, I think. Wouldn't you rather use a for loop like this?

1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
const int maxVal = 10;
char characters[maxVal];

for(int i=0;characters[i] !=x; i++)
{
cout<<"enter character";
cin>>characters[i];
}

}


Edit: I'm too late.
Last edited on
you should use a while loop, while cin is reading a char and its not x then add one to int I. also all variable types should be lower case, and variables
are case sensitive. lastly, if you make the size of characters[10] you can only enter 10 values in the array, use a vector if you dont know how many chars will be entered.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

int main (){

unsigned int maxVal = 10;
char characters[maxVal];
int I = 0;


cout << "enter character" << endl;
while(cin >> characters[I] && characters[I] != 'x')
        ++I;


return 0;

}
Last edited on
 
While(characters[i] != 'x');

should be
 
While(characters[i - 1] != 'x');

As the array starts at 0 you are referencing a value that has not been set in the first one.

Also you may want to add a limit to your loop to prevent it from going past the max value of your array.

Finally
 
cin<<characters[i];

should be
 
cin>>characters[i];


edit: so late bad internet
Last edited on
Oooh Thank you its works :D. Jidder is right. And the the upper case lower case "i" is not the problem. I know c++ is case sensitive.. I just typed the code using my cellphone , that's why. I'm supposed to use a do..while loop.. Now I had the same problem using a switch which was nested inside a do..while loop. Since I'm not using arrays.. What will the condition be inside the while? I'm supposed to enter char 'X' to terminate.
Topic archived. No new replies allowed.