why do i get 5050?

This is a discussion on why do i get 5050? within the C++ Programming forums, part of the General Programming Boards category; Code: #include <iostream> #include <stdlib.h> #include <string> using namespace std; int main(int argc, char *argv[]) { int x = 0; ...

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    34

    why do i get 5050?

    Code:
    #include <iostream>
    #include <stdlib.h>
    #include <string>
    using namespace std;
    
    int main(int argc, char *argv[])
    {
    int x = 0;
    int i;
    for (i = 1; i <= 100; i++){
        x += i;
    }
    cout << x << endl;    
    
      system("PAUSE");	
      return 0;
    }

    how i get 5050 out of this? the tutorial i got i from doesn't tell me anything about it and im very confused.

  2. #2
    Master of Puppets rwmarsh's Avatar
    Join Date
    Feb 2006
    Location
    Texas
    Posts
    96
    Code:
    for (i = 1; i <= 100; i++){
        x += i;
    }
    You are adding i to x. i is increased by one each round though the loop so that by the 100th time through the loop you add 100 to x
    Using DEV-C++ Under Windows XP
    +------------------------------+

    "No! Do, or Do Not. There is no Try..."

  3. #3
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    Code:
    1   + 2   + 3   + 4   + ... + 100
    100 + 99  + 98  + 97  + ... + 1
    101 + 101 + 101 + 101 + ... + 101
    
    101(100) = 10,100
    10,100/2 = 5050
    And thus the formula: n(n+1)/2
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

  4. #4
    Registered User
    Join Date
    Nov 2005
    Posts
    34
    o thanks man

    u guys must know a lot about loops.

  5. #5
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,077
    Quote Originally Posted by findme
    o thanks man

    u guys must know a lot about loops.
    Yeah, I sometimes wonder how they do it.
    Sent from my iPadŽ

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can some one please tell me the cause of the error ?
    By broli86 in forum C Programming
    Replies: 8
    Last Post: 06-26-2008, 09:36 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21