Want to print a n*n matrix in zigzag pattern - java

This is my code:
class Main{
public static void main(String args[]){
System.out.println("Enter the value of N: ");
Scanner sc = new Scanner(System.in);
int n1 = sc.nextInt();
int max = 0, min = 0;
if(n1<=50){
for(int i=1;i<=n1;i++){
for(int j=1;j<=n1;j++){
max = n1*i;
min = (max-n1)+1;
if(i%2!=0){
while(max<=min){
System.out.print(max);
max--;
}
}
if(i%2==0){
while(min<=min){
System.out.print(min);
min++;
}
}
}
System.out.println("");
}
}
else
System.out.print("Invalid Value of n1");
}
}
the problem is to print a zigzag matrix like
if we enter n=4 then the output should be like:
4 3 2 1
5 6 7 8
12 11 10 9
13 14 15 16
and if we enter 3 it should come like
3 2 1
4 5 6
9 8 7
now in the above code its going to a infinite loop

Considering it is most likely some kind of a homework, I won't hand you a solution as it takes away the learning process. Instead, I'll just give you some hints.
You need 2 nested for loops, the outer one for rows and the inner one for columns.
Find out what the max and min numbers in a given row are. They are connected to the row number.
If the row number is odd, start with the max number and go down. If it is odd, start from the min number and go up.

Related

Looping with conditional statement

Hi i want to learn how to do java loop that will determined the number if it is an odd or even like
1st value: 8
2nd value: 15
output:
8 is even
9 is odd
10 is even
11 is odd
12 is even
13 is odd
14 is even
15 is odd
You can do it like so:
Scanner input = new Scanner(System.in);
System.out.print("First value: ");
int start = Integer.parseInt(input.nextLine());//Gets the first number
System.out.print("Second value: ");
int end = Integer.parseInt(input.nextLine());//Gets the second number
for(int i = start; i <= end; i++){
if(i%2==0){//When the number is divided by 2, it gives a remainder of 0. Modulus helps us get the remainder.
System.out.println(i+" is even");
}else{//Doesn't satisfy the first condition. It must be odd.
System.out.println(i+" is odd");
}
}
We use a Scanner to read the user input, then use a for loop and leverage modulus (%). Modulus calculates the remainder of a number after dividing it by a certain number. If a number divided by 2 gives a remainder of 0, that means it is divisible by 2. We can construct an if statement to check whether it is divisble.
Test Run
First value: 1
Second value: 10
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
Hey you can use a for loop it's simple.
for(int i=8;i<=15;i++){
if(i%2==0){
System.out.println(i+"is even");
}else{
System.out.println(i+"is odd");
}
}
And I expect you know how to ask inputs so just pass it on the place of 8 and 15
The short version:
https://www.youtube.com/watch?v=cakN0XC6CcQ
Use number % 2 == 0 for even numbers.
The long version:
// Create a new Scanner() to scan System.in
Scanner scanner = new Scanner(System.in);
// Get the two inputs
int first = scanner.nextInt();
int second = scanner.nextInt();
// Start i as the first number
// While it is less than or equal to the second
// Add one each time
for(int i = first; i <= second; i++) {
// Is there a remainder from dividing i by 2?
// If no, it's even
boolean even = i % 2 == 0;
// Print it
System.out.println(i + " is even: " + even);
}
scanner.close();

How can i determine the formula for determining the first number in Java's loop array for floyd's triangle?

Hi so i have java loop problem.
So i'm trying to figure out how to determine the first number(in the top of the pattern) in the loop for floyd's triangle by entering the height on the triangle.
Note: only the height is to be inputted to determine the first number and the last number should be fixed to 1.
for example:
Enter the height: 5
The first number is: 15
15
14 13
12 11 10
9 8 7 6
5 4 3 2 1
Another one is
Enter the height: 6
The first number is: 21
21
20 19
18 17 16
15 14 13 12
11 10 9 8 7
6 5 4 3 2 1
I've figured out how to do the pattern and the decrementing of the value but i cant seem to figure out the first number. I've been trying to figure out the sequence but it's still confusing to me because i'm still new at java.
Here is my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int n;
int startingnumber = ;
Scanner input = new Scanner(System.in);
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
System.out.print("The first number is "+startingnumber);
for(int i =1; i<=n; i++){
for(int j =1; j<=i; j++){
System.out.print(startingnumber);
startingnumber--;
}
System.out.println();
}
}
}
The code is still not finished because i cant figure out the formula :(
I would appreciate any help that i can find. Thanks!
This mathematical problem is Triangular number and here is a visual demonstration
S1 = 1
S2 = 1 + 2
S3 = 1 + 2 + 3
...
Sn = 1 + 2 + 3 + ... + n
=> 1 + 2 + 3 + ... + n = n * (n + 1) / 2
An also have a look at System.out.printf
public static void main(String[] args) {
int n;
int startingnumber;
Scanner input = new Scanner(System.in);
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
startingnumber = n * (n + 1) / 2;
System.out.println("The first number is " + startingnumber);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.printf("%3d ", startingnumber);
startingnumber--;
}
System.out.println();
}
}
Output
Enter the height of the triangle: 6
The first number is 21
21
20 19
18 17 16
15 14 13 12
11 10 9 8 7
6 5 4 3 2 1
The way you solve that type of question is by finding a mathematical relationship. In this case, you know (when input's 6) that the height's 6. You also know that at each row, you have one less number than at the one that goes after it. The bottom one has 6, as its the same as the height.
Therefore, you need to do 6+5+4+3+2+1 to obtain the starting number.
Now that formulated as a generic solution: n+(n-1)+((n-1)-1)..+1.
A possible implementation for that is:
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
int startingNumber = 0;
for (int i=n;i>0;i--) startingNumber+=i;

Minimum path sum in matrix

Given a matrix of N * M. Find the minimum path sum in matrix. The minimum path is sum of all elements from first row to last row where you are allowed to move only down or diagonally to left or right. You can start from any element in first row.
I've written the code,but what is wrong in my code/logic?
here in my algorithm I am starting from the element of the top row, now I'm going to the second row and algorithm is finding the minimum value and add with the first element and thus it makes way to the bottom(a element can only add with the elment which is under it and also can move diagonally right and left)
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int row, column, i, j,temp=0;
System.out.print("Please enter the desire grid dimension: ");
row = sc.nextInt();
column = sc.nextInt();
int array[][] = new int[row][column];
System.out.println("Please enter the desired input:");
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++) {
array[i][j] = sc.nextInt();
}
}
for(i=1;i<row;i++){
for(j=0;j<column;j++){
array[i][j] += Math.min((j==0)?0:array[i-1][j-1],Math.min(array[i-1][j],(j==column-1)?0:array[i-1][j+1]));
}
}
for(i=0;i<row;i++){
for(j=0;j<column;j++){
System.out.print(array[i][j] + " ");
}
System.out.println();
}
for(j=0;j<column-1;j++){
temp = Math.min(array[row-1][j],array[row-1][j+1]);
}
System.out.println(temp);
}
}
let your input is
1 5 1 5 1* 5
3 3 2 3 3* 4
2 3 4 4 3 2*
2 2 3 2 2* 4
2 2 4 3 4 2*
4 4 4 4 2* 3
your output should be 12,path is marked with(*) 1+3+2+2+2+2=12
I'm getting 3,because after running my algorithm the matrix became
1 5 1 5 1 5
3 4 3 4 4 4
2 6 7 7 7 2
2 4 9 9 4 4
2 4 8 7 8 2
4 6 8 11 4 3
I am not giving you a complete answer. You will learn more from finding out yourself. At the same time this will be more gratifying for you. So I will just guide you slightly on the way and trust you to do the rest yourself. It’s not that hard.
First, however, for other readers to follow what I write I need to give the explanation that you should have given in the question of how your algorithm was supposed to work. You are modifying the matrix in a way so that each cell instead of its original number gets to contain the minimum sum of a path from the top to that cell inclusive. For example:
We see from your matrix after the algorithm has run that the top line is unchanged. This is correct since you can go directly into each cell, so the sum is equal to the original cell value.
In the second line, the second (index 1) cell has been changed from 3 to 4. This is correct since to go to that cell we need to go through 1 or 5 or 1 in the first line. 1 gives the minimal sum, so 1 is added to 3, hence 4.
In the same line, the leftmost cell is unchanged 3. The is incorrect. To get to this cell you also need to go through either 1 or 5 in the first line, so this 3 too should have been changed to 4. I will give you one piece of information: the cell was not forgotten. Your loop assigns a value to the cell, only not the correct value. 1 should have been added, instead 0 was added. Where does this 0 come from? Your turn! Happy debugging.

Printing Odd numbers in a upside down right angle formation

Im trying to take a number and print it's odd number like this:
if i take 5 as a number it should give this:
1 3 5
3 5
5
and if i take 9 it should do the same thing:
1 3 5 7 9
3 5 7 9
5 7 9
7 9
9
This is what i have so far and i am stuck. i can't get the 5 to print after the 3 and to end it with 5 for the triangle:
public class first{
static void afficher(int a){
for(int i=1;i<=a;i++){
if(i%2!=0){
System.out.printf("%d",i);
}
}
System.out.println();
for(int j=3;j<=a-2;j++){
if(j%2!=0){
System.out.printf("%d",j);
}
}
}
public static void main(String[]args){
afficher(5);
}
}
This prints:
1 3 5
3
If you print a surface (2d thus), one expects that the algorithm runs in O(n^2) time complexity. Thus two nested fors:
public class first{
static void afficher(int a){
for(int i = 1; i <= a; i += 2) {
for(int j = i; j <= a; j += 2){
System.out.print(j);
System.out.print(' ');
}
System.out.println();
}
}
}
One can optimize the algorithm a bit by not checking if the number is odd, but taking steps of 2.
See demo.
You have to use nested for-loops to resolve this problem. Go through the following code
public class OddNumberLoop {
public static void main(String[] args) {
Scanner inpupt = new Scanner(System.in);
System.out.print("Input the starting number : ");
int start = inpupt.nextInt();
for(int i = 1 ; i <= start; i += 2){
for(int x = i; x <= start; x += 2) System.out.print(x+ " ");
System.out.println();
}
}
}
The reason it is printing as follows because:
1 3 5 -> your i loop runs here (from 1 to 5)
3 -> your j loop runs here (from 3 to (less than OR equal to 5))
So I suggest the following:
Use 2 nested loops (for universal values):
i running from 1 to the input number increasing by 2
j running from i to the input number increasing by 2 also ending with line change'/n'
Keep a check whether the input number is odd or not.

Multiplication Table For Loop

This is the code I wrote; it's going into an infinite loop and I don't know why..
import java.io.*;
public class Multi{
public static void main(String args[])throws IOException{
int num;
BufferedReader inpt = new BufferedReader (new InputStreamReader (System.in));
System.out.print("Enter a number: ");
num=Integer.parseInt(inpt.readLine());
int z,x,y;
while (num>=1 || num<=11){
for(z=1; z<=num; z++){
for(x=1; x<=z; x++){
y=z*x;
System.out.print(y+" ");
}
System.out.println();
}
}
}
}
The output I want to show in this one is that when a person inputs a number it will display a multiplication table.
e.g.
Enter a number: 5
Result:
- 1 2 3 4 5
- 2 4 6 8 10
- 3 6 9 12 15
- 4 8 12 16 20
- 5 10 15 20 25
Enter a number: 3
- 1 2 3
- 2 4 6
- 3 6 9
Your while condition will never be false:
while (num>=1 || num<=11)
Every possible number is >= 1 or <= 11. I guess you meant "and" instead of "or".
Also, you need to put the code that sets num inside the while-loop.
//To get a multiplication table for the number get from user
#include<stdio.h>
int main() {
int i;
int num;
scanf("%d",&num);
for(i=1; i<=10; i++){
printf("%d\n",i*num);
}
return 0;
}

Categories

Resources