In: Computer Science
SumOfOdd.java
class SumOfOdd
{
public static void main(String args[])
{
//sum variable which store the sum
of odd numbers
int sum=0;
//iterate for loop from 1 to 99
inclusively
for(int i=1;i<=99;i++)
{
//If i is odd
then add i to sum
if(i%2==1)
{
sum=sum+i;
}
}
//print the reuslt
System.out.println("Sum of odd
numbers between 1 to 99 is: "+sum);
}
}
output screenshot:
NamePrint.java
class NamePrint
{
public static void main(String[] args)
{
//n denotes number of times to
print
int n=7;
//name initialization
String name="ABC DEF GHI";
//Iterate while loop for 7
times
while(n>0)
{
//Print the
result
System.out.println(name);
//decrement n by
1
n--;
}
}
}
output screenshot:
ArrayPrint.java
class ArrayPrint
{
public static void main(String[] args)
{
//array of names
initialization
String dogNames[ ] =
{"Sam","Buster","Fido","Patches","Gromit","Flicka"};
//Iterate over array of names
for(int
i=0;i<dogNames.length;i++)
{
//print
horizontal manner
System.out.print(dogNames[i]+" ");
}
//New line for printing result in
vertical manner
System.out.println();
//Iterate over array of names
for(int
i=0;i<dogNames.length;i++)
{
//Print vertical
manner
System.out.println(dogNames[i]);
}
}
}
output screenshot:
IndentText.java
class IndentText
{
public static void main(String[] args)
{
//initialization of userNum
int userNum=5;
//iterate userNum times
for(int
i=userNum;i>=0;i--)
{
//iterate from 1
to i inclusive
for(int
j=1;j<=i;j++)
{
//print s denotes the space
System.out.print("s");
}
//print i
System.out.println(i);
}
}
}
output screenshot:
StringOperation.java
//importing Random class
import java.util.Random;
class StringOperation
{
public static void main(String[] args)
{
//Initialization of fullName
String fullName="ABCDEFG
HIJK";
//creating object for Random
class
Random rand = new Random();
//n denotes the number of time that
while loop repeats
int n=5;
while(n>0)
{
//generate
random numebr between 1 to 4
int
i=rand.nextInt(4)+1;
//If i is 1 then
print full name in upper case
if(i==1)
{
System.out.println(fullName.toUpperCase());
}
//If i is 2 then
print full name in lower case
else
if(i==2)
{
System.out.println(fullName.toLowerCase());
}
//if i is 3 then
replace first name with Three
else
if(i==3)
{
//find the index of first space
int index=fullName.indexOf(' ');
//repalce first name with Three
fullName="Three
"+fullName.substring(index+1);
System.out.println(fullName);
}
//If i is 4
print the character at 4th index
else
if(i==4)
{
System.out.println(fullName.charAt(4));
}
//decrement n by
1
n--;
}
}
}
output screenshot: