Professional Documents
Culture Documents
____________________________________________________________________________________________________________
Instruction: -
Answer ALL questions
Question 1
____________________________________________________________________________________________________________
Puan Maimun Huja Husin 1
(KNL 1353 Structured Programming)
____________________________________________________________________________________________________________
Question 2
Combine the statements into a program that calculates and prints the sum of
the integers from 1 to 10. Use the while statement to loop through the
calculation and increment statements. The loop should terminate when the
value x becomes 11.
Solution:
int sum, x;
x=1;
sum=0;
while (x<=10)
{
sum = sum + x;
x++;
}
____________________________________________________________________________________________________________
Puan Maimun Huja Husin 2
(KNL 1353 Structured Programming)
____________________________________________________________________________________________________________
Question 3
Solution:
i. for(count=1;count<100;count+=2)
sum+=count;
ii. x = 1;
while (x<=20)
{
for (int y=1; y<6; y++)
{
cout<<x;
x++;
}
cout<<endl;
}
____________________________________________________________________________________________________________
Puan Maimun Huja Husin 3
(KNL 1353 Structured Programming)
____________________________________________________________________________________________________________
Question 4
Find the error(s) in each of the following code segments and explain how to
correct it (them).
i. x = 1;
while ( x <= 10 );
x++;
}
ii. for ( y = .1; y != 1.0; y += .1 )
cout << y << endl;
iii. The following code should output the even integers from 2 to 100:
counter = 2;
do
{
cout << counter << endl;
counter += 2;
} while ( counter < 100);
Solution:
i. x = 1;
while ( x <= 10 ) // remove the semicolon
{ // insert the opening braces
x++;
}
ii. for ( y = .1; y != 1.0; y+= .1 ) // will loop forever
cout << y << endl;
iii. counter = 2;
do
{
cout << counter << endl;
counter += 2;
} while ( counter <= 100); // add = so that 100 will be included
End of Section
____________________________________________________________________________________________________________
Puan Maimun Huja Husin 4