在 C++ 中不使用任何循环打印模式
在该问题中,我们给定一个数字 n。我们的任务是用递减到 0 或负数,然后增加回该数字的方式来打印模式。
我们举一个例子来理解这个问题,
Input: n = 12 Output: 12 7 2 -3 2 7 12
为了解决这个问题,我们将使用递归并在每次更新后调用函数。更新的记录通过标志变量进行保存,该变量告诉函数以 5 为单位增加或减少数字。
示例
以下代码给出了我们解决方案的实现,
#include <iostream>
using namespace std;
void printNextValue(int m){
if (m > 0){
cout<<m<<'\t';
printNextValue(m - 5);
}
cout<<m<<'\t';
}
int main(){
int n = 13;
cout<<"The pattern is:\n";
printNextValue(n);
return 0;
}输出
The pattern is − 13 8 3 -2 3 8 13
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP