edited by
449 views
1 votes
1 votes
What will be the output of the following C program? If you think it will give a runtime error, you need to mention it. In either case, your answer must include proper justifications without which no credit will be given.

#include<stdio.h>
main()
{
  unsigned char i, j, a[] = {1, 2, 3, 4, 5};
  int n;
  i = j = n = 5;
  while(i-- != 0)
   n += a[i];
  while(j++ != 0)
       n += 2;
   printf("i = %d, j = %d, n = %d\n", i, j, n);
  while(j-- != 0)
     a[0] += n;
   printf("j = %d, a[0] = %d\n", j, a[0]);
}
edited by

1 Answer

Best answer
1 votes
1 votes
#include <stdio.h>
int main() {
  unsigned char i, j, a[] = {1, 2, 3, 4, 5};
  int n;
  i = j = n = 5;
  while(i-- != 0) { 	// ( at i = 0  stoped) 
  // bit content of i changed from 00000000 = 0 to 11111111 = 255 because of -- 
    n += a[i];
  }
  // therefore i = 255 and n = 5 + 15 = 20 // 
  
  while(j++ != 0) { 	// successfully true for j = 5 to j = 255 
  // after that condition check at j = 0 and ++ is applied
  // stoped and j becomes 1
  // n = 20 + (255 - 5 + 1) * 2 = 522
    n += 2;			
  }
  printf("i = %d, j = %d, n = %d\n", i, j, n);
  // i = 255 , j = 1 , n = 522

  while(j-- != 0) // stop at j = 0 but because of --
  // bit content of j changed from 00000000 = 0 to 11111111 = 255 because of -- 
    a[0] += n;
  // a[0] = 00000001 8 bit
  // n = (22 zeros)1000001010 32 bit
  // in the arithmetic operation a[0] + n
  // char is promoted to int with padding zeros
  // the result is 523 = (22 zeros)1000001011
  // since we are assigning back to a unsigned char take the lowest 8 bits
  // i.e. a[0] <- 00001011 = 11

  printf("j = %d, a[0] = %d\n", j, a[0]);
  // j = 255 a[0] = 11
}
selected by

Related questions

0 votes
0 votes
1 answer
2
N asked May 1, 2019
506 views
Consider a max-heap of n distinct integers, n ≥ 4, stored in an array A[1 . . . n]. The second minimum of A is the integer that is less than all integers in A except th...