+ 2
How to add values in a two dimensional array
I have to add the values of cell with even row and odd column indexes, for example twoDArray[2,5], two twoDarray[4,3] public int twoDim( int [,] twoDArray) //My if condition has syntax and logic errors. { int sum = 0; for( int i = 0; i< twoDArray.Length i++) { for (int j = 0; j < twoDArray.Length; j++) { if ( twoDArray[(i/2==0 && j / 2 != 2]) //My if condition has syntax and logic errors. { sum += twoDArray[i, j]; } } } return sum; }
21 Respostas
+ 3
also dont use Length
use GetLength(d) where d is the dimension
i < twoDArray.GetLength(0);
and
j < twoDArray.GetLength(1);
+ 3
Taste
I don't understand, how can the code run, while the array was defined without using `new`. My understanding of multidimensional array definition was something like this.
int [,]i = new int[4, 2] {{2,3},{2,5},{4,5},{3,5}};
Has things changed now that such multidimensional array definition is valid? (as seen in the code)
(Edited)
+ 3
tbh, i'm not really sure when it was change. i wasnt use c# for very long.
but it seems its valid now. as long as the declaration tell the array dimension.
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays
+ 3
Thank you Taste 🙏
+ 3
Microne mafika Here is an alternative with GetLength without the if's
https://code.sololearn.com/c9I8mAWNTBUS/?ref=app
+ 2
declare twoDim as static.
public static int twoDim
+ 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
public static int twoDim( int [,] twoDArray)
//My if condition has syntax and logic errors.
{
int sum = 0;
for( int i = 0; i< twoDArray.Length; i++)
{
for (int j = 0; j < twoDArray.Length; j++)
{
if (i%2==0&&j%2!=0)
{
sum += twoDArray[i, j];
}
}
}
return sum;
}
static void Main(string[] args)
{
int [,]i ={{2,3},{2,5},{4,5},{3,5}};
Console.Write(twoDim(i));
}
}
}
+ 2
Length return the total of the elements, thats where the error come from. first dimension only has length of 4, but Length return 8.
https://code.sololearn.com/c12B6O6k6uLS/?ref=app
+ 1
i have implement this idea but my program is still not work
+ 1
no. this a the output
./Playground/file0.cs(34,18): error CS0120: An object reference is required for the non-static field, method, or property 'Program.twoDim(int[*,*])'
+ 1
i did make it static
+ 1
Hello
+ 1
import java.util.Scanner;
public class numbereveorodd
{
public static void main(String args[])
{
int x;
Scanner sc=new Scanner(System.in);
System.out.println("enter any number:");
x=sc.nextInt();
if (x%2==0)
{
System.out.println("number is even");
}
else
{
System.out.println("number is odd");
}
}
}
Whats wrong with my code please help me guys?
0
What is billing?