Make a C program that uses a 2d array to read any text file the user enters. For
ID: 2246374 • Letter: M
Question
Make a C program that uses a 2d array to read any text file the user enters.
For example if the user enters a test file called test.txt that contains 2d info like:
20 5
0 5 1 76 2 74 3 99 4 26
0 74 1 21 2 83 3 52 4 90
0 67 1 48 2 6 3 66 4 38
0 97 1 36 2 71 3 68 4 81
0 87 1 86 2 64 3 11 4 31
0 1 1 42 2 20 3 90 4 23
0 69 1 32 2 99 3 26 4 57
0 69 1 12 2 54 3 80 4 16
0 11 1 63 2 24 3 16 4 89
0 87 1 52 2 43 3 10 4 26
0 25 1 59 2 88 3 87 4 40
0 50 1 42 2 72 3 77 4 29
0 58 1 76 2 71 3 82 4 94
0 79 1 48 2 20 3 63 4 97
0 35 1 57 2 78 3 99 4 80
0 70 1 76 2 53 3 2 4 19
0 79 1 22 2 77 3 74 4 95
0 34 1 99 2 49 3 3 4 61
0 37 1 24 2 32 3 35 4 4
0 50 1 88 2 46 3 63 4 76
The program should print out
5 74 67 97 87 1 69 69 11 87 25 50 58 79 35 70 79 34 37 50 76 21 48 36 86 42 32 12 63 52 59 42 76 48 57 76 22 99 24 88 74 83 6 71 64 20 99 54 24 43 88 72 71 20 78 53 77 49 32 46 99 52 66 68 11 90 26 80 16 10 87 77 82 63 99 2 74 3 35 63 26 90 38 81 31 23 57 16 89 26 40 29 94 97 80 19 95 61 4 76
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int m,n;
int *arr;
int k,i,j, count;
int len;
fp = fopen("test9.txt","r");
if (fp == NULL){
printf("Error opening file ");
return 0;
}
if (fscanf(fp,"%d %d",&m, &n) != EOF){ //reading the size of 2d array
arr = (int *)malloc(m * n * sizeof(int));
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
fscanf(fp, "%d %d", &k, arr + i*n + j); //reading arr[i][j] the element
}
count = 0;
len = 34;
for (i = 0; i<5; i++){
for (j = 0; j<20; j++){
printf("%d ", *(arr + j*n + i));
count++;
if (count == len){ //this code is to format the output.The first line contains //34 entries and subsequent lines have 33 entries.
count = 0;
printf(" ");
len = 33;
}
}
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.