1,584 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.

1 Answer

Best answer
6 votes
6 votes

Unsigned char goes like - 0 , 1, 2, ....., 255.

key point-

1. If unsigned char i = 255 then i + 1 = 0.

2. And if i=0 char i - 1 = 255;   

3. If unsigned char i = j , where j is some number which  is greater than 255 then i = j mod 256;


int main()
{
    unsigned char i, j, a[]={1,2,3,4,5};   
    int n;
    i=j=n=5;
    while(i-- !=0) n += a[i];  

    // finally n = 5 + 5 + 4 + 3 + 2 + 1 and i = 255 ( after 0, i = 255 not -1).

    // j = 5 , n=20; 


    while(j++ !=0) n += 2;

    // j goes from 5 to 255 and then 0, so total no of times while statement executed = 251.

    // j = 1 ( after 0 ) and n = 20 + 251*2 = 522 ( note - i is an integer so 522 comes in its range )


    printf("i=%d ,j=%d , n=%d\n ", i,j,n); 

   // i =255 , j = 1 , n = 522 .


    while(j-- !=0) a[0] +=n;

   // a[0] = 1 + 522 = 523 but it exceeds unsigned char limit. so a[0] = 523 mod 256 = 11.

   // j = 255 ( j=0 and then after  j-- , j= 255;


    printf("i=%d ,j=%d , a[0]=%d\n ", i,j,a[0]);

     // i= 255 , j = 255, a[0] = 11

    return 0;
}

selected by

Related questions

2 votes
2 votes
3 answers
2
Laahithyaa VS asked Sep 9, 2023
932 views
. What will be the value returned by the following function, when it is called with 11?recur (int num){if ((num / 2)! = 0 ) return (recur (num/2) *10+num%2);else return 1...
0 votes
0 votes
1 answer
3
0 votes
0 votes
2 answers
4
Nitesh Choudhary asked Apr 21, 2017
1,348 views
#include<stdio.h>int main(){ int i=10; printf("address of i=%d value of i=%d",&i,i); &i=7200; printf("address of i=%d value of i=%d",&i,i); return 0;...