[ create a new paste ] login | about

Link: http://codepad.org/hj6xvEh7    [ raw code | output | fork ]

ninwa - C++, pasted on Apr 10:
// Select exercises out of Deitel and Deitel's "C++ How To Program, 3rd Ed."

#include <iostream>
#include <iomanip>
using namespace std;

// Because I hate cmath's pow.
template< typename T >
T pow(T x, int n)
{
	if( 0 == n ) return 1;

	T v = x;
	for( int i = 1; i < n; i++ )
		v *= x;

	return v;
}

int main(int argv, char* argc)
{
	// 1.33
	// Display an 8x8 checkerboard pattern with as few statements as possible.
	for(unsigned i = 0; i < 8; i++)
		cout << ((i%2) ? " " : "") << "* * * * * * * *" << endl; 

	// 1.36
	// Write a program that inputs a five-digit number, separates the number 
	// into its individual digits and displays then three spaces apart.
	long num = 12345;

        /* So that codepad produces output properly.
	cout << "Enter a five-digit number: ";
	cin >> num;
	*/

	if( !num )
		cout << "0   0   0   0   0" << endl;
	else if( num < 10000 || num > 99999 )
		cerr << "Try a five-digit number next time." << endl;
	else
	{
		for(int i = 5; i > 0; i--){
			int n = (num / pow(10,i-1));
			num -= n * pow(10,i-1);
			cout << left << setw(4) << n;
		}
		cout << endl;
	}

	// 1.37
	// Display a table of n, n^2, and n^3 where n = [0,10]
	cout << left << setw(8) << "number" 
		     << setw(8) << "square"
		     << setw(8) << "cube" << endl;

	for(unsigned i = 0; i <= 10; i++)
		cout << setw(8) << i << setw(8) << i*i 
		     << setw(8) << i*i*i << endl;


	return EXIT_SUCCESS;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
* * * * * * * *
 * * * * * * * *
* * * * * * * *
 * * * * * * * *
* * * * * * * *
 * * * * * * * *
* * * * * * * *
 * * * * * * * *
1   2   3   4   5   
number  square  cube    
0       0       0       
1       1       1       
2       4       8       
3       9       27      
4       16      64      
5       25      125     
6       36      216     
7       49      343     
8       64      512     
9       81      729     
10      100     1000    


Create a new paste based on this one


Comments: