In: Computer Science
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL)); // randomize
int *a; // pointer to array
int i, n;
printf("Size of array:");
scanf("%d", &n);
/* memory allocation */
a = (int*)malloc(n*sizeof(int));
/* array generating */
for (i = 0; i < n; i++) a[i] = rand()%101;
/* output */
for (i = 0; i<n; i++) printf("a[%d] = %d ", i, a[i]);
putchar('\n');
free(a);
return 0;
}
Using the above code please do it to me following
Hints:
Remember to initialize any sum variable to 0
rand() will return a random number too big for 0-99. Use modulo to reduce the range.
rand() needs to be initialized with a seed. You can use: srand(time(0));
Hints:
Make a function to deal with open/read/sum/print/close.
opendir() requires a starting directory. You want to start where in the current directory.
You need to loop over the directory entries. This is similar to walking a linked list.
You want to check every file entry to see if it starts with “numbers.”
CODE TO COPY ALONG
WITH SCREENSHOTS ARE PROVIDED BELOW:
(FOR INDENTS REFER TO SCREENSHOTS)
<<<<<<<<<<<-------------SOLUTION FOR RZRK #1--------------------------->>>>>>>>>>>>>>>>>.
SCREENSHOTS OF
CODE:


OUTPUT
SCREENSHOT:

After running the program txt file gets created.
(Each time code will run it will output the sum of random numbers like output screenshot above, And it will create txt file containing 100 random numbers in each file)
CODE FOR COPYING :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main(void)
{
char s1[] = "numbers.";
char s2[10];
char s3[] = ".txt";
int sum = 0;
int a[100];
srand ( time(NULL) );
for(int i =0;i<100;i++){
a[i] = rand()%101;
}
for(int i=0;i<100;i++){
sum = sum + a[i];
}
sum = sum + a[99]; /*adding last number to sum as it didnt got
added in loop*/
printf("SUM : %d\n",sum);
sprintf(s2,"%d",sum); /*converting sum to a string */
strcat(s1,s2); /*adding all strings together and storing into s1
*/
strcat(s1,s3);
FILE *fp;
fp = fopen(s1,"w"); /*creating file */
for(int i =0;i<100;i++){
fprintf(fp,"%d ",a[i]); /*storing numbers into file */
}
fclose(fp);
return 0;
}
<<<<<<<<<<<<<<<<<<<<----------------SOLUTION FOR RZRK #2 ----------------->>>>>>>>>>>>>>>
SCREENSHOTS:

output
screeenshots:

Code to copy :
#include <stdbool.h>
#include <stdio.h>
#include <dirent.h>
bool StartsWith(const char *a, const char *b)
{
if(strncmp(a, b, strlen(b)) == 0) return 1;
return 0;
}
void action(const char *s){
FILE *file = fopen(s,"r");
int sum = 0;
int x;
while(!feof(file))
{
fscanf(file,"%d",&x);
sum+=x;
}
fclose(file);
printf("FILE_NAME: %s\n",s);
printf("SUM: %d\n\n",sum);
}
int main(void)
{
struct dirent *de; // Pointer for directory entry
// opendir() returns a pointer of DIR type.
DIR *dr = opendir(".");
// for readdir()
while ((de = readdir(dr)) != NULL){
if(StartsWith(de->d_name,"numbers.")){
action(de->d_name);
}
}
closedir(dr);
return 0;
}