Tuesday, December 2, 2014

Evaluating expressions and Pass-by-reference and Lots of functions in C++



Evaluating expressions with side-effects
 
#include 
#include
void main () 
{
  int i;
  i=1;
  cout << "Initial value of i = " << i     << ". The value of ++i is " << ++i 
  << ". Now i = " << i << endl;
  i=1;
  cout << "Initial value of i = " << i     << ". The value of i++ is " << i++ 
      << ". Now i = " << i << endl;
}
 
Example of pass-by-reference
 
#include 
#include 
int exp (int,int);
void readnums (int&, int&);
void main () 
{
  int b, e;
  readnums(b,e);
  cout << b << " to the " << e << " = " << exp(b,e) << endl;
}
void readnums (int& b, int& e) 
{
  int correctInput;
  cout << "Enter the base and the exponent: ";
  cin >> b >> e;
  if (!cin) 
{ 
    cout << "Disaster! Terminating program." << endl;
    exit(-1);
  }
  correctInput = (b >= 0) && (e >= 0);
  while (!correctInput) 
{
    cout << "Something wrong! Try again ..." << endl;
    cout << "Re-enter base and exponent: ";
    cin >> b >> e;
    if (!cin) 
    { 
      cout << "Disaster! Terminating program." << endl;
      exit(-1);
    }
    correctInput = (b >= 0) && (e >= 0);
  }
}
int exp (int b, int e) 
{
  int result;
  result = 1;
  while (e != 0) 
   {
    result = result * b;
    e = e - 1;
  }
  return(result);
}
 
Lots of functions
 
#include 
#include
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);
}

No comments:

Post a Comment