Language – Java | Type – Concept | Last date 3-June-2009 9:00 p.m. IST | Points 5
Lately I have been playing around with the look of the blog quite a bit. I decided its time to get in something new. This question reflects that mood!
Conceptual questions are getting a little boring aren’t they? Let’s get our hands dirty with programming shall we? Here’s your question -
Write a program to scan and print the elements of a matrix. (3 X 3)
Twist: Use a single for loop only. Any other Looping Structure, recursion can not be used. No additional classes except those required to scan the elements – Scanner or Console! (No Collection framework classes)
Note: Scan elements of the matrix first. Print elements later in a normal matrix form (i.e. rows and cols).
You don't have to actually write the program - just mention the principal involved - probably with a little pseudo code!
Link of the day – http://www.getdropbox.com – site gives you 3 GB free storage (who’s doesn’t) but has too many excellent features to ignore. (Use My Referral for free extra space)
for(int i = 0; i < 9; i ++)
ReplyDelete{
element = matrix[(int) i / 3][i%3];
}
Add in any spaces an new lines you want in there. before outputting it.or switch around the numbers for differently sized squares
Scanner scanner =new Scanner(System.in);
ReplyDeleteStringBuffer buffer =new StringBuffer();
for(int i=0;i<9;i++)
{
buffer.append(scanner.next()+" ");
if(i==2 || i==5)
buffer.append("\n");
}
scanner.close();
System.out.println(buffer.toString());
for (int i = 0; i < 9; i++)
ReplyDeleteprintln(matrix(i % 3)(i / 3))
import java.io.BufferedReader;
ReplyDeleteimport java.io.IOException;
import java.io.InputStreamReader;
public class Matrix {
private String[][] matrix = new String[3][3];
public static void main(String[] args) throws IOException {
Matrix matrix = new Matrix();
matrix.readAndOut();
}
private void readAndOut() throws IOException {
BufferedReader bure = new BufferedReader(new InputStreamReader(System.in));
boolean read = true;
for (int x = 0, y = 0; x <= 3; x++) {
if (read) {
if (x == 3) {
y++;
x = 0;
}
if (y != 3) {
System.out.println("Value for field: [" + x + "]" + "[" + y + "]");
matrix[x][y] = bure.readLine();
} else {
x = 0;
y = 0;
read = false;
}
}
//output:
if (!read) {
if (x == 3) {
if (y == 2) {
return;
}
System.out.println();
y++;
x = 0;
}
System.out.print(matrix[x][y] + " ");
}
}
}
}