In: Computer Science
1) Write an algorithm to calculate the sum of the following series:
Sum =x-x3/3! + x5/5! – x7/7! +……. Stop when the term<0.0001.
2) An internet service provider charges its subscribers per month as follows:
Data usage (n), in gbs charges (NIS)
0.0<n<=1.0 250
1.0<n<=2.0 500
2.0<n<=5.0 1000
5.0<n<=10.0 1500
n>10 2000
Write a C program to read the usage(n) from a file and print the charges to be paid by the subscribers.
Your program must include the function calculate that accept the data usage (n ) and returns the charge/month.
1 ans:
#include <stdio.h>
#include <stdio.h>
#include <math.h>
double fact(int n){
double prd=1;
for(int i=1;i<=n;i++){
prd=prd*i;
}return prd;
}
int main(){
double sum=0;
double term;
double x=3.2;
int cnt=1;
int i=0;
while(1){
term=pow(x,cnt)/fact(cnt);
if(term<0.0001){
break;
}
if(i%2==0){
sum=sum+term;
}else{
sum=sum-term;
}
cnt=cnt+2;
i++;
}
printf("%lf\n",sum);
return 0;
}
2 ans:
#include <stdio.h>
#include <stdlib.h>
int usage(double n){
if(n>=0.0 && n<=1.0){
return 250;
}else if(n>1.0 && n<=2.0){
return 500;
}else if(n>2.0 && n<=5.0){
return 1000;
}else if(n>5.0 && n<=10.0){
return 1500;
}else if(n>=10){
return 2000;
}
}
int main(){
FILE *ptr;
double num;
int filecontentlen=5;
if((ptr=fopen("data.txt","r")) != NULL){
for(int i=0;i<filecontentlen;i++){
fscanf(ptr,"%lf", &num);
int cost=usage(num);
printf("usage=%lf and price=%d\n",num,cost);
}
}else{
printf("Error found!");
}
return 0;
}
#data.txt