While Loop

I have to setup a while loop for a question in my class but i'm not sure how to do it (lab is moving a little quicker than lecture)

We have to take the word Python and set up a while loop so that once it reaches the letter h, it displays:
"This is pass block"
"Current Letter:" <print letter here>

any help would be appreciated.
closed account (zb0S216C)
You've done this before in a previous post. All you have to do is replace the for loop with a while loop.
Last edited on
So would it be:
1
2
3
4
5
6
7
8
9
10
11
12
    
string word = "Python";
while(int i = 0) 
    {
        if( word.at(i) == 'h' ) 
        {
             cout << "This is pass block" << endl;
             cout << "Current Letter: h" << endl;
             break;
        }
        cout << word.at(i) <<endl;
    }


Last edited on
closed account (zb0S216C)
Close, but you forgot to increment i. Aftercout << word.at(i) <<endl; put i++;.
1
2
3
4
5
6
7
8
9
10
11
string word = "Python";
while(int i = 0) 
    {
        if( word.at(i) == 'h' ) 
        {
             cout << "This is pass block" << endl;
             cout << "Current Letter: h" << endl;
             break;
        }
        cout << word.at(i) <<endl; i++;
    }


I did that and when i press control F5 (start without debugging) it doesn't display anything :\
When does the condition in the while statement (i.e. int i = 0) become false to break the while loop?

I'm slightly surprised that the loop runs even once;

The value of a condition that is an initialized declaration in a statement other than a switch statement is the value of the declared variable implicitly converted to type bool.

I would have expected that integer value zero converted to type bool would come out as false. Every day is a school day.
Last edited on
I'm sorry, i'm a total beginner when it comes to c++. I took a stab at it and apparently it's completely wrong. Can you please help me figure out what I need to do?
closed account (zb0S216C)
Moschops has a good point. Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
string word = "Python";

int i( 0 );
while( i < word.length( ) ) 
    {
        if( word.at(i) == 'h' ) 
        {
             cout << "This is pass block" << endl;
             cout << "Current Letter: h" << endl;
             break;
        }
        cout << word.at(i) <<endl; i++;
    }
There we go, that worked. Thanks a lot! I really appreciate the help!!
Topic archived. No new replies allowed.