﻿ C exercises and solutions: C increment decrement operators

C exercises and solutions: C increment decrement operators

C increment decrement operators exercises

1. Write C code to produce the output as shown below:

Contents of x               Expression        Value of                Contents of x

before                                                Expression              after

5                 |                  x++             |         5                 |         6

5                 |                  x--               |         5                 |         4

5                 |                  ++x             |         6                 |         6

5                 |                  --x               |         4                 |         4

Solution:
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int x;
x=5;

cout<<"Contents of x\t"<<"Expression\t"<<"Value of\t"<<"Contents of x\n";

cout<<"before\t\t\t\t"<<"Expression\t"<<"after\n";
cout<<"\n";

cout<<x<<"   |\t"<<"x++"<<" |\t\t\t"<<x<<"\t"<<"\t|"<<"x="<<x+1<<"\n";

cout<<x<<"   |\t"<<"x--"<<" |\t\t\t"<<x<<"\t"<<"\t|"<<"x="<<x-1<<"\n";

cout<<x<<"   |\t"<<"++x"<<" |\t\t\t"<<x+1<<"\t"<<"\t|"<<"x="<<x+1<<"\n";

cout<<x<<"   |\t"<<"--x"<<" |\t\t\t"<<x-1<<"\t"<<"\t|"<<"x="<<x-1<<"\n";

system("PAUSE");
return EXIT_SUCCESS;
}

2. Write a program to prompt the user to input the integral value of a and print out the result as shown below:

Result:
The value of a is: 10
……………………..
The value of ++a is: 11
Now the value of a is: 11

The value of a++ is: 11
Now the value of a is: 12

The value of --a is:11
Now the value of a is:11

The value of a-- is: 11
Now the value of a is: 10

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

using namespace std;

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

a=10;
cout<<"The value of a is:"<<a;
cout<<"\n----------------\n";
++a;
cout<<"\nThe value of ++a is:"<<a;
cout<<"\nThe value of a is:"<<a;

cout<<"\nThe value of a++ is:"<<a;
a++;
cout<<"\nThe value of a is:"<<a;
--a;
cout<<"\nThe value of --a is:"<<a;
cout<<"\nThe value of a is:"<<a;
cout<<"\nThe value of a-- is:"<<a;
a--;
cout<<"\nThe value of a is:"<<a;
cout<<"\n";
system("PAUSE");
return EXIT_SUCCESS;

} JuditThis is in C++ right?2018-06-12 Eliwould u please describe different kinds of libraries? how and where should we use each of them?2015-11-01 Bellal Razib#include à¦¨à¦¾ à¦²à¦¿à¦2015-09-13