loop tracking

  • (2 Pages)
  • +
  • 1
  • 2

18 Replies - 508 Views - Last Post: 14 February 2013 - 02:13 AM Rate Topic: -----

#16 raghav.naganathan  Icon User is offline

  • Perfectly Squared ;)
  • member icon

Reputation: 408
  • View blog
  • Posts: 1,440
  • Joined: 14-September 12

Re: loop tracking

Posted 13 February 2013 - 08:54 PM

Well, a small correction...I think it should be

13 if(word.at(i)=='y')// changed the [] to ()


What the program does is, it loops through the entire string word and checks if the letter 'y' is present or not.

Consequently you could also have an else to have continuation in the code...something like this.

else
    {
     cout << "Your word, " << word << " doesn't contain " << word.at(i) << endl;
    }


regards,
Raghav

This post has been edited by raghav.naganathan: 13 February 2013 - 08:54 PM

Was This Post Helpful? 0
  • +
  • -

#17 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1072
  • View blog
  • Posts: 4,532
  • Joined: 09-June 09

Re: loop tracking

Posted 13 February 2013 - 09:14 PM

Quote

Thank you for ur help. my question is how to make sure it only prints out " your word contains Y ", once, even if the word contains more than one 'y'.

If you don't want to use a 'break', you can use a boolean flag siginifying if a letter 'y' has not been found in the word and use this as a condition in your for loop.

flag = false;

loop while index is less than string size && flag == false
   if str[index] equals 'Y'
      print message
      flag = true


Was This Post Helpful? 0
  • +
  • -

#18 TheKirk  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 58
  • Joined: 10-February 13

Re: loop tracking

Posted 14 February 2013 - 12:29 AM

I know the answer, it currently prints if one y is found but keeps printing this if more 'y's are found, the solution is the break statement:

#include <iostream>
#include <string>

using namespace std;

int main() 
{
	string word;
	cout << "Please enter word ";
	cin >> word;
	for(unsigned int i=0; i< word.size(); i++) 
	{
		if(word.at[i]=='y') // Instead of | this must be )
		{
			cout << "Your word, " << word << "contains " << word.at(i) << "\n";
			break; // will stop the loop
		}                
	}
	return 0;
}

Was This Post Helpful? 0
  • +
  • -

#19 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1072
  • View blog
  • Posts: 4,532
  • Joined: 09-June 09

Re: loop tracking

Posted 14 February 2013 - 02:13 AM

Adding an extra condition to your loop will also work, as an alternative to a break


#include <iostream>
#include <string>

using namespace std;

int main() {
   int ndx;
	string word;
	cout << "Please enter word ";
	cin >> word;

	for(ndx=0; i < word.size() && word[i] != 'y'; i++);

   if(ndx != word.size())
	   cout << "Your word, " << word << "contains " << word.at(i) << "\n";


	return 0;
}


Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2