Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
The switch
#include <iostream> using namespace std; int main() { int num; cout << "Enter a number from 1 to 3: "; cin >> num; switch(num) case 1: cout << break; case 2: cout << break; case 3: cout << break; default: cout << } { "111.\n"; "222.\n"; "333.\n"; "You must enter either 1, 2, or 3.\n";
default: cout << "Selection not found.\n"; } return 0; } Help on: 1. if 2. switch Choose one: 1 The if:
cout << break; case '6': cout << break; case '7': cout << break; case '8': cout << break; }
} cout << "\n"; return 0; } Help on: 1. if 2. switch 3. for 4. while 5. do-while 6. break 7. continue 8. goto Choose one (q to quit): 4 The while: Help on: 1. if 2. switch 3. for 4. while 5. do-while 6. break 7. continue 8. goto Choose one (q to quit): 2 The switch: Help 1. 2. 3. 4. 5. 6. 7. 8. on: if switch for while do-while break continue goto
int main() { result = 0; while (true) { std::cout << "Result: " << result << '\n'; std::cout << "Enter operator and number: "; std::cin >> oper_char >> value; if ((oper_char == 'q') || (oper_char == 'Q')) break; switch (oper_char) { case '+':
result += value; break; case '-': result -= value; break; case '*': result *= value; break; case '/': if (value == 0) { std::cout << "Error:Divide by zero\n"; std::cout << " operation ignored\n"; } else result /= value; break; default: std::cout << "Unknown operator " << oper_char << '\n'; break; } } return (0); }
m = f / 3.28; // convert to meters cout << f << " feet is " << m << " meters.\n"; counter++; // every 10th line, print a blank line if(counter == 10) { cout << "\n"; // output a blank line counter = 0; // reset the line counter } } return 0; }
int main() { int i; for(i=50; i >= -50; i = i-10) cout << i << ' '; return 0; }
a a a a
2 3 2 123
3.15.10.Use nested for loops to find factors of numbers between 2 and 100
#include <iostream> using namespace std; int main() { for(int i=2; i <= 100; i++) { cout << "Factors of " << i << ": "; for(int j = 2; j < i; j++) if((ij) == 0) cout << j << " "; cout << "\n"; } return 0; }
3.15.10.Use nested for loops to find factors of numbers between 2 and 100
#include <iostream> using namespace std; int main() { for(int i=2; i <= 100; i++) { cout << "Factors of " << i << ": "; for(int j = 2; j < i; j++) if((ij) == 0) cout << j << " "; cout << "\n"; } return 0; }
";
std::cout << "\nCounter: " << counter << ".\n"; return 0; } Looping! Looping! Counter: 5. Looping! Looping! Looping!
cout << "Year" << setw( 21 ) << "Amount on deposit" << endl; cout << fixed << setprecision( 2 ); for ( int year = 1; year <= 10; year++ ) { amount = principal * pow( 1.0 + rate, year ); cout << setw( 4 ) << year << setw( 21 ) << amount << endl; } return 0; } Year Amount on deposit 1 1050.00 2 1102.50 3 1157.63 4 1215.51 5 1276.28 6 1340.10 7 1407.10 8 1477.46 9 1551.33 10 1628.89
radius =
2.8
area =
24.6176
// Create the separator row for(int i = 0 ; i <= table ; i++) cout << "------"; cout << endl; for(int i = 1 ; i <= table ; i++) { cout << " " << setw(3) << i << " |"; // Output the values in a row for(int j = 1 ; j <= table ; j++) cout << " " << setw(3) << i*j << " |"; cout << endl; } return 0; } | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -----------------------------------------------------------------------1 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 2 | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22 | 3 | 3 | 6 | 9 | 12 | 15 | 18 | 21 | 24 | 27 | 30 | 33 | 4 | 4 | 8 | 12 | 16 | 20 | 24 | 28 | 32 | 36 | 40 | 44 | 5 | 5 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 6 | 6 | 12 | 18 | 24 | 30 | 36 | 42 | 48 | 54 | 60 | 66 | 7 | 7 | 14 | 21 | 28 | 35 | 42 | 49 | 56 | 63 | 70 | 77 | 8 | 8 | 16 | 24 | 32 | 40 | 48 | 56 | 64 | 72 | 80 | 88 | 9 | 9 | 18 | 27 | 36 | 45 | 54 | 63 | 72 | 81 | 90 | 99 | 10 | 10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100 | 110 |
11 |
11 |
22 |
33 |
44 |
55 |
66 |
77 |
88 |
99 | 110 | 121 |
";
std::cout << "\nCounter: " << counter << ".\n"; return 0; } Looping! Looping! Counter: 5. Looping! Looping! Looping!
3.16.2.Counter-controlled repetition
#include <iostream> using std::cout; using std::endl; int main() { int counter = 1; while ( counter <= 10 ) { cout << counter << " "; counter++; } cout << endl; return 0; } 1 2 3 4 5 6 7 8 9 10
using namespace std; int main() { int len; cout << "Enter length (1 to 79): "; cin >> len; while(len>0 && len<80) cout << '.'; len--; } return 0; } {
unsigned long large = 10; unsigned long skip = 2; unsigned long target = 8; const unsigned short MAXSMALL=65535; while (small < large && large > 0 && small < 65535) { small++; if (small skip == 0)// skip the decrement? { cout << "skipping on " << small << endl; continue; } if (large == target) // exact match for the target? { cout << "Target reached!"; break; } large-=2; } cout << "\nSmall: " << small << " Large: " << large << endl; return 0; } skipping on 2 skipping on 4 Target reached! Small: 5 Large: 8
3.16.8.Skip the body of the while loop when the condition is false
#include <iostream> int main() { int counter = 3; while (counter > 0) { std::cout << "Hello!\n"; counter--; } std::cout << "counter is OutPut: " << counter; return 0; } Hello! Hello! Hello! counter is OutPut: 0
2.29.1.Using atof.
#include <iostream> using std::cout; using std::endl;
#include <cstdlib> using std::atof; int main() { double d = atof( "99.0" ); cout << d / 2.0 << endl; return 0; } 49.5
2.29.2.Using atoi
#include <iostream> using std::cout; using std::endl; #include <cstdlib> using std::atoi; int main() { int i = atoi( "2593" ); cout << i - 593 << endl; return 0; } 2000
2.29.3.Using atol
#include <iostream> using std::cout; using std::endl; #include <cstdlib> using std::atol; int main() { long x = atol( "1000000" ); cout << x / 2 << endl; return 0; } 500000
2.29.4.Using strtod
#include <iostream> using std::cout; using std::endl; #include <cstdlib> using std::strtod; int main() { double d; const char *string1 = "51.2 are admitted"; char *stringPtr; d = strtod( string1, &stringPtr ); cout << d << endl; return 0; } 51.2
2.29.5.Using strtol
#include <iostream> using std::cout; using std::endl; #include <cstdlib> using std::strtol; int main() { long x; const char *string1 = "-1234567abc"; char *remainderPtr; x = strtol( string1, &remainderPtr, 0 ); cout << x << " " << remainderPtr << " " << x + 567 << endl; return 0; } -1234567 abc -1234000
2.29.6.Using strtoul
#include <iostream> using std::cout; using std::endl; #include <cstdlib> // strtoul prototype
using std::strtoul; int main() { unsigned long x; const char *string1 = "1234567abc"; char *remainderPtr; x = strtoul( string1, &remainderPtr, 0 ); cout << x << " return 0; } 1234567 1234000 "<< x - 567 << endl;
for (int j = 0; j < COLUMNS; ++j) cout << board[i][j]; cout << endl; } board[1][0] = 'X'; for (int i = 0; i < ROWS; ++i) { for (int j = 0; j < COLUMNS; ++j) cout << board[i][j]; cout << endl; } return 0; }
4.1.1.Initializing an array
#include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setw; int main() { int n[ 10 ]; for ( int i = 0; i < 10; i++ ) n[ i ] = 0; for ( int j = 0; j < 10; j++ ) cout << n[ j ] << endl; return 0; }
for ( int i = 0; i < 3; i++ ) cout << "array2[" << i << "] = " << array2[ i ] << " for ( int j = 0; j < 3; j++ ) array2[ j ] = 0;
";
} array1[0] = 0 array1[1] = 0 array1[2] = 0 array2[0] = 1 array2[1] = 2 array 2[2] = 3 array1[0] = 0 array1[1] = 0 array1[2] = 0 array2[0] = 1 array2[1] = 2 array2[2] = 3
4.1.7.array of strings
#include <iostream> using namespace std; int main(){ const int DAYS = 7; const int MAX = 10; char star[DAYS][MAX] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; for(int j=0; j<DAYS; j++) cout << star[j] << endl; return 0; }
return 0;
cout << endl << "Enter a height as an integral number of inches: "; cin >> height[count++]; // Check if another input is required cout << "Do you want to enter another (y or n)? "; cin >> reply; } while(count < 10 && std::tolower(reply) == 'y'); return 0; } Enter a height as an integral number of inches: 12 Do you want to enter another (y or n)? n
4.3.1.Array pointer
#include <iostream> using namespace std; int main() { int *i, j[10]; double *f, g[10]; int x;
i = j; f = g; for(x=0; x<10; x++) cout << i+x << ' ' << f+x << '\n'; return 0; }
"B", "BB", "C", "CC", "D", "DD", "E", "EE", "", "" }; char word[80]; int i; cout << "Enter word: "; cin >> word; for(i = 0; *dictionary[i][0]; i++) { if(!strcmp(dictionary[i][0], word)) { cout << dictionary[i][1] << "\n"; break; } } if(!*dictionary[i][0]) cout << word << " not found.\n"; return 0; } Enter word: word word not found.
cout << "passing array as a constant pointer.\n\n"; increase(highScores, NUM_SCORES); cout << "passing array as a constant pointer to a constant.\n"; display(highScores, NUM_SCORES); return 0; }
void increase(int* const array, const int NUM_ELEMENTS) { for (int i = 0; i < NUM_ELEMENTS; ++i) array[i] += 500; } void display(const int* const array, const int NUM_ELEMENTS) { for (int i = 0; i < NUM_ELEMENTS; ++i) cout << array[i] << endl; }
{6, 36}, {7, 49}, {8, 64}, {9, 81}, {10, 100} }; cout << "Enter a number between 1 and 10: "; cin >> i; // look up i for(j=0; j<10; j++) if(sqrs[j][0]==i) break; cout << "The square of " << i << " is "; cout << sqrs[j][1]; return 0; } Enter a number between 1 and 10: 7 The square of 7 is 49
void display( const int [][ 3 ] ); int main() { int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } }; int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 }; int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } }; cout << "Values in array1 by row are:" << endl; display( array1 ); cout << "\nValues in array2 by row are:" << endl; display( array2 ); cout << "\nValues in array3 by row are:" << endl; display( array3 ); return 0; } void display( const { for ( int i = 0; { for ( int j = cout << a[ } cout << endl; } } Values in array1 by 1 2 3 4 5 6 int a[][ 3 ] ) i < 2; i++ ) 0; j < 3; j++ ){ i ][ j ] << ' ';
row are:
cout << "Enter name (A): "; cin >> str; for(i=0; i < 10; i += 2) if(!strcmp(str, numbers[i])) { cout << "Number is " << numbers[i+1] << "\n"; break; } if(i == 10) cout << "Not found.\n"; return 0; } Enter name (A): 1 Not found.
"
9 4
7 6 12 14 15 1
0: 1: 2: 3: 4:
1 2 3 4 5
| | | | | | | | | | |
#include <iostream> using namespace std; int main() { int monthlytemps[4][7]; cout << "Enter the temp for week 1 day 1"; cin >> monthlytemps[0][0]; cout << "Enter the temp for week 1 day 2"; cin >> monthlytemps[0][1];
cout << "Enter the temp for cin >> monthlytemps[0][2]; cout << "Enter the temp for cin >> monthlytemps[0][3]; cout << "Enter the temp for cin >> monthlytemps[0][4]; cout << "Enter the temp for cin >> monthlytemps[0][5]; cout << "Enter the temp for cin >> monthlytemps[0][6]; cout << "Enter the temp for cin >> monthlytemps[1][0]; cout << "Enter the temp for cin >> monthlytemps[1][1]; cout << "Enter the temp for cin >> monthlytemps[1][2]; cout << "Enter the temp for cin >> monthlytemps[1][3]; cout << "Enter the temp for cin >> monthlytemps[1][4]; cout << "Enter the temp for cin >> monthlytemps[1][5]; cout << "Enter the temp for cin >> monthlytemps[1][6]; cout << "Enter the temp for cin >> monthlytemps[3][0]; cout << "Enter the temp for cin >> monthlytemps[3][1]; cout << "Enter the temp for cin >> monthlytemps[3][2]; cout << "Enter the temp for cin >> monthlytemps[3][3]; cout << "Enter the temp for cin >> monthlytemps[3][4]; cout << "Enter the temp for cin >> monthlytemps[3][5]; cout << "Enter the temp for cin >> monthlytemps[3][6]; cout << "Enter the temp for cin >> monthlytemps[4][0]; cout << "Enter the temp for cin >> monthlytemps[4][1]; cout << "Enter the temp for cin >> monthlytemps[4][2]; cout << "Enter the temp for cin >> monthlytemps[4][3]; cout << "Enter the temp for cin >> monthlytemps[4][4]; cout << "Enter the temp for cin >> monthlytemps[4][5]; cout << "Enter the temp for cin >> monthlytemps[4][6]; return 0; }
week 1 day 3"; week 1 day 4"; week 1 day 5"; week 1 day 6"; week 1 day 7"; week 2 day 1"; week 2 day 2"; week 2 day 3"; week 2 day 4"; week 2 day 5"; week 2 day 6"; week 2 day 7"; week 3 day 1"; week 3 day 2"; week 3 day 3"; week 3 day 4"; week 3 day 5"; week 3 day 6"; week 3 day 7"; week 4 day 1"; week 4 day 2"; week 4 day 3"; week 4 day 4"; week 4 day 5"; week 4 day 6"; week 4 day 7";
4.4.9.how to define, pass, and walk through the different dimensions of an array
#include <iostream> using namespace std; void vdisplay_results(char carray[][3][4]); char cglobal_cube[5][4][5]= { { {'1','1','1','1','1'}, {'2','2','2','2',' '}, {'3','3','3','3',' '}, {'4','4','4',' ',' '}, }, { {'1','1','1','1','1'}, {'2','2','2','2',' '}, {'3','3','3','3',' '} }, { {'1','1','1','1','1'}, {'2','2','2','2',' '} }, { {'1','1','1','1','1'}, {'2','2','2','2',' '}, {'3','3','3','3',' '}, {'4','4','4',' ',' '}, }, { {'1','1','1','1','1'}, {'2','2','2','2',' '}, {'3','3','3','3',' '}, {'4','4','4',' ',' '}, } }; int imatrix[4][3]={ {1},{2},{3},{4} }; int main( ) { int irow_index, icolumn_index; char clocal_cube[2][3][4]; cout \n"; cout \n"; cout \n"; cout \n"; << "sizeof clocal_cube << "sizeof clocal_cube[0] << "sizeof clocal_cube[0][0] = "<< sizeof(clocal_cube) = "<< sizeof(clocal_cube[0]) = "<< sizeof(clocal_cube[0][0]) << " << " << " << "
vdisplay_results(clocal_cube);
= " << cglobal_cube[0][1][2] << "\n"; = " << cglobal_cube[1][0][2] << "\n";
for(irow_index=0; irow_index < 4; irow_index++) { for(icolumn_index=0; icolumn_index < 5; icolumn_index++) cout << cglobal_cube[0][irow_index][icolumn_index]; cout << "\n"; } for(irow_index=0; irow_index < 4; irow_index++) { for(icolumn_index=0; icolumn_index < 5; icolumn_index++) cout << cglobal_cube[4][irow_index][icolumn_index]; cout << "\n"; } cout << "\nprint all of imatrix\n"; for(irow_index=0; irow_index < 4; irow_index++) { for(icolumn_index=0; icolumn_index < 3; icolumn_index++) cout << imatrix[irow_index][icolumn_index]; cout << "\n"; } return (0); } void vdisplay_results(char carray[][3][4]) { cout << "sizeof carray =" << cout << " sizeof carray[0] =" << cout << " sizeof cglobal_cube =" << cout << " sizeof cglobal_cube[0] =" << << }
sizeof(carray) << "\n"; sizeof(carray[0]) << "\n"; sizeof(cglobal_cube) << "\n"; sizeof(cglobal_cube[0]) "\n";
MyClass(13, 14), MyClass(15, 16) }; int i; for(i=0; i < 4; i++) { cout << obs[i][0].getX() cout << obs[i][0].getY() cout << obs[i][1].getX() cout << obs[i][1].getY() } return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 << << << << ' '; "\n"; ' '; "\n";
8.2.1.Array of structures
#include <iostream.h> #include <stdlib.h> #define Length 5 struct Employee { char title [50]; int year; } employee [Length]; void printemployee (Employee employee); int main () { char buffer [50]; for (int n=0; n<Length; n++) { cout << "Enter title: "; cin.getline (employee[n].title,50); cout << "Enter year: "; cin.getline (buffer,50); employee[n].year = atoi (buffer); } cout << "\nYou have entered these employees:\n"; for (int n=0; n<Length; n++) printemployee (employee[n]); return 0; }
void printemployee (Employee employee) { cout << employee.title; cout << " (" << employee.year << ")\n"; } Enter title: Title Enter year: 123 Enter title: Title 2 Enter year: as Enter title: TitEnter year: ^CTerminate batch job (Y/N)? n
3.6.6.Use sizeof operator on an array name: returns the number of bytes in the array
#include <iostream> using std::cout; using std::endl; int main() { double array[ 20 ]; cout << "The number of bytes in the array is " << sizeof( array ); return 0; } The number of bytes in the array is 160
3.6.5.Using the sizeof operator for base class and derived class
#include <iostream> #include <ostream> class base {}; class derived : public base {}; int main() { using namespace std; cout << sizeof(base) << '\n'; cout << sizeof(derived) << '\n'; base b[3]; cout << sizeof(b) << '\n'; derived d[5]; cout << sizeof(d) << '\n'; } 1 1 3 5
3.6.4.Object sizes
#include <iostream> using std::cout; using std::endl; class Box { public: Box() :length(1.0), width(1.0), height(1.0), pMaterial("new") {} int totalSize() {
return sizeof(length) + sizeof(width) + sizeof(height) + sizeof(pMaterial ); } private: char* pMaterial; double length; double width; double height; }; int main() { Box box; Box boxes[10]; cout << endl << "The data members of a Box object occupy " << box.totalSize() << " bytes."; cout << endl << "A single Box object occupies " << sizeof (Box) << " bytes."; cout << endl << sizeof(boxes) << endl; return 0; } The data members of a Box object occupy 28 bytes. A single Box object occupies 32 bytes. An array of 10 Box objects occupies 320 bytes. << "An array of 10 Box objects occupies " << " bytes."
3.6.3.sizeof a class
/* The following code example is taken from the book * "C++ Templates - The Complete Guide" * by David Vandevoorde and Nicolai M. Josuttis, Addison-Wesley, 2002 * * (C) Copyright David Vandevoorde and Nicolai M. Josuttis 2002. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include <iostream> class EmptyClass { }; int main() { std::cout << "sizeof(EmptyClass): " << sizeof(EmptyClass) << '\n'; } sizeof(EmptyClass): 1