Thread: help please

  1. #1
    mohammed
    Guest

    help please

    Can someone please help me out if you can.

    I am trying to understand the difference between preincrement and postincrement. I am trying to figure out the value of total when exiting each of the following while repetition structures (looking to enter the answer after each while repetition structure):

    int x = 1, total = 0;
    while ( ++x <= 5 ) {
    total += x;
    }

    int x = 1, total = 0;
    while ( x++ <= 5 ) {
    total += x;
    }

    Thanks

  2. #2
    Registered User
    Join Date
    Nov 2002
    Posts
    1,109
    in the first example, the value of x is changed to 2 before it is compared.

    in the second example, the value of x in the initial comparison is 1 and then will change after the comparison.

    compile it, run it, and see the results.

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Here's a simple example of pre/post increment
    Code:
    x = 1;
    std::cout <<"Preincrementing x you get " <<++x <<std::endl;
    std::cout <<"x is now " <<x <<std::endl;
    x = 1;
    std::cout <<"Postincrementing x you get " <<x++ <<std::endl;
    std::cout <<"x is now " <<x <<std::endl;
        
    Preincrementing x you get 2
    x is now 2
    Postincrementing x you get 1
    x is now 2
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  4. #4
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed