Saturday, 11 January 2014

CHAPTER 7—ARRAYS AND STRINGS code;

CHAPTER 7—ARRAYS AND STRINGS code;



Code:
/**1.  Write a function called reversit() that reverses a C-string (an array of char). Use a for loop that
  swaps the first and last characters, then the second and next-to-last characters, and so on. The
  string should be passed to reversit() as an argument. 
  Write a program to exercise reversit(). The program should get a string from the user, call reversit(),
  and print out the result. Use an input method that allows embedded blanks. Test the program with
  Napoleon’s famous phrase, “Able was I ere I saw Elba.”*/
#include<iostream>
#include<string>
#include<conio.h>
using namespace std;

void reversit(char str[]){
 char tmp; int k=strlen(str);
 for(int i=0; i<(k/2); i++){
 tmp=str[i]; str[i]=str[k-i-1]; str[k-i-1]=tmp;}}

void main(void)
{
 cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
 cout<<"-------------------------------------------------------------------------------\n"<<endl;
 
 char mystr[80];
 
 do{
 cout<<"Enter a string: "; cin>>mystr;
 reversit(mystr); cout<<mystr;
 cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
 }while(getch()=='c');
}
Code:
/**2.  Create a class called employee that contains a name (an object of class string) and an employee
  number (type long). Include a member function called getdata() to get data from the user for insertion
  into the object, and another function called putdata() to display the data. Assume the name has no
  embedded blanks. 
  Write a main() program to exercise this class. It should create an array of type employee, and then
  invite the user to input data for up to 100 employees. Finally, it should print out the data for all the
  employees.*/
#include<iostream>
#include<string>
#include<iomanip>
#include<conio.h>
using namespace std;

class employee{
 string name;
 long emp_num;
public:
 void putdata(){
 cout<<"\nEnter the employee name: "; cin>>name;
 cout<<"Enter the employee number: "; cin>>emp_num;}
 void getdata(){ cout<<endl<<setw(10)<<name<<setw(25)<<emp_num;}};

void main(void)
{
 cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
 cout<<"-------------------------------------------------------------------------------\n"<<endl;
 
 employee emp[100]; int i=0;
 
 do{
  while(true){
  emp[i++].putdata();
  if(i<100){
   cout<<"Enter more ? (y) to continue : ";
   if(toupper(getche())=='Y') continue;}
  break;}
  cout<<"\nEmployee name"<<setw(25)<<"Employee number";
  for(int j=0; j<i; j++) emp[j].getdata();
 cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
 }while(getch()=='c');
}
Code:
/**3.  Write a program that calculates the average of up to 100 English distances input by the user.
  Create an array of objects of the Distance class, as in the ENGLARAY example in this chapter. To
  calculate the average, you can borrow the add_dist() member function from the ENGLCON example in
  Chapter 6. You’ll also need a member function that divides a Distance value by an integer. Here’s
  one possibility: 

  void Distance::div_dist(Distance d2, int divisor)
     {
     float fltfeet = d2.feet + d2.inches/12.0;
     fltfeet /= divisor;
     feet = int(fltfeet);
     inches = (fltfeet-feet) * 12.0;
     }
*/
#include<iostream>
#include<string>
#include<iomanip>
#include<conio.h>
using namespace std;

class Distance{
      int feet; float inches;
   public:
   Distance(): feet(0), inches(0) {}
      void getdist(){
      cout<<"\nEnter feet: "; cin>>feet;
      cout<<"Enter inches: "; cin>>inches;}
   void add_dist(Distance d2, Distance d3);
   void div_dist(Distance d2, int divisor);
      void showdist() const { cout<<feet<<"\'-"<<inches<<'\"';}};

void Distance::add_dist(Distance d2, Distance d3)
{
   inches=d2.inches+d3.inches; feet=0;
   if(inches>=12.0){ inches -= 12.0; feet++;}
   feet += d2.feet+d3.feet;
}

void Distance::div_dist(Distance d2, int divisor)
{
   float fltfeet=d2.feet+d2.inches/12.0;
   fltfeet /= divisor; feet=int(fltfeet);
   inches=(fltfeet-feet)*12.0;
}

void main(void)
{
 cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
 cout<<"-------------------------------------------------------------------------------\n"<<endl;
 
 Distance dist[100], tmp; int i=0;
 
 do{
 while(true){
 dist[i].getdist(); tmp.add_dist(tmp, dist[i++]);
 if(i<100){
  cout<<"Enter more ? (y) to continue : ";
  if(toupper(getche())=='Y') continue;}
 break;}
 tmp.div_dist(tmp, i); cout<<"\nAverage is: "; tmp.showdist();
 cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
 }while(getch()=='c');
}
Code:
/*4.  Start with a program that allows the user to input a number of integers, and then stores them in
  an int array. Write a function called maxint() that goes through the array, element by element, looking
  for the largest one. The function should take as arguments the address of the array and the number
  of elements in it, and return the index number of the largest element. The program should call this
  function and then display the largest element and its index number. (See the SALES program in this
  chapter.) */
#include<iostream>
#include<conio.h>
using namespace std;

int maxint(int arr[], int bound){
 int max=0;
 for(int j=1; j<bound; j++) max= arr[max]>arr[j]? max:j;
 return max;}

void main(void)
{
 cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
 cout<<"-------------------------------------------------------------------------------\n"<<endl;
 
 do{
  int a[100], i=1;
 cout<<"Enter numbers : ([0] to quit) "; cin>>a[0];
 while(a[i-1] || i==100) cin>>a[i++];
 cout<<"The maximum is: "<<a[maxint(a, i)];
 cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
 }while(getch()=='c');
}Code:
/*5.  Start with the fraction class from Exercises 11 and 12 in Chapter 6. Write a main() program that
  obtains an arbitrary number of fractions from the user, stores them in an array of type fraction,
  averages them, and displays the result*/
#include<iostream>
#include<conio.h>
using namespace std;

class fraction{
 char c;
 int numerator, denominator;
public:
 void fadd(fraction a, fraction b);
 void fdiv(fraction a, fraction b);
 void getfrac(){ cout<<"Enter fraction: "; cin>>numerator>>c>>denominator;}
 void disp() const { cout<<"Maximum = "<<numerator<<"/"<<denominator;}
 float getFl(){ if(denominator) return numerator/denominator; else return 0;}};

void fraction::fadd(fraction a, fraction b){
 numerator  =a.numerator*b.denominator+a.denominator*b.numerator;
 denominator=a.denominator*b.denominator;}

void fraction::fdiv(fraction a, fraction b){
 if(b.numerator != 0){
 numerator  =a.numerator*b.denominator;
 denominator=b.numerator*a.denominator;}
 else         cout<<"Math error !"<<endl;}
 
int maxfrc(fraction arr[], int bound){ 
 int max=0; 
 for(int j=1; j<bound; j++) max= arr[max].getFl()>arr[j].getFl()? max:j;
 return max;}

void main(void)
{
 cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
 cout<<"-------------------------------------------------------------------------------\n"<<endl;
 
 do{
  fraction a[100]; int i=1;
 cout<<"([0] to quit):\n"; a[0].getfrac();
 while(a[i-1].getFl() || i==100) a[i++].getfrac();
 a[maxfrc(a, i)].disp();
 cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
 }while(getch()=='c');
}
Code:
/*6.  In the game of contract bridge, each of four players is dealt 13 cards, thus exhausting the entire
  deck. Modify the CARDARAY program in this chapter so that, after shuffling the deck, it deals four
  hands of 13 cards each. Each of the four players’ hands should then be displayed. */
#include<iostream>
#include<conio.h>
using namespace std;
#include<cstdlib>
#include<ctime>

enum Suit{ clubs, diamonds, hearts, spades};
const int jack  = 11;
const int queen = 12;
const int king  = 13;
const int ace   = 14;

class card{
      int number;
      Suit suit;
   public:
      void set(int n, Suit s){ suit=s; number=n;}
      void display();};

void card::display()
{
 if(number>=2 && number<=10) cout<<number;
 else switch(number) {
   case jack:     cout<<"J";     break;
   case queen:    cout<<"Q";     break;
   case king:     cout<<"K";     break;
   case ace:      cout<<"A";}
 switch(suit) {
   case clubs:    cout<<char(5); break;
   case diamonds: cout<<char(4); break;
   case hearts:   cout<<char(3); break;
   case spades:   cout<<char(6);}
 cout<<"  ";
}

void main(void)
{
 cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
 cout<<"-------------------------------------------------------------------------------\n"<<endl;
 
 card deck[52]; int j, i;

 do{
  i=0;
 for(j=0; j<52; j++){
  int num=(j%13)+2; Suit su=Suit(j/13);
  deck[j].set(num, su);}
 srand(time(NULL));
 for(j=0; j<52; j++){
  int k=rand()%52; card temp=deck[j];
  deck[j]=deck[k]; deck[k]=temp;}
 cout<<"\nHand "<<++i<<": ";
 for(j=0; j<52; j++){ deck[j].display(); if(!((j+1)%13)&&i<4) cout<<"\nHand "<<++i<<": ";;}
 cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
 }while(getch()=='c');
}
Code:
/*7.  One of the weaknesses of C++ for writing business programs is that it does not contain a built-in
  type for monetary values such as $173,698,001.32. Such a money type should be able to store a
  number with a fixed decimal point and about 17 digits of precision, which is enough to handle the
  national debt in dollars and cents. Fortunately, the built-in C++ type long double has 19 digits of
  precision, so we can use it as the basis of a money class, even though it uses a floating decimal.
  However, we’ll need to add the capability to input and output money amounts preceded by a dollar
  sign and divided by commas into groups of three digits; this makes it much easier to read large
  numbers. As a first step toward developing such a class, write a function called mstold() that takes a
  money string, a string representing a money amount like 

  “$1,234,567,890,123.99”



  as an argument, and returns the equivalent long double. 
  You’ll need to treat the money string as an array of characters, and go through it character by
  character, copying only digits (1 to 9) and the decimal point into another string. Ignore everything
  else, including the dollar sign and the commas. You can then use the _atold() library function (note
  the initial underscore; header file STDLIB.H or MATH.H) to convert the resulting pure string to a long
  double. Assume that money values will never be negative. Write a main() program to test mstold() by
  repeatedly obtaining a money string from the user and displaying the corresponding long double.  */
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<string>
using namespace std;

long mstold(char strm[])
{
 string s=" 0123456789"; char ret[20];
 //long double x;
 for(int i=0, j=0; i<strlen(strm); i++)
  if(s.find(strm[i])<20) ret[j++]=strm[i];
  return atol(ret);
}

void main(void)
{
 cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
 cout<<"-------------------------------------------------------------------------------\n"<<endl;
 
 char mon[20];

 do{
 cout<<"Enter a monetary value: "; cin>>mon; cout<<mstold(mon);
 cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
 }while(getch()=='c');
}
Code:
/*8.  Another weakness of C++ is that it does not automatically check array indexes to see if they are
  in bounds. (This makes array operations faster but less safe.) We can use a class to create a safe
  array that checks the index of all array accesses. 
  Write a class called safearay that uses an int array of fixed size (call it LIMIT) as its only data
  member. There will be two member functions. The first, putel(), takes an index number and an int
  value as arguments and inserts the int value into the array at the index. The second, getel(), takes an
  index number as an argument and returns the int value of the element with that index. 


  safearay sa1;           // define a safearay object
  int temp = 12345;       // define an int value
  sa1.putel(7, temp);     // insert value of temp into array at index 7
  temp = sa1.getel(7);    // obtain value from array at index 7



  Both functions should check the index argument to make sure it is not less than 0 or greater than
  LIMIT-1. You can use this array without fear of writing over other parts of memory. 
  Using functions to access array elements doesn’t look as eloquent as using the [] operator. In
  Chapter 8 we’ll see how to overload this operator to make our safearay class work more like built-
  in arrays. */
#include<iostream>
#include<conio.h>
using namespace std;

const int LIMIT=100;

class safearay{
 int arr[LIMIT];
public:
 void putel(int index, int value){ if(index>-1 && index<LIMIT) arr[index]=value;}
 int getel(int index){ if(index>-1 && index<LIMIT) return arr[index];}};

void main(void)
{
 cout<<"### Programmed By Amahdy(MrJava) ,right restricted.~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
 cout<<"-------------------------------------------------------------------------------\n"<<endl;
 
 safearay sa1; int temp=12345;

 do{
    sa1.putel(7, temp); temp=sa1.getel(7);
 cout<<temp;
 cout<<"\n\n !Press c to continue or any key to exit."<<endl<<endl;
 }while(getch()=='c');
}

8 comments: