fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <sstream>
  4. #include <iomanip> // for setw, setfill
  5.  
  6. using namespace std;
  7.  
  8. int binary(int number);
  9. std::string binStr(unsigned int exponent, unsigned int size);
  10.  
  11. int main()
  12. {
  13.  
  14. vector<vector<int> > matrix;
  15.  
  16. cout<<"Please enter the size of the identity matrix"<<endl;
  17. int n;
  18. cin>>n;
  19.  
  20. // Initialize the matrix
  21. matrix.resize(n);
  22. for (int i=0; i<n;i++)
  23. matrix[i].resize(n);
  24.  
  25. // Fill the matrix
  26. for (int col = 0; col<n; col++)
  27. {
  28. std::string bin = binStr(n-col,n);
  29. for (int row=0; row<n; row++)
  30. matrix[col][row] = bin[row]-'0';
  31. }
  32.  
  33.  
  34. // Print the matrix and return
  35. for(unsigned int y = 0; y < n; y++)
  36. {
  37. for(unsigned int x = 0; x < n; x++)
  38. cout << "\t" << matrix[y][x];
  39. cout << "\n";
  40. }
  41. return 0;
  42. }
  43.  
  44. std::string binStr(unsigned int exponent, unsigned int size)
  45. {
  46. // You do not need a string stream (which is like using a bazooka to kill a fly...)
  47. // Instead, just create a string of the required length
  48. // 'str' will contain the binary representation of 2^exponent
  49. std::string str(size,'0');
  50. if(exponent <= size && exponent > 0)
  51. str[size - exponent] = '1';
  52. return str;
  53. }
Success #stdin #stdout 0.01s 2824KB
stdin
10
stdout
Please enter the size of the identity matrix
	1	0	0	0	0	0	0	0	0	0
	0	1	0	0	0	0	0	0	0	0
	0	0	1	0	0	0	0	0	0	0
	0	0	0	1	0	0	0	0	0	0
	0	0	0	0	1	0	0	0	0	0
	0	0	0	0	0	1	0	0	0	0
	0	0	0	0	0	0	1	0	0	0
	0	0	0	0	0	0	0	1	0	0
	0	0	0	0	0	0	0	0	1	0
	0	0	0	0	0	0	0	0	0	1