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

using Linux 1. (100 pts) Write a program that reads an integer k from user and f

ID: 642240 • Letter: U

Question



using Linux

1. (100 pts) Write a program that reads an integer k from user and finds the number of elements that are divisible by k in the file assign4.trt. A number n is divisible by k if n kz for some integer x > 0. You can use the mod operator % to test for divisibility. The file assign-tt has integer values in the range [0, 100 ]. You should use end-of-file controlled loop for this problem. Sample execution is given below. Consider the file below 90 23 74 83 The output to be displayed on screen for the above file is Enter k 10 1 numbers are divisible by 10 Submit your program electronically using the blackboard system The program you submit should be your oun work. Cheating will be reported to office of academic integrity. Both the copier and copiee will be held responsible.

Explanation / Answer

//C program that prompt for a input k
//value and opens a file assign4.txt
//that contains integer values
//and checks if the values are divisible by k
//value and prints the number of values are
//divisible by k
#include<stdio.h>
#include<conio.h> // for getch function
#include <stdlib.h> //for FILE pointer
int main()
{

   //intialize k value
   int k=0;
   //read number from file
   int number;
   //count value
   int divisibleCount=0;
   FILE *fp;
   //open file for reading input
   fp=fopen("assign4.txt","r");

   //check if file exists or not
   if(fp==NULL)
   {
       printf("File doesnot exist. Terminating program");
       printf("Press any key to exit");
       getch();
   }

   printf("Enter k ");
   //read k value
   scanf("%d",&k);

   //check if the file pointer at the end of the file
   while(fscanf(fp, "%d", &number) != EOF)
   {
       //check divisiblity of number with k
       if(number%k==0)
           //increment the count
           divisibleCount++;          
   }

   //print number of values are divisible by k
   printf("%d number are divisble by %d",divisibleCount,k);
   getch();
   return 0;
}

-----------------------------------------------------------------------------------------------

Sample output:

assign.txt file

90
23
74
83

output:

Enter k
10
1 number are divisble by 10

Hope this helps you