Counting pixels using recursion - c

I have a problem where I need to count the number of 1's in a 2D array that is randomly generated. First the user puts in the size of the 2D array through the command line arguments, and then the user puts in the coordinates to see if there are 1's in the coordinates he put in. If the coordinate happen to land in 0, it is supposed to return 0. Otherwise if the inputted coordinate lands on a 1, then I am supposed to recursively check up, top right, right, bottom right, bottom, bottom left, left, and top left.
The main problem I am having is that I don't know if I can even read in one 1 from the array. I have no idea what to put into my recursive method parameters. I have my array pointer, xcoord, ycoord which are what the user puts in and row and col which are supposed to be command line arguments.
I think everything else works, but I could be wrong. I tried this recursive formula.
if(arr[row][col] == 1)
{
recursive(arr, xcoord-1, ycoord, row, col);
blobsize = blobsize + 1;
//more recursive things down here...
}
to check up but it didn't do anything.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
int recursive(int **arr, int xcoord, int ycoord, int row, int col);//What are the arguments for the recursive function?
int main(int argc, char** argv)
{
int i;//counters
int j;//counters
int xcoord;//x coordinate input
int ycoord;//y coordinate input
//random number generator thing idk lol
srand((unsigned int)time(NULL));
int row = strtol(argv[1], NULL, 0);//ROW from command line arguments (1st number)
int col = strtol(argv[2], NULL, 0);//COL from command line arguments (2nd number)
int *arrStorage = malloc(row * col * sizeof(int));//dynamically allocating memory for 2d array
int **arr = malloc(row * sizeof(int*)); //pointer to pointer to array or whatever
//intializing array
for (i = 0; i < row; i++)
{
arr[i] = arrStorage + col * i;
}
//printing out 2d array
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
arr[i][j] = rand() % 2;
printf("%d\t", arr[i][j]);
}
printf("\n");
}
printf(" ");
//Exit the function when non number is entered
//Otherwise continue
while(1)
{
printf("Enter coordinate i,j (Non numeric to quit) \n");
if(1!=scanf("%d", &xcoord) || 1!=scanf("%d", &ycoord))
{
return 0;
}
printf("Blob size: %d\n", recursive(arr, xcoord, ycoord, row, col));
}
free(arr[0]);
free(arr);
}
int recursive(int **arr, int xcoord, int ycoord, int row, int col)
{
int blobsize = 0;
//This is outside the bounds (BASE CASE)
if(xcoord > row && ycoord > col)
{
return 0;
}
//If the selected xcoord & ycoord is 0
if(arr[xcoord][ycoord] == 0)
{
return 0;
}
else
{
if((arr[xcoord][ycoord]==1))
{
//blobsize = blobsize + 1;
//recursive(arr, xcoord - 1, ycoord, row, col);
}
else
{
}
}
return blobsize;
}
Thanks if you can help
EDIT: Fixed one critical part. Now to die over figuring out the recursion part.

OP was printing a random number, yet not assigning the number to the array.
Simply assign the value and then print.
// printf("%d\t", rand() % 2);
arr[i][j] = rand() % 2;
printf("%d\t", arr[i][j]);

Related

Function changes variables not involved in the function (in c)

So I'm trying to make a program to row reduce a matrix (there are probably a thousand way better ways to do it but I'm trying to figure it out on my own). I have a function that is supposed to make two rows of different arrays equal. It doesn't even take the row variable as an input or have anything to do with it but for some reason after the function is called the row variable switches from whatever was put into the keyboard to 1072693248. I also just noticed a problem with the col variable where it is set to 0 the second time the for loop it is in happens. I have no clue what is causing these problems so any help would be really appreciated. I'm just going to post the entire code since I'm not sure which part is causing the problem (its probably super messy, my only coding experience is one super basic beginner course in c in university). (I put in some printfs to print row or col in different spots to try and find out where the problem was happening).
#include <stdlib.h>
void printArray(double a[][100], int rows, int columns);
void addRow(double a[][100], int columns, int rowToAdd, int rowAddedTo);
void addRowBetweenArrays(double arrayAddedTo[][100],double arrayAdded[][100], int columns, int rowToAdd, int rowAddedTo);
void multiplyRow(double a[][100], int columns, int rowMultiplied, double mupltiplyBy);
void switchRows(double a[][100], int columns, int rowOne, int rowTwo);
//void makeRowsEqual(double rowMadeEqual[][100], double madeEqualTo[][100], int rowInMadeEqualTo, int RowInMadeEqual, int columns);
void makeTwoArraysRowsEqual(double arrayMadeEqual[][100], double arrayMadeEqualTo[][100], int rowMadeEqual, int rowMadeEqualTo, int column);
int main()
{
int row, col, i, j, checkReduced, rowIsReduced = 0, focus;
double multiplyFactor;
printf("Enter the size of your array (rows columns): ");
scanf("%d %d", &row, &col);
double array[row][100];
double tempRow[1][100];
for(j = 0; j < row; j++)
{
printf("Enter row %d: ", j + 1);
for(i = 0; i < col; i++)
{
scanf("%lf", &array[j][i]);
}
printf("\n");
}
printf("\n\nUnreduced array:\n");
printArray(array, row, col);
//start the reducing
for(focus = 0; focus < row; focus++)
{
rowIsReduced = 0;
for(i = 0; i < col; i++)
{
if(i == focus)
{
i++;
}
if(array[i][focus] != 0)
{
rowIsReduced = 1;
}
}
if(rowIsReduced == 1)
{
//now start the reducing process
for(i = 0; i < row; i++)
{
printf("\n%d\n", row);
if(i == focus)
{
i++;
}
//skip the row we are focusing on
//first check if we even need to manipulate the row
if(array[i][focus] != 0)
{
if(array[focus][focus] * array[i][focus] > 0)
{
printf("\n%d\n", row);
//then check if we need to add or subtract
//make temp row equal to focus row
printf("Column before function: %d", col);
makeTwoArraysRowsEqual(tempRow, array, 1, focus, col);
// to check order: makeTwoArraysRowsEqual(double arrayMadeEqual[][100], double arrayMadeEqualTo[][100], int rowMadeEqual, int rowMadeEqualTo, int column)
printf("\nAfter make rows equal: %d\n", row);
//now multiply both rows
multiplyFactor = array[i][focus];
multiplyRow(tempRow, col, 1, multiplyFactor);//getting stuck here
//multiplyRow(double a[][100], int columns, int rowMultiplied, double mupltiplyBy);
multiplyFactor = -1 * array[focus][focus];
multiplyRow(array, col, i, multiplyFactor);
//then add them
addRowBetweenArrays(array, tempRow, col, 1, i);
printf("Made it to end of the loop");
}
else //could also use: if(array[focus][focus] * array[i][focus] < 0)
{
//then check if we need to add or subtract
//make temp row equal to focus row
//makeRowsEqual(tempRow, array, focus, 1, col); need to switch this to new format
//now multiply both rows
multiplyRow(tempRow, col, 1, array[i][focus]);
multiplyRow(array, col, i, array[focus][focus]);
//then add them
addRowBetweenArrays(array, tempRow, col, 1, i);
}
//now the rows are added so there is a zero in the focus column
//will need to check if any rows are zero and move them to the bottom, have to figure that out
//will also need to divide all the rows by their first non zero term
}
printf("\n%d\n", row);//rows are acting weird, getting to be a really big number after the first run
}
printf("Made it out of i loop");
}
}
printf("\n\Reduced array:\n");
printArray(array, row, col);
return 0;
}
void printArray(double a[][100], int rows, int columns)
{
int i, j;
for(j = 0; j < rows; j++)
{
for(i = 0; i < columns; i++)
{
printf("%6.2lf ", a[j][i]);
}
printf("\n");
}
}
void addRow(double a[][100], int columns, int rowToAdd, int rowAddedTo)
{
int i;
for(i = 0; i < columns; i++)
{
a[rowAddedTo][i] += a[rowToAdd][i];
}
return 0;
}
void addRowBetweenArrays(double arrayAddedTo[][100],double arrayAdded[][100], int columns, int rowToAdd, int rowAddedTo)
{
int i;
for(i = 0; i < columns; i++)
{
arrayAddedTo[rowAddedTo][i] += arrayAdded[rowToAdd][i];
}
}
void multiplyRow(double a[][100], int columns, int rowMultiplied, double mupltiplyBy)
{
int i;
for(i = 0; i < columns; i++)
{
a[rowMultiplied][i] *= mupltiplyBy;
}
}
void switchRows(double a[][100], int columns, int rowOne, int rowTwo)
{
int i, temp;
for(i = 0; i < columns; i++)
{
temp = a[rowOne][i];
a[rowOne][i] = a[rowTwo][i];
a[rowTwo][i] = temp;
}
}
/*
void makeRowsEqual(double rowMadeEqual[][100], double madeEqualTo[][100], int rowInMadeEqualTo, int rowInMadeEqual, int columns)
{
int i;
printf("In function: made = to: %d, made =: %d", rowInMadeEqualTo, rowInMadeEqual);
for(i = 0; i < columns; i++) {
rowMadeEqual[rowInMadeEqual][i] = madeEqualTo[rowInMadeEqualTo][i];
}
printf("\nMade equal:\n");
printArray(rowMadeEqual, 1, columns);
printf("\nMade equal to:\n");
printArray(madeEqualTo, 2, columns);
}*/
void makeTwoArraysRowsEqual(double arrayMadeEqual[][100], double arrayMadeEqualTo[][100], int rowMadeEqual, int rowMadeEqualTo, int column)
{
int i;
for(i = 0; i < column; i++) {
arrayMadeEqual[rowMadeEqual][i] = arrayMadeEqualTo[rowMadeEqualTo][i];
}
printf("Column in function: %d", column);
}
Here is a sample output:
Enter the size of your array (rows columns): 2 2
Enter row 1: 1
2
Enter row 2: 2
4
Unreduced array:
1.00 2.00
2.00 4.00
2
2
Column before function: 2Column in function: 2
After make rows equal: 1072693248
Made it to end of the loop
1072693248
1072693248
1072693248
Column before function: 0Column in function: 0
After make rows equal: 1072693248
Made it to end of the loop
1072693248
1072693248
1072693248
Column before function: 0Column in function: 0
After make rows equal: 1072693248
Made it to end of the loop
1072693248
1072693248
Process returned -1073741819 (0xC0000005) execution time : 3.808 s
Press any key to continue.
P.S. Sorry if this question is formatted poorly or something, this is my first question and I've hardly used stack overflow as of right now.
The problem is this line:
makeTwoArraysRowsEqual(tempRow, array, 1, focus, col);
The third argument is used as the row index in tempRow to copy to. tempRow is declared:
double tempRow[1][100];
Since it only has 1 row, the highest row index is 0, but you're copying to row 1, which is outside the array, resulting in undefined behavior.
You should use row index 0:
makeTwoArraysRowsEqual(tempRow, array, 0, focus, col);
You have similar problems in the calls to other functions that use tempRow. They all pass 1 when it should be 0.
It's not clear why tempRow even needs to be 2-dimensional, since it only has one row. Just make it a 1-dimensional array, and remove the row index from all the functions that use it.

Multiply a line of a matrix by a number given

I'm supposed to multiply a certain line (I specify what line exactly in the 4th argument of the function) of a given matrix by a number.
The main function:
int main_tp05(int argc, const char *argv[]){
int mNx100[][MAXCOLS100] = {{1,2,3},{4,5,6},{7,8,9}};
multiply_matrixNx100_line_by_scalar(mNx100,3,3,1,2);
return 0;
}
I've tried to solve it like so:
void multiply_matrixNx100_line_by_scalar(int mNx100[][MAXCOLS100], int lines, int columns, int line, int scalar){
for (int i = 0; i < lines; i++) {
for (int j = 0; j < columns; j++) {
if(i == line){
printf("%d\n", mNx100[i*scalar][j] );
}
}
printf("\n");
}
}
To note that:
1- I can´t change the parameters.
2- MAXCOLS100 is a macro on the .h file. I put it with the value of 3.
3- The scalar is the number I want to multiply the line by.
I WROTE THIS CODING AND VERIFIED BY MYSELF IT WORKS SUCCESSFULLY.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j,a[5][5],b,c,d,m,n,r;
printf("Enter the number of rows and columns\n");
scanf("%d %d",&m,&n);
printf("Enter the matrix\n");
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the number to multiply the matrix\n");
scanf("%d",&b);
printf("Enter 0 to multiply row or 1 to multiply column\n");
scanf("%d",&d);
if(d==0)
{
printf("Enter the row number to be multiplied\n");
scanf("%d",&r);
for(i=r,j=1;j<=n;j++)
{
a[i][j]*=b;
}
}
else if(d==1)
{
printf("Enter the row number to be multiplied\n");
scanf("%d",&c);
for(j=c,i=1;i<=m;i++)
{
a[i][j]*=b;
}
}
printf("matrix after multiplied\n");
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
return 0;
}
OUTPUT OF THIS CODING
I'm supposed to multiply a certain line (I specify what line exactly in the 4th argument of the function) of a given matrix by a number
Usually, "multiply a row of a matrix by a scalar" means to multiply every element of the row by a certain scalar value. That's not what the posted function does, it multiplies the index of the row by the passed argument:
void multiply_matrixNx100_line_by_scalar(int mNx100[][MAXCOLS100], int lines, int columns,
int line, int scalar) {
for (int i = 0; i < lines; i++) { // <-- Useless, the row is known
for (int j = 0; j < columns; j++) {
if(i == line){
printf("%d\n", mNx100[i*scalar][j] );
// ^^^^^^^^
}
}
printf("\n");
}
}
If the intent is to only print the modified row, the previous function could be rewritten as
void multiply_matrixNx100_line_by_scalar(int mNx100[][MAXCOLS100], int lines, int columns,
int line, int scalar) {
if (line < 0 || line >= lines)
return;
for (int j = 0; j < columns; j++) {
printf("%d\n", mNx100[line][j] * scalar);
}
printf("\n");
}
If instead the function is supposed to only modify the matrix, without printing it, we could use
mNx100[line][j] *= scalar;
Inside the loop, in place of the call to printf.

While loop with user input validation to fill array, then search array for largest number.

I am working on a program that will accept user input to fill an array and then quit when the user enters q. Next the array is passed to a function that finds the largest value in the array. My program seems like it would work, but I believe that user input for the array is incorrect and I am not sure how to solve it.
#include <stdio.h>
#define SIZE 30
int maxnum(int userarray[], int maxx);
int main()
{
int i;
int nums[SIZE];
int largest;
printf("Type integer numbers (up to 30), followed by q to quit:\n");
while(scanf("%d", &nums[i]) == 1)
{
for(i = 0; i < SIZE; i++)
{
//blank
}
}
largest = maxnum(nums, SIZE);
printf("The largest number is: %d\n", largest);
return 0;
}
int maxnum(int userarray[], int maxx)
{
int i;
int maxnumber;
maxnumber = userarray[0];
for(i = 1; i < maxx; i++)
{
if(maxnumber < userarray[i])
{
maxnumber = userarray[i];
}
}
return maxnumber;
}
First i is unitialized.
Then your inner for loop is strange (why someone would do that??) and sets i to SIZE in the end, which is not good.
I don't give more details, but the value of i is trash all the time because of those 2 mistakes it should be:
int i = 0;
while((i<SIZE) && (scanf("%d", &nums[i]) == 1))
{
i++;
}
so you read one by one, and protect against array out of bounds by the second condition.
After that you're passing NUMS
largest = maxnum(nums, SIZE);
whereas the array could contain fewer valid values. Just pass
largest = maxnum(nums, i);
Here is another solution for your problem.
In main() function
int n,i=0;
while(scanf("%d",&n) == 1){
nums[i++] = n;
}
n = maxnum(nums, i);
printf("The largest number is: %d\n", n);
Note : Initialize the value of i=0, Then input and update nums[] array
In maxnum() function
for(i = 0; i < maxx; i++) {
if(maxnumber < userarray[i]){
maxnumber = userarray[i];
}
}
Note: Start i=0 and find the max mumber and return the value

How to create a 2d array, the dimensions of which are specified by the user? (in C)

Here is my try. I am not totally sure about my manipulations with the pointer. Maybe this is why I am wrong, maybe there is some other case. I want to take the dimensions from the user and create a square matrix, make some manipulations with its elements, and display the original and results to the user. Last time I accomplished this by creating a 100x100 array, and specifying the end of each line, and end of lines by constants. Then I would print all the elements up to this constant. But it does not seem to be right to create a 100x100 array for 4x4 matrices. I could create a smaller array, but this does not seem to be the right solution to the problem. Is there a way in C to create a 2d array exactly the size specified by the users (it will be a square array). Thanks
#include <stdio.h>
#include <stdlib.h>
double * createMatrix(int dimentions);
void drawMatrix(double * matrix);
int main(void)
{
int n, i, j;
system("cls");
system("color 70");
system("pause");
puts("Enter the matrix's dimension");
scanf("%i", &n);
double * pmatrix = createMatrix(n);
for (i = 0; i < n; ++j)
for (j = 0; j < n; ++j)
{
printf("A%i%i: ", i + 1, j + 1);
scanf("%lf", pmatrix[i][j]);
getchar();
}
for (i = 0; i < n; ++i)
{
putchar('\n');
for (j = 0; j < n; ++j)
printf(" %lf ", &pmatrix[i][j]);
}
system("color 08");
return 0;
}
double * createMatrix(int n)
{
const int N = n;
const int N1 = N;
double matrix[N][N];
double * pmatrix = matrix;
return pmatrix;
}
You can create a matrix directly; you don't need a function for that. Replace the code
double * pmatrix = createMatrix(n);
by the regular way of declaring a 2-D array:
double matrix[n][n];
One more way of doing it using pointers.
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
double **pmatrix;
int rowsize, colsize, i, j;
printf("Enter the number of rows: ");
scanf("%d",&rowsize);
printf("Enter the number of columns: ");
scanf("%d",&colsize);
//Allocate memory for 2D array
pmatrix = malloc(rowsize*sizeof(double*));
for(i=0;i<rowsize;i++)
{
pmatrix[i] = malloc(colsize*sizeof(int));
}
//Accepting the values
for(i=0;i<rowsize;i++)
{
for(j=0;j<colsize;j++)
{
printf("A %i %i: ", i + 1, j + 1);
scanf("%lf",&pmatrix[i][j]);
}
}
//Printing the values
for(i=0;i<rowsize;i++)
{
for(j=0;j<colsize;j++)
{
printf("%lf\t",pmatrix[i][j]);
}
printf("\n");
}
//Free the memory
for(i=0;i<rowsize;i++)
free(pmatrix[i]);
free(pmatrix);
return 0;
}

C program — coding the figure given n when n is odd?

I have to display the following figure (The two triangles intercept) for a n given by the user, where n is odd. The figure is in this link: http://i.imgur.com/mQxarLz.jpg
*******
*****
***
*
*
***
*****
*******
I already wrote this code, but I don't know how to give the n, where n is odd. And my code doesn't compile; it says: "In the fifth row, syntax error before for".
#include <stdio.h>
int main (void) {
int n,i,k,m;
for(m=0;m<2;m++)
for (i=1;i<=n;i++){
if(m==0){
for(k = 1; k<=n-i; k++){
printf(" ");
}
}
}
for (k=1;k<2*i;k++){
printf("%s","*");
//printf("%d",i);
}
scanf("%d",&n);
for (k = 1; k<=i;k++)
for (k=1;k<(n-i)*2;k++)
for (i=1;i<=n;i++) {
printf("\n$");
}
return 0;
}
First, the answer to "how do I check whether an integer is odd": you simply divide by 2 and check if the remainder is 0 (even) or 1 (odd). In C and most related languages, this is what the modulo operator "%" does:
if ((n % 2) == 1) {
// The number is odd.
}
But you should make sure that you read your n right at the start, because in the code that you have submitted, n is read in your second "for" loop before you have actually written something to it. And that means, n contains garbage at that point.
Good programming is to solve problems in the most simple way you can find. This particular algorithm is really fundamental stuff, thus you shouldn't end up with anything much more complicated than this:
#include <stdio.h>
#include <stdbool.h>
void print_chars (char symbol, int n)
{
for(int i=0; i<n; i++)
{
printf("%c", symbol);
}
}
void print_triangle (int base_size, int height, bool pointing_up)
{
int star_count = pointing_up ? 1 : base_size;
for(int row = 0; row < height; row++)
{
int spaces = base_size - star_count;
print_chars (' ', spaces/2);
print_chars ('*', star_count);
print_chars (' ', spaces/2);
printf("%\n");
star_count += pointing_up ? 2 : -2;
}
}
int main (void)
{
print_triangle(7, 4, false);
print_triangle(7, 4, true);
}
Note that the above code will behave strange if the triangle's base isn't in sync with its height - I left that out intentionally, feel free to improve the program further with such.
#include <stdio.h>
void printAsterisk(int n, int length){
int i, slen = (length - n)/2;
for(i=0;i < slen;++i)
putchar(' ');
for(i=0;i < n;++i)
putchar('*');
putchar('\n');
}
/* non-recursive
void printTriangle(int n, int length){//n isn't required as an argument
int d= -2;
for(; n < length + 1; n += d){
if(n < 0) n += (d *= -1);
printAsterisk(n, length);
}
}
*/
void printTriangle(int n, int length){
if(n < 1) return;
printAsterisk(n, length);
printTriangle(n - 2, length);
printAsterisk(n, length);
}
int main(void){
int n;
do{
printf("input odd number:");
scanf("%d", &n);
}while(n % 2 == 0);
printTriangle(n, n);
return 0;
}

Resources