Write complete programs or functions as asked. No comments are needed. These pro
ID: 3916982 • Letter: W
Question
Write complete programs or functions as asked. No comments are needed. These programs and functions will be graded for syntax, semantics, and programming style. Put your answers orn the back of this sheet if there is not enough space. 1 5] Write a complete program, using proper standards, to write into a file called m.txt. T he program will ask the user for positive integer numbers, calculate the sum of the positive integer numbers, and ther write the numbers nd the sum separated with omma into the fil. T he user enters-1 to terminate yhe program. If the user enters any negative number other than-1, display an error message.Explanation / Answer
To solve this question you need to follow these steps:
1. Declare a file pointer fptr and open the file sum.txt file in a write mode.
2. program asks the user to enter the numbers.
3. Iterate while with a true condition to check a given number is positive or not.
4. a) if the netered number is positive then write that number to file with comma and also added to the sum variable.
b) if the entered number is -1 then the write the sum value to file and terminate the program.
c) if the entered number is otherthan the -1 then prints the error message.
5. close the file.
Input : Enter the numbers:1 2 3 4 5 -1
output : sum.txt 1,2,3,4,5,15
C program Code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int ele,sum=0;
FILE *fptr;
fptr = fopen("sum.txt", "w");
if(fptr == NULL)
{
printf("Error!");
exit(0);
}
printf("Enter the Numbers:");
while(1)
{
scanf("%d",&ele);
if(ele==-1)
{
fprintf(fptr,"%d",sum);
exit(0);
}
else if(ele>=0)
{
fprintf(fptr,"%d,",ele);
sum+=ele;
}
else if(ele<-1)
printf("Error!!");
}
return 0;
}
Open the sum.txt file to see the output.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.