Tuesday, December 2, 2014

C++ in simple pro



Problem1
 
#include 
#include
void main () 
{
  int width, horizpos, vertpos, beginhoriz, endhoriz;
  char c;
  cout << "Enter a character: ";
  cin >> c;
  cout << "Enter an integer: ";
  cin >> width;
 
  if ((width % 2) == 0) width = width+1;
  horizpos = 0;
  beginhoriz = width / 2;
  endhoriz = beginhoriz;
  while (beginhoriz >= 0) 
  {
   while (horizpos < width) 
   {
      if (horizpos < beginhoriz) cout << " ";
      else if (horizpos <= endhoriz) cout << c;
      else cout << " ";
      horizpos = horizpos + 1;
    }
    cout << endl;
    horizpos = 0;
    beginhoriz = beginhoriz - 1;
    endhoriz = endhoriz + 1;
  }
  horizpos = 0;
  beginhoriz = 1;
  endhoriz = width - 2;
  while (beginhoriz <= width / 2)
 {
    while (horizpos < width) 
    {
      if (horizpos < beginhoriz) cout << " ";
      else if (horizpos <= endhoriz) cout << c;
      else cout << " ";
      horizpos = horizpos + 1;
    }
    cout << endl;
    horizpos = 0;
    beginhoriz = beginhoriz + 1;
    endhoriz = endhoriz - 1;
  }
}
 

Problem2
 
#include 
#include
#include 
typedef int bool;
const bool true = 1;
const bool false = 0;
int readint (bool&);
int sumsquares (int i);
void main () 
{
  int i;
  bool endofdata;
  i = readint(endofdata);
  while (!endofdata) 
  {
    cout << "Sum of squares from 1 to " << i << " = " <<
      sumsquares (i) << endl;
    i = readint(endofdata);
  }
}
int readint (bool& b)
 {
  int i;
  cout << "Enter an integer greater than 1 (negative number to exit): ";
  cin >> i;
  while (i == 0) 
  {
    cout << "Re-enter integer: ";
    cin >> i;
  }
  if (i < 1) b = true; else b = false;
  return(i);
}
int sumsquares (int i) 
{
  int count, result;
  count = 1;
  result = 0;
  while (count <= i) 
  {
    result = result + count * count;
    count = count + 1;
  }
  return(result);
}
 
Problem3
 
#include 
#include
#include 
typedef int bool;
const bool true = 1;
const bool false = 0;
const char space = ' ';
const char newline = '\n';
void main () 
{
  ifstream f;
  char c;
  int numgaps;
  f.open("test.words");
  numgaps = 0;
  f.get(c);
  while (f) 
   { 
    if (c == newline) 
    {
      numgaps = numgaps + 1;
      f.get(c);
    }
    else if (c == space) 
    {
      while (f && c == space) 
     {
   f.get(c);
      }
      numGaps = numgaps + 1;
    }
    else f.get(c);
  }
  cout << "There are " << numgaps << " words" << endl;
}
 
Problem4
 
#include 
#include
void main () 
{
  int num, count = 1;
  float sum = 0.0;
  cout << endl;
  while (count <= 3) 
  {
    cout << "Enter a number: ";
    cin >> num;
    sum = sum + num;
    count = count + 1;
  }
  cout << "Average is " << sum / count << endl;
}
void main () 
{
  int num, count = 1;
  float sum = 0.0;
  cout << endl;
  while (count <= 3) 
   {
    cout << "Enter a number: ";
    cin >> num;
    sum = sum + num;
    count = count + 1;
  }
  cout << "Average is " << sum / (count - 1) << endl;
}

No comments:

Post a Comment