1 / 34

C++ Basics

C++ Basics. Joaquin Vila. For Thursday. Read Savitch 2.2-2.3 Do practice problems. Quiz. Origins of C++. BCPL B Ken Thomson (Creator of UNIX) C Dennis Ritchie, AT&T Bell Laboratories, 1970s. The Origins of C++. C++ Bjarne Stroustrup AT&T Bell Laboratories, 1980s.

Sophia
Download Presentation

C++ Basics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C++ Basics Joaquin Vila

  2. For Thursday • Read Savitch 2.2-2.3 • Do practice problems

  3. Quiz

  4. Origins of C++ • BCPL • B • Ken Thomson (Creator of UNIX) • C • Dennis Ritchie, AT&T Bell Laboratories, 1970s

  5. The Origins of C++ • C++ • Bjarne StroustrupAT&T Bell Laboratories, 1980s

  6. Chapter 2 C++ Basics • Variables and Assignments • Input and Output • Data Types and Expressions • Simple Flow of Control • Program Style

  7. 2.1 Variables and Assignments • A C++ variable can hold a value • A C++ variable ALWAYS has a value stored in it. • A C++ variable is implemented as a memory location. Information stored is binary -- 0s and 1s. • The concept of memory location will become more important in ACS 169.

  8. Names: Identifiers • The name of a variable (or anything else in C++ that needs naming) is called an identifier. • An identifier must be named starting with a letter or an underscore symbol (_) followed by any number of letters, digits, or underscore symbols.

  9. Example • Valid Examples: x x_1 _abc A2b ThisIsAVeryLongIdentifier

  10. Examples • Invalid Examples: 12 3X %change myFirst.c data-1 • Why are these invalid?

  11. Reserved Words • There are identifiers that are reserved to the use of the C++ language, called keywords, or reserved words. (A complete list is in Appendix 1 of the text.)

  12. Practice • Which of the following are legal variable names in C++? What’s wrong with the illegal names? 3rdItem float TaxRate _left IsGood? Item2 m table4.1 pi_r_sqrd

  13. More Practice • Classify as good, legal but not recommended, or illegal: percent num_students 1999pay tax_rate m _1994tax y2k# variable Days_off my_data if y2k_fig2 Last.year xr3_yz57 Tax-Rate pay99 exam1_avg

  14. Assignment Statements • What does = mean in C++? • What happens when the statement num_items = num_items + 1;is executed?

  15. Initialization • What is an uninitialized variable? • What’s wrong with uninitialized variables? • How can we initialize variables? • When should we initialize variables?

  16. Pitfall: Uninitialized Variables • A variable that has not had a value set by your program will have the value left there by the last program to use the same memory address. • Any uninitialized variable will contain garbage (in the root sense of the word). • Few compilers will catch this error, but most will issue a warning. • If not corrected, it will cause a logic error.

  17. Variable initialization • How do we prevent logic errors caused by uninitialized variables? • Initialize all variables when they are declared. • Any variable whose value is assigned through a cin>> statement or an assignment statement before being used in a calculation or print statement does not need to be initialized.

  18. You must take great care with your program that all variables receive a value prior to using them. • Syntax: There are two different appearing but equivalent ways to initialize a variable in a declaration statement: int x = 3; double pi = 3.14159; int x(3); double pi(3.14159);

  19. Programming Tip • Use meaningful variable names. • Names that tie your program’s code to the problem being solved will make your code easier to read and easier to debug.(Failing to do this in a program assignment will lower your grade.) • Anything that you can do to make your code readable is worth hours, even days in debugging time.

  20. Practice • Give a declaration for a variable speed of type double. • Give declaration-initializations for variables num_goblins and num_knights, initializing both int variables to zero. • Declare an int variable size and use a separate statement to initialize it to 10. • Write an assignment statement that assigns distance to be rate times time.

  21. // Sample Program #include <iostream> using namespace std; int main() { int numStudents, numSections, studentsPerSection; cout << “Please enter the total number of students: ”; cin >> numStudents; cout << “Please enter the number of sections: ”; cin >> numSections;   studentsPerSection = numStudents / numSections;   cout << “If you have ” << numStudents; cout << “in a course\n and you have ”; cout << numSections << “ sections of the course,\n”; cout << “you will average ” << studentsPerSection; cout << “ students in each section.\n”;   return 0; }

  22. Display 2.1 A C++ Program (1 of 2) #include <iostream> using namespace std; int main( ) { int number_of_bars; double one_weight, total_weight; cout << "Enter the number of candy bars in a package\n"; cout << "and the weight in ounces of one candy bar.\n“ << "Then press return.\n"; cin >> number_of_bars; cin >> one_weight; total_weight = one_weight * number_of_bars; cout << number_of_bars << " candy bars\n"; cout << one_weight << " ounces each\n"; cout << "Total weight is " << total_weight << " ounces.\n"; • These lines provide declarations necessary to make iostream library available. • C++ divides collections of names into namespaces. To access names in a namespace, the second line above, the using directive, is sufficient. It means that your program can use any name in the namespace std. • A C++ namespace usually contains more than just names. They usually contain code as well. • These two lines are variable declarations. • Every variable in C++ must be declared. • A declaration introduces a name to the compiler and specifies the type of data that is to be stored in the variable. • A variable declaration has the form Type_name variable_name1, variable_name2, … ; • The kind of data held in a variable is its type. • You must declare all variables prior to use. When an extraction string is too long to fit on one line of code, it can be ended with a semicolon and the next line starts with cout again, or simply end with double quotes “ and leave the cout off the next line. • << is the extraction operator. It extracts the string literal following it to the outstream indicated. In this case it is extracted to the screen using cout. • It is illegal to break a string across two lines. The following is ILLEGAL, though some compilers happily accept it. • cout << “Mary had a little lamb. Its fleece was white as snow.\n”; Likewise, this cin statement could be written as cin >> number_of_bars >> one_weight; Also notice that variable names are not surrounded with quotes, only string literals require quotes. Notice, it is not necessary to break before each << or >> operator.

  23. Display 2.1 A C++ Program (2 of 2) cout << "Try another brand.\n"; cout << "Enter the number of candy bars in a package\n"; cout << "and the weight in ounces of one candy bar.\n"; cout << "Then press return.\n"; cin >> number_of_bars; cin >> one_weight; total_weight = one_weight * number_of_bars; cout << number_of_bars << " candy bars\n"; cout << one_weight << " ounces each\n"; cout << "Total weight is " << total_weight << " ounces.\n"; cout << "Perhaps an apple would be healthier.\n"; return 0; } • The \ (backslash) preceeding a character tells the compiler that the next character does not have the same meaning as the character by itself. • An escape sequence is typed as two characters with no space between them. • To print the backslash character, you must use \\. This tells the compiler the second back slash is not the escape character, but rather a regular character to be printed. • Here are some common escape characters: \n newline \t tab character \a alert, or bell \” double quote (that does not end a string literal). • When a program reaches a cin >> statement, it waits for input. You are responsible for prompting the user of your program for proper input. • Syntax: cin >> number >> size; cin >> time_to_go >> points_needed; • In an assignment statement, the right hand side expression is evaluated, then the variable on the left hand side is set to this value. • Syntax: variable = expression; • distance = rate * time; • count = count + 2;

  24. Formatting for Numbers with a Decimal Point • The following statements will cause your floating point output to be displayed with 2 decimal places and will always show the decimal point even when the output has a zero fractional part. cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); //Output format:78.50 You will need to memorize these three lines of code for use on exams.

  25. 2.3 Data Type and ExpressionsThe types int and double • From the C++ point of view, 2 and 2.0 are very different. • 2 has type int with no fractional part • 2.0 has type double with a fractional part (even if the fractional part is 0). • An int and a double use different amounts of memory and are stored differently.

  26. Other Number types TypeMemory usedRangePrecision short 2 bytes -32,767 to 32,767 NA (short int) int 4 bytes -2,147483,647 NA to 2,147483,647 long 4 bytes same as int NA float 4 bytes 10-38 to 1038 7 digits double 8 bytes 10-308 to 10308 15 digits long double 10 bytes 10-4932 to 104932 15 digits

  27. The Types char and bool • char is a special type that is designed to hold single members of the ASCII character set. • cstring (from C) and string (from the Standard Library) are for more than one char value. More on these in a later chapter. • bool is a type that was added to C++ in the1995 Draft ANSI Standard. There are only two Boolean values: true and false. Almost all compilers support the bool type.

  28. Display 2.3 The Type char #include <iostream> // nec for using cin and cout using namespace std; int main( ) { char symbol1, symbol2, symbol3; cout << "Enter two initials, without any periods:\n"; cin >> symbol1 >> symbol2; cout << "The two initials are:\n"; cout << symbol1 << symbol2 << endl; cout << "Once more with a space:\n"; symbol3 = ' '; cout << symbol1 << symbol3 << symbol2 << endl; cout << "That's all."; return 0; } • Note: in the above line //nec for using cin and cout is a comment added to explain the use of #include<iostream>. • This is a common practice used to make code easier to read, follow, and debug. • You will be expected to comment your program source code often. What does this program do?

  29. Arithmetic Operators and Expressions Common arithmetic operators are encoded: Addition + Multiplication * Subtraction - Division / Modulus % Grouping ( ) These operators are used to make arithmetic expressions: one_weight * number_of_weights

  30. This expression is said to “return a value” that automatically appears where the expression is, and is used in an outside expression. In the statement below, the sum is computed, value returned, and this value is used as a factor in the multiplication. one_weight * (number_of_weights + off_set) (See precedence, later in the text.)

  31. Arithmetic Operators and Expressions • Arithmetic with +, - ,and * behaves as expected for both integer and floating point types. • Arithmetic for / (division) behaves as expected for floating point numbers. • But, arithmetic for / behaves in a somewhat surprising way for integer types (short, int, long). • Division for integers is TRUNCATING - it discards the fractional part. • Modulus, using % is used to return the remainder in integer division.

  32. Division /, and Modulus %, for Integer Values Division /, and modulus % are complementary operations. Mod, or modulus, %, works ONLY for integer types. 4 12 / 3 = 4 4 is the quotient 3 12 12 0 12 % 3 = 0 (read 12 mod 3) 0 is the remainder 4 14 / 3 = 4 NOT 4.66 3 14 12 2 14 % 3 = 2 the remainder after division See the PITFALL - Whole Number Division, page 70.

  33. Arithmetic Operators and Expressions:Precedence When two operators appear in an arithmetic expression, there are PRECEDENCE rules that tell us what happens. Evaluate the expression, X + Y * Z by multiplying Y and Z first then the result is added to X.

  34. Rule: Do inside parentheses first, working your way from the inner most set out, then do the multiplication and division in order from left to right, finally do addition and subtraction in order from left to right.

More Related