Sunday 19 July 2015

Writing Functions in C++

Whenever writing a code, we have to ensure that it is well organised. An important way to reuse blocks of code lines many times in the same program is to make a function and simply call it each time instead of writing it again and again. Let us continue from the last lesson.

 Header Files

•Header files contain
–Function prototypes
–Definitions of data types and constants
•Header files ending with .h
–Programmer-defined header files
#include “myheader.h
•Library header files
#include <cmath>



Random Number Generation

          rand function (<cstdlib>)
        i = rand();
        Generates unsigned integer between 0 and RAND_MAX (usually 32767)
          Scaling and shifting
        Modulus (remainder) operator: %
          10 % 3 is 1
          x % y is between 0 and y – 1
        Example
                                     i = rand() % 6 + 1;
          “Rand() % 6” generates a number between 0 and 5 (scaling)
          “+ 1” makes the range 1 to 6 (shift)
        Next: program to roll dice




          Next
        Program to show distribution of rand()
        Simulate 6000 rolls of a die
        Print number of 1’s, 2’s, 3’s, etc. rolled
        Should be roughly 1000 of each








          Calling rand() repeatedly
        Gives the same sequence of numbers
          Pseudorandom numbers
        Preset sequence of "random" numbers
        Same sequence generated whenever program run
          To get different random sequences
        Provide a seed value
          Like a random starting point in the sequence
          The same seed will give the same sequence
        srand(seed);
          <cstdlib>
          Used before rand() to set the seed




          Can use the current time to set the seed
        No need to explicitly set seed every time
        srand( time( 0 ) );
        time( 0 );
          <ctime>
          Returns current time in seconds



Game of Chance and Introducing "enum"

          Enumeration
        User defined data type
                              enum  typeName {constant1, constant2};
        Constants start at 0 (default), incremented by 1
        Constants need unique names
          Example
               enum Status {CONTINUE, WON, LOST};
               Status enumVar;
               enumVar = WON; // cannot do enumVar = 1

          Enumeration constants can have preset values
               enum Months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};
        Starts at 1, increments by 1
          Next: craps simulator
        Roll two dice
        7 or 11 on first throw: player wins
        2, 3, or 12 on first throw: player loses
        4, 5, 6, 8, 9, 10
          Value becomes player's "point"
          Player must roll his point before rolling 7 to win







About the Author

Unknown

Editorial Team

Post a Comment

 
Codexify © 2015 - Designed by Templateism.com