# Matrix addition of two randomly generated matrices

Seems that you are doing great so far. I found some tiny miss typing in your code, like:

``````for(i = 0; i < n;i++) {
printf("%d ", b[j]=rand()%100);
}
``````

Did you mean? :

``````for(j = 0; j < n; j++) {
printf("%d ", b[j]=rand()%100);
}
``````

Also, you have to print the sum[] array to see the results you want.

I made some modifications to your code. Try something like this:

``````#include <stdio.h>
#include <stdlib.h>

int n=5;
int a[5], b[5];
int sum[5];

int main() {
int i;

for(i = 0; i < n;i++) {
a[i] = rand()%100;
printf("%d ", a[i]);
}
printf("\n");

for(i = 0; i < n;i++) {
b[i] = rand()%100;
printf("%d ", b[i]);
}
printf("\n");

for(i = 0; i < n;i++) {
sum[i]=a[i]+b[i];
printf("%d ", sum[i]);
}
printf("\n");
return 0;
}
``````

ps: to break a line and avoid your string to be printed in front of your prompt, don’t forget to use the “\n” escape.

edit1:

You asked about write this code in fewer lines. Well, i don’t know, maybe yes. But there is something you can do: To stop repeating code.

If you are using three “for’s” that do the same thing, what about use just one? Also, what about a function to print an array for you?

Try something like

``````#include <stdio.h>
#include <stdlib.h>

int n=5;
int a[5], b[5];
int sum[5];

void print(int arr[], int size)
{
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

int main() {
int i;

for(i = 0; i < n; i++) {
a[i] = rand()%100;
b[i] = rand()%100;
sum[i] = a[i] + b[i];
}
print(a, 5);
print(b, 5);
print(sum, 5);
return 0;
}
``````

CLICK HERE to find out more related problems solutions.

Scroll to Top