Syntax 2.1: Output Statement cout << expression1 << expressioun2 << ... << expressionn;
|
Syntax 2.2: Comments /* comment text */
|
Syntax 2.3: Variable
Definition Statement type_name variable_name;
|
cin >> pennies;
cin >> pennies >> nickels >> dimes >> quarters;
8 0 4 3
or
8
0
4
3
Syntax 2.4: Input Statement cin >> variable1 >> variable2 >> ... >> variablen;
|
total = pennies * 0.01;
total = count * 0.05 + total;
Syntax 2.5: Assignment variable = expression;
|
month++; // add 1 to month
month--; // subtract 1 from month
Syntax 2.7: Constant Definition const type_name constant_name = initial_value;
|
a + b / 2 ( a + b ) / 2
9.0 / 4.0 /* 2.25 */
9 / 4.0 /* 2.25 */
9.0 / 4 /* 2.25 */
9 / 4 /* 2 Attention! */
9 % 4 /* 1 remainder */
Syntax 2.8: Function Call function_name(expression1,expressioun2, ..., expressionn);
|
Function Description sqrt(x) square root of x pow(x, y) xy sin(x) sine of x (in radians) cos(x) cosine of x (in radians) tan(x) tangent of x (in radians) exp(x) ex log(x) (natural log) ln(x), x > 0 log10(x) (decimal log) lg(x), x > 0 ceil(x) smallest integer >= x floor(x) largest integer <= x fabs(x) absolute value |x|
string name = "John"; // declaration and initialization
name = "Carl"; // assignment
cout << name << ", please enter your name:"; // output
cin >> name; // input (stops at first space)
getline(cin, name);to read all keystrokes until the Enter key; e.g. should the user type
Harry Hacker
Name Purpose s.length()The length of s s.substr(i, n)The substring of length n of s starting at index i getline(f, s)Read string s from the input stream f
Syntax 2.9: Member Function Call expression.function_name(expression1,expressioun2, ..., expressionn)
|
string greeting = "Hello, World!\n";
string sub = greeting.substr(0,4);
/* sub is "Hell" */
H e l l o ,
W o r l d ! \n 0 1 2 3 4 5 6 7 8 9 10 11 12 13
H e l l o ,
W o r l d ! \n 0 1 2 3 4 5 6 7 8 9 10 11 12 13
string fname = "Harry";
string lname = "Hacker";
string name = fname + " " + lname;
will produce (form1.cpp):cout << pennies << " " << pennies * 0.01 << "\n";
cout << nickels << " " << nickels * 0.05<< "\n";
cout << dimes << " " << dimes * 0.1 << "\n";
cout << quarters << " " << quarters * 0.25 << "\n";
1 0.01
12 0.60
4 0.40
120 30.00
creates the table (form2.cpp):cout << fixed << setprecision(2);
cout << setw(8) << pennies << " "
<< setw(8) << pennies * 0.01 << "\n";
cout << setw(8) << nickels << " "
<< setw(8) << nickels * 0.05<< "\n";
cout << setw(8) << dimes << " "
<< setw(8) << dimes * 0.1 << "\n";
cout << setw(8) << quarters << " "
<< setw(8) << quarters * 0.25 << "\n";
1 0.01
12 0.60
4 0.40
120 30.00