do-while文

繰り返しはwhile文で書く。
while文は前判定型なので、一回目の条件判断で条件から漏れた場合は1回も処理を行わずループを抜ける場合がある

ループ:繰り返しのこと

//単文を繰り返す場合
 
while(継続条件)
 繰り返す処理;
 
//複文(ブロック)を繰り返す
while(継続条件)
{
  繰り返す処理;
}

後判定型の繰り返しはdo-while文で書く。
後判定型なので、必ず繰り返す処理を1度は実行するのが特徴

//単文を繰り返す場合
 
do
 繰り返す処理;
while(継続条件);
 
//複文(ブロック)を繰り返す
do
{
  繰り返す処理;
}
while(継続条件);

1問目

#include <iostream>
 
using std::cout;
using std::cin;
using std::endl;
 
int main()
{
	const char RIGHT_ANS = 'c';//charは1文字の英数字を保持できる型
	char ans;//実際は文字ではなくASCIIコードが保持される(整数だよね)
	         //つまり: charは8ビットの整数
 
	do 
	{
		cout << "問題:「木耳」これはなに?" << endl;
		cout << "a.ところてん b.はるさめ c.きくらげ" << endl;
 
		cout << "解答:";
		cin >> ans;
	} 
	//do の下のブロック{}をwhile();の条件を満たしている間繰り返す
	while (ans != RIGHT_ANS);
 
	cout << "正解!" << endl;
 
	return 0;
}

2問目

#include <iostream>
 
using std::cout;
using std::cin;
using std::endl;
 
int main()
{
	int i = 1;
	//~16時5分まで
	//do~while文を使って羊を100匹数えて寝てください
	//一匹数えるごとに
	//"羊が〇〇匹"と数えること
 
	//ここにdo-while書くよ
	do
	{
		cout << "羊が" << i << "匹" << endl;
		i = i + 1;
		//i++;でもいいよ
	}
	while (i <= 100);
	//100匹数えたらループ抜けて寝る
	cout << "Zzz、Zzz、Zzzzz、...." << endl;
 
	return 0;
}

3問目

#include <iostream>
 
using std::cout;
using std::cin;
using std::endl;
 
int main()
{
	int i = 0;
 
	do
	{
		//1~100までを改行しながら表示するように
		//ソースコードを完成させなさい
		i++;
		cout << i << endl;
	} while (i <= 100);
 
 
	return 0;
}
  • game-engineer/classes/2022/game-programing-1/first-term/6/6-07-5.txt
  • 最終更新: 4年前
  • by root