تحديات برمجيةالتحدي العاشر - حل التمرين الثاني بلغة C++
المطلوب
أكتب برنامج مهمته رسم الشكل التالي بواسطة الحلقات.
عند تشغيل البرنامج, يجب أن يطلب من المستخدم إدخال عدد بين 1 و 9 حتى يتم رسم الشكل المطلوب بناءً عليه.
الحل بلغة C++
#include <iostream>
int main() {
int n;
do {
std::cout << "Enter the number of lines: ";
std::cin >> n;
}
while (n < 1 || n > 9);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (j == 1 || j == i || i == n)
{
std::cout << n - j + 1 << " ";
}
else
{
std::cout << " ";
}
}
std::cout << "\n";
}
char end; std::cin >> end;
return 0;
}
#include <iostream>
int main() {
int n;
do {
std::cout << "Enter the number of lines: ";
std::cin >> n;
}
while (n < 1 || n > 9);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (j == 1 || j == i || i == n)
{
std::cout << n - j + 1 << " ";
}
else
{
std::cout << " ";
}
}
std::cout << "\n";
}
char end; std::cin >> end;
return 0;
}
سنحصل على النتيجة التالية إذا قام المستخدم بإدخال الرقم 6 عند التشغيل.
Enter the number of lines: 6 6 6 5 6 4 6 3 6 2 6 5 4 3 2 1