Function examples

//function to display a number of blank lines
void display_blank_lines (int count) {
//doesn't return any value.  No return statement.
//void is empty type
  int i;
  for (i=1; i<=count; i++)  // "count" blank lines
    cout << endl;
  //returns at end of function
}
-----------
...
display_blank_lines(6);    //call of void function is statement by itself

display_blank_lines(2*size);


***********************

//function to clear the screen
void clear_screen () {    //no arguments
  int i;
  for (i=1; i<25; i++)  // 24 blank lines
    cout << endl;
}
-----------
...
clear_screen();
//parens required even for function with no arguments


***********************
//input a valid grade from user
//Same code as seen before, making a function out of it.
char get_grade () {
  char c;
  do {               //loop inputting until get a valid grade char
    cout << "Enter grade: ";
    cin >> c;
    if (c!='A' && c!='B' && c!='C' && c!='D' && c!='F') 
      cout << "ERROR.  Invalid grade: " << c << "  Re-enter: ";
  } while (c!='A' && c!='B' && c!='C' && c!='D' && c!='F');
  return c;          //return the valid grade
}
-----------
...
char grade;
grade = get_grade();


***********************

//test if a year is a leap year.             
// returns true if arg is a leap year, 
//returns false if arg is not leap year

bool is_leapyear (int year) {
  // evenly divisible by 4 but not by 100 unless also by 400
  if (year%4==0 && year%100!=0 || year%400==0)  
    return true;
  else
    return false;
}

------------
...
cin >> year;   // different variable than function's formal arg
if (is_leapyear(year))
  cout << "Olympics and presidential election year";
else
  cout << "No Feb 29 this year";



************************************
//get valid choice value in range 1 thru 5
int get_valid_input () {
  int num;
  cout << "Enter choice: ";
  cin >> num;
  while (num<1 || num>5) {
    cout << "Must be 1 thru 5.  Re-enter: ";
    cin >> num;
  }
  return num;
}
----------
...
choice = get_valid_input();
...
switch (get_valid_input()) {
  case 1:
.
.


***********************************
//our own version of islower function
bool our_islower (char c) {
  if (c>='a' && c<='z')
    return true;
  else
    return false;
}



//our own version of toupper function
char our_toupper (char c) {
  if (islower(c))
    return c - 32;   // 'a'-'A'==32 in ASCII
  else
    return c;
}


Exercises: write functions to
output rectangle of *'s
output big X of *'s
calcluate number of gpa points of a grade and credits combination

Some programs with functions to look at and try:

Program to make power tables powertbl.cpp

Program to convert Roman numerals roman.cpp

Program to make multiplication etc. tables optable.cpp

Programs to compute if a number is prime primes

Next (reference arguments)


©David Wills