How to make simmetric matrix in C language - c

For a school project of the features asked is to build a symmetric matrix using random number in [1,100], I know how to build a matrix and how to do it using the rand() function in C however I'm not being able to do a symmetric one, this is my code:
int size, num;
fflush(stdin);
system("cls");
printf("Build a simmetric matrix using random numbers\n\n");
printf("Insert matrix size: ");
scanf("%d", &size);
int matrix[size-1][size-1];
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
num = rand()%100+1;
matrix[i][j]=num;
matrix[j][i]=num;
}
}
for(int i=0;i<size;i++){
printf("\n\t");
for(int j=0;j<size;j++){
printf("%03d ", matrix[i][j]);
}
}
printf("\n\nPress Enter to continue...");
system("pause >nul /nobreak");
It builds a square matrix as requested but it isn't symmetric.
I would appreciate and be thankful for any help with the code to do it or pointing me to the right direction.

You are not getting symmetric matrix because you are accessing the index of matrix not properly. Let me explain in a bit detail.
The matrix that you are using is of size size-1 x size-1, so if size=5 then the matrix that you are allocating is of size 4x4, so you effectively have only 16 elements in your matrix. (And you actually want 25 elements).
But when traversing the matrix to populate it, you are accessing index like[4,4] which means your matrix should (logically) have 25 elements. (But it is not having).
So there are two ways to get rid of this mistake:
You can change your for loop to for(int i=0;i<size-1;i++) so you don't access elements in an unexpected way.
You can increase the size of your array to size x size instead of size-1 x size-1.
The final code will look something like this (I'm posting only the core part):
int matrix[size][size];
for(int i=0;i<size;i++){
for(int j=i;j<size;j++){
num = rand()%100+1;
matrix[i][j]=num;
matrix[j][i]=num;
}
}
As an optimization you can avoid re-writing the values by putting starting the inner-loop for j from i itself, so that the values in the upper triangle of matrix are generated by random number and the lower triangle values are filled by the value in the corresponding symmetric cell in the upper triangle.
I think your intention for asking the question is to learn and get better, so I answered in detail with some extra comments. I hope this was helpful. :)

Two mistakes:
off-by-one error in the matrix size: accesses will go to wrong place
you overwrite all columns in all lines, instead of filling just a triangle
Corrected code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char **argv) {
(void) argc;
(void) argv;
int size;
printf("Build a symmetric matrix using random numbers\n\n");
printf("Insert matrix size: ");
scanf("%d", &size);
/* ensure different result every time program is executed */
srand(time(NULL));
int matrix[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < i + 1; j++) {
int num = rand() % 100 + 1;
matrix[i][j] = num;
matrix[j][i] = num;
}
}
for (int i = 0; i < size; i++) {
printf("\n\t");
for (int j = 0; j < size; j++) {
printf("%03d ", matrix[i][j]);
}
}
printf("\n");
return(0);
}
Example output:
Build a symmetric matrix using random numbers
Insert matrix size: 5
084 087 016 087 063
087 078 094 093 028
016 094 036 050 091
087 093 050 022 060
063 028 091 060 064

Line #7:
use
int matrix[size][size];

Related

create a matrix with specific conditions

I would like to create a matrix with these specifics
text of exercise
write a program that reads a number k > 0 and a permutation of the first K numbers (from 0 to k-1) that does not fix any element and produce (printing on consecutive lines) permutations p0, . . . , ph such that (1) p0 is permutation given in input; (2) fro every i > 0, pi is the smallest permutation of K cthat does not fix any element and does not collide with any other permutation from p0 and pi−1. We say that 2 permutations p1, p2 ok
K collides if exists and index i from 1 to k such that p1(i) = p2(i).
my ideas i wanted to create a k*k matrix amd the first row will be the imput of a vector i will declare. I tought to fill the matrix in these way : let's take a specific element v[i][j]
v[i][j]is in the matrix if 1)v[k][j] from k =0,...,i-1 is different from v[i][j],1)v[i][k] from k =0,...,i-1 is different from v[i][j],v[i][j] is different from i , and from the remaining possibilities for v[i][j] it is the minimum from the remainin number 0,...k-1
code implementations
#include <stdio.h>
#include <stdlib.h>
#define N 50
typedef int matrix[N][N];
int min(int vector[],int n)
{
int i;
int p=0;
int min=vector[0];
for(i=0; i<n;i++)
{
if (vector[i]<=min)
{
min=vector[i];
p=i;
}
}
return min;
}
int main()
{
int k;
printf("\n insert a number ");
scanf("%d",&k);
int v[k][k];//creation of matrix I wanted
int input[k];//first row
int arrayindex[k]={0};// array from 0 to k
for(int u=0; u<k;u++)
{
arrayindex[u]=u;
}
printf("insert component of vector:");
for(int l=0;l<k;l++)
{
printf("input[%d]= ",l);
scanf("%d",&input[l]);
}
//print vector
for(int l=0;l<k;l++)
{
printf("%d",input[l]);
}
printf("\n\n");
// copy first row
for(int j=0;j<k;j++)
{
v[0][j]=input[j];
}
//printf of first row
for(int j=0;j<k;j++)
{
printf("\nv[0][%d]=%d ",j,v[0][j]);
}
//try to fill matrix
for(int i=1; i<k;i++)
{
for(int j=0;j<k;j++)
{
if (j=0){
v[i][j]!=v[i-1][j];
v[i][j]!=j;
v[i][j]=min(arrayindex,k);}
if(j!=0)
v[i][j]!=v[i-1][j];
v[i][j]!=v[i][j-1];
v[i][j]!=j;
v[i][j]=min(arrayindex,k);
}
}
//print of matrix
printf("\n the matrix is:\n ");
for(int i=0; i<k;i++)
{ printf("\n");
for(int j=0;j<k;j++)
{
printf("%d",v[i][j]);
}
}
return 0;
}
the problem in this code is in the section called try to fill matrix . When I compile nothing appear on the screen .Where is the problem ? is at least idea correct?

Input multiple values to multidimensional array C

I have an assignment where I have to make a program that takes in 3 sets of data of 5 values and adds them to a 3 * 5 array. I have already made a program where you type in each individual value, but I would rather want it to take in five values over 3 different inputs.
The code is not finished. I also have to do some operations on the data but I got that covered.
#include <stdio.h>
#include <stdlib.h>
#define THREE 3
#define FIVE 5
void totalArray(int, int, int set_numbers[][FIVE]);
void totalArray(int row, int column, int set_numbers[][FIVE]){
int total, subtotal;
printf("\tThe total of your 3-by-5 array is:\n");
for(row = 0, total = 0; row < THREE; row++){
// for each row, the numbers are summed
for(column = 0, subtotal = 0; column < FIVE; column++){
subtotal += set_numbers[row][column];
printf("%d %d", row, subtotal);
total += subtotal; // Total for entire array
}
}
}
int main(){
// 2D array of 15 numbers declaration
int set_numbers[THREE][FIVE] = {{}, {}, {}};
//counter variables for the loop
int i, j, column, row;
printf("\tYou're given an array which is a 3 by 5 array.\n");
printf("\tYou're going to put in each of the total 15 values.\n");
printf("\t___________________________________________________\n");
printf("\n\t\t\t--ATTENTION--\n");
for(i = 0; i < 3; i++){
for(j = 0; j < 5; j++){
printf("\n\t ******************************************");
printf("\n\t ** Array values have to be integers **");
printf("\n\t ******************************************");
printf("\n\tWhich values do you want in set_numbers[%d][%d]\n", i, j);
scanf("%d", &set_numbers[i][j]);
}
}
totalArray(row, column, set_numbers);
printf("The average of your three sets of numbers are: \n\n");
for(i = 0; i < 3; i++){
for(j = 0; j < 5; j++){
printf("%d", set_numbers[i][j]);
if(j == 4){
printf("\n");
}
}
}
return 0;
}
I should specify, that what i want it to do, is take in sets of data. Something along the lines of
int array[][] = {{}, {}, {}}
First, you should rename the macros THREEto COLUMNS and FIVE to ROWS, because it doesn´t make much sense to name macros after values. Consider, that you might want to change the values later and the understanding of what these macros are meant for is unclear at first sight.
Furthermore i don´t see any reason for declare the separate variables column and row inside of main() if you already have such macros. Please adjust that (You also need to change the declaration of totalArray() respectively).
Than you can incorporate this loop:
for (i = 0; i < COLUMNS; i++)
{
scanf("%d %d %d %d %d", &set_numbers[i][0], &set_numbers[i][1], &set_numbers[i][2], &set_numbers[i][3], &set_numbers[i][4]);
}
And you should really only use the macros, instead of hardcoding the actual values in the program. Consider you need to change the values later, then you need to go through the whole program again and change the according parts (which is relatively easy in your case, but just shouldn´t be). Consider also, you need to change them thereafter back again. That is the reason also, what the macros are meant for.

Imprecise average at run time

I am trying to solve a problem and I've run into a bit of an issue.
I have to find the running average of a series of numbers.
Example:
input 4 2 7
output 4 3 4.3333
Now here's the problem although I get the answer, it is not the precise answer.
Accepted Output: accuracy difference shown in the image
290.6666666667
385.4000000000
487.8333333333
477.4285714286
496.4444444444
...
523.8571166992
506.0454406738
495.3043518066
I can't find whats wrong. Some help would be highly appreciated.
#include<stdio.h>
main(){
int n;
printf("set:");
scanf("%d",&n);
float arr[n+1],resarr[n+1];
float sum=0;
for(int i=1; i<=n; i++){
scanf("%f",&arr[i]);
sum=arr[i]+sum;
float res= sum/(float)i;
resarr[i]=res;
}
int i=1;
while(i<=n) {
printf("%0.10f\n",resarr[i]);
i++;
}
return 0;
}
Here
for(int i=1; i<=n; i++){ }
you are trying to access out of bound array elements, this certainly causes undefined behavior as let's assume if n is 5 then you are accessing arr[5] also which doesn't exist.
C doesn't perform array boundary condition check, its programmer responsibility to not to access out of bound elements else it causes UB.
In C array index starts from 0 not from 1. So better start rotating loop from 0 to n. For e.g
for(int i=0; i<n; i++) {
scanf("%f",&arr[i]);
/* some code */
}
Code fails to achieve the desired accuracy as it is using float rather than double. #Some programmer dude
Typical float is precise to 1 part in 223. For printing to 0.0000000001, better to use double which is typically precise to 1 part in 253.
#include<stdio.h>
int main(void) {
//float arr[n + 1], resarr[n + 1];
//float sum = 0;
double arr[n + 1], resarr[n + 1];
double sum = 0;
...
// scanf("%f", &arr[i]);
scanf("%lf", &arr[i]);
...
// float res = sum / (float) i;
double res = sum / i; // cast not needed as `sum` is `double`
...
}
Iterating from 1 is not idiomatic in C. More common to iterate starting at 0.
size_t is best for array sizing and indexing. int may be too narrow. Of course with small arrays, it makes scant difference.
#include<stdio.h>
int main(void) {
printf("set:");
size_t n;
scanf("%zu", &n);
double arr[n], resarr[n];
double sum = 0;
for (size_t i = 0; i < n; i++) {
scanf("%lf", &arr[i]);
sum = arr[i] + sum;
double res = sum / (i+1);
resarr[i] = res;
}
for (size_t i = 0; i < n; i++) {
printf("%0.10f\n", resarr[i]);
}
return 0;
}
More robust code would check the input from the user it insure it is valid, allocate rather than use a VLA if n is allowed to be large, flush output before reading, etc.
Note that array arr[] is not needed, just a single double for the input and sum.

How do i select a number in a matrix in c?

So I have made a matrix, that's formed by (NxN). And the numbers for the matrix are put in through user input into a multidimensional array. I'm using pointers and malloc. So I have to select a number in the array to then get the sum of adjacent numbers, the number is selected just by saying the position. So just saying the 3rd number in the matrix. I am a little confused on how to just select a number, I have a general idea of incrementing to get to the right position? Would this be right? And will this then make it harder or easier to then get the sum of the adjacent numbers?
Just a little confused on how to then do this with a multidimensional array, would i just turn it back into a single array?
This is how i create the matrix:
for(i = 0; i< matrixSize; i++)
{
for(j=0; j < matrixSize; j++)
{
scanf("%d", &matrixValues[i][j]);
}
}
If you mean number in a matrix as follows (example for matrixSize == 4):
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
you can just calculate indexes from number
matrixValues[number/matrixSize][number%matrixSize]
EDIT:
For case when your 2D arreay defined as
int matrixValues[matrixSize][matrixSize];
All elements allocated in memory sequentially, i.e. element matrixValues[1][0] is exact after matrixValues[0][matrixSize-1], so you can use number as shift from adress of element matrixValues[0][0], e.g.:
*(((int*)matrixValues) + number)
For your example it can be
int matrixValues[matrixSize][matrixSize];
// input as 2D array
int i, j;
for(i = 0; i< matrixSize; i++)
{
for(j=0; j < matrixSize; j++)
{
scanf("%d", &matrixValues[i][j]);
}
}
// using address of matrix as begining of array
int* fakeArray = (int*)matrixValues;
// output as 1D arrray
int n;
for(n = 0; n < matrixSize * matrixSize ; n++)
{
printf("%d ", fakeArray[n]);
}

Not giving the right output

The program should create a 2D table 8*8 which consists o random number<3
it should print that table.
Another task is to translate this table into another
For Example
120
210
111
The number in the center should be changed to the sum of all numbers around it 1+2+0+2+0+1+1+1=8
and that should be done for everything;
then the program should be printed
if there are any numbers larger than 9 it shoul be translated to hexadecimal.....
I didn't do the hexadecimal yet. but it is still not working ....
#include <stdio.h>
#include <stdlib.h>
#define cols 8
#define rows 8
void printA(int A[][cols]);
void printC(char C[][cols]);
void SumThemUp(int A[][cols], char C[][cols]);
int main()
{
srand(time(NULL));
int A[rows][cols];
char C[rows][cols];
int i, j;
for(i=0; i<rows; i++)
for(j=0; j<cols; j++)
A[i][j]=rand()%3;
printA(A);
SumThemUp(A,C);
printC(C);
return 0;
}
void printA(int A[][cols])
{ int i, j;
for(i=0;i<rows;i++)
{for(j=0;j<cols; j++)
{printf("%d ", A[i][j]);}
printf("\n");}
return ;
}
void printC(char C[][cols])
{
int i, j;
for(i=0;i<rows;i++)
{for(j=0;j<cols; j++)
{printf("%ch ", C[i][j]);}
printf("\n");}
return ;
}
void SumThemUp(int A[][cols], char C[][cols])
{
int i,j;
for(i=0;i<rows;i++)
{for(j=0;j<cols; j++)
C[i][j]=0;}
for(i=0;i<rows;i++)
{for(j=0;j<cols; j++)
A[i][j]=C[i++][j];
}
for(j=0;j<cols; j++)
{for(i=0;i<rows;i++)
C[i][j]+=A[i][j++];
}return;
}
So - I'm not entirely sure I know what you want the output to be -- but there are several problems with what you have:
0: For your arrays, the names should describe what the array actually holds, A and C are quite ambiguous.
1: Use { } for scoping, and put the { } on their own lines. (Maybe it just pasted poorly in Stack Overflow)
2: You have a set of loops which basically sets everything in C to 0:
for(i=0;i<rows;i++)
{
for(j=0;j<cols; j++)
{
C[i][j]=0;
}
}
Then immediately after that you have:
for(i=0;i<rows;i++)
{
for(j=0;j<cols; j++)
{
A[i][j]=C[i++][j]; // <--- problem here
}
}
So after that, both A and C are full of all 0s. On top of that, you have i++ inline when accessing columns in C. This actually changes the value that your for loop is using, so i is getting incremented for every row and every column. Presumably you want:
A[i][j]=C[i+1][j];
3: You have a similar problem here:
for(j=0;j<cols; j++)
{
for(i=0;i<rows;i++)
{
C[i][j]+=A[i][j++]; // Presumably you want j+1
}
}
4: Why are you using a char array for C? If it's holding the sum of integers it should probably be declared int. If this was your idea of printing the ints as hex (or just plain ints), it would be easier to simply use printf to output the ints as hex:
// use %d to print the integer "normally" (base 10)
// use %x if you want a hex value with lowercase letters
// use %X if you want a hex value with capital letters
printf("125 as hex is: 0x%x", 125); // 0x7d
I hope that points you in the right direction.
-- Dan
Do I understand correctly, that given matrix A, you want to get matrix C in SumThemUp, where each cell in C is a sum of its adjacent cells? In that case, these lines look suspicious as you modify the loop counters
A[i][j]=C[i++][j];
and
C[i][j]+=A[i][j++];
.
Anyway, a simple example, how I would do the summing part.
NB! Note that I use int type for matrix C. Given that you want to convert it to hex and you happend to have values 3 in all adjacent cells somewhere, you get decimal value of 3 * 8 = 24, which requires more than one character to represent. Thus, you should convert to hex during printing. (I understand that char can contain intergral values up to 255 also, but for the sake of consistency)
void SumThemUp(int A[][cols], int C[][cols]) {
int i, j, di, dj, i2, j2;
// iterate through all the rows
for (i=0 ; i<rows ; ++i) {
for (j=0 ; j<cols ; ++j) {
// initialize the cell to zero
C[i][j] = 0;
// iterate over nearby cells
for (di=-1 ; di<=1 ; ++di) {
for (dj=-1 ; dj<=1 ; ++dj) {
// do not count in the center
if (di == 0 && dj == 0) {
continue;
}
// make sure, we do not try to count in cells
// outside the matrix
i2 = i + di;
j2 = j + di;
if (i2 < 0 || j2 < 0 || i2 >= rows || j2 >= cols) {
continue;
}
// append the score here
C[i][j] += A[i2][j2];
}
}
}
}
}
Also, I did not test this code, so it may contain mistakes, but maybe it helps you finishing your summing part.
NB! And take note of comments of #Dan.

Resources