1.迭代的使用
#include
using namespace std;
int age(int);
int main(void)
{
cout << age(5) << endl;
return 0;
}
int age(int n)
{
int c;
if (n == 1)
c = 10;
else
{
c = age(n - 1) + 2;
}
return c;
}
2.静态变量求阶乘(static)
#include
using namespace std;
int fac(int);
int main(void)
{
int i;
for (i = 1;i <=5;i++)
cout << i << “!=” << fac(i) << endl;
return 0;
}
int fac(int n)
{
static int f = 1;
f = f*n;
return f;
}
3.Fibonacci数列
#include
using namespace std;
#include
//int fac(int);
int main(void)
{
int i;
int f[20] = { 1,1 };
for (i = 2;i < 20;i++)
f[i] = f[i - 2] + f[i - 1];
for (i = 0;i < 20;i++)
{
if (i % 5 == 0)cout << endl;
cout << setw(8) << f[i];
}
cout << endl;
return 0;
}
4.冒泡排序(一维数组)
#include
#include
using namespace std;
int main(void)
{
int i, j, t;
int a[5];
for (i = 0;i < 5;i++)
cin >> a[i];
cout << endl;
//
for (i = 0;i < 5;i++)
cout << setw(4)<<a[i];
cout << endl;
/*/
for (j = 0;j < 4;j++)
for (i = 0;i < 5 - i;i++)
if(a[i]>a[i+1])
{
t = a[i];
a[i] = a[i + 1];
a[i + 1] = t;
}
for (i = 0;i < 5;i++)
cout << setw(4)<<a[i];
cout << endl;
return 0;
}
5.二维数组求最大值,并得出下标值
#include
#include
using namespace std;
int main(void)
{
int a[2][3] = { { 15,34,23 },{ 54,27,65 } };
int i, j, k;
int row, col;
int max = 0;
for (i = 0;i <= 1;i++)
for (j = 0;j <= 2;j++)
{
cout << setw(4)<<a[i][j];
if (j == 2)
cout << endl;
}
cout << “***********************” << endl;
for (i = 0;i <= 1;i++)
for (j = 0;j <= 2;j++)
{
if (max < a[i][j])
max = a[i][j];
row = i;
col = j;
}
cout << "The bigger number is:" << max << endl;
cout << "row=" << row << "," << "col=" << col << endl;
return 0;
}
// 15 34 23
54 27 65
The bigger number is:65
row=1,col=2
请按任意键继续. . .
数组名也可以作为实参何形参,传递的数组的首地址
6.数组传参
#include
#include
using namespace std;
int main(void)
{
void select_sort(int array[], int n);
int a[5], i;
cout << "enter the originl array:" << endl;
for (i = 0;i < 5;i++)
cin >> a[i];
select_sort(a, 5);
cout << "the sorted array:" << endl;
for (i= 0;i < 5;i++)
{
cout << a[i];
}
cout << endl;
return 0;
}
void select_sort(int array[], int n)
{
int i, j, k, t;
for (i = 0;i < n - 1;i++)
{
k = i;
for (j = i + 1;j < n;j++)
if (array[j] < array[k])k = j;
t = array[k];array[k] = array[i];array[i] = t;
}
}
//数组名也可以作为实参何形参,传递的数组的首地址
//int *pointe=&a;
&*pointer_2与&a等价
& 和 *是同优先级,但是是从右至左运算。