Automatically filling an array - c

I want to define two variables called x and y.
Depending on that the program shall fill the array from 0 to x and from 0 to y.
I tried filling it with a for and it's kind of working, but I can't print it out properly.
#include <stdio.h>
#define x 4
#define y 4
void build(){
int i=0, k=0;
int matrix[x][y];
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i;
matrix[i][k] = k;
}
}
printf("\t\n%d\n", matrix[x][y]);
}
I expect an array looking like this in the console.
0 1 2 3
0 1 2 3
0 1 2 3
0 1 2 3

You see, in order to print an array you will have to loop over the whole data. You can't print an array in that simple a way in C.
What your code is printing is a garbage value, because at index 4,4 your array has no value. Its indexes go from 0,1..3 in both x and y direction.
Hope it helps.
#include <stdio.h>
#define x 4
#define y 4
void main(){
int i=0, k=0;
int matrix[x][y];
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i ;
}
}
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
printf("\t%d", matrix[i][k]);
}
printf("\n");
}
}

In C there is no way to print an array in one go. You have to loop through each element of the array and print it.
for(int i = 0; i < x; ++i){
for(int j = 0; j < y; ++j){
printf("%d ", matrix[i][j]);
}
printf("\n");
}

I have tried to guess at your misunderstandings and commented and edited your code to make an explanation of how it works and what you need to understand.
#include <stdio.h>
#define x 4
#define y 4
void build(){
int i=0, k=0;
int matrix[x][y]; // top allowed indexes are x-1 and y-1
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i; // first write getting ignored/overridden by next
matrix[i][k] = k;
// printing here gets you many values, note the removed \n
printf("\t%d", matrix[i][k]);
}
// printing line break here gets you lines instead of single values
printf("\n");
}
// not inside any loop, so only one %d value gets printed
// printf("\t\n%d\n", matrix[x][y]); // accessing beyond both dimension
// also your attempt to let printf figure out how to print the whole 2D array,
// at least that is what I think you try, does not work in C
}

Related

C consecutive(not nested) one-liner for loops not iterating properly [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 months ago.
Improve this question
Final Edit
When debugging this code, I would see the first loop line execute n times, but the following lines would execute only once. Only later I would notice that the expected value changes, though, were in fact being made: it was just the loop line was being executed at once, as if the loop went through all iterations in one single step. From the second loop on, Pressing F10 (I use VSCode) would skip straight to the next loop, instead of skipping to the next iteration. That's how the compiler behaved (MinGW64).
Now, formatting the loops like this:
for( ; x<n; x++) {
p[y][x] = h;
} x--;
for( ; y<n; y++) {
p[y][x] = h;
} y--;
etc...
did cause each iteration to be read separately: now from the second loop on, pressing F10 would just jump to the next iteration, not straight to the next loop.
Conclusion: both styles work the same, but debug differently.
Anyway, here's a version that's still pretty ugly, but now works as expected:
#include <stdio.h>
int main(){
int n,size,sqrs,start=0,h,y,x; scanf("%i",&n);
int p[n][n];
size = n;
if(n%2==0) sqrs = n/2;
else sqrs = n/2+1;
h = 1;
y = start;
x = start;
for(int t=0; t<sqrs; t++){
for( ; x<n; x++) p[y][x] = h; x--;
for( ; y<n; y++) p[y][x] = h; y--;
for( ; x>=start; x--) p[y][x] = h; x++;
for( ; y>=start; y--) p[y][x] = h; y++;
y++; x++; h++; start++; n--;
}
for(int i=0; i<size; i++){
for(int j=0; j<size; j++){
printf("%i ",p[i][j]);
} printf("\n");
}
}
Edit:
I'm trying to build a matrix where the numbers grow towards the center, i.e. a "pyramid".
As of yet, I haven't had any problem with single-statemente one-liner for loops in C. Now, placing them consecutively is causing them, except for the first loop, to be skipped.
As I see it, we have a `for` loop, then its single statement, and then a semicolon, which should (at least, I expected it to) terminate the line, then move on to the next piece of code, which just happens to be another `for` loop. The problem is the first `for` loop runs as expected, however, the following ones are just skipped, as they were at their ending condition.
I've stressed "not nested" because:
while searching for this issue, all I had found were about nesting loops and if statements regarding using or not braces;
each for loop/statement ends with a semicolon.
I've tried bracing the single statements, but it did not solve the problem.
What DID solve the problem though was adding braces AND newlines, like this:
for( ; y<n; y++) {
p[y][x] = h;
}
But still, it bothers me to be clueless of why these were required in C, in this case. For example, while debugging I had noticed the second loop is skipped because the value of y changes from 0 to 4. This alone is already a mystery to me.
By the way, my apologies for being vague!
Original post:
Here is my code:
#include <stdio.h>
int main(){
int n,sqrs,start=0,h,y,x; scanf("%i",&n);
int p[n][n];
if(n%2==0) sqrs = n/2;
else sqrs = n/2+1;
h = 1;
y = start;
x = start;
for(int t=0; t<sqrs; t++){
for( ; x<n; x++) p[y][x] = h; // THESE LOOPS
for( ; y<n; y++) p[y][x] = h; // here, y changes from 0 to 4
for( ; x>=start; x--) p[y][x] = h;
for( ; y>=start; y--) p[y][x] = h;
y++; x++; h++; start++; n-=2;
}
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
printf("%i",p[i][j]);
} printf("\n");
}
}
As you can see, these loops aren't nested. They would nest though if there weren't any statements in between them, but there are.
So, the first one iterates normally but all of the following ones don't. They just skip.
I did manage to get around this, but curiously only when I added both braces and newlines, i.e. when all loops (except the first one, which doesn't seem to require it) looked like this:
for( ; y<n; y++) {
p[y][x] = h;
}
This remains a mystery to me.
Of course, I'm sorry if this is a duplicate. I just couldn't find anything about this specifically.
EDIT:
As some of you have thankfully noticed, yes, I'm trying to print a "pyramid" matrix. The reason I didn't mention it is because to me the problem was about syntax only, being the not so relevant.
It's not clear from either the OP code or the description what it is you are trying to achieve.
Based on another recent SO question, perhaps this is what you are seeking. This takes advantage of the symmetry of the (I believe) desired output. Four array elements are assigned in each iteration until the centre of the pattern is reached.
int main() {
const uint8_t n = 9;
uint8_t mat[n][n];
for( int r = 0; r < (n+1)/2; r++ )
for( int c = 0; c < (n+1)/2; c++ )
mat[r ][c ] =
mat[n-1-r][c ] =
mat[r ][n-1-c] =
mat[n-1-r][n-1-c] =
1 + (c<r?c:r);
for( int i = 0; i < n; i++ ) {
for( int j = 0; j < n; j++ )
printf("%d ", mat[i][j]);
puts( "" );
}
return 0;
}
1 1 1 1 1 1 1 1 1
1 2 2 2 2 2 2 2 1
1 2 3 3 3 3 3 2 1
1 2 3 4 4 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 4 4 3 2 1
1 2 3 3 3 3 3 2 1
1 2 2 2 2 2 2 2 1
1 1 1 1 1 1 1 1 1
Perhaps the "not nested" is the criteria?
int main() {
const uint8_t n = 9, h = ((n+1)/2); // 'h'alf way
uint8_t mat[n][n];
for( int x = 0; x < h*h; x++ ) {
int r0 = x / h, r1 = n-1-r0; // top & bottom rows of this square
int c0 = x % h, c1 = n-1-c0; // left & right cols of this square
uint8_t v = 1 + ( c0 < r0 ? c0 : r0 );
mat[r0][c0] = mat[r0][c1] =
mat[r1][c0] = mat[r1][c1] = v;
}
/* same nested output loops */
return 0;
}
There are multiple mistakes in your code:
you should undo the last increment/decrement after each of the inner loops. As coded, you store h beyond the end of the array p.
n should be decremented only by 1
since n is modified, the final loops have no effect.
Here is a modified version, keeping your corny style:
#include <stdio.h>
int main(){
int n,sqrs,start=0,end,h,y,x; scanf("%i",&n);
int p[n][n];
if(n%2==0) sqrs = n/2;
else sqrs = n/2+1;
h = 1;
y = start;
x = start;
end = n;
for(int t=0; t<sqrs; t++){
for( ; x<end; x++) p[y][x] = h; x--;
for( ; y<end; y++) p[y][x] = h; y--;
for( ; x>=start; x--) p[y][x] = h; x++;
for( ; y>=start; y--) p[y][x] = h; y++;
y++; x++; h++; start++; end--;
}
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
printf("%i",p[i][j]);
} printf("\n");
}
}
This code can be simplified as:
#include <stdio.h>
int main(){
int n; scanf("%i",&n);
int p[n][n];
int h=1,start=0,stop=n-1;
for(int t=0; t<n; t+=2,h++,start++,stop--){
int x=start,y=start; p[y][x] = h;
while(x<stop) p[y][x++] = h;
while(y<stop) p[y++][x] = h;
while(x>start) p[y][x--] = h;
while(y>start) p[y--][x] = h;
}
for(int i=0; i<n; i++){
for(int j=0; j<n; j++) printf("%i",p[i][j]);
printf("\n");
}
}
And here is a more classic version:
#include <stdio.h>
int main() {
int n;
if (scanf("%i", &n) != 1 || n <= 0)
return 1;
int p[n][n];
int h = 1, start = 0, stop = n - 1;
for (int t = 0; t < n; t += 2, h++, start++, stop--) {
int i = start, j = start;
if (start == stop)
p[i][j] = h;
for (; j < stop; j++)
p[i][j] = h;
for (; i < stop; i++)
p[i][j] = h;
for (; j > start; j--)
p[i][j] = h;
for (; i > start; i--)
p[i][j] = h;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%i", p[i][j]);
printf("\n");
}
return 0;
}
Note that instead of tracing successive squares, you can compute the array values directly:
#include <stdio.h>
int min(int a, int b) { return a < b ? a : b; }
int main() {
int n, i, j;
if (scanf("%i", &n) != 1 || n <= 0)
return 1;
char p[n][n + 1];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
p[i][j] = '1' + min(min(i, j), min(n - i - 1, n - j - 1));
p[i][j] = '\n';
}
printf("%.*s", (int)sizeof(p), &p[0][0]);
return 0;
}
It appears that you are trying to make a pattern of concentric boxes in a matrix. Your logic is wrong. Following is an example using the Ada programming language. Translating that into C should be easy.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Main is
type matrix is array (Positive range <>, Positive range <>) of Positive;
Side : Positive;
begin
Put ("Enter the number of elements on a side of the array: ");
Get (Side);
declare
Box : matrix (1 .. Side, 1 .. Side);
Center : Positive;
Start : Positive := 1;
Stop : Positive := Side;
Value : Positive := 1;
begin
Center := (if Side mod 2 = 0 then side / 2 else side / 2 + 1);
for turn in 1 .. Center loop
-- sides
for I in Start .. Stop loop
Box (Start, I) := Value;
Box (I, Start) := Value;
Box (Stop, I) := Value;
Box (I, Stop) := Value;
end loop;
-- adjust for inner box values
Start := Start + 1;
Stop := Stop - 1;
Value := Value + 1;
end loop;
for I in Box'Range (1) loop
for J in Box'Range (2) loop
Put (Item => Box (I, J), Width => 1);
end loop;
New_Line;
end loop;
end;
end Main;
The output of a sample execution is:
Enter the number of elements on a side of the array: 7
1111111
1222221
1233321
1234321
1233321
1222221
1111111

How can I export answer that I expected?

#include <stdio.h>
int main()
{
int tarr[3][4];
//this for loop is for making 2d array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
tarr[i][j] = (i++) * (j++);
}
}
// this for loop is for exporting 2d array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
printf("%d ", tarr[i][j]);
}
printf("\n");
}
return 0;
}
expected answer:
1 2 3 4
2 4 6 8
3 6 9 12
actual exported answer:
194 0 -566790131 22024
-1681794240 0 0 0
-566790208 22024 -566790672 2
My expectation was to export as I expected but the weird numbers were exported and I cannot understand where those numbers are from. I want to know where those numbers are from and what should I do for exporting my expected numbers.
Code eventually attempts to access data outside arrays bounds leading to undefined behavior (UB).
for( int j = 0; j<4; j++) {
// On the first iteration, i,j is 0,0
// On the next iteration, i,j is 1,2
tarr[i][j]= (i++)*(j++);
}
Do not increment: (i++)*(j++). Instead, simply add 1.
for( int j = 0; j<4; j++) {
// On the first iteration, i,j is 0,0
// On the next iteration, i,j is 0,1
tarr[i][j]= (i+1) * (j+1);
}

How to connect puzzles so that right edge has same length as left edge of another puzzle?

I have puzzles that looks like this:
=== ====
=== ===
=== ====
left edge has length from 0 to 10 000 and right also, middle part is from 1 to 10 000.
So the question is if i can build a rectangle? like first puzzle has length of left edge equal to 0 and the last puzzle has right edge of length 0 and in the middle they fit perfectly?
I am given the number of puzzle i have and their params like this:
6
1 9 2
0 3 1
0 4 1
8 9 0
2 9 0
1 5 0
and result can be any of that:
2
0 3 1
1 5 0
or
3
0 3 1
1 9 2
2 9 0
or
2
0 4 1
1 5 0
But if there is no result i have to printf("no result")
I have to do this in C, I thought about doing some tree and searching it with BFS where vertices would have edge lengths and edge would have middle length and when reached 0 i would go all way up and collect numbers but it's hard to code. So i decided to do recursion but im also stuck:
#include<stdio.h>
int main(){
int a;
scanf("%d", &a);//here i get how many puzzles i have
int tab[a][3];//array for puzzles
int result[][3];//result array
int k = 0;//this will help me track how many puzzles has my result array
for(int i = 0; i < a; i++){//upload puzzles to array
for(int j = 0; j < 3; j++){
scanf("%d", &tab[i][j]);
}
}
findx(0, a, tab, result, k);//start of recursion, because start has to be length 0
}
int findx(int x, int a, int *tab[], int *result[], int k){//i am looking for puzzle with length x on start
for(int i = 0; i < a; i++){
if(tab[a][0] == x){//there i look for puzzles with x length at start
if(tab[a][2] == 0){//if i find such puzzle i check if this is puzzle with edge length zero at the end
for(int m = 0; m < 3; m++){//this for loop add to my result array last puzzle
result[k][m] = tab[a][m];
}
return print_result(result, k);//we will return result go to print_result function
}
else{//if i have puzzle with x length on the left and this is not puzzle which ends rectangle i add this puzzle
//to my result array and again look for puzzle with x equal to end length of puzzle i found there
for(int m = 0; m < 3; m++){
result[k][m] = tab[a][m];
k += 1;
}
findx(tab[a][2], a, tab, result, k);
}
}
}
printf("no result");
}
int print_result(int *result[], int k){
printf("%d", &k);//how many puzzles i have
printf("\n");
for(int i = 0; i < k; i++){//printing puzzles...
for(int j = 0; j < 3; j++){
printf("%d ", &result[i][j]);
}
printf("\n");//...in separate lines
}
}
I have an error that result array can't look like this int result[][3] because of of [] but I don't know how many puzzles I'm gonna use so?... and I have implicit declaration for both of my functions. Guys please help, I dont know much about C and its super hard to solve this problem.
I'm not sure I understand the overall logic of the problem, but you definitely are in need of some variable sized containers for result AND tab. Arrays are fixed size and must be defined at compile time. The following should at least compile without warnings:
#include<stdio.h>
#include<stdlib.h>
void print_result(int (*result)[3], int k){
printf("%d", k);//how many puzzles i have
printf("\n");
for(int i = 0; i <= k; i++){//printing puzzles...
for(int j = 0; j < 3; j++){
printf("%d ", result[i][j]);
}
printf("\n");//...in separate lines
}
}
void findx(int x, int a, int (*tab)[3], int (*result)[3], int k){//i am looking for puzzle with length x on start
for(int i = 0; i < a; i++){
if(tab[i][0] == x){//there i look for puzzles with x length at start
if(tab[i][2] == 0){//if i find such puzzle i check if this is puzzle with edge length zero at the end
for(int m = 0; m < 3; m++){//this for loop add to my result array last puzzle
result[k][m] = tab[i][m];
}
print_result(result, k);//we will return result go to print_result function
return;
}
else{//if i have puzzle with x length on the left and this is not puzzle which ends rectangle i add this puzzle
//to my result array and again look for puzzle with x equal to end length of puzzle i found there
for(int m = 0; m < 3; m++){
result[k][m] = tab[i][m];
k += 1;
///** Increase size of result **/
//int (*newptr)[3] = realloc(result, (k+1) * sizeof(int[3]));
//if (newptr)
// result = newptr;
}
findx(tab[i][2], a, tab, result, k);
}
}
}
printf("no result\n");
}
int main(){
int a;
scanf("%d", &a);//here i get how many puzzles i have
int (*tab)[3] = malloc(a * sizeof(int[3]));//array for puzzles
int (*result)[3] = malloc(a * sizeof(int[3]));//array for puzzles
int k = 0;//this will help me track how many puzzles has my result array
for(int i = 0; i < a; i++){//upload puzzles to array
for(int j = 0; j < 3; j++){
scanf("%d", &tab[i][j]);
}
}
findx(0, a, tab, result, k);//start of recursion, because start has to be length 0
}
Note that I changed the tab and result types to (*int)[3]. Due to order of operations, we need parentheses here. Because they are variable size, they require dynamic memory allocations. In the interest of brevity and readability, I did not check the returned values of malloc or realloc. In practice, you should be checking that the returned pointer is not NULL. Because we are using dynamic memory allocations, we should also use free if you plan on doing anything else with this program. Otherwise, it doesn't really matter because exiting the program will free the resources anyway. You actually don't want to free. because we are passing a pointer by value to findx and the realloc can change the address, it may come back with a different address. Also, take note that I needed to include <stdlib.h> for the dynamic memory allocations.
Additional Issues
Your functions print_results and findx are not declared when you call them in main. Your function either need to be above main or have "function prototypes" above main.
In the printfs you do not need the &. You do not want to send the address of the variable to printf. You want to send what will actually be printed.
Now what?
The program still does not provide you with the correct results. It simply outputs 0 as the result every time. This should at least give you a starting point. By changing this line in print_results:
for(int i = 0; i < k; i++){//printing puzzles...
to
for(int i = 0; i <= k; i++){//printing puzzles...
I was at least able to output 0 0 0. This seems more correct because if k is 0, we don't loop at all.
#include<stdio.h>
void findx(int x, int a, int tab[a][3], int result[200000][3], int puzzlesinresult) { //i am looking for puzzle with length x on start
for (int i = 0; i < a; i++) {
if (tab[i][0] == x) { //there i look for puzzles with x length at start
if (tab[i][2] == 0) { //if i find such puzzle i check if this is puzzle with edge length zero at the end
for (int m = 0; m < 3; m++) { //this for loop add to my result array last puzzle
result[puzzlesinresult][m] = tab[i][m];
}
return print_result(result, puzzlesinresult); //we will return result go to print_result function
} else { //if i have puzzle with x length on the left and this is not puzzle which ends rectangle i add this puzzle
//to my result array and again look for puzzle with x equal to end length of puzzle i found there
while (result[puzzlesinresult - 1][2] != tab[i][0] && puzzlesinresult > 0) {
puzzlesinresult -= 1;
}
int isusedpuzzle = 0;
for (int j = 0; j < puzzlesinresult; j++) {
if (result[j][0] == tab[i][0] && result[j][1] == tab[i][1] && result[j][2] == tab[i][2]) {
isusedpuzzle = 1;
} else {
//pass
}
}
if (isusedpuzzle == 0) {
for (int m = 0; m < 3; m++) {
result[puzzlesinresult][m] = tab[i][m];
}
puzzlesinresult += 1;
findx(tab[i][2], a, tab, result, puzzlesinresult);
}
}
}
}
}
void print_result(int result[200000][3], int puzzlesinresult) {
printf("%d\n", puzzlesinresult + 1); //how many puzzles i have
for (int i = 0; i < puzzlesinresult + 1; i++) { //printing puzzles...
for (int j = 0; j < 3; j++) {
printf("%d ", result[i][j]);
}
printf("\n"); //...in separate lines
}
exit(0);
}
int main() {
int a;
scanf("%d", & a); //here i get how many puzzles i have
int tab[a][3]; //array for puzzles
int result[100][3]; //result array
int puzzlesinresult = 0; //this will help me track how many puzzles has my result array
for (int i = 0; i < a; i++) { //upload puzzles to array
for (int j = 0; j < 3; j++) {
scanf("%d", & tab[i][j]);
}
}
for (int i = 0; i < a; i++) { //here i delete puzzles that doesnt contribute anything like 1 x 1,2 x 2,..
if (tab[i][0] == tab[i][2] && tab[i][0] != 0) {
for (int p = i; p < a; p++) {
for (int j = 0; j < 3; j++) {
tab[p][j] = tab[p + 1][j];
}
}
}
}
findx(0, a, tab, result, puzzlesinresult); //start of recursion, because start has to be length 0
printf("NONE");
}
This returns sometimes correct result. If you can find when this program fails I would rly appreciate sharing those cases with me :)

How do I rotate a matrix? C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I want a matrix to rotate right. It's working for a square matrix, but i should also work for non square matrix.
I tried rotating it, but i couldn't think of a way to get it to work for non square matrix.
#include <stdio.h>
#define x 7
#define y 7
int build() {
int i = 0, k = 0;
int matrix[x][y];
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i;
}
}
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
printf("\t%d", matrix[k][i]);
}
printf("\n");
}
return matrix[i][k];
}
int turn()
{
int i = 0, k = 0;
int matrix[x][y];
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i;
}
}
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
printf("\t%d", matrix[i][k]);
}
printf("\n");
}
}
int main()
{
build();
printf("\t\n");
turn();
}
i want it to work for diffrent variables like x=5 and y=7.
My thought was to rotate the matrix by 90 degrees.
from
0 0 0 0
1 1 1 1
2 2 2 2
to
2 1 0
2 1 0
2 1 0
2 1 0
80% of work is declaring your functions and understanding what the declarations mean. You can start like this:
#define x 5
#define y 7
void build(int output[y][x]);
This declares a function build, which receives a matrix, and fills it with the needed data. Note: it doesn't return anything (i.e. returns void); instead of returning the data, it receives the pointer which it should write to. This is standard practice in C, because you cannot return arrays from functions.
I didn't write the code for it yet because it would distract you from understanding the flow of information in your program:
int main()
{
int matrix_before_rotation[y][x];
build(matrix_before_rotation);
}
This hypothetical program fills a matrix with values, using your function. It doesn't print it, but you could see the values if you used e.g. a debugger.
To declare a function which does the rotation:
void turn(int input[y][x], int output[x][y]);
Note the difference in dimensions, and the fact that the function receives two arguments - one for input, and one for output. You need to allocate two matrices in your main program:
int main()
{
int matrix_before_rotation[y][x];
int matrix_after_rotation[x][y];
build(matrix_before_rotation);
turn(matrix_before_rotation, matrix_after_rotation);
}
Given this code structure, it's easy to fill in the implementation details.
You might want to add a function for printing a matrix while you are debugging your program:
#define x 5
#define y 7
void build(int output[y][x]);
void turn(int input[y][x], int output[x][y]);
void print(int height, int width, int input[height][width]);
int main()
{
int matrix_before_rotation[y][x];
int matrix_after_rotation[x][y];
build(matrix_before_rotation);
print(y, x, matrix_before_rotation);
turn(matrix_before_rotation, matrix_after_rotation);
print(x, y, matrix_after_rotation);
}
Note: the printing function is more generic than the generating and the rotating functions - it knows how to work with matrices of any dimensions. You need it because you need at least two types of matrices in your new program - [7][5] and [5][7]. You can use this idea to generalize your rotating function so it could work with matrices of any dimensions.
Just a little modification to your code
#include <stdio.h>
#define x 3
#define y 4
int build() {
int i = 0, k = 0;
int matrix[x][y];
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
matrix[i][k] = i;
}
}
for (i = 0; i < x; ++i) {
for (k = 0; k < y; ++k) {
printf("\t%d", matrix[i][k]);
}
printf("\n");
}
return matrix[i][k];}
//for right turn you will have to modify the loop like this
int r_turn()
{
int i = 0, k = 0;
int matrix[x][y];
for(i=0; i<y; i++) //for outer loop, take y, because you're rotating
//loop , and y will come before x
{
for(k=x-1; k>=0; k--) //thereby, x goes after y
{
matrix[k][i] = k;
}
}
for(i=0; i<y; i++) //printing matrix in the same way we wrote
{
for(k=x-1; k>=0; k--) //here, k will start from k because
//index starts from 0
{
printf("\t%d", matrix[k][i]);
}
printf("\n");
}
}
int main()
{
build();
printf("\t\n");
r_turn();
}

C Programming and Matrix multiplication output issue

I'm currently learning C programming, to better my understanding of matrices in C I've tried to make this program.
I seem to be having problems with the output, as you can see the program has 3 functions.
The first one allows you to input the values for the array and then displays it. The second function performs the multiplication and the last should display the output of the multiplied matrix.
However the output is strange. Here is my code. The output is just below the code.
#include <stdio.h>
void read_matrix(int m2[][3] )
{
int i, j;
printf("input values for matrix in order of rows first \n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
scanf("%d",&m2[i][j]);
}
}
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d ", m2[i][j]);
}
printf("\n");
}
}
void multiply_matrices(int m1[][3], int m2[][3] ,int m3[][3])
{
int i, j, k;
for (i = 0; i < 3; i++){
for (j = 0; j < 3; j++){
for (k = 0; k < 3; k++){
m3[i][j] +=m1[i][k]*m2[k][j];
}
}
}
}
void write_matrix(int m3[][3] )
{
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d ", m3[i][j]);
}
printf("\n");
}
}
int main(void)
{
int matrix1[3][3], matrix2[3][3], matrix3[3][3];
read_matrix(matrix1);
read_matrix(matrix2);
multiply_matrices(matrix1, matrix2, matrix3);
write_matrix(matrix3);
return 0;
}
and this is the output!
input values for matrix in order of rows first
1
2
3
2
2
2
1
2
2
1 2 3
2 2 2
1 2 2
input values for matrix in order of rows first
2
1
1
1
2
1
2
1
2
2 1 1
1 2 1
2 1 2
-858993450 -858993452 -858993451 /*This is the multiplied matrix output!*/
-858993450 -858993452 -858993452
-858993452 -858993453 -858993453
Press any key to continue . . .
I fear it may be just a silly mistake; if so I'm sorry, but I can't see where I am going wrong at this moment.
Any help would be greatly appreciated.
You need to initialize all elements of matrix m3 to 0 before performing this operation
m3[i][j] +=m1[i][k]*m2[k][j];
in function multiply_matrices.
Initialize matrix3 in the function multiply matrix like this
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
m3[i][j]=0;
}
}
After this, do the multiplication and everything will work perfectly.
int m3[][]={};
It initially stores 0 for all available index of m3

Resources