Friday 14 October 2011

Chapter 2: [A] What would be the output of the following programs:


(a) 

main( )
{
    int   a = 300, b, c ;
    if ( a >= 400 )
    b = 300 ;
    c = 200 ;
    printf ( "\n%d %d", b, c ) ;
}

output

garbage-value 200




(b)

main( )
{
    int   a = 500, b, c ;
    if ( a >= 400 )
    b = 300 ;
    c = 200 ;
    printf ( "\n%d %d", b, c ) ;
}

output

200 300



(c)

main( ) 
    int x = 10, y = 20 ; 
    if ( x == y ) ; 
    printf ( "\n%d %d", x, y ) ; 

output

10  20



(d)

main( ) 
   int x = 3, y = 5 ; 
   if ( x == 3 ) 
   printf ( "\n%d", x ) ; 
   else
   printf ( "\n%d", y ) ; 

output  
 
5





(e) 

main( ) 
    int x = 3 ; 
    float y = 3.0 ; 
    if ( x == y ) 
    printf ( "\nx and y are equal" ) ; 
    else
    printf ( "\nx and y are not equal" ) ;


output

x and y are equal



(g) 

main( ) 
   int k = 35 ; 
   printf ( "\n%d %d %d", k == 35, k = 50, k > 40 ) ; 

output

0  50  0



(h)

main( ) 
int i = 65 ; 
char j = 'A' ; 
if ( i == j ) 
printf ( “C is WOW” ) ; 
else 
printf( "C is a headache" ) ; 

output 

C is WOW 




(i) 

main( ) 
   int a = 5, b, c ; 
   b = a = 15 ; 
   c = a < 15 ; 
   printf ( "\na = %d b = %d c = %d", a, b, c ) ;


output

a = 15 b = 15 c = 0




(j) 

main( ) 
   int x = 15 ; 
   printf ( "\n%d %d %d", x != 15, x = 20, x < 30 ) ; 


output

1  20  1



Chapter 2: [B] Point out the errors, if any, in the following programs:



(a) 

main( )
{
    float   a = 12.25, b = 12.52 ;
    if ( a = b )
       printf ( "\na and b are equal" ) ;
}

No syntax error however logical error can occur due to missing relational operator == inside if condition.

 
 
(b)  

main( )
{
  int   j = 10, k = 12 ;
  if ( k >= j )
 {
   {
      k = j ;
      j = k ;
   }
 }

No Error



(c)

main( )
{
    if ( 'X' < 'x' )
    printf ( "\nascii value of X is smaller than that of x" ) ;

No Error



(d)  

 main( )
{
    int  x = 10 ;
    if ( x >= 2 ) then
       printf ( "\n%d", x ) ;
}

then is not a keyword in c



(e)

main( )
{
    int  x = 10 ;
    if x >= 2
       printf ( "\n%d", x ) ;
}


condition is not enclosed in braces 


  
(f)

main( )
{
    int  x = 10, y = 15 ;
    if ( x % 2 = y % 3 )
          printf ( "\nCarpathians" ) ;
}


Relational operator (==) is missing inside condition.



(g)
 
main( )
{
    int x = 30 , y = 40 ;
    if ( x == y )
       printf( "x is equal to y" ) ;
    elseif ( x > y ) 
       printf( "x is greater than y" ) ;
    elseif ( x < y )
       printf( "x is less than y" ) ;
}


There should be a space between else and if

(h) 

main( )
{
    int  x = 10 ;
    if ( x >= 2 ) then
       printf ( "\n%d", x ) ;
}

then is not a keyword in c.


(i)

main( )
{
    int a, b ;
       scanf ( "%d %d",a, b ) ;
    if ( a > b ) ;
       printf ( "This is a game" ) ;
    else
       printf ( "You have to play it" ) ;
}

& missing inside scanf