Results 1 to 7 of 7

Thread: C++ paper so far. Please look over to see if ok. Then I will move on.

  1. #1

    Thread Starter
    Frenzied Member aewarnick's Avatar
    Join Date
    Dec 2002
    Posts
    1,037

    C++ paper so far. Please look over to see if ok. Then I will move on.

    C++ PROGRAMMING

    C++ is case sensitive but it is not space sensitive.

    PREPROCESSOR COMMANDS
    # - preprocessor. Tells the compiler to process before compilation.

    #include <iostream> : Tells the processor to include the contents of the input/output stream header file before it compiles.
    The next three may not be the new standard:
    #include <ifstream.h> - file input.
    #include <ofstream.h> - file output.
    #include <iomanip.h> - required for certain in/out changes.

    #include <cmath> - Required for some complicated math and conversion. (One thing to remember about this library is that everything is output as type: double). Here are some of the functions supported:
    ceil (x) - rounds x to the smallest integer not less than x. 9.2 would be 10. -8.8 would be -8.0.
    floor (x) - rounds x to the largest integer not greater than x. 9.2 would be 9. -9.8 would be 9.0.
    cos (x) - trigonometric cosine of x. 0.0 would be 1.0.
    exp (x) - exponential function ex. 1.0 would be 2.71828.
    fabs (x) - absolute value of x.
    fmod (x, y) - remainder of x/y as a floating point #. fmod (13.657, 2.333) would be 1.992.
    log (x) - natural logarithm of x (base e). 2.718282 would be 2.0
    log10 (x) - logarithm of x (base 10). 100 would be 2.0.
    pow (x, y) - x raised to the y power. pow (2, 3) would be 8.
    sin (x) - trigonometric sine of x. 0.0 would be 0.
    sqrt (x) - square root of x. 900.0 would be 30.0.
    tan (x) - trigonometric tangent of x. 0.0 would be 0.
    #include <cstdlib>
    rand () - Random selection. Uses a module operator to represent the max # of choices. 1 + rand () % 6. The 1 represents the starting #.
    srand () - Random selection. When executed it does not start the same every time. Better than rand. This function takes an unsigned variable type. An unsigned variable type looks like this: unsigned x; Ex2: unsigned long x; Notice that int did not need to be used because unsigned by default is of type int. An unsigned variable cannot have a negative value.


    COMMENTS
    // - this makes a comment. Anything after // is ignored by the C++ compiler.
    /* - likewise, this also is comment. Don't forget this ending symbol - */

    STATEMENTS
    Statements always end with ;

    VARIABLES
    Local - any variable declared inside a function or function body or otherwise called block {}.
    Global - any variable declared outside all function blocks {}.
    To use a variable it must be declared (int x;) before it is used. You can specify many at once too - int x, y, z;
    int is the variable type. It states that the variable is an integer - a whole number (0, 1...). You will use int a lot because letters in C++ have # values too. Here are some more:
    float - real # (3.12546) If the decimal #'s are too long it will be rounded off as in math.
    double - takes more memory space than float, but is more accurate because more numbers after the decimal are used.
    Note: When using long or double be careful; C++ does not always round off correctly. There should be some classes that you can get to do exact math.
    char - a single character and nothing more. Can be a number but can't be used for math. c @ $ 1. . . etc.
    string - a sentence or even a single character. Note: strings are not really variable types but can be treated as such for most purposes.
    long - same as int but reserves more space. However, There is no difference between int and long in some compilers.

    When a variable is declared C++ reserves a memory location in the computer for that variable. When cin >> is used it will place whatever the user enters in the memory location. If the user then enters another character, the original data is destroyed and the new replaces it.

    A variable should be less than 31 characters long and should not contain any spaces. Use_for spacing. They also cannot begin with a digit.

    int main ( ) - this is a function. Main is usually where the program starts execution. Even if main is not at the top of the source file.
    ( ) - indicates that main is a function. Notice that there is no ; That is because it is not a statement, it is a function.

    Casting - changing one variable type to another. Example: static_cast<float>(x)

    ESCAPE SEQUENCES
    \n - New line \t - Tab \r - return to the beginning of the line \a - Alert (beep) \\ - backslash
    \" - double quote ( " )

    IN/OUT STREAMS
    cout << "HI there! \n";
    cout - "pronounced, see out". And these: << tell the computer to send the information contained in " " to the output device. The output device is usually the screen and printer.
    I can also do this: cout<< a*b + (x-y) << endl; which will subtract x from y, multiply a and b, and add them together, outputting the result.
    endl; - End line. Not only does it do the same as \n but it also flushes the output buffer.
    flush; - flushes the output buffer.
    Stream Manipulators:
    If you want to keep the decimal places to a certain length do this: cout << setprecision(2) << x << endl; Note: setprecision requires the preprocessor directive <iomanip.h>
    If you want the variable to print out as a fixed # as opposed to a scientific # do this: cout << setiosflags (ios::fixed) << endl;
    If you want cout to print decimals numbers no matter what then use this: cout << setiosflags (ios::showpoint) << endl; 89 will print as 89.00.
    All three combined: cout << "x is " << setprecision (2) << setiosflags (ios::fixed | ios::showpoint) << x << endl; The bar ( | ) is a separator between types of s.m.'s.
    setw (4) - set width to 4 spaces. If the output is less than the reserved space then the value is right justified by default. If it is more than the reserved amount then it is adjusted to accommodate.
    (ios::left) - left justifies output.

    MATHMATICAL OPERATIONS IN C++
    C++ is mathematically sound. It will do basic and complicated math and even follows the order of operations.
    A couple things you need to remember:
    Never put your program in a situation where it could try to divide by 0. That could be a fatal error.
    If you declare a variable as type int and want to get a pretty accurate answer you need to do a variable type cast or declare float or double to accommodate for decimals. Otherwise C++ will not round it to the next highest number but will truncate it - remove the decimal numbers all together. 98.99 would become 98.
    Some examples:
    +, -, *, /, =, pow (x, y) - x to the y power. Ex: pow (x * 4, 2 ). When using power it is always a type, double value.
    x = x+3; can be written as: x+ = 3; x=x/2; can be written as x/=2;

    Incrementing and Decrementing - adds or subtracts 1, either before or after use. Examples:
    to increment x after it is used, write x++; to decrement x before it is used, write --x;
    int c=1; cout << x << endl; cout<< x++ << endl; cout<< x << endl; // would yield: 1-1-2
    Note: do not try to increment an equation. Ex: ++ (x+y)

    RELATIONAL OPERATORS
    a==b - a is equal to b. (Be careful: = is not the same as ==. = is an assignment operator. x=y is stated as x is assigned the value of y.)
    a != b - a is not equal to b. The ! is "Not" and can be used like this - if (! (x==y) && (x==g) ).
    <, >, <=, >= - same as math. Do not switch the order of the <= to => because it will be an error.
    if (a&&b!=c) - && and.
    if (a||b!=c) - || or.
    Note: Do not put spaces in between any of the above operators like this ! =, < =, & & . . .
    ?: - conditional operator. Closely related to if/else. Ex: cout << (x >= 6 ? "true" : "false");
    The ? can be seen as "if it is true do this" and the : "if it is false do this".
    Various ways to use these operators:
    if (x == 1 || y<=6) ++x; x >= 6 ? cout << "true" : cout << "false"; if ((x == 1) && (y<=6)) ++x;
    if (! (x==y) ) x++; for (x != y) cout << "not =";

    OTHER OPERATORS
    Assignment
    =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=

    Bitwise
    & - and, ^ - xor, | - or

    RETURN STATEMENT
    return 0; - simply ends the program successfully.

    CONTROL STRUCTURES:
    IF / ELSE
    Remember this: if and else expect only one statement to be specified. If you want to use 2 or more you must {brace} the body of both if and else. Note: else does not need a corresponding if.
    if (a>=90 || a>=91)
    cout << "A";
    else if (a>=80)
    cout << "B";
    else if (a>=70)
    cout << "C";

    WHILE (loop)
    while (x != 0){ //use the "!= 0" to make sure you don't accidentally divide by 0. Dividing by 0 a program error.
    x = x/2; cout << x;}
    Example:
    int main (){
    int x =1; while (x <= 3) {cout << x << endl; ++x;} return 0;} yield - 1\n 2\n 3\n (\n - is a new line)

    FOR (loop)
    Just like the if loop, the for loop expects only one statement. If there are more than one it must be {braced}. The for loop is more complicated than the while loop. But it is easier to read and debug.

    for (int x=1; x <= 3; x++) /* int x=1; is the initialization of the variable. x<=3; is the condition upon which the for loop executes the body or not. x++ is the increment. x is incremented after it loops back to the top. */
    cout << x << endl; yield - 1\n 2\n 3\n

    Note: if you do not have any arguments to put in the for loop, do not leave it blank. Do this - for (;;).
    Note: the declared variable in the for loop can only be used in that for loop. It will be unknown to the rest of the program. See scope in STORAGE CLASS SPECIFIERS.
    Example 2:
    int x=2, y=10;
    for (int j = x; j <= 4; j += y/x) is == for (int j = 2; j <= 80; j += 5) // j += 5 adds 5 to the value of j.

    DO/WHILE (loop)
    When using the do loop remember that the body will always be carried out at least once. It will check to see if the conditions are met outside the brace in while and continue to loop as long as the conditions hold true.
    do {Your commands}while (x != 11)

    BREAK AND CONTINUE STATEMENTS
    break; - is used to completely exit out of a loop. Break is required to exit a switch structure.
    continue; - is used to immediately go back to the top of a loop.
    Last edited by aewarnick; Jan 3rd, 2003 at 10:42 AM.

  2. #2
    Guru Yonatan's Avatar
    Join Date
    Apr 1999
    Location
    Israel
    Posts
    892

    Re: C++ paper so far. Please look over to see if ok. Then I will move on.

    Originally posted by aewarnick
    The type int is used about 90% of the time
    Where do you get this statistic? Seems very unlikely to me, as in proper C++ it would seem that the most commonly used types are classes.

  3. #3

    Thread Starter
    Frenzied Member aewarnick's Avatar
    Join Date
    Dec 2002
    Posts
    1,037
    I was complaining about the C++ for dummies book earlier and now I have another reason to. Actually I was being modest, the book says: over 90% of the time.

    Thank you for catching that.

  4. #4
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    <iostream> not <iostream.h>

    I suggest you learn how to follow a standards document

    Also:

    { } == braces
    [ ] == brackets
    ( ) == parentheses
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  5. #5

    Thread Starter
    Frenzied Member aewarnick's Avatar
    Join Date
    Dec 2002
    Posts
    1,037
    I think that should do it. Thank you for correcting me. The book I am reading is a little old.
    Last edited by aewarnick; Jan 2nd, 2003 at 11:18 AM.

  6. #6

    Thread Starter
    Frenzied Member aewarnick's Avatar
    Join Date
    Dec 2002
    Posts
    1,037

    More I wrote

    SWITCH
    This switch structure is going to be inside a while loop. To exit the loop you press -1.

    int main () {int letter, account=0, bcount=0, ccount=0;
    while ( (letter = cin.get () ) != -1) {
    switch (letter) {case 'a': ++account; break; case 'b': ++bcount; break; case 'c': ++ccount; break; default: cout << "Incorrect letter entered. Lowercase letters only"; break;}}cout << "totals for each letter\n" << "a: " << account << "\nb: " << bcount << "\nc: " << account << endl; return 0;}

    The while part can be written like this: while (!cin.eof () ) {letter = cin.get();
    Notice that unlike other control structures, it is not necessary to enclose multiple statement cases in { }'s.
    cin.get () - is a function that (in this case) uses the switch structure to acquire a value for the variable "letter".
    The != will cause the program to exit the while loop if -1 is entered. You can also use EOF instead of -1 which means End of File and will exit the loop when certain keys are pressed. The keys you press are unique to each OS.
    Note: Do not forget the space between case and 'x'. Omitting the space there is an error.
    Always include a default case. The break after default is optional. And if break is omitted from all the other cases it will not cause an error but will cause all the cases to be evaluated and if there are more matches then it will execute them.
    Note: Remember, if the user enters an uppercase letter, C++ will not recognize it unless you do this: case 'A': case 'a': ++account; break; and so on . . .

    FUNCTIONS
    Functions are one of the most important parts of C++. They derive from C++ libraries which are called using preprocessor directives. A function looks like this: float main () or this: int sqrt (). Those functions are void, they have no arguments in the (). A void function can also be written like this: int sqrt (void). In a function the int, float, double . . . are the return type of the function.
    Function prototypes
    are defined in all the standard libraries. But we can also make our own.
    This: int time (int, int, int); is a function prototype. (Do not forget the
    The purpose of function proto's is to define our own function and it's expected types (if any at all). If a function prototype is written like this: void function (); It does not take any arguments and does not return a value.

    ENUMERATION
    enum Months {Jan = 1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
    Enumerating kind of creates a new type of variable that is defined by you. The above example will create a variable type called Months. The months shown in {}’s are constants and are numbered 1, 2, 3 . . . 12. If Jan was not set to the value of 1, the enum function would automatically number starting with 0. The constants in enumeration {}’s will be incremented by one with each sequential constant. So if you set Jan to 2, Feb would be 3. If you set Jan to 2 and May to 20, Mar would be 4 and Jun would be 21 and so on.
    Note: Jan, Feb. . . are constants, do not try to assign other numbers to them in any other part of your program.

    STORAGE CLASS SPECIFIERS
    There are 4: auto, register, extern, and static. Storage class specifyer's are used to help determine a variables’ storage class, scope, and linkage.
    Storage class - determines the amount of time the identifier exists in memory.
    Scope - the area in which an identifier can be accessed from the program. If an int variable is declared inside a function block it can only be referenced from the block {} If an int is declared inside main, and main encompasses the whole program (including other functions and blocks) then int will be accessable from anywhere in the source file. Even better would be to place int outside of every block to make it accessable from everywhere. But try to avoid the use of global variables and stick to local.
    Linkage - determines if and which other source files can access the identifier.

    Automatic storage class
    auto - Ex: (auto int x) this class can only be used for variables. It is barely used because local variables are by default, of automatic storage. They exist only when the body {also called; block} for which they are declared is entered. After the block is exited the values are destroyed. Using auto is a way to speed up your program.
    register - Ex: (register int x=2) can only be used for local variables and function paramaters. Most compilers automatically register variables that are used a-lot. So register is not really used much.

    Static storage class
    When a variable is declared using one of these 2, it exists from the program execution but cannot neccesaraly be used all throughout the program.
    extern - Ex: ()
    static - Ex: (static int x = 1) Local variables declared with static are only known within that function just like auto. The difference is that static variables retain their value even after the block is exited. Say that x=1 and we added 4 to x and exited the block. When we come back in the block, the value of x will be 5 and not 1.

    CALL BY REFERENCE
    recognized by the & after the type. Ex: int &x=2; The spacing does not matter between type & and the variable.

    int main () {int x=2, &y=x;
    cout << "x= " << x << "y= " << y << endl; //yeald - x=2, y=2
    y=6; cout << "x= " << x << "y= "<< y << endl; // yeald - x=6, y=6
    return 0; }

    Note: references must always be initialized when they are declared. Ex: int &x=2; Ex (bad): int &x;
    Last edited by aewarnick; Jan 3rd, 2003 at 01:05 PM.

  7. #7

    Thread Starter
    Frenzied Member aewarnick's Avatar
    Join Date
    Dec 2002
    Posts
    1,037
    I just edited my paper a lot. It is much better now.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width