java
Document.java
Java learning
//Package
choose package names related to your specific business topic. Rather than just using technical terms
// import
To simplify programming every program file will resuse existing code to do so you have to import the code in to your program file.
import statement will follow directly after the package declaration
package name must be included in the import statement.
package com.car.garage
import com.car.BMW
import com.car.* // import for specific files or all files using * symbol
import org.junit.Assert.*// beside regular import statementse6
//class
code is classified into different units of code.Such a unit we call a class.
// method
// variable
instance variable
static variable
local variable
parameter
argument
// Static variable
class HelloWorld{
static int age = 26;// static has to be used if the variable is outside the psvm
Public static void main(String[]args){
System.out.println("I am"+age+"years old.");
}
}
// public
Public is an access modifier that defines that any class from any package may use the class or method with public access modifier. Beside
public. ther are also other access modifiers like private default or protected.
//void
for every method, you actually have to define our return value. ironically, even when you dont want to return any value at all. in this
case, you will send void as return value.
query methods which will return a value but do not alter the state.
Command methods which alter the state but do not return a value.
// @Test
The Add symbol indicates an annotation. @Test is used as a test.
// dot " . "
car.drive() alternatively, say call the method drive on class car.
// object
when a java programm is running. it would usually create a certain number of objects that will exist as a set of values in the computers memory.And those values might change while the programm
running.
// object oriented language
Each program language follows certain concept, java is an object oriented language.
Everything is focused around objects in Java. In Java writing classes is a way of defining a model, which focuses on necessary aspects
to slove a specific problem.
// constructor
we need a specific method to create a object from classes files. method used to construct objects from class files.
// Variable decalration
car myPorsche;
// objection allocation
Car myPorsche = new Car(1,320);
___________________________________________________________________________________________________
//static vs non-static variable and methods in Java
// CODE
public class Main {
public static void main(String[] args) {
System.out.println(Cat.getCatCount());
Cat myCat = new Cat();
myCat.meow();
myCat.name = "Stella";
myCat.age = 8;
myCat.livesRemaining = 9;
System.out.println(Cat.Max_Lives);
//
Cat myCat1 = new Cat();
myCat1.meow();
myCat1.name = "July";
myCat1.age = 5;
myCat1.livesRemaining = 7;
System.out.println(Cat.Max_Lives);
System.out.println(Cat.getCatCount());
}
}
public class Cat {
public static final int Max_Lives = 9;
private static int catCount = 0;
String name;
int age;
int livesRemaining;
public void meow(){
System.out.println("Meow");
}
public Cat(){
catCount++;
livesRemaining = Max_Lives;
}
public static int getCatCount(){
return catCount;
}
}
// EXPLAINATION
// in file Main.java
public class Main {
public static void main(String[] args) {
System.out.println(Cat.getcatCount());
// all these fields on this method are non-static
// cat1
Cat myCat = new Cat();
myCat.meow();
myCat.name = "Stella";
myCat.age = 8;
myCat.livesRemaining = 9;
//cat2
Cat myCat1 = new Cat();
myCat1.meow();
myCat1.name = "July";
myCat1.age = 5;
myCat1.livesRemaining = 7;
// Technically you can access static fields and methods through an indvidual object this is going to be discourage and you get a warning. This will be miss leading and confusing
System.out.println(myCat.getCatCount());
// you should always access static methods and fields through the class not throught any individual object
System.out.println(Cat.getCatCount());
//note // non-static fields and methods can never be used without calling them on an indivual object
Cat.meow();
// using final we can make lives to be constant
System.out.Println(Cat.getCatCount());
}
}
// in file Cat.java
public class Cat {
// static fields used all the time is for constants
//Constatns are variable that don't ever change using final
public static final int Max_Lives = 9;
// initializing a static field
private static int catCount = 0;
String name;
int age;
int livesRemaining;
public void meow(){
System.out.println("Meow");
}
public Cat(){
catCount++;
livesRemaining = Max_Lives;
}
public static int getCatCount(){
return catCount;
//note// inside a static method we are not allowed to refer to any non-static fields i can't print out the cat's age here
System.out.println(age);
}
}
__________________________________________________________________________________________________
//
package com.john;
public class TestDemo {
public static void main(String[] args) {
int john_age= 28; // Integer Data type
String john_name="John Logan"; // serious of character data type
Boolean john_Working_Professional= true;
float john_cash=10000.50f; // "f" is used to reduce the floating value
double john_bank= 2000000.25;
System.out.println("John's DATA\n John age:"+john_age+"\n John full name:"+ john_name +"\n Working Professional:"+john_Working_Professional
+"\n Cash in hand:"+john_cash+"\n Cash in bank:"+john_bank);
//
Mr. Vincent works in a doormat manufacturing company. One day, he designed a new doormat with the following specifications:
Mat size must be N X M. ( N is an odd natural number, and M is 3 times N.)
The design should have 'WELCOME' written in the center.
The design pattern should only use |, . and - characters
Sample Designs
Size: 7 x 21
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.---
-------WELCOME-------
---.|..|..|..|..|.---
------.|..|..|.------
---------.|.---------
Size: 11 x 33
---------------.|.---------------
------------.|..|..|.------------
---------.|..|..|..|..|.---------
------.|..|..|..|..|..|..|.------
---.|..|..|..|..|..|..|..|..|.---
-------------WELCOME-------------
---.|..|..|..|..|..|..|..|..|.---
------.|..|..|..|..|..|..|.------
---------.|..|..|..|..|.---------
------------.|..|..|.------------
---------------.|.---------------
Input Format
A single line containing the space separated values of N and M.
Constraints
5 < N < 101
15 < M < 303
Output Format
Output the design pattern.
Sample Input
9 27
Sample Output
------------.|.------------
---------.|..|..|.---------
------.|..|..|..|..|.------
---.|..|..|..|..|..|..|.---
----------WELCOME----------
---.|..|..|..|..|..|..|.---
------.|..|..|..|..|.------
---------.|..|..|.---------
------------.|.------------
time complexity of n^2
Also works for odd numbers only
static void patternPrinting1( int rowVal ) {
int row = rowVal;
int col = row;
int mid = (col + 1) / 2;
int midcolmid = ((col * 3) + 1) / 2;
String str = "welcome";
int strPtr = 0;
int midAdder = 1;
for (int r = 0; r >= 0;) {
if (r == row / 2) {
for (int c = 1; c <= col * 3; c++)
if (c % midcolmid == 0 || (c % midcolmid >= midcolmid - 3 && c < midcolmid)
|| (c % midcolmid <= 3 && c > midcolmid))
System.out.print(str.charAt(strPtr++));
else
System.out.print('-');
midAdder = -1;
} else {
for (int c = 1; c <= col; c++) {
if ((c % mid >= mid - r && c <= mid) || (c % mid <= r && c >= mid)) {
System.out.print(".|.");
} else {
System.out.print("---");
}
}
}
System.out.println();
r += midAdder;
}
}
-------------------------------------------------------------------------------------------------------
// Data types storages in java primitive types and non primitive or reference types
// Primitive data types
// integers types
byte aSingleByte = 100; // -128 to 127
short aSmallNumber = 20000;// -32,768 to 32,767
int anInteger = 214783647; //-214783648 to 214783647
long aLargeNumber = 9223372036854775807L; // 9223372036854775808 to 9223372036854775809
** if the number is long you have append the letter "L" or "l" at the end of the number in long**
// decimal types
double aDouble = 1079769373; //4.9E-234 TO 1.796931348623157E308
float aFloat = 3.4028F;
** append "F" or "f" in a float let the compiler to know it is a float or by default it will consider as double.**
// Booleans
boolean isWeekend = False;
boolean isWeekend = True;
// Characters
char copyrightSymbol = '\u00A9'; // unicode subsequences
int myNumber = 77;
short myShort = 777;
long myLong = 77777;
float myFloat = 345.4f;
double myDouble = 345.456;
//Special characters
char myChar = 'y';
true or false
boolean myBoolean = true;
byte myByte = 127;
String text = "Hello";
String blank = " ";
String name = "John";
String greeting = text + blank + name;
System.err.println(greeting);
concatenating the string directly
System.err.println("my name is "+ name);
// conversion of the variable data types using cast operator
int to double conversion automatically done by compiler
double to int you need a cast operator
double num1 = 5.8;
int num2 = (int)num1;
S.O.P(num2);
https://www.geeksforgeeks.org/operators-in-java/ // to know more about operators
//Unary operators
-(operand)
n1=10
n1=-n1
!(operand)
convert true to false or vice versa
// Tenary operators in place of if -else statement
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
using tennary operator(?:)
num1 = 10;
num2 = 20;
res=(num1>num2) ? (num1+num2):(num1-num2)
Since num1<num2,
the second operation is performed
res = num1-num2 = -10
// String pull
When JVM use system memory to create a string.
// new string
if you create a new string2 with a same data inside it which matches the new string1.
public static void main(String[] args) {
String nam1 = "john";
String nam2 = "john";
System.out.println(nam1 == nam2); true
String name1 = new String("john");
String name2 = new String("john");
System.out.println(name1 == name2);false
System.out.println(name1.equals(name2));true
String n1 = new String("john");
String n2 = new String("JOHN");
System.out.println(n1 == n2);false
System.out.println(n1.equals(n2));false
System.out.println(n1.equalsIgnoreCase(n2));true
// formate specifier for Strings
public static void main(String[] args) {
String name = "John";//%s
String country = "India";
int age = 30;// %d
String company = "Scaler";
double gpa = 3.8;//%f
char percentSing = '%';//%c
boolean amITellingTheTruth = false;//%b
String formattedString = String.format(
"My name is %s. I am from %s. I am %d years old. I work for %s.%f.100%c.%b.", name,
country, age, company, gpa, percentSing, amITellingTheTruth);
System.out.println(formattedString);
//Format Specifiers
%c character
%d decimal (integer) number (base 10)
%e exponential floating-point number
%f floating-point number
%i integer (base 10)
%o octal number (base 8)
%s String
%u unsigned decimal (integer) number
%x number in hexadecimal (base 16)
%t formats date/time
%% print a percent sign
\% print a percent sign
Note: %n or \n are used as line separators in printf().
// Escape Characters
\b backspace
\f next line first character starts to the right of current line last character
\n newline
\r carriage return
\t tab
\\ backslash
// System.out.println
System.out.println(name.length())// length of a string
SOP(name.isEmpty()); // if empty true or else false
SOP(name.toUpperCase());
SOP(name.toLowerCase());
SOP(name1.equals(name2));// used beside ==
SOP(name1.equalsIgnoreCase(name2));//comparing the strings by ignore the cases. like alphetic case
// using for
//print small letters alphabets
for(char i = 'a'; i <='z'; i++){
System.out.print(i);
}
System.out.println();
//print captial letters alphabets
for(char i = 'A'; i <='Z'; i++){
System.out.print(i);
}
String string= "The sky is blue";
SOP(string.replace("blue","red"));// replace a part of string in java
//or
String string= "The sky is blue";
String updatedstring =string.replace("blue","red");
SOP(updatedstring);
SOP(string.contains("sky"))// String or Substring contain a certain word or substring or not by using this method
// using SOPf for formate specifier
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("What is your name?\n"); // \n is used instead of println
String name = scanner.nextLine();
System.out.printf("Hello %s. How are you?", name);
scanner.close();//
// Cleans up the input buffer while using input methods using parse method
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("What is your name?\n");
String name = scanner.nextLine();
System.out.printf("Hello %s. How old are you?\n", name);
int age = scanner.nextInt();
scanner.nextLine(); // this will clear the <enter> buffer from the user
// or
System.out.printf("Hello %s. How old are you?\n", name);
int age = Integer.parseInt(scanner.nextLine());
System.out.printf("%d is an good age to start.\nWhat language do you prefer?\n", age);
String language = scanner.nextLine();
System.out.printf("%s is a very popular programming language!", language);
scanner.close();
// parse method for double
double gpa = Double.parseDouble(scanner.nextLine());
// parse/parsing in java
Parsing is to read the value of one object to convert it to another type. For example you may have a string with a value of "10". Internally that string contains
the Unicode characters '1' and '0' not the actual number 10. The method Integer.parseInt takes that string value and returns a real number.
String tenString = "10"
//This won't work since you can't add an integer and a string
Integer result = 20 + tenString;
//This will set result to 30
Integer result = 20 + Integer.parseInt(tenString);
// CharSequence is an Interface for Period.parse();
" public static Period parse(CharSequence text) "
CharSequence is an Interface, implemented by Strings. So you can use Strings as a text element in parse() method.
Sure the string should be in proper format to return an object of Period class.
import java.time.Period;
class Main {
public static void main(String[] args) {
String age = "P17Y9M5D";
Period p = Period.parse(age);
System.out.println("the age is: ");
System.out.println(p.getYears() + " Years\n"
+ p.getMonths() + " Months\n"
+ p.getDays() + " Days\n");
// System.in input from the system user
please check the various input method like input from the file and and other place
//Declaring int type variable inside the for loop
int[] Intarr = {5,10,15,20,25,30,35};
for (int ArrItem : Intarr) {
// to take a input from the user using scanner.
import java.util.scanner;
Scanner sc = new Scanner(System.in);
String n1 = sc.next();
String n2 = sc.next();
System.out.println(n1 + " says Hi to " + n2);
// to present the out put of each word in separate line
String n1 = "A B C D E";
System.out.println(n1.replace(" ","\n"));
// or
String result = "cat" + System.lineSeparator() + "dog";
System.out.print(result);
import java.util.Scanner;
class Main {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String n1 = sc.next();
String n2 = sc.next();
System.out.println(n1 + " says Hi to " + n2);
}
}
--------------------------------------------------------------------------------------------------------------------------------------
String s1 = "Hello";
String s2 = "world";
String res = s1.concat(s2);
System.out.print("Concatenation result:: ");
System.out.println(res);
Scanner sc = new Scanner(System.in);
int A = sc.nextInt();
int B = sc.nextInt();
int C = sc.nextInt();
int D = sc.nextInt();
int E = sc.nextInt();
double Average = (double)(A+B+C+D+E)/5; // for single decimal
double Average = (A+B+C+D+E)/5.0;// for single decimal
System.out.print(Average);
//for two decimal
double Average = (A+B+C+D+E)/5;
System.out.printf("%.2f",Average);
// Math Functions
rounding numbers
System.out.print(Math.round(2.75) = 3
Floor
System.out.print(Math.floor(2.75) = 2
Ceiling
System.out.print(Math.ceil (2.05)= 3
// Print in the single line entire content " I am John"
Scanner sc = new Scanner(System.in);
String result = sc.nextLine();
System.out.print(result);
// Print the last digit of the number
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int result = num%10;
System.out.print(result);
Scanner sc = new Scanner(System.in);
String name = sc.next();
System.out.print("Hello" +" "+name);
Scanner sc = new Scanner(System.in);
int bill = sc.nextInt();
int no_of_bills = sc.nextInt();
System.out.print(bill*no_of_bills);
Scanner sc = new Scanner(System.in);
float N = sc.nextFloat();// Total budget of the trip
int M = sc.nextInt(); // value of single bill
System.out.print(Math.round(N/M));
--------------------------------------------------------------------------------------------------------------------------------------
// if // else if // else
--------------------------------------------------------------------------------------------------------------------------------------
//Ternary operator
The ternary operator is a shorthand version of the if-else statement. It has three operands and hence the name Ternary.
condition ? if true : if false
// Write a program for calculator using if and else statement
The above statement means that if the condition evaluates to true, then execute the statements after the ‘?’ else execute the statements after the ‘:’.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number:");
double number1 = Double.parseDouble(scanner.nextLine());
System.out.print("Enter the second number:");
double number2 = Double.parseDouble(scanner.nextLine());
System.out.print("What operation do you want to perform? ");
String operation = scanner.nextLine();
if (operation.equals("sum")) {
System.out.printf("%f + %f =%f", number1, number2, number1 + number2);
} else if (operation.equals("sub")) {
System.out.printf("%f - %f =%f", number1, number2, number1 - number2);
} else if (operation.equals("mul")) {
System.out.printf("%f * %f =%f", number1, number2, number1 * number2);
} else if (operation.equals("div")) {
if (number2 == 0) {
System.out.print("Can not divide by zero");
} else {
System.out.printf("%f / %f =%f", number1, number2, number1 / number2);
}
} else {
System.out.printf("%s is not a supported operation.", operation);
}
scanner.close();
// using Switch case statement for above calculator project
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number:");
double number1 = Double.parseDouble(scanner.nextLine());
System.out.print("Enter the second number:");
double number2 = Double.parseDouble(scanner.nextLine());
System.out.print("What operation do you want to perform? ");
String operation = scanner.nextLine();
switch (operation) {
case "sum":
System.out.printf("%f + %f =%f", number1, number2, number1 + number2);
break;
case "sub":
System.out.printf("%f - %f =%f", number1, number2, number1 - number2);
break;
case "mul":
System.out.printf("%f * %f =%f", number1, number2, number1 * number2);
break;
case "div":
if (number2 == 0) {
System.out.print("Can not divide by zero");
} else {
System.out.printf("%f / %f =%f", number1, number2, number1 / number2);
}
break;// using this break function outside the if else statement
default:
System.out.printf("%s is not a supported operation.", operation);
}
scanner.close();
// using Ternary operator for above calculator project
// Calculate the sum of the two numbers
double sum = (num1 + num2) > 0 ? (num1 + num2) : 0;
// Calculate the difference of the two numbers
double diff = (num1 - num2) > 0 ? (num1 - num2) : 0;
// Calculate the product of the two numbers
double product = (num1 * num2) > 0 ? (num1 * num2) : 0;
// Calculate the quotient of the two numbers
double quotient = (num1 / num2) > 0 ? (num1 / num2) : 0;
// Display the results
System.out.println("Sum: " + sum);
System.out.println("Difference: " + diff);
System.out.println("Product: " + product);
System.out.println("Quotient: " + quotient);
scanner.close();
Scanner sc = new Scanner(System.in);
int A = sc.nextInt();
int B = sc.nextInt();
if (A > B) {
System.out.print(A);
}
else if(A < B) {
System.out.print(B);
}
else {
System.out.print("both are equal");
}
if( A > B ) {
System.out.print(A+" is greater");
}
else if( A < B) {
System.out.print(B+" is greater");
}
else {
System.out.print("Both are equal");
}
Scanner sc = new Scanner(System.in);
int A = sc.nextInt();
if (A >= 1) {
System.out.print("1");
}
else if (A <= -1) {
System.out.print("-1");
}
else {
System.out.print("0");
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
if (x%2==0){
System.out.print("0");
}
else {
System.out.print ("1");
}
String [] Months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
Scanner sc = new Scanner(System.in);
int MonthNumber = sc.nextInt();
System.out.print(Months [MonthNumber-1]);
//Write a program to input three numbers(A, B & C) from user and print the maximum element among A, B & C in each line.
Scanner sc = new Scanner(System.in);
int A = sc.nextInt();
int B = sc.nextInt();
int C = sc.nextInt();
if (A > B && A > C){
System.out.print(A);
}
else if ( B > A && B > C) {
System.out.print(B);
}
else {
System.out.print(C);
}
// Calculate Grade of a student on 5 subjects marks
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
int e = sc.nextInt();
int Per = ((a + b + c + d + e)/5);
if (Per >= 90){
System.out.print(Per+"\nA");
}
else if (Per >=80 && Per <90){
System.out.print(Per+"\nB");
}
else if (Per >=70 && Per <80){
System.out.print(Per+"\nC");
}
else if (Per >=60 && Per <70){
System.out.print(Per+ "\nD");
}
else if(Per >= 40 && Per <60){
System.out.print(Per+"\nE");
}
else{
System.out.print(Per+ "\nF");
}
or but not accurate vaules you get
System.out.println(Per);
if(Per>=90) System.out.println('A');
else if(Per>=80) System.out.println('B');
else if(Per>=70) System.out.println('C');
else if(Per>=60) System.out.println('D');
else if(Per>=40) System.out.println('E');
else System.out.println('F');
//Write a program to input from user three numbers(A, B & C) representing side lengths of a triangle.
// You have to print if the traingle is "equilateral", "scalene" or "isosceles".
Scanner sc = new Scanner(System.in);
int A = sc.nextInt();
int B = sc.nextInt();
int C = sc.nextInt();
if (A == B && A == C && B == C) System.out.print("equilateral");
else if( A != B && A != C && B != C ) System.out.print("scalene");
else System.out.print("isosceles");
/// OR
Scanner scn = new Scanner(System.in);
int side1 = scn.nextInt();
int side2 = scn.nextInt();
int side3 = scn.nextInt();
if(side1 == side2 && side2 == side3) {
System.out.println("equilateral");
} else if(side1 == side2 || side1 == side3 || side2 == side3) {
System.out.println("isosceles");
} else {
System.out.println("scalene");
}
--------------------------------------------------------------------------------------------------------------------------------------
// While and dowhile Loops
--------------------------------------------------------------------------------------------------------------------------------------
// do while loop
int num = 5;
int mul = 1;
do {
System.out.printf("%d X %d = %d \n", num, mul, num * mul);
mul++;
} while (mul <= 10);
Scanner s = new Scanner(System.in);
int n = s.nextInt();
print all the numbers from 1 -> n
while( i <= n){
System.out.println(i);
i = i+1;
}
// Print all the odd numbers from 1 -> N
// Even numbers are always divisible by 2.
// Odd numbers are never divisible by 2.
5, 7, 9, 13, 15, 17
a%b == 0 -> b completely divides a.
a is an even number, a % 2 == 0
a is an odd numbers, a % 2 != 0
1, 2, 3, 4, 5, 6 ,7 , 8
1, 3, 5, 7, 9, 11
/*
int i = 1;
while( i <= n){
System.out.println(i);
i = i+2;
} */
/*
i -> 1, n = 20
i ->2, n=20
INCORRECT
True && False -> False
while( i <= n && i % 2 != 0){
System.out.println(i);
i = i+1;
}*/
// Print even numbers from 1->N
2, 4, 6, 8, 10, 12
int i = 2;
while( i <= n){
System.out.println(i);
i = i+2;
}
int i = 1;
while( i <= n){
if( i % 2 == 0){
System.out.println(i);
}
i = i+1;
}
// Print all the multiples of 4 from 1-> N
N = 40
4,8, 12, 16, 20, 24, 28, 32, 36, 40
int i = 1;
while( i <= n){
if( i % 4 == 0){
System.out.println(i);
}
i = i+1;
}
int i = 4;
while( i <= n){
System.out.println(i);
i = i+4;
}
// Q. Print all the perfect squares from 1->N
// DONOT USE BUILT IN FUNCTIONS
N = 20 (Perfect squares till 20)
1*1 = 1
2*2 = 4
3*3 = 9
4*4 = 16
5*5 = 25
// n =40
// 1*1
// 2*2
// 3*3
// 4*4
// 5*5
// 6*6
// 40*40
// 1, 4, 9, 16
int i = 1;
// we want i^2 <= n
// while( i <= n){
// if( i* i <= n){
// System.out.println(i*i);
// }
// i = i +1;
// }
// DRY RUN
/* n = 20
i. , while , if
i = 1, 1 <= 20(T), 1*1 <=20(T)
i =2, 2 <=20(T), 2*2 <=20(T)
i=3, 3 <=20(T), 3*3 <=20(T)
i=4, 4<=20(T), 4*4 <=20(T)
i=5, 5<=20(T), 5*5 <= 20(F)
i=6, 6<=20(T), 6*6 <= 20(F)
.
.
.
.
i=20, 20<=20(T), 20*20 <=20(F)
i=21 , 21<=20(F) -> break out of while
*/
// while( i* i <= n){
// System.out.println(i*i);
// i = i +1;
// }
/* n = 20
i. , while
i = 1, 1*1 <=20(T)
i = 2, 2*2 <=20(T)
i = 3, 3*3 <=20(T)
i = 4, 4*4 <=20(T)
i = 5, 5*5 <= 20(F) -> break out of while loop
*/
// ITERATIONS
int sum = 0;
while( n > 0){
sum = sum + (n%10);
n = n/10;
}
System.out.print(sum);
you have T test cases
Input is in the format :
/*
5
10
20
30
40
60
*/
int t = s.nextInt();
while(t > 0){
int n = s.nextInt();
int m = s.nextInt();
logic for n
System.out.println(n + " " + m);
t = t -1;
}
5
4
3
2
1
0
Scanner sc = new Scanner (System.in);
int N = sc.nextInt();
int i = 1;
while (i <= N){
System.out.print(" "+i); //or (i+" ");
i = i+1;
}
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
int i = 1;
while (i<=n && i%2 != 0){
System.out.print(i+" ");
i =i+2;
}
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
int sum =(n*(n+1)/2);{
System.out.print(sum);
}
// 0r
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int sum = 0;
int i = 1;
while(i <= n) {
sum += i;
i++;
}
System.out.println(sum);
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while (n >=0){
n = n -1;
System.out.print(n+" ");
/// using while print even numbers
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int i = 2;
while(i <= n) {
System.out.print(i + " ");
i += 2;
}
}
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = 2;
while (i < n){
if (i%2 == 0){
System.out.print(i+" ");
}
i++;
}
// using for
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i=1; i<=n; i++){
if((i%2)==0) {
System.out.print(i+" ");
}
}
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i =n ; i>=1; i=i-1){
System.out.print(i+" ");
}
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while (n >=1){
System.out.print(n+" ");
n--;
}
//Given an integer input N, print all multiples of 4 less than or equal to N.
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i =1;
while(i<=n){
if(i*4<=n){
System.out.print(i+" ");
} i= i+1;
}
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = 1;
while ( i <= n ) {
if ( i % 4 == 0 ) {
System.out.print(i + " ");
}
i++;
}
// Days in a months
int days [] = {31, 28, 31, 30, 30, 31, 30, 31, 30, 31, 30, 31};
Scanner scn = new Scanner(System.in);
int A = scn.nextInt();
int months= days[A -1];
System.out.print(months);
//sum of all odd numbers in the range [1, A].
//while loop
int odd=0;
Scanner scn= new Scanner(System.in);
int A = scn.nextInt();
int i=1;
while (i <= A){
if ( i%2 != 0){
odd=odd+i;
}
i++;
}
System.out.print(odd);
//using for loop
for(int i=1;i<=A; i++){
if(i%2 != 0){
odd= odd+i;
}
}
System.out.print(odd);
//You are given two integers A and B. You have to find the value of A to the power B.
Scanner scn = new Scanner(System.in);
int A = scn.nextInt();
int B= scn.nextInt();
int N= 1;
int i=0;
while(i<B){
i++;
N=N*A;
}
System.out.print(N);
// for loop
Scanner scn = new Scanner(System.in);
int A = scn.nextInt();
int B= scn.nextInt();
int N= 1;
for(int i=0;i<B;i++){
N=N*A;
}
System.out.print(N);
// print multiplication table
Scanner scn = new Scanner(System.in);
int A = scn.nextInt();
int range=10;
int i =1;
while(i<=range){
System.out.println(A+" "+"*"+" "+i+" "+ "="+" "+ A*i);
i++;
}
// print all the perfect quare root of N integer.
Scanner scn = new Scanner(System.in);
int N = scn.nextInt();
for(int i =1; (i*i)<=N;i++){
System.out.print(i*i+" ");
}
Scanner sc = new Scanner (System.in);
int A = sc.nextInt();
int i =1;
while((i*i)<=A) {
System.out.print(i*i +" ");
i++;
}
// Printing bank balance with credit and debit values.
Scanner scn = new Scanner(System.in);
long N = scn.nextLong(); // total balance
int M = scn.nextInt(); // no of transaction
for(int i =0; i<M;i++){
long T = scn.nextLong(), X= scn.nextLong(); // type of transaction // amount
if(T == 1){
N=N+X;
System.out.println(N);
}
else if(T ==2 && N>X){
N=N-X;
System.out.println(N);
}
else if(T==2 && N<X){
System.out.println("Insuffient Funds");
}
else{
System.out.println("Insuffient Funds");
}
}
------------------------------------------------------------------------------------------------------------------------------------
//For loop
------------------------------------------------------------------------------------------------------------------------------------
/* In Programming you may want to repeat a certain set of instruction again and again you can do that by using the loops
*/
for ( initialization , condition and variable update ){
logic}
int i = 1; int N = sc.nextInt(); for (int i=1; i<=N;i++){ if(i%2!=0){ System.out.print(i); }
// for loop to loop over an array
int num[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < num.length; i++) {
System.out.println(num[i]);
}
// sum
int num1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for (int i = 0; i < num1.length; i++) {
System.out.println(num1[i]);
sum += num1[i];
}
System.out.println("Sum of the array is " + sum);
// nested for loops for multiplication table
int num2 = 5;
for (int mul = 1; mul < 10; mul++) {
System.out.printf("%dx%d=%d\n", num2, mul, num2 * mul);
}
/*
* any variable declared outter forloop can be accessed by the nested for
* loop but the variables decalred in nested loop can be accessble for outter
* loop
*/
for (int n = 1; n <= 10; n++) {
for (int m = 1; m <= 10; m++) {
System.out.printf("%d x %d = %d \n", n, m, n * m);
}
}
/* for loop looping over collections such as array is mych easier */
int numbers[] = { 1, 2, 3, 4, 5 };
for (int number : numbers) {
System.out.println(number);
}
// sum of array using for loop
int numbers1[] = { 1, 2, 3, 4, 5 };
int sum1 = 0;
for (int number : numbers1) {
sum1 += number;
}
System.out.println("Sum of the array is " + sum1);
// SCOPES -> boundaries
{ //parent scope
int y = 1000;
{ //any scope within a scope becomes child scope
int x = 100;
System.out.println(y);
}
System.out.println(x);
}
int i;
Odd numbers from 1 to N
for(i = 1; i <= n; i++){
if( i % 2 != 0){
System.out.println(i);
}
}
System.out.println();
// Even numbers from 1 to N
for(i = 1; i <= n; i++){
if( i % 2 == 0){
System.out.println(i);
}
}*/
// for(int i = 1; i <= n; i = i + 2){
// System.out.println(i);
// }
// int n = s.nextInt();
// int sum = 0; // will add values starting from 1.
// int count = 0;
// for(int i = 1; i <= n ; i++){
// System.out.println("i = " + i);
// //our sum >= N, we need to stop adding further
// if( sum < n){
// //System.out.println("if i = "+ i);
// sum = sum + i;
// count++;
// } else { // sum >= N
// break;
// }
// }
// System.out.println(count);
/*
N = 10
i. sum. count.
1. 1. 1
2. 3. 2
3. 6. 3
4 10. 4
5 10. 4 -> from her onwards, everything else is pretty much useless
6. 10 4
7. 10. 4
8. 10. 4
9. 10. 4
10. 10. 4
11 -> exit out of for loop
N = 11
i. sum. count.
1. 1. 1
2. 3. 2
3. 6. 3
4 10. 4
5 15. 5
6. 15 5 -> from her onwards, everything else is pretty much useless
7. 15. 5
8. 15. 5
9. 15. 5
10. 15. 5
11 -> exit out of for loop
*/
int n = s.nextInt();
int sum = 0; // will add values starting from 1.
int count = 0;
for(int i = 1; sum < n ; i++){
System.out.println("i = " + i);
//our sum >= N, we need to stop adding further
sum = sum + i;
count++;
}
System.out.println("Final count = " + count);
// Printing first and last digit of the given input
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int first;
int last;
for( int i=1; i<=t;i++){
int n = sc.nextInt();
first = n;
//first digit
while (first>=10){
first=first/10;
}//lastdigit
last = n%10;
System.out.println(first + " " + last);
}
Scanner scn= new Scanner(System.in);
int n = scn.nextInt();
int first;
int last;
for(first=n; first>=10;first=first/10){
}last =n%10; System.out.println(first + " "+last);
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
for(int k = 1; k <= t;k++) {
int n = scn.nextInt();
int first = 0;
int last = 0;
last = n % 10;
for(; n > 0 ; n = n / 10) {
first = n % 10;
}
System.out.println(first + " " + last);
}
/// counting the factore for 5
Scanner sc= new Scanner(System.in);
int n= sc.nextInt();
int count = 0;
for (int i =1; i<=n; ++i){
if (n%i==0){
count++;
}
}
System.out.print(count);
Scanner sc= new Scanner(System.in);
int n= sc.nextInt();
boolen flag = true;
for(int i= 1; i<=n; i++){
if(n%i ==0){
System.out.print("Yes");
}else{
System.out.print("NO");
}
}
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i=1; i<=n; i=i+1){
if(n%i==0){
System.out.print("NO");
}
else if(n%i!=0){
System.out.print("YES");
}
}
// Prime number
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
boolean prime = true;
for(int i =2; i< n; i++){
if(n%i==0){
prime =false;
}
}
if(prime == true){
System.out.print("YES");
}
else{
System.out.print("NO");
}
Scanner sc = new Scanner(System.in);
int A = sc.nextInt();
boolean flag = true;
int i = 2;
while(i < A){
if(A % i == 0){
flag = false;
break;
}
i++;
}
if(flag == true)
System.out.print("YES");
else
System.out.print("NO");
//printing proper positive divisors
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int sum =0;
for(int i =1; i<n; i++){
if(n%i==0){
sum= sum +i;
}
}
if(sum==n){
System.out.print("YES");
}
else{
System.out.print("NO");
}
//printing proper positive divisors
Scanner scn = new Scanner(System.in);
int N = scn.nextInt();
for(int x=1; x<=N; x++){
int n = scn.nextInt();
int sum =0;
for(int i =1; i<n; i++){
if(n%i==0){
sum= sum +i;
}
}
if(sum==n){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
//or
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
for(int n = 1 ; n <= N ; n++) {
int A = sc.nextInt();
int sum = 0;
for(int i = 1 ; i < A ; i++) {
if(A % i == 0){
sum += i;
}
}
if(sum == A){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
or
public class Solution {
public int solve(int A) {
if(A == 1){
return 0;
}
int sum = 1;
for (int j = 2; j * j <= A;j++){
if(A % j == 0){
sum += j;
if(j != A / j){
sum += A / j;
}
}
}
if(sum == A){
return 1;
}
return 0;
}
}
// count the digits of given numbers
// Mr Q has a diary in which he has written a lot of numbers. He is confused with the number of digits in every number. Ask Mr Q about the total different numbers written in the diary and then write a code to find the number of digits in every number.
// Note: Total different Numbers are T and for every number (let's say N) you need to find the total number of digits.
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for(int n=1; n<=T; n++){
int A = sc.nextInt();
int sum = 0 ;
while (A!=0){
A=A/10;
sum++;
}
System.out.println(sum);
}
//determine whether it is palindromic
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int t,s,rev=0;
t=n;
for(s=0;n>0;n/=10){
rev=n%10;
s=(s*10)+rev;
}
if(s == t){
System.out.print("YES");
} else {
System.out.print("NO");
}
// using while
Scanner sc = new Scanner(System.in);
int A = sc.nextInt();
int tempA = A;
int revA = 0;
while(tempA > 0){
int lastdig = tempA % 10;
revA = (revA * 10) + lastdig;
tempA /= 10;
}
if(revA == A){
System.out.print("Yes");
}
else{
System.out.print("No");
}
//Printing HCF/GCD of two integers
Scanner scn = new Scanner(System.in);
int A = scn.nextInt(),B = scn.nextInt();
int result;
while(B > 0){
result= B;
B=A%B;
A=result;
}
System.out.print(A);
// for loop
Scanner scn = new Scanner(System.in);
int a = scn.nextInt(),b = scn.nextInt();
int g=1;
for(int i =1;i<a;i++){
if(a%i == 0 && b%i == 0){
g=i;
}
}
System.out.println(g);
// Sum the digits
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for(int n=1; n<=T; n++){
int A = sc.nextInt();
int sum=0;
for(sum=0; A!=0;A=A/10){
sum+=A%10;
}
System.out.println(sum);
}
//or
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
while(t > 0) {
int n = scn.nextInt();
int sum = 0;
while(n > 0) {
int d = n % 10;
sum += d;
n = n / 10;
}
System.out.println(sum);
t--;
}
// print all the Armstrong Numbers between 1 to N.
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for(int i=1; i<=T;i++){
int num =i;
int M=0;
while(num>0){
int dig =num%10;
M+=(dig*dig*dig);
num=num/10;
}
if(i == M) System.out.println(i);
}
// print all the Prime Numbers between 1 and N.
Scanner scn = new Scanner(System.in);
int N = scn.nextInt();
for(int i=1; i<=N; i++){
int count =0;
for (int j = 1; j <= N; j++) {
if (i % j == 0) {
count++;
}
}
if (count == 2) {
System.out.println(i);
}
}
public class Solution {
public int solve(int A) {
int cnt = 0;
// Looping from 1 to A
for(int i=1 ; i<=A ; i++){
int factors = 0;
// Looping from 1 to i
for(int j=1;j<=i;j++) {
if(i%j==0){
factors++;
}
}
if(factors==2) {
cnt++;
}
}
return cnt;
}
//integers A and B in the input and prints their LCM.
Scanner scn = new Scanner(System.in);
int A = scn.nextInt();
int B = scn.nextInt();
int hcf = 1;
for (int i = 1; i <= A && i <= B; i++) {
if (A % i == 0 && B % i == 0) {
hcf = i;
}
}
int lcm = (A * B) / hcf;
System.out.print(lcm);
----------------------------------------------------------------------------------------------------------
// Patter printings
----------------------------------------------------------------------------------------------------------
/*
for(int i = 1; i<=10; i=i+2){
System.out.println(i);
} // 1 3 5 7 9
*/
// B -> * N-1 times
//for(int i=1; i<N; i++){
// System.out.print("*");
// }
// DRY RUN : N = 10
//1, 2, 3, 4, 5, 6, 7, 8, 9 -> 9 numbers
// C -> * N+1 times
//for(int i=0; i<=N; i++){ System.out.print("*");}
// DRY RUN : N = 10
// 0, 1, 2,3 ,4 ,5 ,6 ,7 , 8, 9, 10 -> 11 numbers
// A -> * N times
//for(int i=1; i<=N; i++){ System.out.print("*");}
// DRY RUN : N = 10
// 1,2, 3, 4,5, 6, 7,8, 9, 10 -> 10
// MATHEMATICAL NOTATION:
// i takes values from 1-> 10 : Boundary numbers are included
// i -> [1, 10]
// i -> [9, 99]
// i -> (1, 10 ] , i takes value of 10.
// i -> [2, 10]
// i -> (1, 10) : boundary numbers are excluded.
// i : 2, 3,4 ,5,6,7,8,9
// i -> [1, 10] : 1, 2,3,4,5 ,6,7,8,9,10
// i-> [9, 99]: 90 => 99 - 9 + 1 => 91
// - - - - - - - - - - - -
// L=9 R=99
// [L, R] -> R - L +1
// Q. Print the following Pattern
// N = 3
/*
***
***
***
*/
// N = 4
/*
****
****
****
****
*/
// Open IDE -> Code the logic -> Check output.
Scanner s = new Scanner (System.in);
int n= s.nextInt();
// for(int i=1;i<=n;i++){
// System.out.println("***");
// }
// Number of rows? N
// row number 1 -> print stars
// row number 2 -> print stars
// row number 3-> print stars
/*
for(int i = 1; i <= n; i++){
// this logic prints ith row
// in each row, I need to print n stars
for(int j=1; j <= n; j++){
System.out.print("*");
}
System.out.println();
}*/
/* Dry run :
N = 3.
i. j. output
1. 1 ***
2.
3
4 ( break )
2. 1 ***
2. ***
3.
4 ( break )
3. 1 ***
2. ***
3. ***
4 ( break )
4.(break)
*/
// Q. Print the following Pattern
// N = 3
/*
***
**
*
*/
// N = 4
/*
****
***
**
*
*/
// N = 5
/*
*****
****
***
**
*
*/
/*
for(int i =1; i <= n; i++){
// logic for ith row
// [ 1, n - i + 1] => n - i + 1
for(int j = 1; j <= (n - i + 1); j++){
System.out.print("*");
}
System.out.println();
}*/
/*
for(int i =1; i <= n; i++){
// logic for ith row
// [ 1, n - i + 1] => n - i + 1
for(int j = i; j <= n ; j++){
System.out.print("*");
}
System.out.println();
}*/
// Now I just need to find out number
// of stars in ith row.
// Value known to me before executing
// internal for loop
// 'i', 'n'
// if I can figure out the number
// of stars in terms of n and i,
// I'm almost done!
/*
N = 5
i. number of stars
1 5 -> 5(N) - 0 (1(i) - 1)
2 4 -> 5(N) - 1 (2(i) - 1)
3 3 -> 5(N) - 2 (3(i) - 1)
4 2 -> 5(N) - 3 (4(i) - 1)
5 1 -> 5(N) - 4 (5(i) - 1)
ith row -> N - ( i -1) -> N - i + 1
ith row -> N - i + 1
n = 5
i = 5, 5 -5 +1 = 1 stars
i = 1, 5 - 1 + 1 = 5 stars
*/
// in ith row, need to print n-i+1 stars
// j = 1 to n-i +1
// j = i to n -> [i, n] -> n -i +1
// Q. Print the following pattern
// N = 3
/*
*
**
***
*/
// N = 4
/*
*
**
***
****
*/
// N = 5
/*
*
**
***
****
*****
*/
/*
for(int i = 1; i <= n; i++){
// logic for every ith row
// 'i' & 'n' are known to me.
for(int j = 1 ; j <= i; j++){
System.out.print("*");
}
System.out.println();
}*/
/*
N = 3
output
*
**
***
i. j.
1. 1
2 (break)
2. 1
2
3(break)
3. 1
2
3
4(break)
4(break)
/*
N -> 5
i. number of stars
1. 1(i)
2. 2(i)
3. 3(i)
4. 4(i)
5. 5(i)
*/
// Pattern with spaces ( - )
/*
// N = 3
*--*
*--*
*--*
// N = 4
*---*
*---*
*---*
*---*
// N = 5
*----*
*----*
*----*
*----*
*----*
*/
/*
for(int i = 1; i <= n; i++){
// logic for ith row
for(int j = 1; j <= n+1; j++){
if( j == 1 || j == n+1){
System.out.print("*");
} else {
System.out.print("-");
}
}
System.out.println();
}*
*/
// each row -> * + some - + *
/*
for(int i = 1; i <= n; i++){
// logic for ith row
System.out.print("*");
for(int j = 1; j <= n-1; j++){
System.out.print("-");
}
System.out.print("*");
System.out.println();
} */
/* DRY RUN
N = 3;
Output
*--*
*--*
*--*
i j
1. 1
2
3(break)
2. 1
2
3(break)
3. 1
2
3(break)
4( break)*/
// Q. Pattern printing
/*
N =3
*--*
*-*
**
N = 4
*---*
*--*
*-*
**
N =5
*----*
*---*
*--*
*-*
**
*/
// each row -> * + some - + *
/*
for(int i = 1; i <= n; i++){
// logic for ith row
System.out.print("*");
for(int j = 1; j <= n- i; j++){
System.out.print("-");
}
System.out.print("*");
System.out.println();
}*/
******
* *
* *
for(int i = 1; i <= n; i++){
// logic for ith row
for(int j = 1; j <= n - i + 2; j++){
if( j == 1 || j == n - i + 2){
System.out.print("*");
} else {
System.out.print("-");
}
}
System.out.println();
}
/*
N = 5
i -> how many items
1. 6 -> 5(N) - 1(i) + 2
2. 5 -> 5(N) - 2(i) + 2
3. 4 -> 5(N) - 3(i) + 2
4. 3 -> 5(N) - 4(i) + 2
5. 2 -> 5(N) - 5(i) + 2
//ith -> n - i + 2
// N = 5
/*
i. number of dashes(-)
1. 4 -> 5(N) - 1(i)
2. 3 -> 5(N) - 2(i)
3. 2 -> 5(N) - 3(i)
4. 1 -> 5(N) - 4(i)
5. 0 -> 5(N) - 5(i)
*/
// ith row -> n-i
// Scanner s = new Scanner (System.in);
// int n= s.nextInt();
// for(int i=1;i<=n;i++){
// System.out.println("***");
// }
// Scanner s = new Scanner (System.in);
// int col= s.nextInt();
// int row= s.nextInt();
// for(int i = 1; i <= col; i++){
// for(int r=1; r<= row; r++){
// System.out.print("*");
// }
// System.out.println();
// }
// Scanner sc = new Scanner(System.in);
// int A= sc.nextInt();
// for(int lp = 1; lp <= A; lp++){
// for(int lp1 = 0; lp1 <= A-lp; lp1++){
// System.out.print(" * ");
// }
// System.out.println("");
// }
// Scanner sc = new Scanner(System.in);
// int A= sc.nextInt();
// for(int lp = 1; lp <=A; lp++){
// for(int lp1 = 1; lp1 <=lp; lp1++){
// System.out.print("*");
// }
// System.out.println("");
// }
// Scanner sc = new Scanner(System.in);
// int n= sc.nextInt();
// for(int i = 1; i <= n; i++){
// //logic for ith row
// for(int j = 1; j <= n+1; j++){
// if( j == 1 || j == n+1){
// System.out.print(i);
// } else {
// System.out.print("-");
// }
// }
// System.out.println();
// }
// Scanner sc = new Scanner(System.in);
// int n= sc.nextInt();
// for(int i = 1; i <= n; i++){
// for (int j= 1; j<=i; j++){
// if((j%2!=0)){
// System.out.print(j);
// } else {
// System.out.print("_");
// }
// }
// System.out.println();
// }
// for (int i =1; i<=n;i++){
// for(int j=1;j<=i;j++){
// if(j%2 !=0){
// System.out.print("*");
// }else{
// System.out.print("_");
// }
// }System.out.println();
// }
// for (int i =1; i<=n;i++){
// for(int j=1;j<=i;j++){
// System.out.print("*");
// }
// for(int j=1;j<=2*(n-i);j++) {
// System.out.print(" ");
// }
// for(int j=1;j<=i;j++){
// System.out.print("*");
// }
// System.out.println();
// }
// for (int i =1; i<=n;i++){
// for(int j=1;j<=(n-i+1);j++){
// System.out.print("*");
// }
// for(int j=1;j<=2*(i-1);j++) {
// System.out.print(j);
// }
// for(int j=1;j<=(n-i+1);j++){
// System.out.print("*");
// }
// System.out.println();
// }
// for(int i = n; i > 0; i--){
// for(int j = 1; j <= n; j++){
// if(j < i){
// System.out.print(" ");
// }else{
// System.out.print("*");
// }
// }
// System.out.println();
// }
// for (int i =1; i<=n;i++){
// for(int j=1;j<=(n-i);j++){
// System.out.print("0 ");
// }
// for(int j=i;j<=(2*i)-1;j++){
// System.out.print(j+" ");
// }
// for(int j=(2*i)-2;j>=i;j--){
// System.out.print(j+" ");
// }
// for(int j=1;j<=(n-i);j++){
// System.out.print("0 ");
// }
// System.out.println();
// }
______________________________________________________________________________________________________________________________________
\\ Functions
______________________________________________________________________________________________________________________________________
Block of code that take some input and perform some task on it and returns the output
import java.util.Scanner;
class Main {
Public static int sum(int a, int b){
int c = a+b;
return c;
}
public static void main(String args[]) {
int s=sum(4,30);
System.out.print(s);
}
// Given two integers A and B. A represents the count of mangoes and B represent the count of slices of mangoes. Mango can be cut into three slices of mangoes. A glass of mango shake can be formed by two slices of mangoes.
import java.util.Scanner;
class Main {
public static int solve(int A, int B) {
int slice= A*3;
int glass = (slice + B)/2;
return glass;
}
public static void main(String args[]) {
Scanner scn = new Scanner(System.in);
int A = scn.nextInt();
int B = scn.nextInt();
int S = solve(A,B);
System.out.print(S);
//WAF(write a function) to return the max of 2 numbers
static int maxOfTwo(int a, int b) {
if(a>b) {
return a;
}
return b;
}
static int maxOfTwo(int a, int b) {
return Math.max(a, b);
}
*/
static int minOfTwo(int a, int b) {
return Math.min(a, b);
}
//WAF to check if a given number is prime or not?
public static boolean checkPrime(int x) {
int factors =0;
for(int i=1; i<=x; i++) {
if(x%i == 0) {
factors++;
}
}
if(factors == 2){
return true;
}
else {
return false;
}
}
// floor(x): largest integer less than equal to x
4.6 => 4
8.3 => 8
0.6 => 0
System.out.println((int)Math.floor(4.6));
ceil(x): smallest integer greater than equal to x
4.6 => 5
8.3 => 9
0.6 => 1
System.out.println((int)Math.ceil(0.6));
double pi = Math.PI;
System.out.println(pi)
______________________________________________________________________________________________________________________________________
\\ Arrays
______________________________________________________________________________________________________________________________________
Collection of simmilar type of data arranged in a liner fashion.
// importing the arrays class to convert the array output to strings
import java.util.Arrays;
// Printing out the complete array indexs
char vowels[] = new char[5];
vowels[0] = 'a';
vowels[1] = 'e';
vowels[2] = 'i';
vowels[3] = 'o';
vowels[4] = 'u';
System.out.println(vowels[2]);
System.out.println("The complete array indexs are: " + Arrays.toString(vowels));
// declare and define your array in one line
char vowels[] = {'a','e','i','o','u'};
// Printing out the complete array indexs
char vowels[] = { 'a', 'e', 'i', 'o', 'u' };
vowels[2] = 'x';// replace the array in the indexes
// incase of a string the length is a method but in case of an array it is a
// propert
System.out.println(vowels.length); // to get the length of an array
System.out.println(vowels[2]);
System.out.println("The complete array indexs are: " + Arrays.toString(vowels));
// sorting and unsorting of an array using the sort method
char num[] = { '4', '3', '1', '0', '2' };
Arrays.sort(num);
System.out.println(Arrays.toString(num));
// sorting within a certain range
char num1[] = { '4', '3', '1', '0', '2' };
Was this helpful?
Similar Posts