﻿ C++ exercises and solutions: arithmetic compound operators

C++ exercises and solutions: arithmetic compound operators

C++ arithmetic and compound operators

1.Write a C++ program to produce the output as shown below:

Results:

x value y   value   expressions   results
10            | 5         | x=y+3       | x=8
10            | 5         | x=y-2        | x=3
10            | 5         | x=y*5        | x=25
10            | 5         | x=x/y         | x=2
10            | 5         | x=x%y       |  x=0

Solution:
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
int x;
int y;
x=10;
y=5;
cout<<"Result:\n";
cout<<"x value\t"<<"y value\t"<<"Expressions\t"<<"Result\n";
cout<<x<<" |\t"<<y<<" |\t"<<"x=y+3\t"<<"\t|"<<"x="<<y+3<<"\n";
cout<<x<<" |\t"<<y<<" |\t"<<"x=y-2\t"<<"\t|"<<"x="<<y-2<<"\n";
cout<<x<<" |\t"<<y<<" |\t"<<"x=y*5\t"<<"\t|"<<"x="<<y*5<<"\n";
cout<<x<<" |\t"<<y<<" |\t"<<"x=x/y\t"<<"\t|"<<"x="<<(float)(x/y)<<"\n";
cout<<x<<" |\t"<<y<<" |\t"<<"x=x%y\t"<<"\t|"<<"x="<<x%y<<"\n";

system("PAUSE");
return EXIT_SUCCESS;
}

2. Write a program to produce the output as shown below:

Results:

x value y value expressions results
10       | 5         | x+=y      | x=15
10       | 5         | x-=y-2    | x=7
10       | 5         | x*=y*5   | x=250
10       | 5         | x/=x/y     | x=5
10       | 5         | x%=y     | x=0

Solution:
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int x;
int y;
x=10;
y=5;
cout<<"Result:\n";
cout<<"x value\t"<<"y value\t"<<"Expressions\t"<<"Result\n";

cout<<x<<" |\t"<<y<<" |\t"<<"x+=y\t"<<"\t|"<<"x="<<x+y<<"\n";
cout<<x<<" |\t"<<y<<" |\t"<<"x=y-2\t"<<"\t|"<<"x="<<x-(y-2)<<"\n";
cout<<x<<" |\t"<<y<<" |\t"<<"x=y*5\t"<<"\t|"<<"x="<<x*y*5<<"\n";
cout<<x<<" |\t"<<y<<" |\t"<<"x=x/y\t"<<"\t|"<<"x="<<(float)x/(x/y)<<"\n";
cout<<x<<" |\t"<<y<<" |\t"<<"x=x%y\t"<<"\t|"<<"x="<<x%y<<"\n";

system("PAUSE");
return EXIT_SUCCESS;
}