Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Programming Language : C++ In your program, define a union with the following me

ID: 3812060 • Letter: P

Question

Programming Language : C++

In your program, define a union with the following members:

Type Name Description

char ch (char is 1 byte)
short s (short is 2 bytes)
int i (int is 4 bytes)
float f (float is 4 bytes)
double d (double is 8 bytes)

3. Your program should perform the following 5 operations:

A. Set all of the members of the union to 0.

Insert the character 'A' into the member ch.

Display all 5 members on the console.

B. Set all of the members of the union to 0.

Insert the number 32,767 into the member s.

Display all 5 members on the console.

C. Set all of the members of the union to 0.

Insert the character 2,147,483,647 into the member i.

Display all 5 members on the console.

D. Set all of the members of the union to 0.

Insert the character 999.999 into the member f.

Display all 5 members on the console.

E. Set all of the members of the union to 0.

Insert the character 999.999 into the member d.

Display all 5 members on the console.

There is no need to format the values, just dump them to the console.

Display a title for each data block, a label for each member and insert spaces between each output block so that the output makes sense.

Explanation / Answer

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<stdio.h>
using namespace std;

union member
{
   char ch;
   short s;
   int i;
   float f;
   double d;
}mem;

int main()
{
   cout << "Initialized Member values are: " << endl;
   memset(&mem, 0, sizeof(mem));
   cout << mem.ch << " " << mem.s << " " << mem.i << " " << mem.f << " " << mem.d << endl;

   mem.ch = 'A';
   cout << " Member values after inseting 'A' are: "<<endl;
   cout << " ch: "<<mem.ch << " s:" << mem.s << " i:" << mem.i << " f:" << mem.f << " d:" << mem.d<<endl;

   memset(&mem, 0, sizeof(mem));
   mem.s = 32767;
   cout << " Member values after inseting 32767 in short are: " << endl;
   cout << " ch: " << mem.ch << " s:" << mem.s << " i:" << mem.i << " f:" << mem.f << " d:" << mem.d << endl;

   memset(&mem, 0, sizeof(mem));
   mem.f = 999.999;
   cout << " Member values after inseting 999.999 in float are: " << endl;
   cout << " ch: " << mem.ch << " s:" << mem.s << " i:" << mem.i << " f:" << mem.f << " d:" << mem.d << endl;

   memset(&mem, 0, sizeof(mem));
   mem.d = 999.99;
   cout << " Member values after inseting 999.999 in double are: " << endl;
   cout << " ch: " << mem.ch << " s:" << mem.s << " i:" << mem.i << " f:" << mem.f << " d:" << mem.d << endl;


   cout << " Member values after resetting to zero are: " << endl;
   memset(&mem, 0, sizeof(mem));
   cout << mem.ch << " " << mem.s << " " << mem.i << " " << mem.f << " " << mem.d << endl;

   getchar();
   return 0;
}