Sample – functions

by Nideesh C on February 8, 2011 · 0 comments

in C++




#include <iostream.h>

typedef int Bool;
const Bool TRUE = 1;
const Bool FALSE = 0;

Bool even (int);
Bool odd (int);
int readPosNum();
void testOneNum();
void panic();

void main () {
int i;
char c;
Bool more = TRUE;

while (cin && more) {
testOneNum();
cout << “More? [y = Yes, anything else No]: “;
cin >> c;
if (cin) more = (c == ‘y’);
}
}

void testOneNum () {
int i;

i = readPosNum();
if (even(i)) cout << “The number ” << i << ” is even.” << endl;
else cout << “The number ” << i << ” is odd.” << endl;
}

int readPosNum () {
int j;

cout << “Enter a number >= 0: “;
cin >> j;
while (cin && j < 0) {
cout << “Unacceptable, reenter: “;
cin >> j;
}
if (cin) return(j);
else panic();
}

Bool even (int i) {
if (i == 0) return(TRUE);
else return(odd(i-1));
}

Bool odd (int i) {
if (i == 0) return(FALSE);
else return(even(i-1));
}

void panic() {
cout << “Disaster! Exiting …” << endl;
exit(-1);
}

Not Satisfied ? Just search & get the result

Related Posts Plugin for WordPress, Blogger...
Be Sociable, Share!

Related posts:

  1. Sample – example of pass-by-reference
  2. Sample – factorial
  3. Sample – understanding call-by-value and call-by-reference
  4. Sample – check if a number is prime
  5. Sample – Fibonacci numbers

Leave a Comment

Previous post:

Next post: