There are three additional worked examples:-
Example 1 | |
Example 2 - using reference variables | |
Example 3 - Functions and arrays |
PROBLEM:
Write a function that will display a line of n asterisks on the
screen. n will be passed as a argument to the function. After
writing the line of n asterisks a new line should be printed.
Write a program to call this function, using it to display a grid of
m times n asterisks. The user should be prompted to enters the
values for m and n.
SOLUTION:
Considering initailly the function, the first thing to consider is
What arguments are to be sent to the function?
Obviously, it need to be told how many asterisks to write, in this case
n which will be integer?
The next thing to consider is what will be returned by the function?
Obviously, the function only prints to screen and therefore does not need to
return anything to the main calling program. The return type is therefore
void
We can now continue and write the function.
The complete program, has to call this function m times, and so a loop
will be used to call the program. The complete solution is then.
ADDITIONAL EXERCISE
Amend the main program written above, so that the following
type of pattern is displayed. This is shown for the case of m = 5.
SOLUTION
Note that no changes are required to the function, we simply need to amend
the main calling program.
Example 1
void line (int n)
{
int i;
for (i=0; i < n;i++)
cout << "*";
cout << "\n";
}
#include <iostream.h>
// function declaration */
void line( int n);
main()
{
int i;
int m,n;
cout << "Enter values for m and n \n";
cin >> m >> n ;
// Loop to call function m times
for (i=0; i < m; i++)
line(n);
}
// function definition
void line (int n)
{
int i;
for (i=0; i < n;i++)
cout << "*";
cout << "\n";
}
*
**
***
****
*****
#include <iostream.h>
// function declaration
void line( int n);
main()
{
int i;
int m;
cout << "Enter a value for the number of rows\n";
cin >> m ;
//Call to function in loop
for (i=1; i <= m; i++)
line(i);
}
Back to Main Page for Lecture 6 |