As mentioned in the title, I do not know how to format my std::cout
output such that the inner for
-loop writes in "rows" but the outer for
-loop produces columns.
My Code:
#include <iostream>
#include <iomanip>
using namespace std;
class LoopTest
{ //Access specifier
public:
//Data Members
int outer_size = 2;
int inner_size = 3;
//Memberfunction
int testing()
{
freopen("/home/user/training/exercise/e0/TESTPROGRAM_OUTPUT.dat", "w", stdout); //redirect output to file
for(int i = 0; i <= outer_size; i++)
{
cout << " number: " << i;
for(int j = 0; j <= inner_size; j++)
{
cout << " j*(j*i): " << j*(j*i);
cout << " ";
cout << "\n";
}
}
fclose(stdout);
return 0;
}
};
The code shown above produces the following output:
number: 0 j*(j*i): 0
j*(j*i): 0
j*(j*i): 0
j*(j*i): 0
number: 1 j*(j*i): 0
j*(j*i): 1
j*(j*i): 4
j*(j*i): 9
number: 2 j*(j*i): 0
j*(j*i): 2
j*(j*i): 8
j*(j*i): 18
As mentioned, the ideal output would be:
number: 0 j*(j*i): 0 number: 1 j*(j*i): 0 number: 2 j*(j*i): 0
j*(j*i): 0 j*(j*i): 1 j*(j*i): 2
j*(j*i): 0 j*(j*i): 4 j*(j*i): 8
j*(j*i): 0 j*(j*i): 9 j*(j*i): 18
You have to interleave your outputs, first outputting all your first line, and the second...
for(int i = 0; i <= outer_size; i++)
{
cout << " number: " << i << "\t"; // Add the tabs necessary
}
for(int j = 0; j <= inner_size; j++)
{
for(int i = 0; i <= outer_size; i++)
{
// The the first result line
}
}
Change the order of for loops.
You can do something like this:
#include<iostream>
#include<cmath>
using namespace std;
int main (int argc, char* argv[])
{
int outer_size=2, inner_size=3;
int j=0;
for(int i = 0; i <= outer_size; i++)
{
cout << " number: " << i;
cout << " j*(j*i): " << j*(j*i)<<"\t";
}
std::cout<<endl;
for( j = 1; j <= inner_size; j++)
{
for (int i=0; i<=outer_size; i++)
{
cout << " j*(j*i): " << j*(j*i)<<"\t\t";
}
std::cout<<endl;
}
return 0;
}
Producing this output on Terminal:
number: 0 j*(j*i): 0 number: 1 j*(j*i): 0 number: 2 j*(j*i): 0
j*(j*i): 0 j*(j*i): 1 j*(j*i): 2
j*(j*i): 0 j*(j*i): 4 j*(j*i): 8
j*(j*i): 0 j*(j*i): 9 j*(j*i): 18
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.