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

Write a program which reads an input file values.txt consisting of a series of p

ID: 3930380 • Letter: W

Question

Write a program which reads an input file values.txt consisting of a series of positive integers, n. Your program should then compute the sum from 1 to n for each integer read, and write the result to a file called sums.txt. For example, if values.txt contains

3

8

then sums.txt should contain:

sum from 1 to 3 = 6

sum from 1 to 8 = 36

THIS IS MY WORK:

#include<stdio.h>

int main(void){
  
   FILE*fin = fopen("values.txt", "r");
   FILE*fout = fopen("sums.txt", "w");
  
   int i, n, sum=0;
  
  
   while(fscanf(fin, "%d", &n)!= EOF){
      
       for(i =1; i <= n; i++){
          
           fprintf(fout, "sum from %d to %d = %d ", i, n, sum);
           sum = sum + i;
       }
   }
  
  
  
   fclose(fin);
   fclose(fout);
   system("notepad.exe sums.txt");
   return 0;
}

AND THIS IS MY OUTPUT:

sum from 1 to 3 = 0
sum from 2 to 3 = 1
sum from 3 to 3 = 3
sum from 1 to 8 = 6
sum from 2 to 8 = 7
sum from 3 to 8 = 9
sum from 4 to 8 = 12
sum from 5 to 8 = 16
sum from 6 to 8 = 21
sum from 7 to 8 = 27
sum from 8 to 8 = 34

Explanation / Answer

#include<stdio.h>
int main(void){
  
FILE*fin = fopen("values.txt", "r");
FILE*fout = fopen("sums.txt", "w");
  
int i, n, sum=0;
  
  
while(fscanf(fin, "%d", &n)!= EOF)
{
sum=0; //initialize sum =0 every time
for(i =1; i <= n; i++){
sum = sum + i; //sum = 0+1=1, sum =1 +2=3 ,sum =3+3=6
}
  
fprintf(fout, "sum from 1 to %d = %d ", n, sum); //compute sum and store it in file after the for loop
  
}
  
  
  
fclose(fin);
fclose(fout);
//system("notepad.exe sums.txt");
return 0;
}

sums.txt

sum from 1 to 3 =6

sum from 1 to 8 =36

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