WAP to do the following: (E Balagurusamy, Programming In ANSI C, Problem 2-7)

  1. Declare x and y as integer variables and z as a short integer variable.
  2. Assign two 6 digit numbers to x and y.
  3. Assign the sum of x and y to z.
  4. Output the values of x, y and z.
Comment on the output

//E Balagurusamy, Programming In ANSI C,4E
//Exercise 2.7, page 51

//Note:
//. comments with //scaff indicate code to help during development of code
//. can be safely commented out/removed
#include <stdio.h>
#include <conio.h>
#include <math.h>

int main(void)
{
   //declaring as specified in the problem
   int x=0, y=0;

   short int z=0;
        //scaff
        int bytes_int_current_machine=0;
        float range_int_current_machine=0.0;
   printf("\n\n");
   //assigning two six digit numbers to x and y
   x=655360;
   y=156414;
   z= x + y;
   //output code option 1
   printf("x = %d\n",x);
   printf("y = %d\n",y);
   printf("z = x + y = %d",z);
   //output code option 2
   //evaluating write-time vs read-time convenience,
   //as suggested by Code Complete 2
   printf("\n\n");
   printf("x = %d\ny = %d\nz = x + y = %d",x,y,z);
        //scaff
            //calculating ranges of the current machine
            bytes_int_current_machine = sizeof(int);
            range_int_current_machine = pow(2,(8*bytes_int_current_machine)); //1 byte = 8 bits
        printf("\n\n===Some Data To Help Understand===");
        printf("\nSize of int on this machine  = %d bytes",bytes_int_current_machine);
        printf("\nTherefore range of int (2^%d) = %.0f",bytes_int_current_machine, range_int_current_machine); //note %.0f
   printf("\n\n");
   return 0;
}

code output Some outputs
  • when 999999
    and  999999
    sum = –31618
  • when 111111
    and  111111
    sum  = 25614
  • when 655360
    and 156414
    sum = 25342
Remarks:
We are putting int into short and that should clearly jeopardise the results. But why exactly are outputs showing up like this, I can’t figure out right now. Any Ideas?

Comments