Sei sulla pagina 1di 40

3.14.1.

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";

return 0; } Enter a number from 1 to 3: 2 222.

3.14.2.A switch without break statements.


#include <iostream> using namespace std; int main() { int i; for(i=0; i<5; i++) { switch(i) { case 0: cout << "less case 1: cout << "less case 2: cout << "less case 3: cout << "less case 4: cout << "less } cout << '\n'; } return 0; }

than than than than than

1\n"; 2\n"; 3\n"; 4\n"; 5\n";

3.14.3.switch case falling through


#include <iostream> using namespace std; int main() { int i; for(i=0; i<5; i++) { switch(i) { case 1: case 2: case 3: cout << "i is less than 4"; break; case 4: cout << "i is 4"; break; } cout << '\n'; } return 0; } i i i i is is is is less than 4 less than 4 less than 4 4

3.14.4.char navigation based on switch


#include <iostream> using namespace std; int main() { char choice; cout << "Help on:\n"; cout << " 1. if\n"; cout << " 2. switch\n"; cout << "Choose one: "; cin >> choice; cout << "\n"; switch(choice) { case '1': cout << "The if:\n\n"; break; case '2': cout << "The switch:\n\n"; break;

default: cout << "Selection not found.\n"; } return 0; } Help on: 1. if 2. switch Choose one: 1 The if:

3.14.5.A Help system that process multiple requests.


#include <iostream> using namespace std; int main() { char choice; for(;;) { do { cout << "Help on:\n"; cout << " 1. if\n"; cout << " 2. switch\n"; cout << " 3. for\n"; cout << " 4. while\n"; cout << " 5. do-while\n"; cout << " 6. break\n"; cout << " 7. continue\n"; cout << " 8. goto\n"; cout << "Choose one (q to quit): "; cin >> choice; } while( choice < '1' || choice > '8' && choice != 'q'); if(choice == 'q') break; cout << "\n\n"; switch(choice) { case '1': cout << "The break; case '2': cout << "The break; case '3': cout << "The break; case '4': cout << "The break; case '5':

if:\n\n"; switch:\n\n"; for:\n\n"; while:\n\n";

cout << break; case '6': cout << break; case '7': cout << break; case '8': cout << break; }

"The do-while:\n\n"; "The break:\n\n"; "The continue:\n\n"; "The goto:\n\n";

} 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

Choose one (q to quit): q

3.14.6.switch statement based on data type


#include <iostream.h> void increase (void* data, int type) { switch (type) { case sizeof(char) : (*((char*)data))++; break; case sizeof(short): (*((short*)data))++; break; case sizeof(long) : (*((long*)data))++; break; } } int main () { char a = 5; short b = 9; long c = 12; increase (&a,sizeof(a)); increase (&b,sizeof(b)); increase (&c,sizeof(c)); cout << (int) a << ", " << b << ", " << c; return 0; } 6, 10, 13"

3.14.7.Calculator based on switch statement


#include <iostream> int char int result; oper_char; value;

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); }

3.15.1.Simplest for loop statement


#include <iostream> using namespace std; int main() { int count; for(count=1; count <= 100; count=count+1) cout << count << " "; return 0; }

3.15.2.A conversion table of feet to meters


#include <iostream> using namespace std; int main() { double f; // holds the length in feet double m; // holds the conversion to meters int counter; counter = 0; for(f = 1.0; f <= 100.0; f++) {

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; }

3.15.3.Use multiple statements in for loops


#include <iostream> int main() { for (int i=0, j=0; i<3; i++, j++) std::cout << "i: " << i << " j: " << j << std::endl; return 0; } i: 0 j: 0 i: 1 j: 1 i: 2 j: 2

3.15.4.Display the alphabet: use char to control for loop


#include <iostream> using namespace std; int main() { char letter; for(letter = 'A'; letter <= 'Z'; letter++) cout << letter; return 0; }

3.15.5.A negatively running for loop


#include <iostream> using namespace std;

int main() { int i; for(i=50; i >= -50; i = i-10) cout << i << ' '; return 0; }

3.15.6.Loop until a random number that is greater than 20,000.


#include <iostream> #include <cstdlib> using namespace std; int main() { int i; int r; r = rand(); for(i=0; r <= 20000; i++) r = rand(); cout << "Number is " << r << ". It was generated on try " << i << "."; return 0; } Number is 26500. It was generated on try 3."

3.15.7.A for loop with no increment


#include <iostream> using namespace std; int main() { int x; for(x=0; x != 123; ) { cout << "Enter a number: "; cin >> x; } return 0;

} Enter Enter Enter Enter

a a a a

number: number: number: number:

2 3 2 123

3.15.8.The body of a for loop can be empty


#include <iostream> #include <cstdlib> using namespace std; int main() { int i; int sum = 0; // sum the numbers from 1 through 10 for(i=1; i <= 10; sum += i++) ; cout << "Sum is " << sum; return 0; } Sum is 55"

3.15.9.Declare loop control variable inside the for


#include <iostream> using namespace std; int main() { int sum = 0; int fact = 1; for(int i = 1; i <= 5; i++) { sum += i; // i is known throughout the loop fact *= i; } // but, i is not known here. cout << "Sum is " << sum << "\n"; cout << "Factorial is " << fact; return 0; } Sum is 15 Factorial is 120"

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; }

3.15.11.For loops with null statements


#include <iostream> int main() { int counter = 0; for( ; counter < 5; ) { counter++; std::cout << "Looping! }

";

std::cout << "\nCounter: " << counter << ".\n"; return 0; } Looping! Looping! Counter: 5. Looping! Looping! Looping!

3.15.12.empty for loop statement


#include <iostream> int main() { int counter=0; int max = 3; for (;;) { if (counter < max) { std::cout << "Hello!\n"; counter++; // increment } else break; } return 0; } Hello! Hello! Hello!

3.15.13.Compound interest calculations with for


#include <iostream> using std::cout; using std::endl; using std::fixed; #include <iomanip> using std::setw; using std::setprecision; #include <cmath> using std::pow; int main() { double amount; double principal = 1000.0; double rate = .05;

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

3.15.14.Floating point control in a for loop


#include <iostream> #include <iomanip> using std::cout; using std::endl; int main() { const double pi = 3.14; cout << endl; for(double radius = .2 ; radius <= 3.0 ; radius += .2) cout << "radius = " << std::setw(6) << radius << " area = " << std::setw(12) << pi * radius * radius << endl; return 0; } radius radius radius radius radius radius radius radius radius radius radius radius radius = = = = = = = = = = = = = 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 area area area area area area area area area area area area area = = = = = = = = = = = = = 0.1256 0.5024 1.1304 2.0096 3.14 4.5216 6.1544 8.0384 10.1736 12.56 15.1976 18.0864 21.2264

radius =

2.8

area =

24.6176

3.15.15.Generating multiplication tables


#include <iostream> #include <iomanip> #include <cctype> using std::cout; using std::cin; using std::endl; using std::setw; int main() { int table = 11; const int table_min = 2; const int table_max = 12; // Create the cout << " for(int i = 1 cout << " " cout << endl; top line of the table |"; ; i <= table ; i++) << setw(3) << i << " |";

// 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 |

3.16.1.Looping with while


#include <iostream> int main() { int counter = 0; while(counter < 5) { counter++; std::cout << "Looping! }

";

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

3.16.4.While statement with 'and'&&


#include <iostream>

using namespace std; int main() { int len; cout << "Enter length (1 to 79): "; cin >> len; while(len>0 && len<80) cout << '.'; len--; } return 0; } {

3.16.5.Use three conditions in while statement


#include <iostream> int main() { unsigned short small = 1; unsigned long large = 123; const unsigned short MAXSMALL=65535; std::cout << "small: " << small << "..."; // for each iteration, test three conditions while (small < large && large > 0 && small < MAXSMALL) { std::cout << "."; small++; large-=2; } std::cout << "\nSmall: " << small << " Large: " << large << std::endl; return 0; } small: 1............................................ Small: 42 Large: 41

3.19.2.Set up 3 stop conditions for the loop: break and continue


#include <iostream> using namespace std;// this file uses std::cout, // std::cin, std::endl, etc. int main() { unsigned short small = 1;

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.7.A while true loop


#include <iostream> int main() { int counter = 0; while (1) { counter ++; if (counter > 10) break; } std::cout << "counter: " << counter << "\n"; return 0; } counter: 11

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

3.16.10.Calculate the sum of the integers from 1 to 10 using while loop


#include <iostream> using std::cout; using std::endl; int main() { int sum; int x; x = 1; sum = 0; while ( x <= 10 ) { sum += x; x++; } cout << "The sum is: " << sum << endl; return 0; } The sum is: 55

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;

5.31.1.Generating random numbers


#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { srand(time(0)); int randomNumber = rand(); int die = (randomNumber % 6) + 1; cout << "You rolled a " << die << endl; return 0; }

2.20.16.multidimensional char arrays


#include <iostream> using namespace std; int main() { const int ROWS = 3; const int COLUMNS = 3; char board[ROWS][COLUMNS] = { {'O', 'X', 'O'}, {' ', 'X', 'X'}, {'X', 'O', 'O'} }; for (int i = 0; i < ROWS; ++i) {

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; }

2.20.15.Read from keyboard and output char array


#include <iostream> using namespace std; int main(void){ int age; float salary; char name[128]; cout << "Enter your first name age salary: "; cin >> name >> age >> salary; cout << name << ' ' << age << ' ' << salary; }

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; }

4.1.2.Initializing an array in a declaration.


#include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setw; int main() { int n[ 10 ] = { 2, 7, 4, 8, 5, 4, 9, 7, 6, 3 }; for ( int i = 0; i < 10; i++ ) cout << n[ i ] << endl; return 0; }

4.1.3.Static arrays are initialized to zero.


#include <iostream> using std::cout; using std::endl; void staticArrayInit( void ); void automaticArrayInit( void ); int main() { staticArrayInit(); automaticArrayInit(); staticArrayInit(); automaticArrayInit(); return 0; } void staticArrayInit( void ) { static int array1[ 3 ]; for ( int i = 0; i < 3; i++ ) cout << "array1[" << i << "] = " << array1[ i ] << " for ( int j = 0; j < 3; j++ ) array1[ j ] = 0; } void automaticArrayInit( void ) { int array2[ 3 ] = { 1, 2, 3 }; ";

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.4.Passing arrays and individual array elements to functions


#include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setw; void modifyArray( int [], int ); // appears strange void modifyElement( int ); int main() { const int arraySize = 5; // size of array a int a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize array a modifyArray( a, arraySize ); for ( int i = 0; i < arraySize; i++ ) cout << setw( 3 ) << a[ i ]; modifyElement( a[ 3 ] ); cout << a[ 3 ] << endl; return 0; } void modifyArray( int b[], int sizeOfArray ) { for ( int i = 0; i < sizeOfArray; i++ ) b[ i ] = 200; } void modifyElement( int e ) { e = 200 ; } 200200200200200200

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; }

4.1.8.Obtaining the number of array elements


#include <iostream> using std::cout; using std::endl; int main() { int values[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; cout << << << << << } There are 10 elements in the array. endl "There are " sizeof values/sizeof values[0] " elements in the array." endl;

return 0;

4.2.1.Read array element one by one from keyboard


#include <iostream> #include <cctype> using std::cout; using std::cin; using std::endl; int main() { int height[10]; int count = 0; char reply = 0; do {

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.2.2.Read array element from keyboard and output


#include <iostream> int main() { int myArray[5]; for (int i=0; i<5; i++) // 0-4 { std::cout << "Value for myArray[" << i << "]: "; std::cin >> myArray[i]; } for (int i = 0; i<5; i++) std::cout << i << ": " << myArray[i] << "\n"; return 0; } Value for myArray[0]: 1 Value for myArray[1]: 2 Value for myArray[2]: 3 Value for myArray[3]: 4 Value for myArray[4]: 5 0: 1 1: 2 2: 3 3: 4 4: 5

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; }

4.3.2.Index a pointer as if it were an array


#include <iostream> #include <cctype> using namespace std; int main() { char *p; int i; char str[80] = "This Is A Test"; cout << "Original string: " << str << "\n"; p = str; for(i = 0; p[i]; i++) { if(isupper(p[i])) p[i] = tolower(p[i]); else if(islower(p[i])) p[i] = toupper(p[i]); } cout << "Inverted-case string: " << str; return 0; } Original string: This Is A Test Inverted-case string: tHIS iS a tEST

4.3.3.Use a 2-D array of pointers to create a dictionary


#include <iostream> #include <cstring> using namespace std; int main() { char *dictionary[][2] = { "A", "AA",

"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.

4.3.10.Relationship between pointers and arrays


#include <iostream> using namespace std; void increase(int* const array, const int NUM_ELEMENTS); void display(const int* const array, const int NUM_ELEMENTS); int main() { const int NUM_SCORES = 3; int highScores[NUM_SCORES] = {5, 3, 2}; cout cout cout cout << << << << "using array name as a constant pointer.\n"; *highScores << endl; *(highScores + 1) << endl; *(highScores + 2) << "\n\n";

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; }

4.4.1.Declare a two-dimension array


#include <iostream> using namespace std; int main() { int t,i, nums[3][4]; for(t=0; t < 3; ++t) { for(i=0; i < 4; ++i) { nums[t][i] = (t*4)+i+1; cout << nums[t][i] << ' '; } cout << '\n'; } return 0; } 1 2 3 4 5 6 7 8 9 10 11 12

4.4.2.Initialize a two-dimension array


#include <iostream> using namespace std; int main() { int i, j; int sqrs[10][2] = { {1, 1}, {2, 4}, {3, 9}, {4, 16}, {5, 25},

{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

4.4.3.Creating A Multidimensional Array


#include <iostream> int main() { int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6}, {4,8}}; for (int i = 0; i<5; i++) for (int j=0; j<2; j++) { std::cout << "a[" << i << "][" << j << "]: "; std::cout << a[i][j]<< std::endl; } return 0; } a[0][0]: 0 a[0][1]: 0 a[1][0]: 1 a[1][1]: 2 a[2][0]: 2 a[2][1]: 4 a[3][0]: 3 a[3][1]: 6 a[4][0]: 4 a[4][1]: 8

#include <iostream> using std::cout; using std::endl;

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:

Values in array2 by row are: 1 2 3 4 5 0 Values in array3 by row are: 1 2 0 4 0 0

4.4.5.Search a two-dimension array


#include <iostream> #include <cstdio> using namespace std; int main() { int i; char str[80]; char numbers[10][80] = { "A", "322",

"B", "C", "D", "E", };

"976", "037", "400", "873"

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.

4.4.6.Use nested for loop to display the two dimesional array


#include <iostream.h> main() { const int Length=4; int *p = new int[Length*Length]; int a[Length][Length]={{16, 2, 3,13},{ 5,11,10, 8},{ 9, 7, 6,12},{ 4,1 4,15, 1},}; for (int i = 0;i < Length; i++) for (int j = 0;j < Length; j++) p[ i * Length + j ] = a[ i ][ j ]; cout<<"display:\n"; for (int i = 0;i < Length; i++) { for (int j = 0;j < Length; j++) cout << p[ i * Length + j] <<" cout << endl; } delete []p; return 0; } display: 16 2 3 13 5 11 10 8

"

9 4

7 6 12 14 15 1

4.2.1.Read array element one by one from keyboard


#include <iostream> #include <cctype> using std::cout; using std::cin; using std::endl; int main() { int height[10]; int count = 0; char reply = 0; do { 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.2.2.Read array element from keyboard and output


#include <iostream> int main() { int myArray[5]; for (int i=0; i<5; i++) // 0-4 { std::cout << "Value for myArray[" << i << "]: "; std::cin >> myArray[i]; } for (int i = 0; i<5; i++) std::cout << i << ": " << myArray[i] << "\n"; return 0; } Value for myArray[0]: 1 Value for myArray[1]: 2 Value for myArray[2]: 3 Value for myArray[3]: 4 Value for myArray[4]: 5

0: 1: 2: 3: 4:

1 2 3 4 5

4.4.7.Using pointer notation with a multidimensional array


#include <iostream> #include <iomanip> #include <cctype> using std::cout; using std::endl; using std::setw; int main() { const int table = 12; long values[table][table] = {0}; for(int i = 0; i < table ; i++) for(int j = 0; j < table ; j++) *(*(values + i) + j) = 0; for(int i = 0 ; i < table ; i++) { for(int j = 0 ; j < table ; j++) cout << " " << setw(3) << values[i][j] << " |"; cout << endl; } return 0; } 0 | 0 0 0 0 0 0 0 0 0 0 0 | | | | | | | | | | | 0 | 1 2 3 4 5 6 7 8 9 10 11 | | | | | | | | | | | 0 | 2 4 6 8 10 12 14 16 18 20 22 | | | | | | | | | | | 0 | 3 6 9 12 15 18 21 24 27 30 33 | | | | | | | | | | | 0 | 4 8 12 16 20 24 28 32 36 40 44 | | | | | | | | | | | 0 | 5 10 15 20 25 30 35 40 45 50 55 | | | | | | | | | | | 0 | 6 12 18 24 30 36 42 48 54 60 66 0 | | | | | | | | | | | | 7 14 21 28 35 42 49 56 63 70 77 0 | | | | | | | | | | | | 8 16 24 32 40 48 56 64 72 80 88 0 | | | | | | | | | | | | 9 18 27 36 45 54 63 72 81 90 99 0 | | 10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100 | 110 0 | | 11 | 22 | 33 | 44 | 55 | 66 | 77 | 88 | 99 | 110 | 121

| | | | | | | | | | |

#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]) << " << " << " << "

<< "sizeof clocal_cube[0][0][0]= "<< sizeof(clocal_cube[0][0][0])

vdisplay_results(clocal_cube);

cout << "cglobal_cube[0][1][2] is cout << "cglobal_cube[1][0][2] is

= " << 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";

4.5.1.Two dimensional object array and Initialization


#include <iostream> using namespace std; class MyClass { int x, y; public: MyClass(int i, int j) { x = i; y = j; } int getX() { return x; } int getY() { return y; } }; int main() { MyClass obs[4][2] = { MyClass(1, 2), MyClass(3, 4), MyClass(5, 6), MyClass(7, 8), MyClass(9, 10), MyClass(11, 12),

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

8.2.2.Structure array and structure pointer


#include<iostream.h> #include<stdio.h> #include<stdlib.h> #include<string.h> struct st { char name[20]; long num; int age; char sex; float score; }; int main() { struct st student[3],*p; p=student; for(int i=0;p<student+3;p++,i++) { cout<<"Enter all data of student :["<<i<<"]\n"; cin>>student[i].name; cin>>p->num; cin>>p->age; cin>>p->sex; cin>>p->score; } cout<<"record num name age sex score"<<"\n"; p=student; for(int i=0;p<student+3;p++,i++) cout<<i<<p->name<<p->num<<p->age<<p->sex<<p->score<<"\n"; } Enter all data of student :[0] 1 2 3 4 Enter all data of student :[1] E^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

Potrebbero piacerti anche