Creating a Parameterized Function

Creating a Parameterized Function

Lesson Details:
July 10, 2020


I: Introduction

The first version of the C programming language was created in 1972 by Dennis Ritchie. The language was designed to use a simple syntax that could be read and understood by anyone who had knowledge of programming. The purpose of the C programming language was to create an executable program that would run on multiple platforms, including UNIX.

II: Body

A: Creating a parameterized function

The parameterized function is one that uses parameters to describe its input. Parameters are used to allow flexibility in the input of the program. Consider the following function:

#include int main(void) { int i; printf("Enter a number between 1 and 10: "); scanf("%d", &i); if ( i >= 1 && i <= 10 ) printf( "You entered %d which is between 1 and 10!

", i ); else printf( "You entered %d which is NOT between 1 and 10!

", i ); return 0; }

The above code uses the scanf function to get an integer from the user and then compares it to a predefined range. If the user enters a number between 1 and 10, the program outputs that it is in that range. However, if they enter a number outside that range, the program outputs that it is not in that range. We can alter this program using parameters. Consider the following:

#include int main(int nRange, int &iNum) { int i; printf("Enter a number between 1 and 10: "); scanf("%d", &i); if ( i >= 1 && i <= 10 ) printf( "You entered %d which is between 1 and 10!

", i ); else printf( "You entered %d which is NOT between 1 and 10!

", i ); return 0; }

The program now uses two parameters instead of one. The first parameter is named nRange and accepts a value from 1 to 10. The second parameter is named iNum and receives the value passed from the user. The rest of the program is identical to the previous example. Using parameters allows us to define a set of parameters with a variable number of arguments. We will discuss how this works in more detail when we talk about functions in another tutorial.

loader
Course content