# C++ Programming/Exercises/Variables and types

## Exercises for beginners : Variables and types

### EXERCISE 1

Write a program that asks the user to type the width and the height of a rectangle and then outputs to the screen the area and the perimeter of that rectangle.

Solution

Solution #1

```#include <iostream>
#include <sstream>
using namespace std;

int main()
{
string swap;

cout << "Input the width of the rectangle: ";
double width;
cin >> swap;
while ( !(stringstream(swap) >> width) )
{
cout << "Error! Type mismatch! \nInput again: ";
cin >> swap;
}

cout << "Input the height of the regtangle: ";
double height;
cin >> swap;
while ( !(stringstream(swap) >> height) )
{
cout << "Error! Type mismatch! \nInput again: ";
cin >> swap;
}

cout << "The area of the rectangle is " << height * width << endl;
cout << "The perimiter of the rectangle is " << 2 * (height + width) << endl;
return 0;
}
```

Solution #2

```//By Fate-X
#include<iostream>

using std::cout;
using std::cin;

int main(){
double width, height, area, perimeter;

cout << "This program takes the height and width (when given) of a rectangle and returns\nits area and perimeter.\n\n";
cout << "Input Width: ";

cin >> width;
cin.ignore();

cout << "Input height: ";

cin >> height;
cin.ignore();

area = height * width;
perimeter = 2 * (width + height);

cout << "\n\nArea: " << area << "\n";
cout << "Perimeter: " << perimeter << "\n\n";

cout << "Please press the 'return' key to exit the program.";
cin.get();

return 0;
}
```

Solution #3

```//By Md. Bothiujjaman
#include <stdio.h>
#include <conio.h>

Void main()
{
float width, height;
clrscr();
scanf("%f", &width);
scanf("%f", &height);
area = width * height;
perimeter = 2 (height + width);

printf("The area is: %.2f and the perimeter is: %.2f\n", area, perimeter ");
getch();

}
```

Solution #4

```//by Pak S.
#include<iostream>
using namespace std;
struct side
{
int a, b;
};
void area(side &x)
{
cout<<" The area is "<<x.a*x.b<<endl;
}
void para(side &x)
{
cout<<" The parameter is "<<(2*x.a+2*x.b)<<endl;
}
int main()
{
side x;
cout<<" Enter each side "<<endl;
cin>>x.a;
cin>>x.b;
area(x);
para(x);
return 0;
}
```

Solution #5

```#include<iostream>
using namespace std;
double w,l;
int main()
{
cout<<"Please enter the width and height:";
cin>>w>>l;
cout<<"The area is "<<w*l<<endl<<"The perimeter is "<<2*(w+l)<<endl;
return 0;
}
```

Solution #6

```//------------------------- By Brandon Cox ---------------------------------
#include <iostream>
using namespace std;

void outputFunc(int w, int l);

void inputFunc(int& w, int& l);
//--------------------------------------------------------------------------
int main(int argc, char* argv[])
{  int width, height;

inputFunc(width, height);

outputFunc(width, height);

system("pause");
return 0;
}
//--------------------------------------------------------------------------
void inputFunc(int& w, int& l)
{  cout << "Width: ";
while(! (cin >> w) )
{  cout << "\nInvalid parameter.  Please enter width again: ";
cin.clear();
cin.ignore(10000, '\n');
}

cout << "height: ";
while(! (cin >> l) )
{  cout << "\nInvalid parameter.  Please enter height again: ";
cin.clear();
cin.ignore(10000, '\n');
}
}
//--------------------------------------------------------------------------
void outputFunc(int w, int l)
{  cout << "\nArea: " << w * l << endl << "Perimeter: " << 2 * (w + l) << endl
<< endl;
}
```

solution #7

```/*
By Ellie Garcia
*/

#include <iostream>

using std::cout;
using std::cin;

float getPerimeter(float height, float width);
float getArea(float height, float width);
float getUserInput(float &height, float &width);
void outputUserInput(float area, float perimeter, float height, float width);
void inputFail();

int main()
{
float height    = 0.0;
float width     = 0.0;
float perimeter = 0.0;
float area      = 0.0;

getUserInput(height, width);
perimeter = getPerimeter(height, width);
area = getArea(height, width);
outputUserInput(area, perimeter, height, width);

return 0;
}

float getPerimeter(float height, float width)
{
return 2*(height+width);
}

float getArea(float height, float width)
{
return height*width;
}

float getUserInput(float &height, float &width)
{
do
{
inputFail();
cout << "Please enter the height: ";
cin  >> height;
}
while(!cin);

do
{
inputFail();
cout << "Please enter the width: ";
cin  >> width;

}
while(!cin);
}

void inputFail()
{
if(!cin)
{
cin.clear();
cin.ignore(3000, '\n');
cout << "Invalid character, try again\n";
}
}

void outputUserInput(float area, float perimeter, float height, float width)
{
cout << "The perimeter of a " << height << " by " << width << " Rectangle is " << perimeter;
cout << "\nThe area of a " << height << " by " << width << " Rectangle is " << area;
}
```

Solution #8

```/* By Shankar */
#include <iostream>
#include <cstdio>
#include <typeinfo>
#include <limits>

using namespace std;

float Area(float width, float height){
return(width*height);
}

float Perimeter(float width,float height){
return(2*(width+height));
}

// Can be used to check any type of input

template <typename Type>
Type check (Type type){
bool valid = false;
while (!valid){
valid = true; //Assuming that cin will be of the desired type
cin >> type;

/* cin.fail() checks to see if the value in the cin /stream is the correct type,
if not it returns true, false otherwise  */

if((cin.fail())||(type<=0)){
cin.clear(); //This corrects the stream.
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Please enter a positive " << typeid(type).name() <<" - type value only: " ;
valid = false; //The cin was not of desired type so try again.
}
}
return type;
}

int main(){

float width,height,area,perimeter;

printf("Please input the width of the rectangle: ");
width = check(width);

printf("Please input the height of the rectangle: ");
height = check(height);

area = Area(width,height);
perimeter = Perimeter(width,height);

printf("Area is:  %f\nPerimeter is: %f\n",area,perimeter);
/*
Note :
Some compilers give warnings like:
1.width is used uninitialized in this function.
2.height is used uninitialized in this function.
You can ignore it or you can initialize them to some positive value(say '1').
*/
}
```

### EXERCISE 2

Write a program that asks the user to type 5 integers and writes the average of the 5 integers. This program can use only 2 variables.

Solution

Solution #1

```#include <iostream>
using namespace std;
int main()
{
int a;double s=0;

cout<<"Type integer 1 : ";cin>>a;s=s+a;
cout<<"Type integer 2 : ";cin>>a;s=s+a;
cout<<"Type integer 3 : ";cin>>a;s=s+a;
cout<<"Type integer 4 : ";cin>>a;s=s+a;
cout<<"Type integer 5 : ";cin>>a;s=s+a;

s=s/5.0;
cout<<"The average is : "<<s<<endl;

return 0;
}
```

Solution #2

```#include<iostream>

using std::cout;
using std::cin;

int main(){
int a = 0;
double b = 0.0;

cout << "This program will take 5 integers that you input and return their average.\n\n";
cout << "Input Integer One: ";

cin >> a; b = b + a;
cin.ignore();

cout << "Input Integer Two: ";

cin >> a; b = b + a;
cin.ignore();

cout << "Input Integer Three: ";

cin >> a; b = b + a;
cin.ignore();

cout << "Input Integer Four: ";

cin >> a; b = b + a;
cin.ignore();

cout << "Input Integer Five: ";

cin >> a; b = b + a;
cin.ignore();

b = b / 5.0;

cout << "\n\nThe average is: " << b << "\n\n";

cout << "Please press the 'return' key to exit the program.";
cin.get();

return 0;
}
```

Solution #3

```//By Zhen
#include <stdio.h>

int main(){
float a = 0, b = 0;
printf("Please input the first integer: ");
scanf("%f", &a); b += a;

printf("Please input the second integer: ");
scanf("%f", &a); b += a;

printf("Please input the third integer: ");
scanf("%f", &a); b += a;

printf("Please input the fourth integer: ");
scanf("%f", &a); b += a;

printf("Please input the fifth integer: ");
scanf("%f", &a); b += a;

printf("The average is: %.2f\n", (b/5));
return 0;
}
```

Solution #4

```#include <iostream>
using namespace std;

main()
{

double numbers[5];
double average=0;

cout<<"enter 1st integer"<<endl;
cin>>numbers[0];

cout<<"enter 2nd integer"<<endl;
cin>>numbers[1];

cout<<"enter 3rd integer"<<endl;
cin>>numbers[2];

cout<<"enter 4th integer"<<endl;
cin>>numbers[3];

cout<<"enter 5th integer"<<endl;
cin>>numbers[4];

average= numbers[0] + numbers[1] + numbers[2] + numbers[3]+ numbers[4];

average=average/5;

cout<<" The average is" " "<< average<<endl;

}
```

Solution #5

```//By Christian Popovici
#include <iostream.h>
using namespace std;

void opp(double& b){
int a;cin >> a;b=b+a;
cout << "            Total: "<< b << endl;
}

int main(double b = -1){
cout << "Enter five numbers to add:" << endl << endl;
opp(b); opp(b); opp(b); opp(b); opp(b);
cout << endl << "Total: " << b << " Average: " << b/5 << endl << endl;
system("pause");
}
```

Solution #6

```#include <iostream.h>
using namespace std;

void opp(double& b){
int a;cin >> a;b=b+a;
cout << "            Total: "<< b << endl;
}

int main(double b = -1){
cout << "Enter five numbers to add:" << endl << endl;
opp(b); opp(b); opp(b); opp(b); opp(b);
cout << endl << "Total: " << b << " Average: " << b/5 << endl << endl;
system("pause");
}
```

Solution #7

```//Using only one variable
#include <iostream>
using namespace std;
int main()
{
float nums[5];

for (int n = 0; n < 5; ++n){
cout << "Input number: ";
cin >> nums[n];
}

cout << "The average is " << ( nums[0] + nums[1] + nums[2] + nums[3] + nums[4] ) / 5  << ".";
system("PAUSE");
return (0);
}
```

Solution #8

```//by Pak S.
//A bit different from #1
#include<iostream>
using namespace std;
int main()
{
cout<<" Enter five datas to find their average "<<endl;

float a, b;
b = 0;

cout<<" Enter the first data "<<endl;
cin>>a;
b = b + a;

cout<<" Enter the second data "<<endl;
cin>>a;
b = b + a;

cout<<" Enter the third data "<<endl;
cin>>a;
b = b + a;

cout<<" Enter the forth data "<<endl;
cin>>a;
b = b + a;

cout<<" Enter the last data "<<endl;
cin>>a;
b = b + a;

cout<<" The average is "<<b/5.0<<endl;

return 0;
}
```

Solution #9

```//By Using Pointers
#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
double* pFiveVal = new double[5];
double* pAverage = new double[1];

cout << "Type 5 integers andget the Average of them " << endl;
cin >> *pFiveVal;
cin >> *(pFiveVal+1);
cin >> *(pFiveVal+2);
cin >> *(pFiveVal+3);
cin >> *(pFiveVal+4);

*pAverage = (*pFiveVal + *(pFiveVal+1) + *(pFiveVal+2) + *(pFiveVal+3) + *(pFiveVal+4))/5;
cout << endl << "Your average value is " << *pAverage << endl;

delete [] pFiveVal;
delete [] pAverage;

pFiveVal = 0;
pAverage =0;
//system("pause"); use this to pause the screen to see the result.!
return 0;
}
```

Solution #10

```//------------------------- By Brandon Cox ----------------------------------
#include <iostream>
using namespace std;

//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{  int integer[6], count;

for(count = 0; count < 5; ++count)
{  cout << "Integer " << count + 1 << ": ";
while(! (cin >> integer[count]) )
{  cout << "\n\tNot an integer...  Please enter integer " << count + 1
<< " again." << endl;
cin.clear();
cin.ignore(10000, '\n');
cout << "Integer " << count + 1 << ": ";
}
}

cout << "\nAverage: ";
for(count = 0, integer[5] = 0; count < 5; ++count)
integer[5] += integer[count];
cout << integer[5] / (1. * count) << ".\n" << endl;

system("pause");
return 0;
}
//---------------------------------------------------------------------------
```

### EXERCISE 3

Write a program that asks the user to type 2 integers A and B and exchange the value of A and B.

Solution

Solution #1

```#include<iostream>
using namespace std;

int main()
{
double a,b,temp;

cout<<"Type the value of a : ";cin>>a;
cout<<"Type the value of b : ";cin>>b;

temp=a;
a=b;
b=temp;

cout<<"The value of a is "<<a<<endl;
cout<<"The value of b is "<<b<<endl;

return 0;
}
```

Solution #2

```#include <iostream>
#inlcude <sstream>
using namespace std;

int main(void)
{
string swap;
int a, b;
cout << "Input a: ";
cin >> swap;
while ( !(stringstream(swap) >> a) )
{
cout << "Error! Type mismatch! \nInput again: ";
cin >> swap;
}

cout << "Input b: ";
cin >> swap;
while ( !(stringstream(swap) >> b) )
{
cout << "Error! Type mismatch! \nInput again: ";
cin >> swap;
}

a ^= b ^= a ^=b;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
```

Solution #3

```#include<iostream>

using std::cout;
using std::cin;

int main(){
int a, b, c;

cout << "This program takes the value of integers A and B (when given) and\nexchanges them.\n\n";
cout << "Input A: ";

cin >> a;
cin.ignore();

cout << "Input B: ";

cin >> b;
cin.ignore();

c = a;
a = b;
b = c;

cout << "\n\nA is now: " << a;
cout << "\nB is now: " << b << "\n\n";

cout << "Please press the 'return' key to exit the program.";
cin.get();

return 0;
}
```

Solution #4

```//By Zhen
#include <stdio.h>

void Swap(int&, int&);

int main(){
int a, b;
printf("Input the first integer: ");
scanf("%i", &a);

printf("Input the second integer: ");
scanf("%i", &b);

Swap(a, b);

printf("Integer #1 is now: %i and Integer #2 is now: %i\n", a, b);
return 0;
}

void Swap(int& a, int& b){
int c;
c = a;
a = b;
b = c;
}
```

Solution #5

```// By Davidov

#include <iostream>

using namespace std;

int main()
{
int a, b;

cout << "A: ";
cin >> a;
cout << "B: ";
cin >> b;

// this is simillar to the xor encryption....
// It'd be nice if you catch the trick
// The good thing:
//    It's quick, no extra memory, no info loss

b = a ^ b;
a = a ^ b;
b = a ^ b;

cout << "A = " << a <<endl;
cout << "B = " << b << endl;

return 0;
}
```

Solution #6

```//by Pak S.
#include<iostream>
using namespace std;
int swap(int&a, int&b)
{
cout<<" Enter the first number "<<endl;
cin>>a;
cout<<" Enter the second number "<<endl;
cin>>b;

int tfirst;
tfirst = a;
a = b;
b = tfirst;
cout<<a<<"   "<<b<<endl;
return(a, b);

}

int main()
{
int a, b;
swap(a,b);
return 0;
}
```

Solution #7

```#include<iostream>
using namespace std;
int a,b;
int main()
{
cout<<"enter a and b:";
cin>>a>>b;
swap(a,b);//There is a swap function in the library
cout<<"a="<<a<<endl<<"b="<<b<<endl;
return 0;
}
```

Solution #8

```//by Using Pointers

/*
EXERCISE 3
Write a program that asks the user to type 2 integers A and B and exchange the value of A and B.
*/

#include <iostream>

using std::cin;
using std::cout;
using std::endl;
using std::swap;

int main()
{
double* pInt(0);
pInt = new double[2];

cout << "type two integer values to exchange them " << endl;
cin >> *pInt>>*(pInt+1);

swap(*pInt,*(pInt+1));

cout << "A : " << *pInt;
cout << endl << "B : " << *(pInt+1) << endl;

delete [] pInt;
pInt = 0; //you can also use nullptr in C++0x .!

system("pause"); //use this to hold the command prompt
return 0;
}

}
```

Solution #9

```//------------------------- By Brandon Cox ----------------------------------
#include <iostream>
using namespace std;
//---------------------------------------------------------------------------
void printFunc(int a, int b);

void exchangeFunc(int& a, int& b);

void inputFunc(int& a, int& b);

int main(int argc, char* argv[])
{  int A, B;

inputFunc(A, B);

exchangeFunc(A, B);

printFunc(A, B);

system("pause");
return 0;
}
//---------------------------------------------------------------------------
void inputFunc(int& a, int& b)
{  cout << "Enter the first integer: ";
while(! (cin >> a) )
{  cout << "\n\tNot an integer...  Please enter another.\n";
cin.clear();
cin.ignore(10000, '\n');
cout << "Enter the first integer: ";
}

cout << "Enter the second integer: ";
while(! (cin >> b) )
{  cout << "\n\tNot an integer...  Please enter another.\n";
cin.clear();
cin.ignore(10000, '\n');
cout << "Enter the second integer: ";
}
}

void exchangeFunc(int& a, int& b)
{  b = a ^ b;                       // I borrowed this new bit of code
a = a ^ b;                       // from Solution #5 (Davidov) above.
b = a ^ b;                       // It works GREAT...  it seems much
}                                   // cleaner.  Thank you!!

void printFunc(int a, int b)
{  cout << "\n\tSwapped values: " << a << ", " << b << ".\n" << endl;
}
}}
```

Solution #10

```// cxl
#include <iostream>
using namespace std;

int main ()
{
int A, B;
cout << "Type the first integer A: "; cin >> A;
B = A;
cout << "Type the second integer B: "; cin >> A;
cout << "A = " << A << ", B = " << B << endl;
return 0;
}
```

Solution #11

```#include <iostream>

using namespace std;

int main()
{
int a, b;

cout << "[Exchange A and B]\n";

cout << "Input A: ";
cin >> a;

cout << "Input B: ";
cin >> b;

a += b;
b = a - b;
a -= b;

cout << ">> A: " << a << "\n";
cout << ">> B: " << b << "\n";

cin.get();
return 0;
}
```

### EXERCISE 4

Write a program that asks the user to type the price without tax of one kilogram of tomatoes,the number of kilograms you want to buy and the tax in percent units. The program must write the total price including taxes.

Solution

Solution #1

```//by sniper.org
#include<iostream>
using namespace std;
int main()
{
double price_without_taxes,weight,taxes,total;

cout<<"Type the price of 1 kg of tomatoes without taxes : ";cin>>price_without_taxes;
cout<<"How much tomatoes do you want (in kilogram) : ";cin>>weight;
cout<<"What is the tax in percent : ";cin>>taxes;

total= ((((price_without_taxes*taxes)/100)+ price_without_taxes)*weight);

cout<<"The total price is : "<<total<<endl;

return 0;
}
```

Solution #2

```#include<iostream>
#include<iomanip>

using std::cout;
using std::cin;
using std::setprecision;
using std::fixed;

int main(){
double price_without_taxes, amount_in_kg, tax_percent, total;

cout << "This program asks the user to type the price, without tax, of one\nkilogram of tomatoes, the number of ";
cout << "kilograms you want to buy, and the tax\nin percent units, then outputs the total price.\n\n";
cout << "Input the price of 1kg of tomatoes (without tax): ";

cin >> price_without_taxes;
cin.ignore();

cout << "How many kilograms of tomatoes do you wish to buy: ";

cin >> amount_in_kg;
cin.ignore();

cout << "Tax percent per kg of tomatoes: ";

cin >> tax_percent;
cin.ignore();

total = (1 + tax_percent / 100) * price_without_taxes * amount_in_kg;

cout << setprecision(2) << fixed;
cout << "\nThe total amount due is: " << total << "\n\n";

cout << "Please press the 'return' key to exit the program.";
cin.get();

return 0;
}
```

Solution #3:

```//By Zhen
#include <stdio.h>

int main(){
float number, price, tax;
printf("Please input the number of kilograms of tomatoes: ");
scanf("%f", &number);
printf("Please input the price of one kilogram of tomatoes: ");
scanf("%f", &price);
printf("Please input the tax percentage: ");
scanf("%f", &tax);

printf("The price for the tomatoes including tax will be \$%.2f\n", ((1 + tax / 100) * price * number));
return 0;
}
```

Solution #4:

```//By Phenomenal Rob

#include <iostream>
using namespace std;

int main() {

float price = 0, tax = 0; int num = 0;

cout<< "Please enter the price of one kilo in dollars: ";
cin>> price; cin.ignore(); cout<<endl;
cout<< "Thank you. Please enter the tax percentage. ";
cin>> tax; cin.ignore(); cout<<endl;
cout<< "Thank you. Please enter the number of kilos you wish to buy. ";
cin>> num; cin.ignore(); cout<<endl;

price = price * num;
cout<< "Total cost minus tax... \$"<< price <<endl;
cin.get();

price = price + ( price * ( tax / 100 ));
cout<< "Total cost including tax... \$"<< price <<endl;
cin.get();
}
```

Solution #5

```//By Karan
#include "stdafx.h"
#include <iostream>
using namespace std;

int main ()

{
float price, kg, tax;
price=0;
kg=0;

tax=0;
cout << "What is the price of 1 kg tomatoes ";
cin >> price;
cout << "How many kg do you want to buy ";
cin >> kg;
cout << "What is the tax in decimal units? ";
cin >> tax;
cout << "The total price is " << (price * kg) * tax + (price * kg);

return 0;
```

Solution #6

```//by Pak S.
#include<iostream>
using namespace std;
struct num
{
float a;// price per kilogram
float b;// number of kilogram.
float c;// The total price.
};
int tax(num&x)
{
float tax;

cout<<" How much price per kilogram without tax? "<<endl;
cin>>x.a;
cout<<" How many kilogram do you need? "<<endl;
cin>>x.b;
cout<<" How much is the tax?"<<endl;
cin>>tax;

x.c = (x.a*x.b)+(tax*x.a*x.b/100);
cout<< " You have to pay "<<x.c<<endl;
return x.c;
}
int main()
{
num x;
tax(x);
return 0;
}
```

Solution #7

```//by Using Pointers + Multi-Dimensional Arrays
//DON'T CLEANUP THE POINTER AT LAST SINCE THIS IS NOT DYNAMIC MEMORY ALLOCATION.!
//And also you gotta have both Array and Pointer to proceed unless it's may not possible.!

#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
double priceVar[2][2] = {0};
double (*pPrice)[2] = priceVar;
cout << " type the price without tax of one kilogram of tomatoes " << endl << endl;
cout << " price without tax of one kilogram of tomatoes.? " << endl;
cin >> *(*(pPrice)+0);
cout << "the number of kilograms you want to buy.? " << endl;
cin >> *(*(pPrice)+1);
cout << "tax in percent units %.?" << endl;
cin >> *(*(pPrice+1)+0);

*(*(pPrice+1)+1) = (*(*(pPrice)+0)) * (*(*(pPrice)+1));
cout << "the Total value without tax is : " << *(*(pPrice+1)+1) << endl;
*(*(pPrice+1)+1) = ((*(*(pPrice+1)+0)/100) * *(*(pPrice+1)+1)) +  *(*(pPrice+1)+1);
cout << "the total value with tax is : " << *(*(pPrice+1)+1) << endl << endl;

system("pause"); //Visual C++
return 0;
}
```

Solution #8

```//------------------------- By Brandon Cox ----------------------------------
#include <iostream>
#include <iomanip>
using namespace std;
//---------------------------------------------------------------------------
struct vegetable
{  int units;
double price, tax, total;
void inputFunc();
void printFunc();
}tomato;
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{  tomato.inputFunc();

tomato.printFunc();

system("pause");
return 0;
}
//---------------------------------------------------------------------------
void vegetable::inputFunc()
{  cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios::showpoint);

cout << "Price (1 Kg, without taxes)? ";
while(! (cin >> tomato.price) )
{  cout << "\tInvalid input... try again.\n" << endl;
cin.clear();
cin.ignore(10000, '\n');
cout << "\nPrice (1 Kg, without taxes)? ";
}
fflush(stdin);

cout << "\nNumber of units (Kg)? ";
while(! (cin >> tomato.units) )
{  cout << "\tInvalid input... try again.\n" << endl;
cin.clear();
cin.ignore(10000, '\n');
cout << "\nNumber of units (Kg)? ";
}
fflush(stdin);

cout << "\nTaxes (percent)? ";
while(! (cin >> tomato.tax) )
{  cout << "\tInvalid input... try again.\n" << endl;
cin.clear();
cin.ignore(10000, '\n');
cout << "\nTaxes (percent)? ";
}
fflush(stdin);
}

void vegetable::printFunc()
{  total = price + (price * units * (tax / 100) );

cout << "\n\tTotal price: \$" << setprecision(2) << total << "\n" << endl;
}
```

### EXERCISE 5

Write a program that asks the user to type the coordinate of 2 points, A and B (in a plane), and then writes the distance between A and B.

Solution

Solution #1:

```#include<iostream>
using namespace std;

#include<cmath>

int main()
{
double XA,YA,XB,YB,dx,dy,distance;

cout<<"Type the abscissa of A : ";cin>>XA;
cout<<"Type the ordinate of A : ";cin>>YA;
cout<<"Type the abscissa of B : ";cin>>XB;
cout<<"Type the ordinate of B : ";cin>>YB;

dx=XA-XB;
dy=YA-YB;
distance=sqrt(dx*dx+dy*dy);

cout<<"The distance AB is : "<<distance<<endl;

return 0;
}
```

Solution #2:

```//By Zhen
#include <stdio.h>
#include <math.h>

int main(){
float x1, x2, y1, y2;
printf("Please input the first coordinate as X Y: ");
scanf("%f %f", &x1, &y1);
printf("Please input the second coordinate as X Y: ");
scanf("%f %f", &x2, &y2);

printf("The distance between the two points is %.2f units.\n", (float)sqrt(((x1 - x2)*(x1 - x2)) + ((y1 - y2) * (y1 - y2))));
return 0;
}
```

Solution #3

```//by Coca-Cola
#include <iostream>
#include <cmath>

using namespace std;

float distance(float &xs1, float &ys1 , float &xs2, float &ys2)
{
float d = sqrt(pow((xs2 - xs1), 2) + pow((ys2 - ys1), 2));
return d;
}

int main()

{
float x1, y1, x2, y2;
cout << "Usage: x1 y1 x2 y2\n\n";

cin >> x1;
cin >> y1;
cin >> x2;
cin >> y2;

cout << distance(x1,y1,x2,y2);

}
```

Solution #4

```//by Pak S.
#include<iostream>
#include<cmath>
using namespace std;
struct co // coordinate x-y
{
float x1, x2, y1, y2;

};
int main()
{
float distance;
co a;
char x = ',';

cout<<" End the coordinate of two points "<<endl;
cout<<" The first coordinate x1,y1"<<endl;
cin>>a.x1>>x>>a.y1;
cout<<" The second coordinate x2,y2"<<endl;
cin>>a.x2>>x>>a.y2;

distance = sqrt(pow((a.x1 - a.x2),2) + pow((a.y1 - a.y2),2));
cout<<" the distance = "<<distance<<endl;
return 0;
}
```

Solution #5

```//By Using Pointers
/*
Write a program that asks the user to type the coordinate of 2 points, A and B (in a plane), and then writes the distance between A and B.
*/

#include <iostream>

using std::cin;
using std::cout;
using std::endl;
using std::powf;

int main()
{
double Distance[2][2] = {0};
double (*pDistance)[2] = Distance;
cout << "Type the Coordinate of the A X1.? " << endl;
cin >> *(*(pDistance)+0);
cout << "Type the Coordinate of the A Y1.? " << endl;
cin >> *(*(pDistance)+1);
cout << "Type the Coordinate of the A X2.? " << endl;
cin >> *(*(pDistance+1)+0);//g
cout << "Type the Coordinate of the A Y2.? " << endl;
cin >> *(*(pDistance+1)+1);
double __an=0;
__an = powf(powf(( *(*(pDistance+1)+0) - *(*(pDistance)+0) ) ,2) + powf(( *(*(pDistance+1)+1) - *(*(pDistance)+1)) ,2),1);
cout << "The Distance Between A and B is : " << __an << endl;

system("pause"); //in VS C++
return 0;
}
```

Solution #6

```//------------------------- By Brandon Cox ----------------------------------
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
//---------------------------------------------------------------------------
bool isRational(double param);

void outputFunc(double x1, double y1, double x2, double y2);

void inputFunc(double& x, double& y);

int main(int argc, char* argv[])
{  double x1, y1, x2, y2;

cout << "Enter the rectangular coordinates for point A (x, y):\n";
inputFunc(x1, y1);

cout << "\nEnter the rectangular coordinates for point B (x, y):\n";
inputFunc(x2, y2);

outputFunc(x1, y1, x2, y2);

system("pause");
return 0;
}

void inputFunc(double& x, double& y)
{  cout << "x - coordinate? ";
while(! (cin >> x) )
{  cout << "\tInvalid input... try again.\n" << endl;
cin.clear();
cin.ignore(10000, '\n');
cout << "x - coordinate? ";
}
fflush(stdin);
cout << endl;

cout << "y - coordinate? ";
while(! (cin >> y) )
{  cout << "\tInvalid input... try again.\n" << endl;
cin.clear();
cin.ignore(10000, '\n');
cout << "y - coordinate? ";
}
fflush(stdin);
cout << endl;
}

void outputFunc(double x1, double y1, double x2, double y2)
{  double side1, side2, D;

cout << "\n\tThe distance between the points: " << endl << "\tA (" << x1
<< ", " << y1 << ") and B (" << x2 << ", " << y2 << ")";

side1 = y2 - y1;
side2 = x2 - x1;
D = sqrt(pow(side1, 2) + pow(side2, 2) );

if(isRational(D) )
cout << " = "<< D << ".\n" << endl;
else
cout << (char)0xF7 << fixed << setprecision(4) << " " << D << ".\n"
<< endl;
}

bool isRational(double param)
{  double fractPart, intPart;

param *= 1000000000;

fractPart = modf(param, &intPart);
if(fractPart == 0)
return true;
else
return false;
}
```

### EXERCISE 6

Find the Answer to 100C10 ; Find the Answer to 20C5  ; Find the Answer to 40C30 ; Find the Answer to 90C10.6 ; Find the Answer to 120C30 ; Find the Answer to 150C32.32 ;

Write a program in C++ ISO/IEC or C++/CLI without ever closing down the program find the answers to all above questions.

Solution

Solution #1

```//by Faulknerck2 :P

#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
int iteration=0;
double _n = 0;
double _r = 0;
double _aN = 1 , _aR =1 , _aNR = 1 , _nr =0;

back:
if(iteration==6)
goto end;

iteration++;

cin >> _n;
cin >> _r;
_nr = (_n -_r) ;

for(double i=0; i <_n ; i++)
{
_aN *= (_n -i);
}

for(double i=0 ; i < _r ; i++)
{
_aR *= (_r - i);
}

for(double i=0 ; i < _nr ; i++)
{
_aNR *= (_nr -i);
}

cout << "Answer is : " << _aN / (_aNR * _aR) << endl << endl;

//reset all values
_aN = 1 , _aR =1 , _aNR = 1 , _nr =0 , _n = 0 ,_r = 0;
goto back;
end:

return 0;
}
```

Solution #2

```#include <iostream>
#include <iomanip>
#include <limits>
#include <string>

using namespace std;

template<typename T>
void performSingleInput(const string& msg, T& output);

double findCombinationsAmount(int objectAmount, int groupSize);

int main()
{
for (int i = 0; i < 6; i++){
int objectAmount, groupSize;

performSingleInput("Input the amount of objects: ", objectAmount);
performSingleInput("Input the group size: ", groupSize);

cout << "\nThe amount of possible combinations is " << setprecision(0) << fixed << findCombinationsAmount(objectAmount, groupSize) << endl;
}
}

template<typename T>
void performSingleInput(const string& msg, T& output)
{
cout << msg;
while (!(cin >> output))
{
cout << "Invalid value, please try again: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

double multSequence(int first, int last);

double findCombinationsAmount(int objectAmount, int groupSize)
{
if (groupSize >= objectAmount)
return 1;

return multSequence(groupSize + 1, objectAmount)/multSequence(1, objectAmount - groupSize);
}

double multSequence(int first, int last)
{
double result = 1;

for (int i = first; i <= last; i++){
result *= i;
}

return result;
}
```

### EXERCISE 7

Write a program which asks for a student score. Score is a number from 0-100. Translate the score into grade according to the next limits:
score >= 90 ==> "A"
score >= 80 ==> "B"
score >= 70 ==> "C"
score >= 60 ==> "D"
anything else ==> "F"

if the score is 100 print "Perfect score!".

Solution

Solution #1

```//By Peter G. Marczis for wikibooks.
//Absolutely free to use anyhow.
#include <iostream>
#include <string>
#include <sstream>

using namespace std; //Sorry, I'm lazy, this is not a good practice

bool isNumber(string &inp)
//Function to check if a string consist only numbers.
{
int i;
if (inp[0] == '-') { //Handle "-" sign
i = 1;
} else {
i = 0;
}
for( i ; i < inp.length() ; i++) { //Along the string
for (int z = 0x30 ; z < 0x3A ; z++) { //With every numbers in the ASCII table.
if (inp[i] == (char)z) break; //If we find a number go to the next char
if (z == 0x39) return false; //if we reached number "9" and no hit, return false.
}
}
return true; //All char. were numbers, happy !
}

{
if ( score >= 90 ) return 'A';
if ( score >= 80 ) return 'B';
if ( score >= 70 ) return 'C';
if ( score >= 60 ) return 'D';
return 'F';
}

int main(int argc, const char* argv[])
{
int    score;
string score_str;

while ( 1 ) {
getline(cin, score_str);
if (isNumber(score_str)) {
stringstream(score_str) >> score; //Convert the string into number.
if ( score > -1 && score < 101 ) { //Check limits break if we inside.
break;
}
}
cout << "!!! Score should be a number in 0-100 !!!" << endl; //Print error message if not.
}
if ( score == 100 ) {
cout << "Perfect score !" << endl; //And do the extra "tap" if the student is great.
}
}
```

Solution #2: Here is an example that refrains from copying string data by tying directly into std::cout.

```// Solution by Matt Bisson for Wikibooks
#include <iostream>
#include <string>

#include <boost/lexical_cast.hpp>

{
public:
{
// Input validation:
}

private:
friend std::ostream& operator<<(std::ostream& out, letter_grade_from_percentage const& data);
};

// std::cout calls me when it gets a "letter_grade_from_percentage" instance...
std::ostream& operator<<(std::ostream& out, letter_grade_from_percentage const& data)
{
case 10: return out << "A (Perfect score!)";
case 9:  return out << "A";
case 8:  return out << "B";
case 7:  return out << "C";
case 6:  return out << "D";
default: return out << "F";
}
}

int main()
{
std::string one_line;

while (true) {
std::cout << "Input a number [0-100] (^C to exit): ";
std::getline(std::cin, one_line);

try {