I'm doing pattern programming in C and java. I have written code for both the languages with same condition so i'm expecting the same output but i'm not getting same output.
Here is C code of pattern program
#include<stdio.h>
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=9;j++)
{
if(j<=(6-i)||j>=(4+i))
printf("*");
else
printf(" ");
}
printf("\n");
}
}
Output:
*********
**** ****
*** ***
** **
* *
Java Code:
public class Main {
public static void main(String [] args) {
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=9;j++)
{
if(j<=(6-i)||j>=(4+i))
System.out.print("*");
else
System.out.println();
}
}
}
}
Output:
*************
*******
*****
***
*
Help me to fix this problem
The Java version prints a new line instead of a space like in the C version. Try this instead.
public class Main {
public static void main(String [] args) {
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=9;j++)
{
if(j<=(6-i)||j>=(4+i))
System.out.print("*");
else
System.out.print(" "); // Prints space
}
System.out.println(); // Prints a newline for each row
}
}
}
In your Java program you forget to write a line of code corresponding to printf(" "); in your C code. This in Java will be like System.out.print(" ");
Try this modified code :
public class Main {
public static void main(String[] args) {
int i, j;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= 9; j++) {
if (j <= (6 - i) || j >= (4 + i))
System.out.print("*"); // in C printf("*");
else
System.out.print(" "); // in C printf(" ");
}
System.out.println(); // in C printf("\n");
}
}
}
Output :
*********
**** ****
*** ***
** **
* *
Related
Below You Can see Output of My Program I want to end my program on line no. 7 How Can i Achieve i spent 1 hours but still not able to solve this problem. I saw multiple solution but all are same type the are getting the correct output.
Note: - Main method should not alter any line of code
import java.io.*;
import java.util.*;
public class Person {
private int age;
public Person(int initialAge) {
age = initialAge;
if (age < 0) {
age = 0;
System.out.println("Age is Not Valid, Setting age to 0");
}
}
private void amIOld() {
String s = "";
if (age < 13) {
s = "You are Young";
} else if (age >= 13 && age < 18) {
s = "Your are Teenager";
} else {
s = "You are Old";
}
System.out.println(s);
}
private void yearPasses() {
age++;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
int age = sc.nextInt();
Person p = new Person(age);
p.amIOld();
for (int j = 0; j < 3; j++) {
p.yearPasses();
}
p.amIOld();
System.out.println();
}
sc.close();
}
}
You can use System.exit(0); on the line where you want to terminate the program.
Here is the link where you can learn more:
https://www.geeksforgeeks.org/system-exit-in-java/
I understood what your problem is above question is part of Hackerank 30 days of code java challenge, and the problem your code won't be accepted has nothing to do with the new line. In your constructor just change the line age to 0 to age to 0. and it will work.
You have not added the dot after 0 in print statement is the issue.
In python, to print
******
*****
****
***
**
*
*
**
***
****
*****
******
We would code the following:
for e in range (11,0,-1):
print((11-e) * ' ' + e * '*')
print ('')
for g in range (11,0,-1):
print(g * ' ' + (11-g) * '*')
My question is, can this be done in Java as well?
Java doesn't let you multiply a string (int) times, e.g. 4 * " ", so how can we implement this in java?
It wouldn't be a concise:
// top half..
for (int i=11;i>0;i--){
for (int a=0;a<11-i;a++){
System.out.print(' ');
}
for (int b=0;b<i;b++){
System.out.print('*');
}
System.out.println();
}
public class Loops {
public static void main(String[] args) {
//print first half
for(int i = 0; i < 6; i++) {
printChar(' ', i);
printChar('*', 6-i);
System.out.println();
}
//print second half
for(int i = 0; i <= 6; i++) {
printChar(' ', 6-i);
printChar('*', i);
System.out.println();
}
System.out.println();
}
//helper function to print a char n specific times
private static void printChar(char ch, int n) {
for(int i = 0; i < n; i++) {
System.out.print(ch);
}
}
}
To run through a string multiple times in Java, you can use a for loop.
for(int i = 0; i < yournum; i++){
System.out.print(" ");
}
yournum is the number of spaces you want
IntStream.range(0, 6).forEach(i -> {
IntStream.range(0, i)
.forEach(t -> System.out.print(" "));
IntStream.range(0, 6 - i)
.forEach(t -> System.out.print("*"));
System.out.println();
});
In Java8 you can use Stream to do the samething. Use IntStream to range and println
If you are open to using: Commons Lang StringUtils ...
using Commons Lang StringUtils.repeat() can help you repeat a string...
as an example:
StringUtils.repeat("*", 3) //produces ***
Here is a Core Java solution which can generate the entire output using a single for loop:
String before = "", after = "";
for (int i=0; i < 6; ++i) {
String starRepeat = String.format("%0" + (6-i) + "d", 0).replace("0", "*");
String spaceRepeat = (i>0) ? String.format("%0" + i + "d", 0).replace("0", " ") : "";
String line = spaceRepeat + starRepeat;
if (i == 0) {
before = line;
after = line;
}
else {
before = before + "\n" + line;
after = line + "\n" + after;
}
}
System.out.println(before + "\n\n" + after);
Output:
******
*****
****
***
**
*
*
**
***
****
*****
******
You can add the message you want to print on a String, then print out the string value by System.out.println(message);
I am going to post my code below because this is kind of hard to describe. The code below works, but it is using Math.pow in the main method rather than in the helper, so if someone could show me a way to move the power to the helper method without messing up the program that would be much appreciated.
Main method:
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer: ");
double input = keyboard.nextInt();
double x = Math.pow(2.0, input);
int n = (int)x;
System.out.println(starStr(n));
Helper method:
public static String starStr(int n)
{
if (n >= 1) {
return ("*" + starStr(n-1));
}
else {
return "";
}
}
EDIT:
if(n == 0) {
return "*";
}
else {
return starStr(n - 1) + "**";
}
Something like this would work. You don't really need to use a power function at all. Just start with 1 star and double the number of stars in every step of the recursion.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer for the number of stars: ");
int input = keyboard.nextInt();
System.out.println(doStars(input));
}
public static String doStars(int n)
{
//If n == 0 the recursion is done
//Otherwise, reduce n by 1 and double the number of stars
if(n == 0)
return "*";
else
{
String output = doStars(n - 1);
return output + output;
}
}
I think this is what you are looking for. Not sure if you have learned the tree data-structure, but that's the purpose of my variable names.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
// 1 + (2^n)-1 = 2^n
System.out.println("*" + doStars(i));
}
}
public static String doStars(int n)
{
if (n == 0) {
return "";
}
else {
String subTree = doStars(n - 1);
return subTree + "*" + subTree; // length = (2^n)-1
}
}
}
Output
*
**
****
********
****************
Visualization - read clockwise in triangles from little to big
"*"
+
doStars(2)
"*"
doStars(1) + doStars(1)
"*" "*"
doStars(0) + doStars(0) doStars(0) + doStars(0)
"" "" "" ""
My program reads in values from a file and uses a recursive method to print patterns of asterisks based on those values. I'm just having a problem getting everything to line up properly.
The output is supposed to look like this:
*
* *
* * *
* *
*
Regarding the format of the output, the directions are:
"Note that the pattern is aligned symmetrically (vertically) about the center line. The pattern should be aligned symmetrically on each line (horizontally) as well- hint: use the line value to help space."
But my output looks like this:
*
* *
* * *
* *
*
The code I'm using to get this pattern:
public static void makePattern(int thisRow, int num) {
if(thisRow >= num) {
for(int i = 0; i < num; i++) {
System.out.print(" " + "*" + " ");
}
System.out.println();
}
else {
for(int i = 0; i < thisRow; i++) {
System.out.print(" " + "*" + " ");
}
System.out.println();
makePattern(thisRow + 1, num);
for(int i = 0; i < thisRow; i++) {
System.out.print(" " + "*" + " ");
}
System.out.println();
}
}
Also my main method:
import java.util.Scanner;
import java.io.*;
public class Program3 {
public static void main(String[] args) throws Exception {
int num = 0;
int thisRow = 1;
java.io.File file = new java.io.File("../instr/prog3.dat");
Scanner fin = new Scanner(file);
while(fin.hasNext()) {
num = fin.nextInt();
if(num >=0 && num <= 25)
makePattern(thisRow, num);
System.out.println();
}
fin.close();
}
Any suggestions on how to edit my code to make my output appear like the example pattern I included?
Let's analyse the output first!!
First step is to analyse the output
Conclusions:
The total number of characters on every line is always n (=3)
Number of Spaces has the following pattern:
1st line 3 - 1 spaces
2nd line 3 - 2 spaces
3rd line 3 - 3 spaces
4th line 4 - 3 spaces
5th line 5 - 3 spaces
So
if(num < thisRow) {
numberOfSpaces = thisRow - num;
} else {
numberOfSpaces = num - thisRow;
}
Number of Stars is always [n - the number of spaces]
So
int numberOfStars = num - numberOfSpaces;
And the recursion should end on the 6th line, i.e. when current line number is n*2
So the return condition in your recursive method should be
if(thisRow == num * 2)
return;
Final Code : Putting the peices together
When we put the peices together, we get:
public static void makePattern(int thisRow, int num) {
//the termination condition
if(thisRow == num * 2)
return;
//the number of spaces
int numberOfSpaces = 0;
if(num < thisRow) {
numberOfSpaces = thisRow - num;
} else {
numberOfSpaces = num - thisRow;
}
//the number of stars
int numberOfStars = num - numberOfSpaces;
//compose the string before printing it
StringBuffer outputBuffer = new StringBuffer(num);
for (int i = 0; i < numberOfSpaces; i++){
outputBuffer.append(" ");
}
for (int i = 0; i < numberOfStars; i++){
outputBuffer.append("* ");
}
//print the string
System.out.println(outputBuffer.toString());
//recursion
makePattern(thisRow + 1, num);
}
This is code for printing diamond shaped pattern using recursion technique.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class patternRecursion {
static int n,k;
public static void main(String[] args) throws IOException{
try(Scanner s = new Scanner(System.in)){
n=Integer.parseInt(reader.readLine());
k=n-1;
printPattern(n);
}
}
public static void printChar(int m,char c){
if(m==0) return;
try{
printChar(m-1,c);
System.out.print(c);
}catch(StackOverflowError s){return;}
}
public static void printPattern(int m){
if(m==0){
return ;
}else{
printChar(m-1,' ');
printChar(n-m,'#');
printChar(n-m+1,'#');
System.out.println();
printPattern(m-1);
printChar(m,' ');
printChar(k-m,'#');
printChar(k-m+1,'#');
System.out.println();
}
}
}
I am trying to write a program which can calculate factorial from 1-9 by iteration, but I encounter some problems while I am trying to. Please help me figure out my problems in my program, I am just learning programming.
The following is my program, please tell me what's wrong with it:
public class iterative {
static int ans=1;
public static void iteration() {
System.out.println("n n!");
for (int n=1; n<10; n++) {
while ((n-1)>0)
ans=n*(n-1);
System.out.println(n + " " + ans);
}
}
public static void main(String[] args) {
iteration();
}
}
First of all, don't use a static for ans. A local is what you want.
Secondly the factorial recurrence relationship you use is incorrect. You should do it like this.
int ans = 1;
for (int n=1; n<=9; n++) {
ans = ans*n;
System.out.println(n + " " + ans);
}
The answers above is close perfect,you also get it with the recursion:
here is code:
public class iterative {
public static int iteration(int n) {
int result;
if(n==1)return n;
else
result = n*iteration(n-1);
return result;
}
public static void main(String[] args) {
System.out.println("Result is :" + iteration(9));
}
}
I see three big problems.
Firstly, "ans" is global and is never reassigned. So over time it will display an accumulated incorrect value.
The other is that the while loop will run forever for n > 1.
Lastly, the recurrence relationship is wrong. Should be ans = ans * (n-1). See code.
The fact that you have nested loops suggests to me that you are trying to print a table of factorials.
Try this:
for (int n=1; n<10; n++) {
int ans = 1;
int x = 0;
while ((n-x)>0){
ans=ans*(n-x);
x++;
}
System.out.println(n + " " + ans);
}
Like #David's solution but shorter
for(int i=1, ans=1; i <= 9; i++, ans *= i)
System.out.println(i + " " + ans);
Your algorithm needed work as well:
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
int i = 1;
while(i < 10)
iteration(i++);
}
public static void iteration(int max) {
System.out.println("n n!");
int ans = 1;
for (int n=1; n<=max; n++) {
ans *= n;
}
System.out.println(" " + ans);
}
ideone example