Repeated display function without any returned value – void type
Function to repeat a character in display for number of times desired.
Learning Objectives
- Use of void return type for a function where no value is returned.
- Passing multiple parameters in a function.
Source Code
|
|
Alternate (?) : |
Run Output
Code Understanding
void repeat(char,int);
This is function prototype declaration with first parameter as char type and second parameter as int type. Since this function is not expected to return anything so the void return type is written.
char c=’*’; //This is character to be repeated
int rc=15; //This is repeat count
repeat(c,rc);
This is function call with first actual parameter as c which contains the character to be repeated and second parameter as rc which is repeat count. These parameter type should necessarily be of same type as declared in the prototype.
void repeat(char c,int rc)
This is function definition header where again it starts with void keyword, which means that function doesn’t return anything. As this function just displays things so nothing is returned.
for(int i=0;i<rc;++i) cout<<c;
This loop runs till the repeat count and print the symbol passed by character parameter of the function.
Watch that there is no return instruction at the end of the function. This clearly means that nothing is being returned.
Notes
- Giving void for a function which doesn’t return anything is a necessary requirement as per ISO C++ standard. It can not be omitted.
- The position of multiple parameters in a function prototype can not be interchanged. However some parameters which are not required for a function can be omitted starting from end to the first.
Common Errors
- Students often interchange parameters while passing. This is not allowed.
Suggested Filename(s): fn-noret.cpp
Created: 5-Jan-2018 14:08 | Updated: 15-Sep-2018 14:07|
