31.9k views
1 vote
The following programs each have a single error that prevents them from operating as specified. With as few changes as possible, correct the programs. They all should output a single number: the sum of the integers from 1 to 10 , inclusive.

a.

#include
int main (void) {
int i=1;
int sum =0;
while (i<11){
sum = sum +i; ++i;
printf ("%d\\", sum);
}
}

User Eyberg
by
6.9k points

1 Answer

3 votes

Final answer:

The error in the C program provided is that the printf statement is inside the while loop. By moving the printf outside the loop, the program will correctly output the sum of integers from 1 to 10: a single sum after completion of the loop.

Step-by-step explanation:

The error in the given C program is that the printf statement is inside the while loop, which causes the sum to be printed multiple times as it updates with each iteration. To correct the program so that it outputs the sum of integers from 1 to 10, the printf statement should be placed outside of the loop. This way, the program adds each number from 1 to 10 inclusive to the sum, and only at the end will it output the final sum.

Corrected Program:

#include <stdio.h>
int main (void) {
int i=1;
int sum =0;
while (i<11){
sum += i;
i++;
}
printf ("%d\\", sum);
return 0;
}

User Ajeet Sharma
by
8.0k points