Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Loops and Text

In the lesson on vectors, you saw that a std::string is a sequence of characters of type char: word[0] is its first character, and word.size() is the number of characters. That's why you can go through text with the same loops as through a vector. With an index:

std::string word = "Hello";
for (int i = 0; i < word.size(); i++) {
    std::cout << word[i] << std::endl;
}

Or with the range-based for, where the variable has the type char:

std::string word = "Hello";
for (char character : word) {
    std::cout << character << std::endl;
}

Both loops print:

H
e
l
l
o

A space is a character too, so for "Hi there", the loop would run 8 times. And uppercase and lowercase letters are different characters: 'H' == 'h' is false.

To compare a character, write it in single quotes: character == 'l'. With double quotes, character == "l", you would compare a character with a text, and Clang reports error: comparison between pointer and integer ('char' and 'const char *').

Printing on one line. So far, the loops printed every value on its own line, because of std::endl. Without it, the next output continues on the same line. This loop prints a space after each character, and the line ends only once, after the loop:

std::string word = "Hello";
for (char character : word) {
    std::cout << character << " ";
}
std::cout << std::endl;
H e l l o 

The loop with an index can also go backwards: start at the last index, word.size() - 1, and count down to 0 with i--. You'll try that in the exercise.

Instructions

  1. 1

    Go through text with a range-based for loop and print each of its characters on its own line.

  2. 2

    Below that, print the text backwards, on one line. Go through it with a loop with an index that starts at the last index, text.size() - 1, and counts down to 0. In the loop, print text[i] without std::endl, and end the line with std::endl after the loop. The output is desserts.

Back

5/13

  1. 1. The while Loop
  2. 2. Infinite Loops
  3. 3. The for Loop
  4. 4. Looping over a Vector
  5. 5. Loops and Text
  6. 6. Sum and Average
  7. 7. Counting
  8. 8. The Largest Value
  9. 9. Building a New Vector
  10. 10. The break Statement
  11. 11. The continue Statement
  12. 12. Nested Loops
  13. 13. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.