Not giving the right output - c

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.

Related

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.

Arduino C Multi dimensional array switching

Im stuck with a piece of my Arduino code
Basically I have a multi dimensional array in which every index will store a random letter. But after a small time (eg. 900 milliseconds) every value in the index will move up to the index above it. Ofcourse when the index reaches e.g. [9][0] it will go to the largest index like [9][9]
E.g.: myArray[9][8] contains "K" and myArray[9][7] contains "L"
The "K" in myArray[9][8] will be put in myArray[9][7] and the "L" in myArray[9][7] will go to myArray[9][6] etc. etc
But I have no clue how to do this in C...
myArray[9][8] = myArray[9][7] obviously wouldnt work
There is not problem with assignment, but you must save the element you are writing over first.
In this example all the rewritten values are kept in the last slot of every row, this is just an example- not the only way to go, if you need to move the letters across the rows as well the idea is similar.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void moveLettersInRow(char sArr[][3], int row)
{
int i = 0;
int j = 0;
char temp ;
for (i = 0; i < row; ++i)
{
for(j = 2 ;j > 0;--j)
{
temp = sArr[i][j-1]; /*save the value to be rewritten */
sArr[i][j-1]= sArr[i][2]; /* set the last val in its new place*/
sArr[i][2]= temp; /* set the last elem to the latest rewritten value*/
}
}
}
void printArr(char arr[][3], int size)
{
int i = 0, j= 0;
for(i = 0; i< size; ++i)
{
for(j = 0; j< 3; ++j)
{
printf("%c | ", arr[i][j]);
}
printf("\n");
}
}
int main()
{
char arr[2][3]= {{'a','b','c'},{'a','b','c'}};
moveLettersInRow(arr, 2);
printArr(arr, 2);
return 0;
}
There are several ways to go about this. One would be to use a temporary variable while copying, as Kami Cuk and Fred pointed out.
Another way, which would avoid copying the values, would be to index the array using a modulo operation while reading the array.
myArray[9][(index + offset) % numberOfElementsInArray]
index and offset should both be positive integers.
numberOfElementsInArray is the number of elements in myArray[9]
To get a -1 offset with a positive integer, set offset to numberOfElementsInArray - 1

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).

Array of structure changes the contents itself

I am currently working on a simple code to store and display top-right triangular matrix. Well, everything was fine till I tried to input 4x4 matrix structure and gave the input. The first array of structure's (called a) last value changed although I did not put any code to change ANY of the values in a. It happens in the mReorder() function. Then I tried some try-and-errors find out the problem in the 3rd row of mReorder() function. I wonder why and how to solve it.
Here is my complete code:
#include<stdio.h>
//CMO fashion
typedef struct
{
int row;
int col;
int val;
}term;
#define MAX_TERMS 10
term a[MAX_TERMS], b[MAX_TERMS];
void mReorder(void);
int main()
{
int n, i, j;
printf("Enter the number of rows: ");
scanf("%d", &n);
if (n<1 || n>MAX_TERMS)
{
printf("\nInvalid number of rows!!");
exit(0);
}
i=nCount(n);
mRead(n,i);
for (j=0; j<i+1; j++) printf("\n%d\t%d\t%d", a[j].col, a[j].row, a[j].val);
mReorder();
for (j=0; j<i+1; j++) printf("\n%d\t%d\t%d", a[j].col, a[j].row, a[j].val);
printf("\n");
for (j=0; j<i+1; j++) printf("\n%d\t%d\t%d", b[j].col, b[j].row, b[j].val);
mDisplay();
return 0;
}
void mReorder(void)
{
int i, j, k, m=1;
b[0].col=a[0].col;
b[0].row=a[0].row;
b[0].val=a[0].val;
for(i=0; i<a[0].col; i++)
for (j=1; j<=a[0].val; j++)
if (a[j].row==i)
{
b[m].col=a[j].col;
b[m].row=a[j].row;
b[m].val=a[j].val;
m++;
}
}
void mDisplay(void)
{
int i, j, k, m=1;
printf("\nThe resulting matrix is:\n");
for (i=0; i<b[0].col; i++)
{
//printf("\na");
for (k=0; k<i; k++) printf("%5c", '-');
for (j=i; j<b[0].col; j++)
{
printf("%5d", b[m].val);
m++;
}
printf("\n");
}
}
void mRead(int n, int x)
{
int i, j, m=1, val;
printf("\nEnter %d elements of the matrix: \n", x);
a[0].row=a[0].col=n;
a[0].val=x;
for (i=0; i<n; i++)
{
for (j=0; j<=i; j++)
{
scanf("%d", &val);
a[m].row=j;
a[m].col=i;
a[m].val=val;
m++;
}
}
}
int nCount(int n)
{
if (n==1)
return 1;
return (n+nCount(n-1));
}
Can you explain what's going on here?
You allocate enough space for 10 term items, but nCount(4) returns 10, and nCount(5) returns 15, etc. If you specify a value bigger than 4, you overflow your array boundaries, leading to undefined behaviour — which is something to be avoided at all costs. In practice, one of your two arrays tramples over the other, but what happens when you access the other array out of bounds is entirely up to the compiler. It may appear to work; it may crash horribly; it may corrupt other data structures.
Nominally, since you allocate 10 elements in the arrays a and b, you should be OK with the 4x4 data, but in mRead(), you set m = 1 to start with, so you end up writing to a[10] in the last iteration of the loop, which is outside the bounds of the array. Remember, C arrays are indexed from 0, so an array defined as SomeType array[N]; has elements from array[0] to array[N-1].
Note that you can rewrite nCount() as a simple (non-recursive) function:
static inline int nCount(int n) { return (n + 1) * n / 2; }
(which would need to appear before it is called, of course). Or, if you're stuck using an archaic compiler that doesn't support C99 or C11, drop the inline keyword.

Sorting 2d matrix cols and rows in C

Given set two - dimensional integers. The array consists of 5 rows and 10 columns.
Each value in the system is a random number between 0 and 20.
Have to write a program that performs the sorting of the array values as follows:
First there arrange the values in each column so that they are sorted in ascending order (top to bottom), then - so there can sort the columns right "comes right" by comparing pairs of values in different columns in the same row (a "comparison lexicography"): comparing two values ​​in two columns in the first row, if they are the same compared to the values in the second row, and so on, and accordingly change the order of columns (see example in the third printing of the array, below).
To display the array before sorting and after each of the two phases of the emergency.
for example :
I stuck with the sorting of the each cols. I don't get the sorting i want. I would like to get your help please.
This is my code:
#include "stdio.h"
#include "conio.h"
#include "malloc.h"
#include "stdlib.h"
#define N 5
#define M 10
#define LOW 0
#define HIGH 20
void initRandomArray(int arr[N][M]);
void printArray(int arr[N][M]);
void SortInColumn(int arr[N][M],int m);
int main()
{
int arr[N][M];
int m;
m=M;
srand((unsigned)time(NULL)); //To clear the stack of Random Number
initRandomArray(arr);
printf("Before sorting:\n");
printArray(arr);
printf("Sorting elements in each column:\n");
SortInColumn(arr,M);
system("pause");
return 0;
}
void initRandomArray(int arr[N][M])
{
int i,j;
for (i=0 ; i<N ; i++)
for (j=0 ; j<M ; j++)
{
arr[i][j]=LOW+rand()%(HIGH-LOW+1);
}
}
void printArray(int arr[N][M])
{
int i,j;
for (i=0 ; i<N ; i++)
{
for (j=0 ; j<M ; j++)
printf("%d ", arr[i][j]);
printf("\n");
}
}
void SortInColumn(int arr[][M],int m)
{
int i,j;
int temp;
for( i=m-1 ; i>=0 ; i--)
{
for(j=0; j<N-1; j++)
if (arr[i][j]>arr[i][j+1]) // compare adjacent item
{
temp=arr[i][j];
arr[i][j]=arr[i][j+1];
arr[i][j+1]=temp;
}
}
for (i=0 ; i<N ; i++)
{
for (j=0 ; j<M ; j++)
printf("%d ", arr[i][j]);
printf("\n");
}
}
This is mine, and it runs and gives the correct answer.
Basically, you did two things wrong.
you need three loops instead of two. The outer loop loops around each columns. the second loop makes sure you compare each column N-1 times since for each run you get one item in the right place. The inner loop do the adjacent comparison.
you need to change the comparison between arr[i][k] and arr[i][k+1] to arr[i][k] to arr[i+1][k]. Because you want to compare them in the same column, you hold the value k (column) unchanged and change the rows i.
void SortInColumn(int arr[][M],int m)
{
int i,j,k;
int temp;
for( k=0 ; k<m ; ++k)
{
for(j=0; j<N-1; j++)
{
for(i=0; i < N-1 - j; i++)
{
if (arr[i][k]>arr[i+1][k]) // compare adjacent item
{
temp=arr[i][k];
arr[i][k]=arr[i+1][k];
arr[i+1][k]=temp;
}
}
}
}
}
BTW, this algorithm is very bad in performance in general. You may want to try something else.
Let's look at your SortInColum function. I've changed the formatting to get a better understanding of what's going on, and renamed some variables.
void SortInColumn(int arr[][M],int m)
{
int row,col;
int temp;
for( row=m-1 ; row>=0 ; row--) // foreach row
{
for(col=0; col<N-1; col++) { // foreach column
if (arr[row][col]>arr[row][col+1]) { // comparing adjacent entries
// in different cols? Why?
temp=arr[row][col];
arr[row][col]=arr[row][col+1];
arr[row][j+1]=temp;
}
}
printArray(arr);
}
This function (given some changes) will sorts a single column, you can then call this for each column. Hopefully this gives you a good starting point.

Resources