Docsity

Java Programming Examples: Pattern Printing, String Manipulation, and Number Sum, Assignments of Java Programming

Toggle sidebar
bg1
1. Accept two numbers M and N .print M rows and
N columns in the following format
For eg M=4 and N=4
# * * #
& # # &
* # # *
# & & #
a. Odd rows contains ‘*’ and even rows contains &
b. Diagonal elements contains “#”
Code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int m,n;
Scanner s=new Scanner(System.in);
System.out.println("Enter number of rows :");
m=s.nextInt();
System.out.println("Enter number of columns :");
n=s.nextInt();
System.out.println("Pattern :");
if(m==n)
{
for(int i=1;i<=m;i++)
{
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Java Programming Examples: Pattern Printing, String Manipulation, and Number Sum and more Assignments Java Programming in PDF only on Docsity!

1. Accept two numbers M and N .print M rows and

N columns in the following format

For eg M=4 and N=

a. Odd rows contains ‘*’ and even rows contains &

b. Diagonal elements contains “#”

Code: import java.util.Scanner; public class Main { public static void main(String[] args) { int m,n; Scanner s=new Scanner(System.in); System.out.println("Enter number of rows :"); m=s.nextInt(); System.out.println("Enter number of columns :"); n=s.nextInt(); System.out.println("Pattern :"); if(m==n) { for(int i=1;i<=m;i++) {

for(int j=1;j<=n;j++) { if(i==j) { System.out.print("#"); } else if(i%2==1) { System.out.print("*"); } else { System.out.print("&"); } } System.out.println(""); } } else { for(int i=1;i<=m;i++) { for(int j=1;j<=n;j++)

public static String swapPair(String str) { if (str == null || str.isEmpty()) return str; char[] ch = str.toCharArray(); for (int i = 0; i < ch.length - 1; i += 2) { char temp = ch[i]; ch[i] = ch[i + 1]; ch[i + 1] = temp; } return new String(ch); } public static void main(String args[]) { String str; Scanner scnr = new Scanner(System.in); System.out.print("Enter a string: "); System.out.println(); str = scnr.nextLine(); System.out.print("String after rearrange: "); System.out.println(); System.out.println(swapPair(str)); } }

4. Accept a string from user. Check whether it can

be a palindrome if we change a single character.

If it is so print “ Can be palindrome” and the

character need to be changed.

a. Else print “Not possible”

b. Eg : abcdcbg → reverse is “gbcdcba” If you

are changing g to a then it became a

palindrome

c. abcdaaa → “ Not possible”