Practice Problems

Conditionals

Notice when you get compile errors (when gcc gives you an error)
vs. errors that crash the program (run-time errors)
vs. logical errors (compile and run fine but problem with your code)

  1. If originally x=4, y = 0, z = 2, what is the value of x, y, and z after the following code executes?
    		if ( x != 0 )
    			y = 3;
    		else
    			z = 2;
    	
  2. If originally x=4, y = 0, z = 2, what is the value of x, y, and z after the following code executes?
    		if ( z == 2 )
    			y = 1;
    		else
    			x = 3;
    	
  3. If originally x=4, y = 0, z = 2, what is the value of x, y, and z after the following code executes?
    		if ( x && y )
    			x = 3;
    		else
    			y = 2;
    	
  4. If originally x=4, y = 0, z = 2, what is the value of x, y, and z after the following code executes?
    		if ( x || y || z )
    			y = 1;
    		else
    			z = 3;
    	
  5. If originally x=4, y = 0, z = 2, what is the value of x, y, and z after the following code executes?
    		if ( x && y )
    			x = 3;
    		else
    			y = 2;
    	
  6. If originally x=4, y = 0, z = 2, what is the value of x, y, and z after the following code executes?
    		if ( x )
    		   if ( y )
    			z = 3;
    		else
    			z = 2;
    	
  7. If originally x=0, y = 0, z = 1, what is the value of x, y, and z after the following code executes?
    		if ( z < x || y >= z && z == 1)
    		   if ( z && y )
    			y = 1;
    		else
    			x = 1;
    	
  8. If originally x=0, y = 0, z = 1, what is the value of x, y, and z after the following code executes?
    		if ( z = x < y )
    		{
    			y = 5;
    			z = -3;
    		}
    		else
    			x = 2;
    	
  9. If originally x=0, y = 0, z = 1, what is the value of x, y, and z after the following code executes?
    		switch(x)
    		{
    			case 0 :  x = 2;
    				  y = 3;
    			case 1:	  x = 4;
    			default:  y = 3;
    				  x = 1;
    		}
    
    
  10. Rewrite the following code fragment using one switch statement
    		if ( ch == 'E' || ch == 'e' )
    			countE = 1;
    		else if ( ch == 'A' || ch == 'a' )
    			countA = 1;
    		else if ( ch == 'I' || ch == 'i' )
    			countI = 1;
    		else
    			printf ("Error - not A, E, or I\n");
    			countA = 1;
    	
  11. Write the code that reads in a number for month and prints out the month as a string (e.g. 1 = January, 2 = February, ...)
    First implement as an if structure, then a switch
  12. True/False. You can implement any switch statement in to an if-else structure.
  13. True/False. You can implement any if-else statement in to a switch structure.
  14. What is the numeric value of the expression 3 < 4 ?
  15. Under what conditions will this code print ``water''?
    	if(T < 32)
    		printf("ice\n");
    	else if(T < 212)
    		printf("water\n");
    	else	printf("steam\n");
    
  16. What would this code print?
    	int x = 3;
    	if(x)
    		printf("yes\n");
    	else	printf("no\n");