Functions

Additional Example


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.


void line (int n)
{
        int i;

        for (i=0; i < n;i++)
                printf("*");
        printf("\n");
}

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.

#include <stdio.h>

/*function declaration */
void line( int n);

main()
{
        int     i;
        int     m,n;

        printf("Enter  values for m and n \n");
	scanf("%d %d",&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++)
                printf("*");
        printf("\n");
}


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.


#include <stdio.h>

/*function declaration */
void line( int n);

main()
{
        int     i;
        int     m;

        printf("Enter  a value for the number of rows\n");
	scanf("%d", &m);

	/*Call to function in loop */
        for (i=1; i <= m; i++)
                line(i);
}


Back to Main Page for Lecture 6