Write a program which reads an input file valuestxt consisti

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

Solution

#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

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 ea
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 ea

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site