Multiplication Table For Loop - java

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;
}

Related

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;

Want to print a n*n matrix in zigzag pattern

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.

Java - Simple formatting regarding power of 2 triangle

Overview
I'm sure this is a simple problem for most of you on here, but I have been struggling with a small spacing problem and was hoping I can learn from someone more experienced. I need to produce a triangle similar to the one below. You can see that the numbers are aligned correctly no matter the length.
Enter the number of lines: 8
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
My Code
Here is what I have so far. It isn't the prettiest, but it seems to give me the correct values at least.
import java.util.Scanner;
public class Pyramid2
{
public static void main(String[] args)
{
int i, j, k, l, a;
//Create a Scanner object
Scanner in = new Scanner (System.in);
//Prompt the user to enter number of rows in pyramid
System.out.print("Enter number of rows: ");
int rows = in.nextInt();
a = rows;
//Variables to determine length
int length = ("" + rows).length();
String str = " %" + length + "s";
//Logic
for (i = 1; i <= rows; i++)
{
for (j = a; j > 0; j--)
{
System.out.printf(str, " ");
}
for (j = 1; j <= (2*rows); j++)
{
if (j == (rows+1))
{
continue;
}
if (j < (rows+1))
{
k = j;
}
else
{
k = ((2*rows)-j+1);
}
if (k >= (rows+1-i))
{
l = (int)Math.pow(2, (i+k-rows-1));
String str1 = "" + l;
System.out.printf(str, str1);
}
}
a--;
System.out.println();
}
}
}
My Results
This is the console output when 6 rows are chosen. Everything looks good until row 5 when a 2 digit number (16) appears. What are some efficient ways to align the results properly?
Enter number of rows: 6
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
You calculate length as the number of digits in rows, but it needs to be number of digits in largest number in triangle.
E.g. for rows = 6, largest number is 32, so length should be 2.
For rows = 8, largest number is 128, so length should be 3.
Largest number is 2rows, which in Java means 1 << rows, so change length calculation to:
int length = ("" + (1 << rows)).length();
You are also adding one too many blanks on the left.
Change code to this:
a = rows - 1;
First of all i can recommend to determine the largest number in pyramid. Then count digits in this number. For 8 rows this number is 128, it has 3 digits. According this information we can decide that we need 3+1=4 (including spaces) characters to print every value in pyramid.
After it you have to complete every output number by spaces (from the left) to achive string size of 4 characters.
And the global prefix for every pyramid line will contain (rows - i) * 4 spaces.

Java Multiplication

How will do a program that displays a multiplication table based on the size that the user inputs? And will add each row and each column? Something like this:
Enter a number: 4
1 2 3 4 10
2 4 6 8 20
3 6 9 12 30
4 8 12 16 40
10 20 30 40
I tried this:
Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int x = s.nextInt();
for(int i = 1; i <= x; i++)
{
for (int j = 1; j <=x; j++)
{
System.out.print((i*j) + "\t");
}
System.out.println();
}
Sample Output:
Enter a number: 4
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
How I will do to add each row and each column?
Since this seems like homework, I wouldn't feel comfortable writing your code for you. However, keep the following things in mind.
Your matrix will always be a square, as the user only enters a single number, of n x n numbers.
Since these numbers increment by one along the row and column, the sum of each row and column pair will be the same. In other words, the total of row[n] will equal the total of column[n].
Using that, you can create a single array of size n to store the sum of each row. For example:
Enter a number: 3
1 2 3 x
2 4 6 y
3 6 9 z
x y z
When you're looping through each row, you can store the row total in the array.
Row 0: Add 1 + 2 + 3 and store in array[0]
Row 1: Add 2 + 4 + 6 and store in array[1]
Row 2: Add 3 + 6 + 9 and store in array[2]
At the end of each row you can simply display the total in array[row]. When you finish drawing all rows, you'd simply loop through array and display each total value.
Hope this points you in the right direction!
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.print("Enter size of table: ");
int x = s.nextInt();
int r = 0;
int l = 0;
int f = 0;
for(int i=1;i<=x;i++){
for (int j=1; j <=x; j++)
{
r = r + j;
System.out.print(i*j+"\t");
}
System.out.print(r);
System.out.println();
System.out.println();
l=l+i;
}
for(int k = 1; k<=x;k++)
{
f=f+l;
System.out.print(f + "\t");
}

How to find element number from either a single, or a range of values in an array

This is the code for an upcoming university practical I have:
import java.util.Random;
public class Practical4_Assessed
{
public static void main(String[] args)
{
Random numberGenerator = new Random ();
int[] arrayOfGenerator = new int[100];
int[] countOfArray = new int[10];
int count;
for (int countOfGenerator = 0; countOfGenerator < 100; countOfGenerator++)
{
count = numberGenerator.nextInt(10);
countOfArray[count]++;
arrayOfGenerator[countOfGenerator] = count + 1;
}
int countOfNumbersOnLine = 0;
for (int countOfOutput = 0; countOfOutput < 100; countOfOutput++)
{
if (countOfNumbersOnLine == 10)
{
System.out.println("");
countOfNumbersOnLine = 0;
countOfOutput--;
}
else
{
if (arrayOfGenerator[countOfOutput] == 10)
{
System.out.print(arrayOfGenerator[countOfOutput] + " ");
countOfNumbersOnLine++;
}
else
{
System.out.print(arrayOfGenerator[countOfOutput] + " ");
countOfNumbersOnLine++;
}
}
}
System.out.println("");
System.out.println("");
String occurrencesReport = "";
String graph = "";
for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
{
occurrencesReport += "The number " + (countOfNumbers + 1) +
" occurs " + countOfArray[countOfNumbers] + " times.";
if (countOfNumbers != 9)
graph += (countOfNumbers + 1) + " ";
else
graph += (countOfNumbers + 1) + " ";
for (int a = 0; a < countOfArray[countOfNumbers]; a++)
{
graph += "*";
}
occurrencesReport += "\n";
graph += "\n";
}
System.out.println(occurrencesReport);
System.out.println(graph);
int max = 0;
int test = 0;
for (int counter = 0; counter < countOfArray.length; counter++)
{
if (countOfArray[counter] >= max)
{
max = countOfArray[counter];
test = counter + 1;
}
}
System.out.println("The number that appears the most is " + test + ".");
}
}
The program creates an array that will store 100 integers (all of which are between 1 and 10), which are generated by a random number generator, and then print out ten numbers of this array per line. It then scans these integers, counts up how often each number appears and store the results in a second array.
Following this, it outputs a horizontal bar chart of asterisks showing how often each number appears before finally outputting the number that appears the most often.
I thought I had the code totally and completely done, but I've just realised that if multiple numbers occur the same amount of times, the last part of my code can't handle this, e.g. if the numbers 3 and 5 both appears 12 times, the code can only produce one of them.
Does anyone have a way around this?
Thanks,
Andrew
There are a couple of ways to address this, which range from quick to complex. The easiest way is to brute force it like such:
int max = 0;
//int test = 0;
for (int counter = 0; counter < countOfArray.length; counter++)
{
if (countOfArray[counter] >= max)
{
max = countOfArray[counter];
//test = counter + 1;
}
}
System.out.print("The number that appears the most is");
boolean first = true;
for(int i = 0; i < countOfArray.length; i++)
{
if(countOfArray[i] == max)
{
if(first)
first = false;
else
System.out.print(",");
System.out.print(" " + (i+1) );
}
}
System.out.println(".");
Here's the output:
6 2 6 5 6 8 9 3 5 8
9 8 10 10 4 5 8 9 8 5
1 7 8 5 6 7 10 4 5 4
2 7 9 2 3 3 1 2 10 3
5 2 10 1 1 6 3 3 8 10
2 6 10 2 5 1 4 10 8 7
7 8 7 3 7 8 3 4 5 5
7 8 9 8 6 6 8 1 10 3
2 5 4 6 9 9 10 10 1 10
9 4 10 9 7 3 4 3 2 4
The number 1 occurs 7 times.
The number 2 occurs 9 times.
The number 3 occurs 11 times.
The number 4 occurs 9 times.
The number 5 occurs 11 times.
The number 6 occurs 9 times.
The number 7 occurs 9 times.
The number 8 occurs 13 times.
The number 9 occurs 9 times.
The number 10 occurs 13 times.
1 *******
2 *********
3 ***********
4 *********
5 ***********
6 *********
7 *********
8 *************
9 *********
10 *************
The number that appears the most is 8, 10.
There are much cleaner ways to go about it, but hopefully that gives you a decent start!
I am assuming this is not some kinda homework, so i am providing you another approach than this.
- Use Collection like ArrayList instead of Array.
- Use method like Collections.frequency(Object o) to know the number of time the value got occurred in that Collection.
Instead of just doing
System.out.println("The number that appears the most is " + test + ".");
Again loop through countOfArray, do the print for each element that has the same value as max.

Categories

Resources