I'm stuck in place. I cannot come up with the algorithm and will fill up the square matrix as below:
"Gets a natural number n from the user n not more than 20. Fills in a square table as below. The numbers below the main diagonal (a21; a31; a32, etc.) are given by the user."
#include <stdio.h>
int main() {
int tab[20][20] = { {0},{0} };
int size = 0;
printf("Enter the natural number n not more than 20: ");
while (scanf_s("%d", &size) != 1 || size < 0 || size >20 || getchar() != '\n')
{
while (getchar() != '\n');
printf("Error. Correct!");
}
for (int x = 0; x < size; x++)
{
for (int y = 0; y < size; y++)
{
if (y==x)
{
tab[x][y]=1; // what's next?
}
}
}
for (int x = 0; x < size; x++)
{
for (int y = 0; y < size; y++)
{
printf("%d ",tab[x][y]);
}
printf("\n");
}
return 0;
}
This is what you want.
You do not need to use if statement.
#include <stdio.h>
int main()
{
int tab[20][20]={ {0},{0} };
int size = 6,n=0;
for (int x = 0; x < size; x++)
{
n=0;
for (int y = x; y < size; y++)
{
n++;
tab[x][y]=n; //fill the upper part of the matrix including diagonal
}
}
for (int x = 1; x < size; x++)
{
for (int y = 0; y < x; y++)
{
tab[x][y]=8; //fill the lower part of the matrix
//or ask for user input
}
}
for (int x = 0; x < size; x++)
{
for (int y = 0; y < size; y++)
{
printf("%d ",tab[x][y]);
}
printf("\n");
}
return 0;
}
i think this would work for just above the main diagonal..
#include <stdio.h>
int main() {
int tab[20][20] = { {0},{0} };
int size = 0;
printf("Enter the natural number n not more than 20: ");
while (scanf("%d", &size) != 1 || size < 0 || size >20 || getchar() != '\n')
{
while (getchar() != '\n');
printf("Error. Correct!");
}
for (int x = 0; x < size; x++)
{
printf("%d. diagonal value:", x+1);
scanf("%d", & tab[0][x]);
}
for (int x = 0; x < size; x++)
{
for (int y = x; y < size; y++)
{
if (y==x)
{
tab[x][y]=1; // what's next?
}
else if(x>0){
tab[x][y]=tab[x-1][y-1];
}
}
}
for (int x = 0; x < size; x++)
{
for (int y = 0; y < size; y++)
{
printf("%d ",tab[x][y]);
}
printf("\n");
}
return 0;
}
output:
Related
I have a AxBxC matrix filled with 0 and need to make an ellipse inside. The area that it covers needs to b filled with 1.
I have the code to create the 3d matrix, but don't know how to do the ellipse.
The user needs to give all the matrix dimensions and the ellipse dimensions as well.
#include <stdio.h>
#include <stdlib.h>
void criaMatriz() // Function to create 3d matrix
{
int ***m;
int x, y, z, i, j, k;
// Number of lines
printf("Digite o número de linhas:");
scanf("%d", &y);
// Number of columns
printf("Digite o número de colunas:");
scanf("%d", &z);
// depth
printf("Digite a largura do paralelepipedo:");
scanf("%d", &x);
m = malloc(x * sizeof(int **));
for (i = 0; i < x; i++)
{
m[i] = malloc(y * sizeof(int *));
}
for (i = 0; i < x; i++)
{
for (j = 0; j < y; j++)
{
m[i][j] = malloc(z * sizeof(int));
}
}
for (i = 0; i < x; i++)
{
for (j = 0; j < y; j++)
{
for (k = 0; k < z; k++)
{
m[i][j][k] = 0;
}
}
}
for (i = 0; i < x; i++)
{
for (j = 0; j < y; j++)
{
for (k = 0; k < z; k++)
{
printf("%2d ", m[i][j][k]);
}
printf("\n");
}
printf("\n");
}
for (i = 0; i < x; i++)
{
for (j = 0; j < y; j++)
{
free(m[i][j]);
}
}
for (i = 0; i < x; i++)
{
free(m[i]);
}
free(m);
}
int main()
{
criaMatriz();
return 0;
}
I tried making a sphere first, but it didn't work.
Hi everyone I made some changes in the code so that it's easy to understand, looks what I have so far, I kept the function's prototype at the beginning of the code and it works fine, but it just works fine just when I try a 2x2 matrix because if I try a 3x3, 4x4 or 6x6 matrix it does not works fine the determinant is not calculated right, I guess that's the problem the determinant but I don't know how to solve it. Here is the code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<math.h>
float determinant(int tam,float [][tam]);
void cofactor(int tam,float [][tam]);
void transpose(int tam,float [][tam],float [][tam]);
int validate(){
int val;
char *buf = (char *) malloc(10);
memset(buf,0,10);
while(fgets(buf, 10, stdin) != NULL ){
if(buf[0]!='\n') {
val = atoi(buf);
break;
}
}
free(buf);
return val;
}
float determinant(int tam, float matrix[][tam])
{
float s = 1, det = 0, b[tam][tam];
int i, j, m, n, c;
if (tam == 1)
{
return (matrix[0][0]);
}
else
{
det = 0;
for (c = 0; c < tam; c++)
{
m = 0;
n = 0;
for (i = 0;i < tam; i++)
{
for (j = 0 ;j < tam; j++)
{
b[i][j] = 0;
if (i != 0 && j != c)
{
b[m][n] = matrix[i][j];
if (n < (tam - 2))
n++;
else
{
n = 0;
m++;
}
}
}
}
det = det + s * (matrix[0][c] * determinant( tam - 1,b));
s = -1 * s;
}
}
return (det);
}
void cofactor( int tam,float num[][tam])
{
float b[tam][tam], fac[tam][tam];
int p, q, m, n, i, j;
float x = 0;
for (q = 0;q < tam; q++)
{
for (p = 0;p < tam; p++)
{
m = 0;
n = 0;
for (i = 0;i < tam; i++)
{
for (j = 0;j < tam; j++)
{
if (i != q && j != p)
{
b[m][n] = num[i][j];
if (n < (tam - 2))
n++;
else
{
n = 0;
m++;
}
}
}
}
x = pow(-1, q + p) * determinant( tam - 1,b);
fac[p][q] = x;
}
}
transpose(tam,num, fac);
}
void transpose(int tam,float num[][tam], float fac[][tam])
{
int i, j;
float b[tam][tam], inverse[tam][tam], d;
for (i = 0;i < tam; i++)
{
for (j = 0;j < tam; j++)
{
b[i][j] = fac[j][i];
}
}
d = determinant(tam,num);
for (i = 0;i < tam; i++)
{
for (j = 0;j < tam; j++)
{
inverse[i][j] = b[i][j] / d;
}
}
printf("\n\n\nThe inverse of matrix is : \n");
for (i = 0;i < tam; i++)
{
for (j = 0;j < tam; j++)
{
printf("\t%f", inverse[i][j]);
}
printf("\n");
}
}
int verify_Size(int line){
if((line > 0) && (line <= 6))
{
return 1;
}
return 0;
}
int create_Matrix(int LINE){
int matrix[LINE][LINE];
float aux[LINE][LINE];
printf("\n\n\nPle:", (LINE * LINE));
printf("\n--------------------------------\n");
for(int i=0;i<LINE;i++)
{
for(int j=0;j<LINE;j++)
{
printf("Value[%d][%d]: ",i,j);
matrix[i][j] = validate();
}
}
printf("\n\nYour Bidimensional Matrix is:");
printf("\n--------------------------------\n");
for(int i=0;i < LINE;i++)
{
for(int j=0; j< LINE;j++)
{
printf("\t%2d",matrix[i][j]);
aux[i][j] = (float) matrix[i][j];
}
printf("\n");
}
float d = determinant(LINE,aux);
printf("\n\nDeterminante Main: %f \n",d);
if (d == 0)
printf("\nInverse of Entered Matrix is not possible\n");
else
cofactor(LINE,aux);
return 0;
}
int main(){
int flag,line;
do{
printf("Enter the order of the Matrix:\n");
printf("-------------------------------\n");
printf("Lines: ");
line = validate();
if(verify_Size(line)== 1)
{
create_Matrix(line);
}else{
printf("\nMatrix must to be till 6 X 6!\n");
flag = 0;
}
}while(flag != 1);
return 0;
}
It looks like you are finding the inverse matrix by Cramer's rule. While it works Ok for 2x2 or 3x3 matrix sizes, the hard part about implementing Cramer's rule generally is evaluating determinants. If you compute an NxN determinant following the definition, the computation is recursive and has factorial O(N!) computational complexity (Wikipedia).
I suggest switching to another algorithm. LUP factorization is fast and relatively simple, and Wikipedia has an example implementation.
This program which written in C should remove duplicated elements from 2 input arrays by user, so when I print the second array which is b[z] after removing duplicates, the output is not true as it prints weird number instead of the input number by the user. (the problem in code is determined by comment).
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, z ;
printf("Enter size of array\n");
scanf("%d", &n);
int a[n];
if(n <= 20) {
for(int i = 0 ; i < n; i++) {
printf("Enter integer \n");
scanf("%d", &a[i]);
}
}
for(int i = 0 ; i < n; i++) {
printf("%d ", a[i]);
}
printf("\nEnter size of the 2nd array\n");
scanf("%d", &z);
int b[z];
if(z <= 20) {
for(int i = 0 ; i < z; i++) {
printf("Enter integer \n");
scanf("%d", &b[z]);
}
}
for(int i = 0 ; i < z; i++) {
printf("%d ", b[z]);
}
for(int i = 0 ; i < n; i++) {
for(int j = i + 1; j < n; j++) {
if(a[i] == a[j]) {
for(int l = j; l < n; l++)
{
a[l] = a[l + 1];
}
n--;
j--;
}
}
}
printf("\nArray1: ");
for(int i = 0; i < n; i++) {
printf("%d ", a[i]);
}
for(int t = 0; t < z; t++) {
for(int u = t + 1; u < z; u++) {
if(b[t] == b[u]) {
for(int l = u; l < z; l++)
{
b[l] = b[l + 1];
}
z--;
u--;
}
}
}
printf("\nArray2: ");
for(int e = 0; e < z; e++) {
printf("%d ", b[e]);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define N_MAX 10
#define N_MIN 2
#define TEMPSIZE 1024
float RowSum(float **matrix, int sizearray,int row) {
float sum;
for (int j=0 ; j <= row; j++) {
sum = 0;
for (int i=0 ; i < sizearray; i++) {
sum = sum + matrix[j][i];
}
}
return sum;
}
float ColSum(float **matrix, int sizearray, int col) {
float sum;
for (int j = 0; j <= col; j++) {
sum = 0;
for (int i = 0; i < sizearray; i++) {
sum = sum + matrix[i][j];
}
}
return sum;
}
int RepNum(int arraysize, float **matrix) {
int i, j, counter = 0;
int temparray[N_MAX*N_MAX];
for (i = 0; i < N_MAX*N_MAX; i++) {
temparray[i] = 0;
}
for (i = 0; i < arraysize; i++) {
for (j = 0; j < arraysize; j++) {
temparray[(int)matrix[i][j]]++;
}
}
for (i = 1; i < arraysize*arraysize; i++) {
if (temparray[i] > 1)
counter++;
}
return counter;
}
void PrintArray(float **matrix, int arraysize) {
for (int i = 0; i<arraysize; i++)
{
for (int j = 0; j<arraysize; j++)
printf("%3d ", (int)matrix[i][j]);
printf("\n");
}
}
int CheckInt(float **matrix, int arraysize) {
int counter = 0;
for (int i = 0; i < arraysize; i++) {
for (int j = 0; j < arraysize; j++) {
if (((int)matrix[i][j]) != matrix[i][j])
counter++;
}
}
return counter;
}
void main() {
printf("Hello! this program will help you to find out if you have a magic square!\nPlease enter your matrix order and following it the numbers you'd like to check: \n");
float **matrix;
char input[TEMPSIZE];
int sizear = 0;
float correctsum = 0.0;
int counter = 0, row, column;
fgets(input, TEMPSIZE, stdin);
char* str = strstr(input, " ");
if (str == 0)
return;
str[0] = 0;
str++;
sizear = atof(input);
if (sizear > N_MAX || sizear < N_MIN)
{
printf("ERROR: The matrix size cannot be %d size. \n", sizear);
exit(0);
}
matrix = (float**)calloc(1, sizear * sizeof(float*));
for (column = 0; column < sizear; column++)
{
matrix[column] = (float*)calloc(1, sizear * sizeof(float));
}
for (row = 0; row < sizear; row++)
{
for (column = 0; column < sizear; column++)
{
char* temp = strstr(str, " ");
if (temp == 0) /*gets the last number*/
{
++counter;
matrix[row][column] = atof(str);
goto end;
}
if (atof(temp) <= sizear*sizear && atof(temp) > 0) { /*puts all numbers in matrix*/
temp[0] = 0;
matrix[row][column] = atof(str);
str = temp + 1;
++counter;
}
else {
printf("you cannot enter the number %.3f \n", atof(temp));
exit(0);
}
}
}
end:
if (counter > sizear*sizear) {
printf("you've entered %d numbers, while you should've enter %d numners \n", counter, sizear*sizear);
}
else if (counter < sizear*sizear) {
printf("you've entered %d numbers, while you should've enter %d numners \n", counter, sizear*sizear);
}
else if (counter == sizear*sizear) {
correctsum = (float)((sizear*(sizear*sizear + 1)) / 2);
float row = RowSum(matrix, sizear, 0);
float coul = ColSum(matrix, sizear, 0);
if (row == coul && row== correctsum && coul==correctsum && RepNum(sizear, matrix) ==0 && CheckInt(matrix,sizear)==0) {
printf("It's a magic matrix!\n");
PrintArray(matrix, sizear);
}
else {
printf("Not a magic square:\n");
if (row != coul && row != correctsum && coul != correctsum) {
printf("* Coloums and rows sum do not match.\n");
}
if (RepNum(sizear, matrix) != 0) {
printf("* There are repeating numbers.\n");
}
if (CheckInt(matrix, sizear) != 0) {
printf("* One of the numbers or more you've entered isn't integer.\n");
}
}
}
for (column = 0; column < sizear; column++)
{
free(matrix[column]);
}
free(matrix);
}
When I hit more than sizearrayXsizearray numbers it doesn't add into the counter and stops at sizearrayXsizearray counting. Can anyone point out why it doesn't count it?
The exercise asked to check if the input is a magic square (sum rows=columns=diagonals), making sure there are no duplicates, only int numbers and that I don't enter more or less than sizearrayXsizearray numbers. The input from the user should look like 3 1 2 3 4 5 6 7 8 9 where the first number (here it is 3) is the array size and the rest are the numbers that would be checked as a magic square.
When I hit more than sizearrayXsizearray numbers it doesn't add into the counter and stops at sizearrayXsizearray counting. Can anyone point out why it doesn't count it?
Sure, it's simple: the counter is incremented in the loops
for (row = 0; row < sizear; row++)
{
for (column = 0; column < sizear; column++)
{
…
}
}
- the inner statements are run through (at most) sizear × sizear times, so the counter, starting from 0, cannot reach a higher value.
insdead of my static matrix i try to get 2d dynamic matrics
all i want to do is to change the init function so instead of using the defined heigh and width
it would init dynamicaly - please show me the how
void init(int board[][WIDTH], int rows) {
int x, y;
for (y = 0; y < rows; y++)
for (x = 0; x < WIDTH; x++)
board[y][x] = 0;
/* Scatter some live cells: */
board[10][25] = 1;
board[10][26] = 1;
board[10][27] = 1;
board[11][25] = 1;
board[12][26] = 1;
}
int main(void) {
int board[HEIGHT][WIDTH];
init(board, HEIGHT);
..
..
}
this is the code i wanted to use - please show me the right implamintation
without using #define WIDTH 50 #define HEIGHT 20
int **matrix_dyn(int n, int m)
{
int i = 0;
int j = 0;
printf ("please enter the horizontal size of the board \n");
scanf ("%d", &n);
printf ("please enter the vertical size of the board \n");
scanf ("%d", &m);
int **board = (int**)malloc(n * sizeof(int*));
printf("please enter the 0's or 1's to fill the matrix \n");
for (i = 0; i <= n; i++)
board[i] = (int*)malloc(m*sizeof(int));
for(i = 0; i <= n; i++)
{
for(j = 0; j <= m; j++)
scanf ("%d", &board[i][j]);
}
return board;
}
this is all my code:
#include <stdio.h>
#define WIDTH 50
#define HEIGHT 20
void init(int board[][WIDTH], int rows) {
int x, y;
for (y = 0; y < rows; y++)
for (x = 0; x < WIDTH; x++)
board[y][x] = 0;
/* Scatter some live cells: */
board[10][25] = 1;
board[10][26] = 1;
board[10][27] = 1;
board[11][25] = 1;
board[12][26] = 1;
}
void print(int board[][WIDTH], int rows, int cols)
{
int x, y;
char c;
for (y = 0; y < rows; y++) {
for (x = 0; x < cols; x++) {
if (board[y][x] == 1)
printf("X");
else
printf(" ");
}
printf("\n");
}
printf("Press any key to continue:\n");
getchar();
}
int count_neighbors(int board[][WIDTH], int rows,
int y, int x)
{
int i, j;
int result = 0;
for (i = -1; i <= 1; i++)
if ((y+i >= 0) && (y+i < rows))
for (j = -1; j <= 1; j++)
if ((x+j >= 0) && (x+j < WIDTH))
if ((i != 0) || (j != 0))
result += board[y+i][x+j];
return result;
}
int step(int board[][WIDTH], int rows) { // now returns a bool
int x, y;
int neighbors[HEIGHT][WIDTH];
int changed = 0; // save changes
for (y = 0; y < rows; y++)
for (x = 0; x < WIDTH; x++)
neighbors[y][x] = count_neighbors(board, rows, y, x);
for (y = 0; y < rows; y++)
for (x = 0; x < WIDTH; x++)
if (board[y][x] == 1) { /* Currently alive */
if (neighbors[y][x] < 2)
{
board[y][x] = 0; /* Death by boredom */
changed = 1; // change happened
}
else if (neighbors[y][x] > 3)
{
board[y][x] = 0; /* Death by overcrowding */
changed = 1; // change happened
}
}
else { /* Currently empty */
if (neighbors[y][x] == 3)
{
board[y][x] = 1;
changed = 1; // change happened
}
}
return changed; // return the status (changed yes/no?)
}
int main(void) {
int board[HEIGHT][WIDTH];
init(board, HEIGHT);
while (1) {
print(board, HEIGHT, WIDTH);
if(step(board, HEIGHT) == 0) // no change
break; // leave the loop
}
return 0;
}
Declare & allocate board like so:
int *board = malloc( n * m * sizeof(int) );
Then, anytime you wish to access board[x][y], use the following expression:
board[y*n+x]
Try using a struct, heres a simple implementation I wrote up (compiled using GCC, to support the constructor attribute.
// IntGrid.h
typedef struct intGrid_t {
int **data;
int rows;
int cols;
} *IntGridRef;
struct {
IntGridRef(* create)(int, int);
void (* print)(IntGridRef);
void (* free)(IntGridRef);
int **(* data)(IntGridRef);
int (* rows)(IntGridRef);
int (* cols)(IntGridRef);
} IntGrid;
// IntGrid.c
IntGridRef _intGrid_create(int rows, int cols);
void _intGrid_print(IntGridRef this);
void _intGrid_free(IntGridRef this);
int **_intGrid_data(IntGridRef this);
int _intGrid_rows(IntGridRef this);
int _intGrid_cols(IntGridRef this);
__attribute__((constructor))
static void intGrid_setup()
{
IntGrid.create = _intGrid_create;
IntGrid.print = _intGrid_print;
IntGrid.free = _intGrid_free;
IntGrid.data = _intGrid_data;
IntGrid.rows = _intGrid_rows;
IntGrid.cols = _intGrid_cols;
}
IntGridRef _intGrid_create(int rows, int cols)
{
IntGridRef this = calloc(1, sizeof(struct intGrid_t));
this->rows = rows;
this->cols = cols;
this->data = calloc(rows, sizeof(int *));
for (int i = 0; i < rows; i++) {
this->data[i] = calloc(cols, sizeof(int *));
}
return this;
}
void _intGrid_print(IntGridRef this)
{
printf("{\n");
for (int i = 0; i < this->rows; i++) {
printf(" { ");
for (int j = 0; j < this->cols; j++) {
printf("%i", this->data[i][j]);
if (j != this->cols - 1)
{
printf(", ");
}
}
printf(" }\n");
}
printf("}\n");
}
void _intGrid_free(IntGridRef this)
{
for (int i = 0; i < this->rows; i++) {
free(this->data[i]);
}
free(this->data);
free(this);
}
int **_intGrid_data(IntGridRef this)
{
return this->data;
}
int _intGrid_rows(IntGridRef this)
{
return this->rows;
}
int _intGrid_cols(IntGridRef this)
{
return this->cols;
}
Example Usage:
int main(int argc, char *argv[])
{
IntGridRef grid = IntGrid.create(10, 10);
for (int i = 0; i < IntGrid.rows(grid); i++) {
for (int j = 0; j < IntGrid.cols(grid); j++) {
IntGrid.data(grid)[i][j] = arc4random_uniform(10);
}
}
IntGrid.print(grid);
IntGrid.free(grid);
return 0;
}
You're basically there, but instead of having the compiler generate code to map [x][y] to a specific element in the memory allocated for board, you have to do the mapping yourself: board[x*h+y] or board[y*w+x] (where w is width & h is height); it doesn't matter which you choose, just be consistent (a function or macro would help here).