title: C++ Random Number Generator For Loop
body: <p>So, I have a small problem here with a rather large for loop. This program is to simulate random walks of 100 steps each - what I want to do is have the program perform 1 million of these random walk simulations (the random walk is done by the nested for loop essentially by simulating the flipping of a coin, as you can see in my code below) and take the resultant displacement from each of these random walks and print them to the console window and to the specified output file.</p>
  
  <p>However, my code seems to be adding each final value of x from the nested for loop and then printing them to the console window (and saving to output file) - I don't want this, I just want the standalone net result from each random walk to be outputted for each value of j (which ranges from 1 to 1E6 as specified by the outer for loop). </p>
  
  <p>Thus, any help would be greatly appreciated. Also, I would very much appreciate you to not just quote some code for me to use instead but rather explain to me where my program logic has gone wrong and why.</p>
  
  <p>Thanks in advance, my code is below!</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;ctime&gt;
  #include &lt;fstream&gt;
  
  using namespace std;
  
  int main(void) {
  
      const unsigned IM = 1664525;
      const unsigned IC = 1013904223;
  
      const double zscale = 1.0/0xFFFFFFFF;      //Scaling factor for random double between 0 and 1
      unsigned iran = time(0);                        //Seeds the random-number generator from the system time
      const int nsteps(100);                          //Number of steps
      const int nwalks(1E6);
  
      int x(0);           // Variable to count step forward/back
  
      ofstream randout;
      randout.open("randomwalkdata2.txt");
  
      // Table headers for console window and output file
  
      cout &lt;&lt; "Random Walk Number \t Resultant Displacement \n";
      randout &lt;&lt; "Random Walk Number \t Resultant Displacement \n";
  
      for ( int j = 1 ; j &lt;= nwalks ; j++ ) {
  
          for ( int i = 1 ; i &lt;= nsteps ; i++ ) {
  
              // if-else statement to increment/decrement x based on RNG
  
              if ( zscale * double( iran = IM * iran + IC ) &lt; 0.5 )   //RNG algorithm
                  x++;
              else 
                  x--;
  
          }
  
          cout &lt;&lt; j &lt;&lt; "\t" &lt;&lt; x &lt;&lt; endl;
          randout &lt;&lt; j &lt;&lt; "\t" &lt;&lt; x &lt;&lt; endl;
  
      }
  
      randout.close();
  
      return 1;
  
  }
  </code></pre>