Iteration


  1. Change to following code to a while loop.
    
    int	x, y;
    for (x=1; x < 57; x+= 2)
    	y = x;
    

  2. What is wrong with the following?
    
    int	n=0;
    while (n < 100)
    	value = n*n;
    

  3. Write a while loop that calculates the sum of all numbers between 0 and 20 inclusive?

  4. Convert the above loop to a do ... while loop.

  5. Convert the above loop to a for loop.

  6. What is wrong with the following?
    
    i = 1;
    while (i <= 10 )	
    	printf("%d\n", i);
    	i++;
    


Answers


































  1. 
    x = 1;
    while (x < 57)
    {
    	y = x;
    	x += 2;
    }
    
  2. The value of n within the loop is never incremented. It will therefore always have a value of 0, which is less than 100, and hence this will produce an infinite loop which will never terminate. The program will therefore never end.

  3. int	i, sum =0;
    i = 0;
    while (i <= 100)
    {
    	sum += i;
    	i++;
    }
    
  4. int	i, sum =0;
    i = 0;
    do
    {
    	sum += i;
    	i++;
    }while (i <= 100);
    
  5. int	i, sum =0;
    for (i=0; i <= 100, i++)
    {
    	sum += i;
    }
    
  6. There are no braces around the printf() and increment i statements, therefore it will execute only the printf() statement within the loop, and an infinite loop will again occur.


    Back to Questions Back to Main Page for Lecture 4