C - Access a certain row or column in a matrix - c

I want to know how I can print a certain row, certain column and the anti diagonal in an NxN matrix. So far I know how to print the matrix itself and the main diagonal. As you can see in the code I'm printing the main diagonal.
#include <stdio.h>
int main() {
int r1, c1;
printf("\n Enter number of rows for M1");
scanf("%d", &r1);
printf("\n Enter number of columns for M1");
scanf("%d", &c1);
int m1[r1][c1];
// int m2[][];
int i, j;
printf("\n Enter first Matrix: \n");
for(i = 0; i < r1; i++){
for(j = 0; j < c1; j++){
scanf("%d", &m1[i][j]);
}
}
for(i = 0; i < r1; i++){
for(j = 0; j < c1; j++){
if(i == j){
printf("%d", m1[i][j]);
}
}
printf("\n");
}
return 0;
}

This exercise is supposed to teach you how to translate a task into the correct loop.
In order to understand how to do that, I'd suggest this way:
Take a specific example (matrix), and write down the expected result. Then try to reverse-engineer it to the right loop code by understanding the indices pattern:
Let's take this matrix:
1 6 4 3
9 3 5 2
3 3 8 0
1 5 4 4
Example 1 - Main diagonal
Expected result would be 1384
which is practically cells (0,0) (1,1) (2,2) (3,3). Now, look at this list of indices and figure out the pattern - it's one index that increments in every iteration ==> one index (one loop) is enough:
for(i = 0; i < r1; i++) {
printf("%d", m1[i][i]);
}
Example 2 - Anti diagonal
Expected result would be 3531 which is practically cells (0,3) (1,2) (2,1) (3,0). Again, look at this list of indices and figure out the pattern - it's one index that increments in every iteration and the other one decrements. But if you think about it, the second index is a function of the first one. That means that also this one can be done with one index only:
for(i = 0; i < r1; i++) {
printf("%d", m1[i][r1 - i + 1]);
}
Because second-index = r1 - first-index + 1, always.
I tried to explain here how you should go about thinking and writing the correct loop given a task. Now try to use this method for the rest of your tasks - a certain row and a certain column (it's even easier than the diagonals).
For row 2 the indices will be (2,0) (2,1) (2,2) (2,3) - so what's the pattern?
Good luck.

Related

how can I print the final matrix correctly?

Problem Statement
A matrix is a 2D array of numbers arranged in rows and columns. We give you a Matrix of N rows and M columns.
Now your task is to do this operation on this matrix:
If the value matches with the current row and column number then add 3 with the value.
If the value matches with only the current row number then add 2 with the value.
If the value matches with only the current column number then add 1 with the value.
Input Format
The first line contains N is the number of rows in this matrix and M is the number of columns in this matrix
The second line contains a 2D array Arr[i][j].
Constraints
1 <= N, M <= 10
0 <= Arr[i][j] <= 100
Output Format
Print the matrix after the operation is done.
Sample Input 0
3 3
1 1 1
1 1 1
1 1 1
Sample Output 0
4 3 3
2 1 1
2 1 1
#include <stdio.h> 
int main(){
//here taking the row and column from the users
int row;
int column, temp;
printf("enter row and column\n");
scanf("%d%d", &row, &column);
int arr[row][column];
//here taking the matrix input through the users
for(int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
scanf("%d", &arr[i][j]);
}
for (int i=0; i<row; i++){
for(int j=0; j<column; j++ ){
if (arr[i][j] == arr[i+1] && arr[i][j]== arr[j+1]){
temp= arr[i][j]+3;
printf("%d", temp);
}
else if (arr[i][j] == arr[i+1]){
temp= arr[i][j]+ 2;
printf("%d", temp);
}
else if (arr[i][j]== arr[j+1]){
temp= arr[i][j]+ 1;
printf("%d", temp);
}
else{
temp= arr[i][j];
printf("%d", temp);
}
}
}
}
return 0;
}
After I run the code, this doesn't work.
At least this issue:
if (arr[i][j] == arr[i+1] && arr[i][j]== arr[j+1]){ is undefined behavior (UB) as code attempts to access outside int arr[row][column]; with arr[i+1] and arr[j+1].
arr[i][j] == arr[i+1] is not sensible as it attempts to compare an int with a pointer.
In c, there are two types of memories. One of them is run-time memory, where your program dynamically allocates memory based on actions done in the program execution time.
In your answer, you are setting your matrix size based on the numbers inputed by the user, which is dynamic memory.
A static array(what you are using) is not dynamic and it is the reason that you can't add more elements and change the size of it.
https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/amp/

C - Entering values for 2d Array using for loop produces different values than entered

I have this simple program I am working on in class, it initialized a 3x5 2d Array of integers whose values are inputted for each cell by the user. The program then calls a function which runs through the array with a for loop to display each value, then calls a function which again uses a for loop to double every value, and calls the previous display function to show the array again.
All of this seems to be working, however I am consistently getting odd outputs for certain areas when initializing the values for the 2dArray.
For example: Entering 5 rows of "1, 2, 3" and then calling the display function produces this as output:
1,1,2,
1,2,3,
1,2,3,
1,2,5,
1,2,3
Further more, the doubling function produces further strange results but only in the areas where the output was different from what the user had inputted.
Output of the double function on the array I just posted displays as:
2,4,8
2,4,6
2,4,6
2,4,10,
4,8,6
The only real mathematical operation in the entire program is in the doubling functions, where it runs through a for loop setting the value of "array[j][i] = (array[j][i] = array[j][i] * 2)"
I cannot for the life of me figure out which part of the program I've written would cause the user inputs to change to what has been displayed. Inputting values other than "1,2,3" produces similarly odd results. Anyone have any idea what is wrong here? I feel like it must be a very simple mistake I am missing. Here is my source code:
#include <stdio.h>
#include <stdlib.h>
void displayArray(int array[][4]);
void doubleArray(int array[][4]);
int main() {
int dArray[2][4];
int i, j, k;
for(i = 0; i <= 4; i++){
for(j = 0; j <= 2; j++){
printf("Enter a value for the array at position %d,%d.\n", j, i);
scanf("%d", &dArray[j][i]);
}
}
printf("Displaying your original array...\n");
displayArray(dArray);
printf("Doubling your array...\n");
doubleArray(dArray);
printf("Displaying your doubled array....\n");
displayArray(dArray);
system("pause");
}
void displayArray(int array[][4]){
int i, j;
for(i = 0; i <= 4; i++){
printf("\n");
for(j = 0; j <= 2; j++){
if(j == 2 && i == 4){
printf("%d", array[j][i]);
}
else{
printf("%d,", array[j][i]);
}
//system("pause");
}
}
printf("\n");
}
void doubleArray(int array [][4]){
int i, j;
for(i = 0; i <= 4; i++){
for(j = 0; j <= 2; j++){
array[j][i] = (array[j][i] * 2);
//printf("%d\n", array[j][i]);
}
}
}
It's all in one .c file, and I am using devc++ if that makes any difference.
To calculate the DIMENSIONS of your 2D C arrays you have to count how many columns and how many rows there are. In your examples, it is 3 columns and 5 rows, and those are the values you must enter in your array definition:
int array[3][5]
Then, because C starts indexing with 0 offset, you can referr to the elements of the array using the columns 0 to 2 (that is, 3 columns) and rows 0 to 4 (that is, 5 rows). As other people said, this can be achieved using "lower than the limit" (correct: <3 for the columns, <5 for the rows) instead of "lower or equal than the limit" (incorrect, out of bounds: <=3 for the columns, <=5 for the rows).

Graph Coloring in C: Unable to identify the logical error

I am trying to implement the graph coloring algorithm in C, this implementation is based on how we assign the colors by iterating through the adjacency matrix. I am unable to get it after assigning a color to the second vertex.
Here is the code of my program:
int n, a[10][10], i, j, k, c[10], max = 0, col, ct = 0, rt = 0, m, count = 2;
void main() {
printf("enter n\n");
scanf("%d", &n);
printf("enter the Adjacency Matrix for %d rows and %d columns\n", n, n);
for (i = 0; i < n; i++) {
c[i] = 0;
for (j = 0; j < n; j++)
scanf("%d", &a[i][j]);
}
c[0] = 1;
c[1] = 2;
for (i = 1; i < n; i++) {
for (j = 0; j < n; j++)
if (a[i][j] > 0) {
m = 0;
for (col = 0; col < n; col++) {
if (a[i][col] > 0)
rt++;
if (a[col][i] > 0)
ct++;
}
m = rt;
if (ct > rt)
m = ct;
if (m < 2) {
if (a[0][i] > 0)
c[i] = 2;
else
c[i] = 1;
} else {
c[i] = count;
if (m > max) {
max = m;
count++;
}
}
rt = 0;
ct = 0;
}
if (c[i] < 1)
if (c[i - 1] > 1)
c[i] = 1;
else
c[i] = 2;
}
printf("The proper coloring is\n");
for (i = 0; i < n; i++)
printf("c%d=%d ", i + 1, c[i]);
printf("\n");
}
Example Input:
Consider a complete graph:
0 1 1 1
1 0 1 1
1 1 0 1
1 1 1 0
Expected output:
c1=1 c2=2 c3=3 c4=4
Observed output:
c1=1 c2=2 c3=3 c4=3
The error seems to be in logic, as you may have inferred by the looks of the question title. The conditional statement where you are checking if m is greater than max and then updating max and count accordingly seem to be incorrect.
I could not exactly figure out what the intended logic was, but I can tell why it is incorrect.
In your usage, you keep the maximum number of neighbors you encountered in max, and update it when you find a vertex which has more neighbors. With it, you also update count, which I think holds the color of currently highest value. Now, unless you encounter a vertex with more neighbors at each step(while traversing each row), you don't update max, and therefore you don't update count. Consequently, unless you encounter such a vertex, you keep assigning the same currently highest count to all vertices you encountered.
You should explain some more about the algorithm you implemented. However, just by looking at your code I think you should at least increment count somewhere different.
A good idea might by just keeping an array equal to the number of vertices. Then for each vertex (inside outermost loop) you can reset the array and by traversing all of the neighbors of ith vertex you can set the colors used in them, and pick the smallest unused color.
It is probably not the most efficient way to do it, but you already have an O(n3) algorithm, so I think it wouldn't hurt going this way.
Below is your code, updated to reflect the changes I mentioned.
int n,a[10][10],i,j,k,c[10],max=0,col,ct=0,rt=0,m,count=2;
int used[11]; /* indices used are from 1 to n, inclusive */
void main()
{
printf("enter n\n");
scanf("%d",&n);
printf("enter the Adjacency Matrix for %d rows and %d columns\n",n,n);
for(i=0; i < n ; i++)
{
c[i]=0;
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
c[0]=1;
c[1]=2;
for(i = 1 ;i < n;i++)
{
for(j = 1 ;j <= n ;j++)
used[j] = 0;
for(j = 0 ;j < i ;j++)
{
if(a[i][j] > 0)
used[c[j]] = 1;
}
for(j = 1 ;j <= n ;j++)
if(!used[j])
{
c[i] = j;
break;
}
}
printf("The proper coloring is\n");
for(i = 0;i < n ;i++)
printf("c%d=%d ",i+1,c[i]);
printf("\n");
}
What does a straightforward algorithm to colour the verices look like?
Consider all vertices in a loop and assign a colour. Vertices that have been visited already have a colour; vertices that will still be visited are still uncoloured.
Determine which colours are used by adjacent vertices that have already been coloured.
With this information, pick the lowest possible colour.
What does your algorithm look like:
Assign colour 1 to vertex 1 and colour 2 to vertex 2. (Note that vertex 2 can use the same colour as vertex 1 if the two aren't connected.)
Loop over all remaining vertices; then loop over all vertices cnnected to that.
Count the number of incoming and outgoing links to the second vertex in yet another loop. (Note that merely counting the links doesn't give you information on which colours are still available. You could have many vertices coloured with colours 3 and 4, for example, but you base your new colour on the number of links. In this example, colour 1 would be a good choice.)
Your criterion for chosing a new colour is whether the number of links is greater or equal to 2. You then assign the count, but before incrementing it. That gives you the second 3 in your example, where there should be a 4.
So you loop once too many and have a poor criterion for choosing a colour. Instead of counting the lonks, you should keep a list of used colours in adjacent nodes and base your new colour on that list.
Other stylistic issues with your code:
All your variables should be local to main; there's no reason to make them global, especially since you don't use functions.
Please be more systematic with your variable declarations. To have them all slapped together in one large definition, which even claoesces arrays and scalars, make them hard to understand.
Please use braces around all code blocks, even if they are not strictly necessary. It makes reading the code easier. Small if s without an else in the inner block such as if (ct > rt) m = ct; don't need braces, but consider using them everywhere else.

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]);
}

Find location of numbers in 2d array

I have two arrays. Array A and Array B. Now I need to get where in array B is sequence from array A located. I need to get location of last number and I don't know how.
A[4]={6,3,3,2};
B[10][18]={
{5,3,6,5,6,1,6,1,4,4,5,4,4,6,3,3,1,3},
{6,2,3,6,3,3,2,4,3,1,5,5,3,4,4,1,6,5},
{6,4,3,1,6,2,2,5,3,4,3,2,6,4,5,5,1,4},
{5,3,5,6,6,4,3,2,6,5,1,2,5,6,5,2,3,1},
{1,2,5,2,6,3,1,5,4,6,4,4,4,2,2,2,3,3},
{4,1,4,2,3,2,3,6,4,1,6,2,3,4,4,1,1,4},
{5,3,3,2,6,2,5,2,3,1,2,6,5,1,6,4,1,3},
{4,5,2,1,2,5,2,6,4,3,3,2,3,3,3,1,5,1},
{1,3,5,5,2,1,3,3,3,1,3,3,6,3,3,3,6,5},
{4,5,2,4,2,3,4,2,5,6,5,2,6,3,5,4,5,2}
};
For example: Sequence 6,3,3,2 start in second row and in forth column and ends in seventh column. I need to get location of number 2. My result should be:
Row = 2,
Column= 7
Sequence isn't always in row. It can be in column to. For example:
3,2,4,3 and I ned to know location of number 4.
I know how to search one number in one dimensional array but in this case I don't have solution.
Language is C.
You can compare blocks using memcmp:
for (i = 0; i < rows; i++) { /* For each row */
for (j = 0; j < cols - size; j++) { /* For each col until cols - 4 */
if (memcmp(A, &B[i][j], sizeof(A)) == 0) { /* Compare entire block */
#include <stdio.h>
#include <string.h>
int main(void)
{
int A[4] = {6,3,3,2};
int B[10][18] = {
{5,3,6,5,6,1,6,1,4,4,5,4,4,6,3,3,1,3},
{6,2,3,6,3,3,2,4,3,1,5,5,3,4,4,1,6,5},
{6,4,3,1,6,2,2,5,3,4,3,2,6,4,5,5,1,4},
{5,3,5,6,6,4,3,2,6,5,1,2,5,6,5,2,3,1},
{1,2,5,2,6,3,1,5,4,6,4,4,4,2,2,2,3,3},
{4,1,4,2,3,2,3,6,4,1,6,2,3,4,4,1,1,4},
{5,3,3,2,6,2,5,2,3,1,2,6,5,1,6,4,1,3},
{4,5,2,1,2,5,2,6,4,3,3,2,3,3,3,1,5,1},
{1,3,5,5,2,1,3,3,3,1,3,3,6,3,3,3,6,5},
{4,5,2,4,2,3,4,2,5,6,5,2,6,3,5,4,5,2}
};
size_t i, j, size, rows, cols;
int founded = 0;
size = sizeof(A) / sizeof(A[0]);
rows = sizeof(B) / sizeof(B[0]);
cols = sizeof(B[0]) / sizeof(B[0][0]);
for (i = 0; i < rows; i++) {
for (j = 0; j < cols - size; j++) {
if (memcmp(A, &B[i][j], sizeof(A)) == 0) {
founded = 1;
break;
}
}
if (founded) break;
}
if (founded) printf("Row: %zu Col: %zu\n", i + 1, j + size);
return 0;
}
The problem is not the language. The problem you face is you need to come out with the algorithm first.
Actually this can be easily done by just looking at the first number of the 1D array. In your example it is 6 from (6,3,3,2).
Look for 6 in your 2D array.
Once 6 is found use a loop which loop 4 times (because there are 4 numbers to look for - (6,3,3,2).
In the loop, check whether the subsequent numbers are 3,3,2.
If it is, return the location
Else continue the process to look for 6.
Done!
It will look like this:
for(x=0; x<rows; x++)
for(y=0; y<cols; y++)
{
if(matrix[x][y] == array1D[0])
for(z=1; z<array1DSize; z++){
if(matrix[x][y] != array1D[z])
break;
location = y;
}
}
If you know how to do it with a one dimensional array, you can do it like that in C with multidimensional arrays too!
For instance, say you have a two dimensional array like so:
int array[5][5]; // 5x5 array of ints
You can actually access it in linear fashion, by doing:
(*array)[linear offset]
So that means if you want to access the 2nd column of the 2nd row, you can do:
(*array)[6]
Because the 2nd row starts at index 5, and the second column is at index 1, so you would do (5+1) to get 6. Likewise, the 3rd row would start at index 10, so if you wanted the 2nd column in the third row, you can do (10+1).
Knowing that, you can take your original algorithm and adapt it to access the multidimensional array in a linear fashion. This takes place of the "wrap around" possibility as well.

Resources