Confused on how you would get the program to print out the sum of the first elem
ID: 3689461 • Letter: C
Question
Confused on how you would get the program to print out the sum of the first elements on each row inside the array. Need help badly this is C language only.
Name this program sum1.c – Using the Data1 file, write a program that allocates an array of rows and columns based on what the user specifies as command line arguments. It should then compute and print the sum of the first elements on each row of the array (all the element at location zero on each row of the array).
TO DOWNLOAD THE DATA1 FILE, USE: (wget or curl) troll.cs.ua.edu/cs100/labs/Data1
EXAMPLE INPUT AND OUTPUT:
./a.out 1000 1000
The sum of the first number on each row is 495461
./a.out 1000000 1
The sum of the first number on each row is 500562283
./a.out 1 1000000
The sum of the first number on each row is 384
thank you to whoever can help me out.
Explanation / Answer
Here is the code for you:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fp;
fp = fopen("Data1.txt", "r");
int row, col, a, number;
row = atoi(argv[1]);
col = atoi(argv[2]);
// allocate the matrix:
int **array;
array = (int **)malloc(row * sizeof(int *));
for(int i = 0; i < row; i++)
array[i] = (int *)malloc(col * sizeof(int));
long sum = 0;
for(int i = 0; i < row; i++)
sum += array[i][0];
printf("The sum of the first number on each row is %ld ", sum);
}