C++ 程序:改进的弗洛伊德三角形
原文:https://www.studytonight.com/cpp-programs/cpp-modified-floyds-triangle-program
大家好!
在本教程中,我们将学习如何用 C++ 编程语言打印修改后的弗洛伊德三角形。
什么是弗洛伊德三角?
弗洛伊德的三角形是自然数的直角三角形数组。它是通过用连续的数字填充三角形的行来定义的,从左上角的 1 开始。
在修改的弗洛伊德三角形中,每行从行号开始,打印所有连续的数字,并包含与行号相等的列数。下面的代码以及输出片段将帮助您理解所提到的定义。
使用 * 或字母或数字的所有此类模式都是通过使用嵌套循环结构实现的,知道如何迭代以及迭代到哪里。
我们相信,本节涵盖的所有模式将帮助您理解这个概念,并在形成您自己的模式时更好地可视化它,因为这类问题在各种稍加修改的采访中经常被问到。
代号:
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to print Floyd's Triangle ===== \n\n";
//i to iterate the outer loop and j for the inner loop
int i, j, rows;
//to denote the range of numbers in each row
int n=0, first,last;
cout << "Enter the number of rows in the pyramid: ";
cin >> rows;
cout << "\n\nThe required Floyd's Triangle containing " << rows << " rows is:\n\n";
//outer loop is used to move to a particular row
for (i = 1; i <= rows; i++)
{
first = i;
last = first + i -1;
//to display that the outer loop maintains the row number
//cout << "Row # " << i << " contains the numbers from " << first << " to " << last << " : ";
//inner loop is used to decide the number of columns in a particular row
for (j = 1; j <= i; ++j) // remember: in such cases, ++j works same as j++ (but not always- we will cover this in upcoming posts)
cout << n + j << " ";
n++;
cout << endl; //endl works same as '\n'
}
cout << "\n\n";
return 0;
}
您可以通过删除//
来取消对下面显示的代码行的注释,从而获得每行数字范围的详细信息。
//cout << "Row # " << i << " contains the numbers from " << first << " to " << last << " : ";
输出 1 :当你按原样运行提供的代码时,
输出 2 :当打印出范围的行没有注释时,
我们强烈建议您在开始编程之前先在纸上一行一行地画出这样的模式,因为这将帮助您更好地理解嵌套结构。
继续学习: