Arrays, Functions, Recursive Functions Examples
Arrays, Functions, Recursive Functions Examples
CMP 132
Computer Programming
Exercise (1)
Exercise (2)
#include <iostream>
using namespace std; j n Fun(j) m=5
int Fun(int n)
0 0 0 5
{
n*3; 1 1 1 6
return n; 2 2 2 8
} 3 3 3 11
int main()
4 4 4 15
{
int j, m = 5; 5 stop stop stop
for( j = 0; j < 5; j++)
m = m + Fun(j); Output:
cout << m << "\n";
15
return 0;
}
Exercise (3)
#include <iostream>
using namespace std; j n Fun(j) m=5
int Fun(int n)
0 0 0 5
{
n= n*3; 1 3 3 8
return n; 2 6 6 14
} 3 9 9 23
int main()
4 12 12 35
{
int j, m = 5; 5 stop stop stop
for( j = 0; j < 5; j++)
m = m + Fun(j); Output:
cout << m << "\n";
35
return 0;
}
Exercise (4)
Exercise (5)
#include <iostream>
using namespace std;
int calculatePower(int, int);
int main() {
int base, powerRaised, result;
cout << "Enter base number: ";
cin >> base;
cout << "Enter power number(positive integer): ";
cin >> powerRaised;
result = calculatePower(base, powerRaised);
cout << base << "^" << powerRaised << " = " << result;
return 0;
}
int calculatePower(int base, int powerRaised) {
if (powerRaised != 0)
return (base*calculatePower(base, powerRaised-1));
else
return 1;
}
2003 Prentice Hall, Inc. All rights reserved.
8
Output:
Enter base number:2
Enter power number(positive integer):3
2^3= 8