【問1(横の棒グラフ)】
要素型がint型で要素数が15の配列の全要素に0~10の乱数を代入して、下のように棒グラフで値を表示するプログラムを作成せよ。棒グラフは記号文字'*'を横方向に並べたものとする。
・問1の実行例
a[ 0]: ****
a[ 1]: ********
a[ 2]: ******
a[ 3]: **********
a[ 4]: *****
a[ 5]: *
a[ 6]: ********
…中略…
a[12]: *****
a[13]: *
a[14]: *******
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL));
const int n = 15;
int a[n];
for (int i = 0; i < n; i++)
a[i] = rand() % 11;
for (int i = 0; i < n; i++) {
cout << "a[" << setw(2) << i << "]: ";
for (int j = 0; j < a[i]; j++)
cout << '*';
cout << '\n';
}
}
C:\Users\skonishi\Documents>bargraphh
a[ 0]: *********
a[ 1]: ********
a[ 2]:
a[ 3]: ******
a[ 4]: **
a[ 5]: ****
a[ 6]: ******
a[ 7]: *******
a[ 8]: **********
a[ 9]: *********
a[10]: ****
a[11]: **
a[12]: ****
a[13]:
a[14]: *****
C:\Users\skonishi\Documents>bargraphh
a[ 0]:
a[ 1]: *****
a[ 2]: ***
a[ 3]: *
a[ 4]:
a[ 5]: ****
a[ 6]: ****
a[ 7]: **
a[ 8]: ***
a[ 9]: *
a[10]: *******
a[11]: **
a[12]:
a[13]:
a[14]: ******
C:\Users\skonishi\Documents>bargraphh
a[ 0]: ***
a[ 1]: *******
a[ 2]: ***
a[ 3]: *********
a[ 4]: ********
a[ 5]: ****
a[ 6]: ***
a[ 7]: **********
a[ 8]: ****
a[ 9]: **
a[10]: **
a[11]: **
a[12]: ********
a[13]: ***
a[14]: *
【問2(縦の棒グラフ)】*
*
* *
* *
* * * *
* * * * *
* * * *: * *
* * * *中 * *
* * * *略 * *
* * * *: * * *
----------------
0 1 2 3 2 3 4
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL));
const int n = 15;
int a[n], max = 0;
for (int i = 0; i < n; i++) {
a[i] = rand() % 11;
if (max < a[i])
max = a[i];
}
for (int i = max; i > 0; i--) {
for (int j = 0; j < n; j++)
if (a[j] >= i)
cout << " *";
else
cout << " ";
cout << '\n';
}
for (int i = 0; i < n; i++)
cout << "--";
cout << '\n';
for (int i = 0; i < n; i++)
cout << setw(2) << i % 10;
cout << '\n';
}
C:\Users\skonishi\Documents>bargraphv
*
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * *
------------------------------
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4
C:\Users\skonishi\Documents>bargraphv
* *
* * * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
------------------------------
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4
C:\Users\skonishi\Documents>bargraphv
* *
* * * * *
* * * * * *
* * * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * * *
------------------------------
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4