Search

Language Selector

5.5 — While statements

The while statement is the simplest of the four loops that C++ provides, and it has a definition very similar to that of an if statement:

while (expression)
    statement;

A while statement is declared using the while keyword. When a while statement is executed, the expression is evaluated. If the expression evaluates to true (non-zero), the statement executes.

However, unlike an if statement, once the statement has finished executing, control returns to the top of the while statement and the process is repeated.

Let’s take a look at a simple while loop. The following program prints all the numbers from 0 to 9:

This outputs:

0 1 2 3 4 5 6 7 8 9 done!

Let’s take a closer look at what this program is doing. First, count is initialized to 0. 0 < 10 evaluates to true, so the statement block executes. The first statement prints 0, and the second increments count to 1. Control then returns back to the top of the while statement. 1 < 10 evaluates to true, so the code block is executed again. The code block will repeatedly execute until count is 10, at which point 10 < 10 will evaluate to false, and the loop will exit.

It is possible that a while statement executes 0 times. Consider the following program:

The condition 15 < 10 immediately evaluates to false, so the while statement is skipped. The only thing this program prints is done!.

Infinite loops

On the other hand, if the expression always evaluates to true, the while loop will execute forever. This is called an infinite loop. Here is an example of an infinite loop:

Because count is never incremented in this program, count < 10 will always be true. Consequently, the loop will never terminate, and the program will print "0 0 0 0 0 ..." forever.

We can declare an intentional infinite loop like this:

The only way to exit an infinite loop is through a return statement, a break statement, an exit statement, a goto statement, an exception being thrown, or the user killing the program.

Programs that run until the user decides to stop them sometimes intentionally use an infinite loop along with a return, break, or exit statement to terminate the loop. It is common to see this kind of loop in web server applications, that run continuously and service web requests.

Loop variables

Often, we want a loop to execute a certain number of times. To do this, it is common to use a loop variable, often called a counter. A loop variable is an integer variable that is declared for the sole purpose of counting how many times a loop has executed. In the examples above, the variable count is a loop variable.

Loop variables are often given simple names, such as i, j, or k. However, naming variables i, j, or k has one major problem. If you want to know where in your program a loop variable is used, and you use the search function on i, j, or k, the search function will return half your program! Many words have an i, j, or k in them. Consequently, a better idea is to use iii, jjj, or kkk as your loop variable names. Because these names are more unique, this makes searching for loop variables much easier, and helps them stand out as loop variables. An even better idea is to use "real" variable names, such as count, or a name that gives more detail about what you're counting.

It is best practice to use signed integers for loop variables. Using unsigned integers can lead to unexpected issues. Consider the following code:

Take a look at the above example and see if you can spot the error. It's not very obvious.

It turns out, this program is an infinite loop. It starts out by printing "10 9 8 7 6 5 4 3 2 1 blastoff!" as desired, but then goes off the rails, and starts counting down from 4294967295. Why? Because the loop condition count >= 0 will never be false! When count is 0, 0 >= 0 is true. Then --count is executed, and count overflows back to 4294967295. And since 4294967295 is >= 0, the program continues. Because count is unsigned, it can never be negative, and because it can never be negative, the loop won't terminate.

Rule: Always use signed integers for your loop variables.

Iteration

Each time a loop executes, it is called an iteration. Often, we want to do something every n iterations, such as print a newline. This can easily be done by using the modulus operator on our counter:

This program produces the result:

01 02 03 04 05 06 07 08 09 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50

Nested loops

It is also possible to nest loops inside of other loops. In the following example, the inner loop and outer loops each have their own counters. However, note that the loop expression for the inner loop makes use of the outer loop's counter as well!

This program prints:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Quiz

1) In the above program, why is variable inner declared inside the while block instead of immediately following the declaration of outer?

Show Solution

2) Write a program that prints out the letters a through z along with their ASCII codes. Hint: to print characters as integers, you have to use a static_cast.

Show Solution

3) Invert the nested loops example so it prints the following:

5 4 3 2 1
4 3 2 1
3 2 1
2 1
1

Show Solution

4) Now make the numbers print like this:

        1
      2 1
    3 2 1
  4 3 2 1
5 4 3 2 1

hint: Figure out how to make it print like this first:

X X X X 1
X X X 2 1
X X 3 2 1
X 4 3 2 1
5 4 3 2 1

Show Solution

5.6 -- Do while statements
Index
5.4 -- Goto statements

92 comments to 5.5 — While statements

  • Cameron

    Why does the last program print

    Instead of

    ? Am I missing something? It seems to only print one number each time it repeats by looking at the code.

    • This happens because there is a loop inside of a loop.

      The outer loop iterates iii from 1 to 5. The inner loop iterates jjj from 1 to iii.

      Each time the outer loop iterates, all of the inner loop iterations are restarted.

      So the first time, iii = 1 and jjj = 1. The inner loop executes once and prints 1.
      The second iteration, iii = 2 and jjj = 1. The inner loop executes twice and prints 1 2.
      The third iteration, iii=3 and jjj = 1. The inner loop executes three times and prints 1 2 3.
      And so on.

    • Noha

      notice what i changed in the given example…

      • how do i get the previous code to read this?
        12345
        1234
        123
        12
        1

        pliz reply asap!!!

        • Elpidius

          This program prints:

          1 2 3 4 5
          1 2 3 4
          1 2 3
          1 2
          1

          I hope this helps.

    • Canute

  • Mohamad

    I rerote the code from the first example to request an integer from the user and then add each number to the next number on the row and give the combined sum of the row.

    The resulting output for 5 iterations is:
    Enter the number you want to add up to: 5
    1 = 1
    1 + 2 = 3
    1 + 2 + 3 = 6
    1 + 2 + 3 + 4 = 10
    1 + 2 + 3 + 4 + 5 = 15

    Not sure but If I’m right, but I think this is a fibonacci sequence. (please correct me if I’m wrong)
    It took a while to figure out the logic (and I sure this is probably not the most efficient solution, but it works)… sorry for the lack of comments… I’m gonna go back and comment more. Great Tutorial… I finally feel like I’m getting somewhere.

  • CSESTUDENT

    Is it acceptable to write the quiz question in this way?

    • Quinn

      It’s acceptable and will compile, but for readability it’s a bit ambiguous. It may not be plainly obvious what is meant by 97 and 122.

      I also believe static_cast<char>(chValue) is unnecessary, it should just be chValue.

  • Matthew

    Instead of doing:

    I did:

    It compiled and worked fine. It seems easier than the static_cast code. Is that bad coding/is there a reason why it shouldn’t be done like that?

    Thanks

    • Quinn

      (int)chValue is a C-style cast, whereas static_cast<int>(chvalue) is a C++ style one, and they are different in the fact that C-style casts are less type safe than C++ ones. Because of this, it is always suggested that you do, and get into the habit of doing, static_cast instead of C-style casts. Alex talked about this in lesson 4.4.

  • Radek

    Don’t forget that infinite loops like

    is usually used in web servers!

  • mks

    first i want to thank for this awesome tutorial
    i tried this code

    i thought the output is 1
    12
    123
    but it shows
    1
    12
    wats the wrong can somebody explain

    • nishido

      You would need


      while(jjj<=iii)...

      notice the extra equals. Just using less than stops before the value of iii. So in your code you have, while jjj is between 1 and 2 inclusive (i.e. less than iii which equals a max of 3), print jjj.

  • nishido

    So I tried to solve Euler’s problem #1 (calculate the sum of all multiples of 3 or 5 below 1000) using a while statement, but for some reason there’s a problem with a local variable. Here’s my code:


    int sumOfMultiples(int limit)
    {
    int sum;
    int iii=0;
    while (iii<=limit)
    {
    if (iii % 3 == 0 || iii % 5 == 0)
    {
    sum += iii;
    }
    iii++;
    }

    return sum;
    }

    I keep getting an error when I try to run, saying sum isn’t initialized. When it is. It’s initialized outside the if and while blocks, so it should still carry into those blocks shouldn’t it? If I declare sum as “static int sum” then it works, but I don’t see why it doesn’t work otherwise.

  • pranesh

    the following code prints like:
    98 a
    99 b
    .
    .
    .
    .
    123 z
    what is the problem with the code, please answer?

    int main()
    {

    int iii = 97;
    while (iii <= 122)
    {
    cout << iii << "t" << (char)iii++ << endl;

    }

    return 0;

    }

  • Leolas

    Hi! this is how i made the question 2, i think that is very similar, but i used the correspondent ASCII code instead of the letter; however, it prints the same thing.

  • Jackson maduranga_SAC

  • Francis

    On the last program, What if I wanted to print in reverse to the left like this here:

                  1
               2 1
            3 2 1
         4 3 2 1
      5 4 3 2 1

    How should I do it? reply asap.

    • Alex

      My advice would be to figure out how to do this first:

      X X X X 1
      X X X 2 1
      X X 3 2 1
      X 4 3 2 1
      5 4 3 2 1

      Then replace ‘X’ with ‘ ‘.

      • UsoToChinmoku

        Well, I created a third loop that prints white space and tied the counter to the outer loop. Is there a better solution?
        (EDIT: I double-posted by mistake, and for some reason can’t edit/delete the older post. Feel free to remove it.)

        • Alex

          The only thing that I can think of is since your inner loop always needs to execute 5 times (to print either a space or a number) perhaps both of the inner loops could be consolidated into a single inner loop that uses an if statement to determine whether it should print a space or a number. The code might be easier to follow since it has one less loop.

        • Shiva

          That felt like a bonus challenge (thank you Francis), so I went on to try and crack it myself:

          Just now I saw it also conforms with Alex’s suggestion to use a single inner loop and an if statement. Yay!

          A humble suggestion back to Alex: it’d be great if you could put this problem up as Quiz #4 (or at least as a bonus question) to this section; it is a little more challenging as well as rewarding. People are always asking for more practice questions to work out, and I don’t think everyone reads all the comments.

          • Alex

            Done. I hope you don’t mind that I used your solution as the answer too. It looks good. :)

            • Shiva

              Mind? I couldn’t have a greater honour! Thanks for the complement, Alex! Emotion-buffer overflowed. =)

              Just overwhelmed to see my own code featured at the top.. 😀

            • Alex

              I’ve added a comment to the solution to note that the solution came from you. :)

            • Shiva

              Oh! There was no need at all.. I was overwhelmed enough already. 😀

              Glad that I could contribute something. Thanks the umpteenth time for these tutorials. Keep making them better. :)

  • Andy356

    Hi, I was making a program to check if a number is a palindrome. While doing that, I thought, if I can reconstruct the reverse of a number using single digits, then I can easily reconstruct the number itself. Turns out, not so easy. I’ve dry run this code on paper several times. I keep getting wrong answers. For single digits, I get (10,20,30…) for (1,2,3…). For double digits, for example 15, I get [(1+5)10]+1=61. My mistake constantly slips through my eyes. Please help me out. Here’s the code:

    • Andy356

      Oops. Sorry. I forgot that ^ isn’t the exponent operator and I had to use pow(10,i) from <cmath>. ^_^ Stupid thing lost me marks in school too.

      And I just learned that it is actually a bitwise operator. Now I definitely won’t forget it. :)

      Thank you for your awesome tutorials! I hope you’ll keep updating them as the language evolves.

  • Eric

    Hey!  Just wondering why you are using iii++ instead of ++iii, as you said the latter was preferable in an earlier lesson?

  • ProCodes

    This was mine. Instead of letters, I used starting from a to go to 122 for the end of the characters in the order of the integer char uses. I think this is more performance efficient since static casting and such should only be done is absolutely neccessary.

  • Aacon

    good tutorial.

  • Todd

    Typos.

    "The code block will repeatedly execute until iii == 10" (what do you mean by ‘iii’? This notation hasn’t been introduced yet)

    "Then count-- (--cout) is executed"

    "An (And) since some large number is >= 0"

    "instead of following immediately following the declaration of outer?" (remove the first ‘following’)

    Quiz 3:

    Your solution to Quiz 3 doesn’t appear as code formatting. This is because you start your code with [/code] instead of [code].

    Also, you forgot to write ‘<iostream>’ after ‘#include’.

  • Samirax

    Your solution in Question 2 lacks "return 0;" I think, doesn’t it?

  • Jahan

    I don’t think you’re blastoff code will actually return "10 9 8 7 6 5 4 3 2 1 blastoff! 10 9 8 7 6 5 4 3 2 1 blastoff! …". Once it overflows, count is much much bigger than ten. It returns more like

    "10 9 8 7 6 5 4 3 2 1 blastoff! 4294967295 4294967294 4294967293 4294967292 4294967291 4294967290 4294967289 4294967288 4294967287 4294967286 4294967285 4294967284 4294967283 4294967282 4294967281 4294967280 4294967279 4294967278 4294967277 4294967276 4294967275 4294967274 4294967273 4294967272 4294967271 4294967270 4294967269 4294967268 4294967267 4294967266 4294967265 4294967264 4294967263 4294967262 4294967261 4294967260 4294967259 4294967258 … "

  • Hey Alex. I have cleeared while loop in this tutorial. Can I solve Project Euler questions now or it would take some more time to knock there. What would you expect from me If my knowledge is limited to while loops.

    • Alex

      I’m not familiar with Project Euler. Regardless, my advice is the same: Try it, and if you hit a blocker, come back and learn some more, then try again.

  • "The only way to exit an infinite loop is through a return statement, a break statement, an exit statement, an exception being thrown, or the user killing the program."

    did you forgot the goto statement here or just left itintentionally. If excluding goto is intentional, please explain why?
    Thanks…

  • Jinno

    1.Write a program that will compute for and display the sum of all numbers divisible by 3 from 1 to 1000.

    2.Write a program that will display the following pattern, given the value of n.
    Example:
    Enter a Number: 5
    *****
    ****
    ***
    **
    *

    3.Write a program that will display the following pattern, given the value of n.
    Example:
    Enter a Number: 5
    *
    **
    ***
    ****
    *****

    4.Write a program that will display the following pattern, given the value of n.
    Example: if n = 4, output
    4321
    321
    21
    1

    5.Write a program that will display the following pattern, given the value of n.
    Example: if n = 5, output
    *
    * *
    * * *
    * * * *
    * * * * *

    Can you help me?

  • Mr D

    In the code snippet below (your last prog from the tutorial) i don’t understands why the program doesn’t print (as first number) "2"!
    Because the first print-out is generated by the code:
    std::cout << inner++ << " ";
    But as inner = 1, surely inner++ evaluates to "2". So it should print "2", right?!

  • Mr D

    Ahhh wait, the compiler first prints inner, then ++’s it????

    So this:
    std::cout << inner++ << " " << inner << "n";
    prints out: 1 2

    I don’t understand that. Or is it a simple question of the arrow of time (compiler-wise) first reading to the end of the word "inner", printing it out, and only then seeing the "++"?

    Weird!

  • > Rule: Always use signed integers for your loop variables.

    I am not OK with this affirmation. Your code is just badly conceived: a count cannot go under 0, so using unsigned integers is the right thing to do, but the code should be organized as follows.

    • Alex

      Bjarne Stroustrup (the creator of C++) says, “The unsigned integer types are ideal for uses that treat storage as a bit array. Using an unsigned instead of an int to gain one more bit to represent positive integers is almost never a good idea. Attempts to ensure that some values are positive by declaring variables unsigned will typically be defeated by the implicit conversion rules.”

      I agree that while you could rewrite the program as you suggest (I need to find a better example), use of unsigned int here is still not recommended.

  • Sreedev

    An easier way to do quiz #2 for beginners who doesn’t know about static_cast is as following:

  • ibran

    how to code that one
    1****
    12***
    123**
    1234*
    12345

  • ibran

    how to code that one using while
    1****
    12***
    123**
    1234*
    12345

  • Rob G.

    Hi Alex, another great session. I used the static cast but an alternative is to use the increment itself that matches the ASCII code (60-95) counter (60-95). Post both

    no static cast:

    former - with static cast

    • Alex

      What you’ve done here is used an C++’s ability to implicitly convert an int to a char. Your compiler should give you warning about this since loss of data may result (since you’re putting the value of a variable with a larger range into a variable with a smaller range).

      Personally, I think the static_cast version is better, as it avoids the temporary variable, and makes it clear you’re intending to do a conversion rather than relying on C++ to infer that.

  • Ian R

    Hey so I wanted to test myself on a bunch of the code you’ve taught up to this point. Below I have a program where a user can create a character, review the character and decide whether to do it over. I’ve gotten it to work as intended up until the user decides to redo the creation. At this point the while loop prints ‘getName’ but doesn’t wait for user input before moving on to ‘getType’. I’ve had good luck finding other answers on google but I haven’t been able to search for this problem.

    [code]
    #include "stdafx.h"
    #include <iostream>
    #include <string>

    enum class Type
    {
        None = 0,
        Warrior = 1,
        Thief = 2,
        Priest = 3,
        Mage = 4
    };

    enum class Race
    {
        Human,
        Elf,
        Dwarf,
        HalfOrc
    };

    struct Character
    {
        std::string name;
        Type type;
        //Race race;
        int level;
    };

    std::string getName()
    {
        std::string name;

        std::cout << "Enter a name for your character: ";
        std::getline(std::cin, name);
        std::cout << "\n";

        return name;
    }

    Type getType()
    {
        Type classType = Type::None;
        int tempType;

        std::cout << "Choose a class for your character: \n";
        std::cout << "1. Warrior\n" << "2. Thief\n" << "3. Priest\n" << "4. Mage\n";
        std::cin >> tempType;
        std::cout << "\n";

        switch (tempType)
        {
            case 1:
                classType = Type::Warrior;
                break;
            case 2:
                classType = Type::Thief;
                break;
            case 3:
                classType = Type::Priest;
                break;
            case 4:
                classType = Type::Mage;
                break;
        }

        return classType;
    }
    /*
    Character getRace()
    {
        Character race;

        return race;
    }
    */
    int getLevel()
    {
        int level;

        std::cout << "Enter a starting level for you character: ";
        std::cin >> level;
        std::cout << "\n";

        return level;
    }

    void reportCharacter(Character playerCharacter)
    {
        std::cout << "Your character’s name is: " << playerCharacter.name << "\n";
        
        if (playerCharacter.type == Type::None)
            std::cout << "Your character’s class is: Warrior\n";
        else if (playerCharacter.type == Type::Thief)
            std::cout << "Your character’s class is: Thief\n";
        else if (playerCharacter.type == Type::Priest)
            std::cout << "Your character’s class is: Priest\n";
        else if (playerCharacter.type == Type::Mage)
            std::cout << "Your character’s class is Mage\n";
        else
            std::cout << "Your character does not have a class";
        
        //std::cout << "Your character’s race is: " << playerCharacter.race << "\n";
        std::cout << "Your character’s level is: " << playerCharacter.level << "\n";
    }

    void characterCreation()
    {
        Character playerCharacter;
        
        bool creatingCharacter = 0;
        
        std::string tempName;
        Type tempType;
        //Race tempRace;
        int tempLevel;

        while (!creatingCharacter)
        {
            tempName = getName();
            tempType = getType();
            //tempRace = getRace();
            tempLevel = getLevel();
            
            playerCharacter = { tempName , tempType , /*tempRace , */tempLevel };

            reportCharacter(playerCharacter);

            std::cout << "Is this correct? Enter 0 for no and 1 for yes: ";
            std::cin >> creatingCharacter;
            std::cout << "\n";
        }
    }

    int main()
    {
        characterCreation();
        
        return 0;
    }

    • Alex

      When you enter 0 for no, it actually enters “0\n” into the I/O stream. creatingCharacter pulls out the 0, but the ‘\n’ character is still in the stream. So when getName() is executed again, getline() goes to get input, sees the ‘\n’ and reads that.

      After you read a number using std::cin, it’s a good idea to remove the ‘\n’ from the stream. You can do this via ignore:

      • Ian R

        Thanks for the explanation! Love the tutorials.

        Is there an easy explanation for what that solution you provided does?

        • Alex

          Yes. cin.ignore(32767, ‘\n’) tells cin to discard up to 32767 consecutive newline characters at the front of the stream.

          So, we entered “0\n”. The 0 went into variable creatingCharacter, but the ‘\n’ was still inside std::cin, waiting to be extracted. This clears it out, so that by the time we get to the next getline(), the buffer is empty, and getline() will appropriately wait for user input.

  • Roberto

    Hi Alex!
    I’ve solved exercise 2 like this instead:

    let me know if it’s fine the same. thanks!

    • Alex

      Since you’re using chars, you really should use char literals (e.g. ‘a’) instead of integer literals (97).

      You could also static_cast count to a char in your output statement rather than assign count to a temporary char variable to do the conversion.

  • Sandro

    Hello. In the second quiz, I first tried this (wrongly):

    This returns something like "b = 97 …". Shouldn’t it print like "a = 98 …"?

    I understand that the precedence of the parenthesis is higher than the "++" operator.

    • Alex

      Regardless of how this statement is evaluated, it breaks one of the cardinal rules of programming in C++: Don’t use any variable that has a side effect applied more than once in a single expression. Doing so is just begging for trouble.

      It does appear chValue++ is being evaluated first. chValue starts at value 97. static_cast(chValue++) evaluates to int 97, and chValue is incremented. Then everything is printed left to right: chValue is ‘b’, and the static_cast already evaluated to 97, so you get b = 97.

  • Elpidius

    Hey Alex, I just noticed 2 typos.

    The first is at the top, right before the first example:
    "The following program prints all the numbers from 0 and 9", which should read "0 to 9".

    Also at the end, in the last example, inside the inner loop:

    Should read:

  • Joshua Richards

    Hi Alex,
    I did question 4 a bit differently and was wondering what you thought about it?

    #include <iostream>

    int main()
    {
       int count = 1;
       while (count <= 5)
         {
            switch (count)
            {
               case 1:
               {
                  std::cout << "        1\n";
                  break;
               }
               case 2:
               {
                  std::cout << "      2 1\n";
                  break;
               }
               case 3:
               {
                  std::cout << "    3 2 1\n";
                  break;
               }
               case 4:
               {
                  std::cout << "  4 3 2 1\n";
                  break;
               }
               case 5:
               {
                  std::cout << "5 4 3 2 1\n";
                  break;
               }
            }
            ++count;
         }
         return 0;
    }

    • Alex

      It works, but it sort of misses the point of the lesson. What would you have done if I’d ask you to do this with 100 rows instead of 5? :)

  • joy

    how to do this?? Problem

    * * * * * * * * * *
    * * * * * * * * * *
    * * * * * * * * * *
    * * * * * * * * * *
    * * * * * * * * * *
    * * * * * * * * * *

  • joy

    how to do this?? Problem

    1 + 1 = 2
    2 + 2 = 4
    3 + 3 = 6
    4 + 4 = 8
    5 + 5 = 10

    thanks for response. :)

  • Hani-7amad

    hello guys
    I have a little problem
    and I don’t know from where to start :ermm:
    there is a program I couldn`t write
    and I`d like to ask you if you could help me , I`d appreciate so much

    here it is

    http://i.imgur.com/kctDHPO.png

    http://i.imgur.com/nbdgd5C.png

    I’m really struggling , Plz help me here
    thank you.

  • Patrick

    Hi Alex,

    I try to create functions to solve your quizzes in this chapter. It is my understanding that each function should complete one task only.

    In commercial applications/code, is there a lot of code in the main() function or only one statement that points to other class file(s) with functions? What is best practice here?

    For example under exercise 4, I only have PrintExercise() in the main() function but I don’t know if this is advisable and the right thing to do. Could you please shed some light based on your professional experiences?

    • Alex

      It totally depends on the program and programmer. I’ve seen main() functions that are super long, and main functions that are super short.

      I personally tend to write main() functions that look like some variant of this:

      • Patrick

        Thank you for sharing your review and your setup makes perfect sense to me. I almost see the main() function as a table of content for the program. Meaning that function calls listed under the main functions are calls to distinct top hierarchy components of the program.

  • fernando

    Write a program that will take from user two signs on interval [‘a’, ‘z’] and print out pyramid made of
    letters. For example, if ‘c’ and ‘g’ are entered, pyramid should look like this:
    c
    cdc
    cdedc
    cdefedc
    cdefgfedc

  • Amber

    This may have been asked and answered but I have a question about the increments. In your final example in this section, you use a post-increment on "inner" and a pre-increment on "outer." Then in question #2, you use a post-increment on "chValue" (on my first attempt before looking at your solution, I used a pre-increment because I thought "chValue" was very similar to the "outer" variable in your example). How are you determining whether to do a pre- or post-increment? Back when you first talk about increments in Chapter 3, you mention that as a general rule it is better to favor pre over post. I am having a hard time figuring out which one I am supposed to use in certain situations, and you don’t really go into details about why you are choosing one over the other (unless I missed something).

    • Alex

      I always favor pre-increment unless there’s a specific reason to use post-increment. I used a post-increment in the inner loop because I want to print a value and THEN increment it.

      The chValue post-increment should have been a pre-increment -- just a mistake on my part. I’ve updated the example.

  • abaidullah

    a C++ program that first reads lower and upper limits and reads 10 numbers from the user. The program
    should print numbers of time a number is in between the given limits
    I Need this program with whilw loop

  • Jane Doe

    Ummmm maybe we shouldn’t name our loop variables kkk… You are kinda sending the wrong message here Alex.

  • Jane Doe

    Solution to 3. My brain didn’t see the nice simple solution.

    • Jane Doe

      Is it bad to get a different answer? My answer wasn’t as neat.

      • Alex

        Different isn’t bad in and of itself. There are often many ways to solve the same problem at the same level of quality. What’s worse is if the alternative solution is a lower quality solution in terms of readability, performance, robustness, etc…

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter

  

  

  

four × three =