[C] Write a program that prompts the user for a number of rows and a number of c
ID: 3688137 • Letter: #
Question
[C] Write a program that prompts the user for a number of rows and a number of columns for a two-dimensional array of integers. Your program should dynamically allocate a two dimensional array of integers and read values from a separate file called "Data1" into it. Data1 has 1 million random numbers inside of it. You can assume that the number of rows times the number of columns (total elements in the array) will never be more than one million. After reading these values, print the size of the array and the sum of all elements in the array.Explanation / Answer
my file has store the values 1 to 7 only but we can put a random numbers upto 1 million and number of rows and number of coloumns are 1 and 7 .
#include <stdio.h>
#include <stdlib.h>
int main()
{
//int data[100][100];
int i,j,sum=0,row,col;
printf("enter number of rows:");
scanf("%d",&row);
printf("enter number of coloumns:");
scanf("%d",&col);
int *data = (int *)malloc(row * col * sizeof(int));
FILE *fr;
fr = fopen ("data1.txt", "r");
if(row*col > 100000)
{
printf("Array elements must be below 1000000");
}
else{
for (i = 0; i < row; i++) {
for(j=0;j < col;j++){
fscanf(fr, "%d", &(*(data+i*col+j)));
printf("%d ",*(data + i*col + j));
sum=sum+*(data + i*col + j);
}
}
}
printf("size of the array : %d ",sizeof(data));
printf("sum of the array elements : %d ",sum);
fclose(fr); /* close the file prior to exiting the routine */
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.