Multiply a line of a matrix by a number given - c

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.

Related

Got stuck in a customizable dimensional matrix operation program

`
//MATRIX INPUT
#include<stdio.h>
int main(void)
{
//declaring variables
size_t row=0;
size_t column=0;
int limit=0;
int en=0;
int mat[row][column];
//starting
printf("ENTRE THE NUMBER OF R
EPETITIONS OF MATRIX
INPUT:");
scanf("%d",&limit);
//starting loop
for(int i=0;i<=(limit-1);++i)
{
printf("\nINITIALIZED THE
MATRIX-%d...\n",i+1);
printf("\nENTER ROW
NUMBER FOR MATRIX:\n");
scanf("%d",&row);
printf("\nENTER COLUMN
NUMBER FOR MATRIX:\n");
scanf("%d",&column);
//entering the entries..
for(int j=0; j<row ;++j)
{
for(int k=0;
k<column;++k)
{
printf("ENTRY (%d,%d):",(j+1),(k+1));
scanf("%d",&mat[k][j]);
}
}
}
//starting the console output
of matrix
int v=0;
printf("Which matrix do you
want to see?\n");
scanf("%d",&v);
for(v=0; v<=limit; ++v)
{
for(int l=0; l<row; ++l)
{
for( int m=0; m<column;
++m)
{
printf("%2d", mat[m][l]);
}
}
}
return 0;
}`
I have written a program in C where the user can firstly define the number of matrices. Then, the dimension of individual matrix is defined. I have successfully proceeded to individual matrix input. But I am stuck in writing the operational codes like multiplying and adding matrices as well as to write code for showing output in matrix style.
How to fix this?
incomplete source code
Console of output
I couldn't get the part why you created an empty static array, and then changed its boundaries at least tried to change. However, I believe dynamic array allocation would serve your purpose better than static one. I implemented a 3D array that has the first index as matrices, the second index as rows of the current matrix, and the third index as columns of the current matrix. Also, fixed the display method, you have been using. However, there can be different-sized matrices for each matrix you have. Therefore, I implemented another list to keep track of the rows and columns. Lastly, I put two links at the top of the code that you can implement addition and multiplication operations by yourself. You can see the code from here:
//MATRIX INPUT
#include<stdio.h>
#include<stdlib.h>
//Add two matrices
//https://www.programmingsimplified.com/c-program-add-matrices
//Multiplying two matrices
//https://www.programiz.com/c-programming/examples/matrix-multiplication
void display_matrix(int** , int , int );
void fillWithNum(int**,int,int,int);
int main(void)
{
//declaring variables
size_t row=0;
size_t column=0;
int limit=0;
int en=0;
int ***mat;
//starting
printf("ENTRE THE NUMBER OF REPETITIONS OF MATRIX INPUT:");
scanf("%d",&limit);
mat = (int***)malloc(sizeof(int**) * limit);
//Two keep track of the rows and columns
//First index of the second dimension will be rows, and
//second index will be columns of matrices at the mat variable.
int **indexingList;
indexingList = (int**)malloc(sizeof(int*) * limit);
for(int i=0;i<limit;++i) {
indexingList = (int*) malloc(sizeof(int) * 2);
}
//starting loop
for(int i=0;i<limit;i++)
{
printf("\nINITIALIZED THE MATRIX-%d...\n",i+1);
printf("\nENTER ROW NUMBER FOR MATRIX:\n");
scanf("%d",&row);
printf("\nENTER COLUMN NUMBER FOR MATRIX:\n");
scanf("%d",&column);
mat[i] = (int**) malloc(row * sizeof(int*));
for (int j = 0;j < row;j++) {
mat[i][j] = (int*)malloc(column * sizeof(int));
}
//entering the entries..
for(int j=0;j < row;j++)
{
for(int k=0;k < column;k++)
{
printf("ENTRY (%d,%d):",(j+1),(k+1));
scanf("%d",&mat[i][j][k]);
}
}
indexingList[i][0] = row;
indexingList[i][1] = column;
}
//starting the console output of matrix
int v=1;
printf("Which matrix do you want to see?\n");
scanf("%d",&v);
//v-1 because if user want to display first matrix it should be 0, so user will enter 1
//therefore, 1-1 will give us 0 to display 0 index matrix
display_matrix(mat[v-1], indexingList[v-1][0], indexingList[v-1][1]);
//Problem at freeing memory for some purpose crash at here.
//I couldn't figure it out as well.
for(int i = 0;i < limit;i++) {
for(int j = 0;j < indexingList[i][0];j++) {
free(mat[i][j]);
}
free(mat[i]);
}
free(mat);
for(int i = 0;i < limit;i++) {
free(indexingList[i]);
}
free(indexingList);
return 0;
}
void display_matrix(int** matrix, int r, int c) {
for(int i = 0 ;i < r;i++){
for(int j = 0;j < c;j++) {
printf("%d\t",matrix[i][j]);
}
printf("\n");
}
}
//Test purpose
void fillWithNum(int** arr,int r, int c, int num) {
for (int i = 0;i<r;i++) {
for(int j = 0;j<c;j++) {
arr[i][j] = num;
}
}
}
However, this code also crashes at the end of the memory-freeing part. I couldn't figure out why, but if someone finds it out as well, I would appreciate it.

Adding the same number multiple times to an empty array in C

This is a piece of code to add the same number multiple times to an empty array but when I am printing the now non empty array, I am getting some other values:
#include<stdio.h>
#include<stdlib.h>
void sort_0(int arr[100], int i, int n){
int final_array[100], c=0;
// Count the number of '0' in the array
for(i=0;i<n;i++){
if(arr[i] == 0){
c++;
}
}
// Add the c number of '0' to the final_array
for(i=0;i<c;i++){
scanf("%d",final_array[i]);
}
for(i=0;i<c;i++){
printf("%d ", final_array[i]);
}
}
int main(){
int arr[100], i, n;
// Entering the size of the array
scanf("%d", &n);
// Entering n elements into the array
for(i=0;i<n;i++){
scanf("%d", &arr[i]);
}
sort_0(arr,i,n);
return 0;
}
In the above code, the number of times 0 appears in the array is counted. Then the count is taken as the range and 0 is adding to the empty array final_array count times.
If c = 5, the final_array = {0,0,0,0,0}
Expected Output:
arr = {0,1,4,3,0}
Output = 2
I am not getting any output
Since you don't know how much 0 you'll need to add to your array_final I figured out that a better solution could be to create that array after you have the number of 0 of the first array. Also, I see no reason why you were passsing i to the function since you can simply define it in the function itself.
void sort_0(int arr[10], int n, int* c){
int i;
for(i=0;i<n;i++){
if(arr[i] == 0){
(*c)+= 1;
}
}
}
int main (void) {
int size;
printf("Enter array size: ");
scanf("%d", &size);
int arr[size];
for (int i=0;i<size;i++) {
scanf("%d",&arr[i]);
}
int c = 0;
sort_0(arr, size, &c);
printf("C is: %d\n",c);
int* final_array;
if ((final_array=malloc(c * sizeof(int)))==NULL) // should always check malloc errors
{
perror("malloc");
return -1;
}
for (int i=0;i<c;i++) {
final_array[i]= 0;
}
printf("{");
for (int i=0;i<c-1;i++) {
printf("%d,", final_array[i]);
}
printf("%d}\n",final_array[c-1]);
return 0;
}

how to scan a 2d array using a function without deleting it's content

as a homework assignment, i need to scan N matrices and a user input integer, and scan if any of the matrices values contains that number
without using pointers.
as soon as i finish scanning the array and exits the function, the content of the array resets to zero, or trash if i dont init the array.
#pragma warning(disable:4996)
#include<stdio.h>
#define N 2
int exist(int matrix[][N], int elem);
void input_matrix(int matrix[][N], int size);
void main()
{
int matrix_1[][N] = { 0 }, matrix_2[][N] = { 0 }, matrix_3[][N] = { 0 };
int elem;
printf("please enter values of squared matrix:\n");
input_matrix(matrix_1[][N], N);
//(input_matrix(&matrix_2[N][N]));
// (input_matrix(&matrix_3[N][N]));
printf("please enter number to search for in the matrix:\n");
scanf("%d", &elem);
if (exist(matrix_1,elem))
//printf("exist.");//the next part of h.w to be written when input func works
}
void input_matrix(int matrix[][N], int size)//something here fishy
{
int i, j;
for (i = 0; i < size; i++)
{
for (j = 0; j < size; j++)
{
scanf("%d", &matrix[i][j]);
}
}
}
int exist(int matrix[][N], int elem)
{
int i, j;
int flag = 0;
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
if ((matrix[i][j]) == elem)
{
flag = 1;
break;
}
}
}
return flag;
}
Inside the main function, in the call input_matrix(matrix_1[][N], N) you pass the invalid parameter. Instead should pass the whole matrix, like input_matrix(matrix_1, N).
As noted in a comment, it will be better to declare matrix like matrix_1[N][N].

Error: CentralTendencies.exe has stopped working, upon clicking Build & Run in codeblocks

This code is to find the mean, median and mode for a given sequence of number.
#include <stdio.h>
#include <math.h>
int main()
{ /*Inputs*/
int n;
int a[n];
/*Outputs*/
float mean;
int median;
int mode;
printf("Enter the size of array: ");
scanf("%d",&n);
for(int i=0; i<n; i++)
{
printf("\nEnter the values of array: ");
scanf("%d",&a[i]);
}
/*arrange in ascending order */
int i=0;
for(i=0; i<n-1; i++)
{for(i=0; i<n-1; i++)
{
if(a[i]>a[i+1])
{
int temp = a[i+1];
a[i+1] = a[i];
a[i] = temp;
}
}
}
/*Mean of the series*/
for(i=0; i<n; i++)
{
int sum = 0;
sum = sum + a[i];
mean = sum/n;
}
/*Median of the series*/
I hope the syntax of typecasting here is right, right?
int m = floor((double)n/2);
if(n%2==0)
{
median = (a[m]+a[m-1])/2;
}
else
{
median = a[m];
}
/*Mode of the series*/
int count;
int b = 0;
for(i=0; i<n-1; i++)
{
for(int t=0; t<n; t++) //Compare a[i] with all the elements of the array
{if(a[i]==a[t])
{
count = 0;
count++;
}
if(b<count) //Update the new value of mode iff the frequency of one element is greater than that
{ // of its preceding element.
mode = a[i];
}
}
}
printf("The value of mean: %f",mean);
printf("\nThe value of mean: %d",median);
printf("\nThe value of mean: %d",mode);
return 0;
}
There were no errors in the code.
I received the following message on the prompt after "CentralT...... working":
Process returned -1073741571 (0xC00000FD) execution time : 47.686 s
Press any key to continue.
In C you cannot resize an array.
This line
int n;
defines n and leaves its value as garbage, a random value, perhaps 0.
Based on what ever n holds this line
int a[n];
defines a as array to have the number of element as per n now has.
Reading into n in this line
scanf("%d",&n);
does not change the number over a's elements.
To fix this, define a only after n has a well defined, valid value:
scanf("%d",&n);
int a[n];
To really make sure n had been set you want to test the outcome of scanf() like for example:
do {
if (1 != scanf("%d, &n))
{
puts("Bad input or failure reading n!\n");
continue;
}
} while (0);

How to add integers in from two 2d arrays into a new 2d array with specified length by user?

I am fairly new around here and this year is the first time I am learning c. I have run into a problem concerning 2D arrays and such. The question is: Write a program that finds the sum of two 2D matrixes.
I can do this fairly easily but there is a problem I'm running into. For example I'll give the first set of arrays a length of 3x3.
If my first 2D array and the second array has:
{1,2,3; 4,5,6; 7,8,9} (1st array)
{0,0,0; 0,0,0; 0,0,0} (2nd array)
I am also given a the number of rows and columns by user. (User inputs 3x2) then it should appear like
{1,2; 3,4; 5,6} (OUTPUT)
but I am getting
{1,2; 3,5; 6,8}
Another example
User inputs 2x4 OUTPUT should be {1,2,3,4; 5,6,7,8}
What am I doing wrong here?
#include <stdio.h>
#include <stdlib.h>
#define MAXROW 3
#define MAXCOL 3
int main() {
int ray1[MAXROW][MAXCOL], ray2[MAXROW][MAXCOL];
int r, c;
printf("Enter the number of ROWS: ");
scanf("%d", &r);
printf("Enter the number of COLUMNS: ");
scanf("%d", &c);
int sumRay[r][c];
printf("\n");
printf("Input integers for Array %d.\n", 1);
arrayIN(ray1);
printRay(ray1);
printf("Input integers for Array %d.\n", 2);
arrayIN(ray2);
printRay(ray2);
arraySUM(ray1, ray2, r, c, sumRay);
printSumRay(r, c, sumRay);
//printRay(sumRay);
}
void arrayIN(int ray[MAXROW][MAXCOL]) {
int r, c;
for (r = 0; r < MAXROW; r++) {
for (c = 0; c < MAXCOL; c++) {
printf("Enter Number for [ROW:%d COL:%d]: ", r, c);
scanf("%d", &ray[r][c]);
}
}
}
void arraySUM(int ray1[MAXROW][MAXCOL], int ray2[MAXROW][MAXCOL],
int r, int c, int sumRay[r][c]) {
int i, j;
int x, y;
i = j = 0;
int sum;
for (x = 0; x <= r; x++, i++) {
if (i < MAXROW) {
for (y = 0; y <= c; y++, j++) {
if (j < MAXCOL) {
sum = ray1[i][j] + ray2[i][j];
sumRay[x][y]= sum;
} else {
j = 0;
}
}
} else {
i = 0;
}
}
printf("\n");
}
void printSumRay(int r, int c, int sumRay[r][c]) {
int i, j;
for (i = 0; i < r; i++) {
printf("\n");
for (j = 0; j < c; j++) {
printf("%d\t", sumRay[i][j]);
}
}
}
void printRay(int ray[MAXROW][MAXCOL]) {
int i, j;
for (i = 0; i < 3; i++) {
printf("\n");
for (j = 0; j < 3; j++) {
printf("%d\t", ray[i][j]);
}
}
printf("\n");
}
First off, you need to put function prototypes before main(), or at least move the function definitions before main(). It is not at all clear to me why you use a VLA for sumRay[][], but arrays of constant dimensions for ray1[][] and ray2[][]. Unless you have a compelling reason for doing so, it will be better to use VLA's all around.
You should be using the size_t type for variables that hold array indices. The scanf() and printf() statements that handle the size_t variables must then be modified to use the %zu conversion specifier.
The arraySum() function iterates over two pairs of duplicate array indices for reasons which are unclear. The logic here is convoluted and overly complex. The spurious output that you reported can be traced to this function; it is difficult to read and understand, which should be a sign that it needs to be rewritten. And if your intention is to add the input arrays only partially, the name does not reflect this intention. I have simplified this function, tightening the logic and removing the duplications. See the update below for a version that does partial array addition.
The printSumRay() function seems superfluous, since the printRay() function can do the same work, so I removed it, rewriting printRay() to use VLA's and tightening the code. The original code was using the magic number 3 in the controlling expressions of the loops here, instead of taking advantage of MAXROW and MAXCOL. But, even when not using VLA's, it is better practice to pass the dimensions to any function that will work with an array.
Here is a modified version of the original code:
#include <stdio.h>
#include <stdlib.h>
void arrayIN(size_t r, size_t c, int ray[r][c]);
void arraySUM(size_t r, size_t c, int ray1[r][c], int ray2[r][c], int sumRay[r][c]);
void printRay(size_t r, size_t c, int ray[r][c]);
int main(void)
{
size_t r,c;
printf("Enter the number of ROWS: ");
scanf("%zu", &r);
printf("Enter the number of COLUMNS: ");
scanf("%zu", &c);
int ray1[r][c], ray2[r][c], sumRay[r][c];
printf("\n");
printf("Input integers for Array %d.\n", 1);
arrayIN(r, c, ray1);
putchar('\n');
printRay(r, c, ray1);
putchar('\n');
printf("Input integers for Array %d.\n", 2);
arrayIN(r, c, ray2);
putchar('\n');
printRay(r, c, ray2);
putchar('\n');
arraySUM(r, c, ray1, ray2, sumRay);
printRay(r, c, sumRay);
putchar('\n');
return 0;
}
void arrayIN(size_t r, size_t c, int ray[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
printf("Enter Number for [ROW:%zu COL:%zu]: ", i, j);
scanf("%d", &ray[i][j]);
}
}
}
void arraySUM(size_t r, size_t c, int ray1[r][c],int ray2[r][c], int sumRay[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
sumRay[i][j] = ray1[i][j] + ray2[i][j];
}
}
}
void printRay(size_t r, size_t c, int ray[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
printf("%8d",ray[i][j]);
}
putchar('\n');
}
}
As a next step, you might add some error-checking to the input code, checking the return values from the calls to scanf(). And, as it is, it is awkward to enter the numbers for the arrays, being prompted for each element. You might experiment with ways to improve this.
Update
If your true goal is to combine only the initial rows and columns of your arrays, the above code works with only minor modification. You should still use VLAs, but instead of defining the global constants MAXROW and MAXCOL, define const size_t maxrow and const size_t maxcol within the body of main(). You should be passing these array dimensions to the functions anyway, not relying on global values.
A function has been added, partArraySUM(), with a name that more closely captures its purpose. The only difference between this function and arraySUM() is that the input arrays ray1[][] and ray2[][] have different dimensions than the array sumRay[][] which holds the results. There is no need to keep separate indices for this.
#include <stdio.h>
#include <stdlib.h>
void arrayIN(size_t r, size_t c, int ray[r][c]);
void arraySUM(size_t r, size_t c, int ray1[r][c], int ray2[r][c], int sumRay[r][c]);
void partArraySUM(size_t r_sz, size_t c_sz, int ray1[r_sz][c_sz], int ray2[r_sz][c_sz], size_t r, size_t c, int sumRay[r][c]);
void printRay(size_t r, size_t c, int ray[r][c]);
int main(void)
{
const size_t maxrow = 3;
const size_t maxcol = 3;
size_t r,c;
printf("Enter the number of ROWS: ");
scanf("%zu", &r);
printf("Enter the number of COLUMNS: ");
scanf("%zu", &c);
int ray1[maxrow][maxcol], ray2[maxrow][maxcol], sumRay[r][c];
printf("\n");
printf("Input integers for Array %d.\n", 1);
arrayIN(maxrow, maxcol, ray1);
putchar('\n');
printRay(maxrow, maxcol, ray1);
putchar('\n');
printf("Input integers for Array %d.\n", 2);
arrayIN(maxrow, maxcol, ray2);
putchar('\n');
printRay(maxrow, maxcol, ray2);
putchar('\n');
partArraySUM(maxrow, maxcol, ray1, ray2, r, c, sumRay);
printRay(r, c, sumRay);
putchar('\n');
return 0;
}
void arrayIN(size_t r, size_t c, int ray[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
printf("Enter Number for [ROW:%zu COL:%zu]: ", i, j);
scanf("%d", &ray[i][j]);
}
}
}
void arraySUM(size_t r, size_t c, int ray1[r][c],int ray2[r][c], int sumRay[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
sumRay[i][j] = ray1[i][j] + ray2[i][j];
}
}
}
void partArraySUM(size_t r_sz, size_t c_sz, int ray1[r_sz][c_sz], int ray2[r_sz][c_sz], size_t r, size_t c, int sumRay[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
sumRay[i][j] = ray1[i][j] + ray2[i][j];
}
}
}
void printRay(size_t r, size_t c, int ray[r][c])
{
for(size_t i = 0; i < r; i++) {
for(size_t j = 0; j < c; j++) {
printf("%8d",ray[i][j]);
}
putchar('\n');
}
}
Sample interaction:
Enter the number of ROWS: 2
Enter the number of COLUMNS: 2
Input integers for Array 1.
Enter Number for [ROW:0 COL:0]: 1
Enter Number for [ROW:0 COL:1]: 2
Enter Number for [ROW:0 COL:2]: 3
Enter Number for [ROW:1 COL:0]: 4
Enter Number for [ROW:1 COL:1]: 5
Enter Number for [ROW:1 COL:2]: 6
Enter Number for [ROW:2 COL:0]: 7
Enter Number for [ROW:2 COL:1]: 8
Enter Number for [ROW:2 COL:2]: 9
1 2 3
4 5 6
7 8 9
Input integers for Array 2.
Enter Number for [ROW:0 COL:0]: 1
Enter Number for [ROW:0 COL:1]: 1
Enter Number for [ROW:0 COL:2]: 1
Enter Number for [ROW:1 COL:0]: 1
Enter Number for [ROW:1 COL:1]: 1
Enter Number for [ROW:1 COL:2]: 1
Enter Number for [ROW:2 COL:0]: 1
Enter Number for [ROW:2 COL:1]: 1
Enter Number for [ROW:2 COL:2]: 1
1 1 1
1 1 1
1 1 1
2 3
5 6
Just a minor change is needed. In arraySUM(), inside the else part you have re initialized
i=0 and j=0.
But after the re initialization they are incremented. So it will become 1 so while execution it will read ray[1], not ray[0].
Just re initialize them to -1.
i=-1 and j=-1

Resources