Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Find the error in each of the following (There may be more than one error): a) F

ID: 3801206 • Letter: F

Question

Find the error in each of the following (There may be more than one error):

a) For ( x = 100, x >= 1, ++x )

printf( "%d ", x );

b) The following code should input an integer and a character and print them. Assume the

user types as input 100

scanf( "%d", &intVal );

charVal = getchar();

printf( "Integer: %d Character: %c ", intVal, charVal );

c) for ( x = .000001; x == .0001; x += .000001 )

printf( "%.7f ", x );

d) The following code should output the odd integers from 999 to 1:

for ( x = 999; x >= 1; x += 2 )

printf( "%d ", x );

Explanation / Answer

Answer:

a) Error-1 : Line 1 in the code snippet has ++x, since the loop starts from 100 and checks whether x is greater than or equal to 1, ++x will cause x to keep on incrementing and it will always be greater than or equal to 1, hence leading to an infinite loop. Hence ++x should be replaced by x-- .

b) Error-1 : The getchar() in Line 2, will not get any input from stdin, as scanf in the Line-1, takes up the input. Hence the print statement in Line-3 returns :

Integer:100

Character:

To correct, this, the user should be made to enter the char value separately in a different statement.

c) Error-1 : In a for loop, the assignment operation takes place first, and then the condition is checked. If it is satisified, the statament within the for loop is executed and the increment operation in the for loop takes afterwards, and the condition is checked again.

In the question, x==0.0001 , is a condition which is never met, hence the flow of control doesn't ever get inside the loop.

d) Error-1: In line 1 of the for loop, the increment operation : x+=2, causes the loop to run forever as the condition is x>=1, which will always be met.

Hence, x+=2 should be replaced by x-=2.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote