Java exercises and solutions: loops in Java


Loops in Java

Exercise 1: Write a Java program by using two for loops to produce the output shown below:



*******

******

*****

****

***

**

*

Solution:


public class JavaExercises
{
public static void main(String[] args)
{
printStars();
}

static void printStars(){

int i,j;
for(i=0;i<=6;i++){
for(j=1;j<=7-i;j++) System.out.print("*");
System.out.println("");
     }



  }

}

Exercise 2: Write a Java program by using three for loops to print the following pattern:


1******

12*****

123****

1234***

12345**

123456*

1234567

Solution:


public class JavaExercises
{
public static void main(String[] args)
{
   printPattern();
}

static void printPattern(){

int i,j,k;

for (i = 1; i <= 7; i++)
{
  for (j = 1; j <= i; ++j)
      System.out.print(j);

  for (k = 7 - i; k >= 1; k--)
     System.out.print("*");

  System.out.println("");
      }



  }

}




Comments

Yuzana Hninn comment

 Yuzana Hninn

How can I write this java program with nested loop?
*****
* *
*****

**********
* *
**********

***************
* *
***************


2018-03-26
Yuzana Hninn comment

 Yuzana Hninn

*****
* *
*****

**********
* *
**********

***************
* *
***************


2018-03-26
Muuhammed Ajmal comment

 Muuhammed Ajmal

Check this code

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test_projects;

import java.util.Scanner;

/*
*
* @author majmals..............com
*/
public class Patterns
{

public static void main(String[] args)
{

Scanner in = new Scanner(System.in);
// Scanner funtion is used to input values

int i,j,k,n,c;
String s,l;

System.out.println("Note:- Never type a decimal value instead of integer value\n\n");
/* Below this code is to give color to the text */

////////////////////////////////////////////////////////////////////////////
System.out.println("Type your favorite color code " );
System.out.print("Color's \n " + "\u001B[31m" + "RED ");
System.out.print("\u001B[32m" + "GREEN " );
System.out.print("\u001B[33m" + "YELLOW ");
System.out.print("\u001B[34m" + "BLUE " );
System.out.print("\u001B[35m" + "PURPLE" );
System.out.print("\u001B[30m \n");
l = in.nextLine();
if(l.equalsIgnoreCase("red")){s="\u001B[31m";}
else if(l.equalsIgnoreCase("green")){s="\u001B[32m";}
else if(l.equalsIgnoreCase("yellow")){ s="\u001B[33m";}
else if(l.equalsIgnoreCase("blue")){s="\u001B[34m";}
else if(l.equalsIgnoreCase("purple")){s="\u001B[35m";}
else { System.out.println("Choose a correct color");s=null;}
if(s==null)
{
System.err.println("Program Terminated");
}
else{
////////////////////////////////////////////////////////////////////////////



System.out.println("\u001B[36m Choose the pattern\u001B[30m");
System.out.println("1. String \n2. Numeric \n3. Symbols");
c = in.nextInt();
switch(c)
{
////////////////////////////////////////////////////////////////////////
// Printing String
case 1:
System.out.println("\u001B[30m"+"ASCII Code of Alphabets"+"\u001B[30m");
for(k=65;k<91;k++)
{
if(k==78){System.out.println("");}

System.out.print("\u001B[35m" +(char) k + " = " + "\u001B[34m" +k + " ; " );
}
System.out.println("\nEnter the value start from");
n = in.nextInt();
for(i=65;i<=(n);i++)
{
System.out.println("");
for(j=65;j<=i;j++)
{
System.out.print(" "+s+ (char)j + " " );
}
}
////////////////////////////////////////////////////////////////////////
break;
////////////////////////////////////////////////////////////////////////
// Printing Numerics
case 2:
System.out.println("Enter the number to print the pattern order");
n = in.nextInt();

for(i=1;i<=n;i++)
{
System.out.println("");
for(j=1;j<=i;j++)
{
System.out.print(" "+s+ j + " " );
}
}
////////////////////////////////////////////////////////////////////////
break;
////////////////////////////////////////////////////////////////////////
// Printing Symbols
case 3:
System.out.println("Enter the times to itrate");
n = in.nextInt();
System.out.println("Enter your favorite symbol to print pattern order");
char v = in.next().charAt(0);
for(i=1;i<=n;i++)
{
System.out.println("");
for(j=1;j<=i;j++)
{
System.out.print(" "+s+ v + " " );
}
}
////////////////////////////////////////////////////////////////////////
break;
////////////////////////////////////////////////////////////////////////
// Default Text
default:
System.err.println("Choose a correct Pattern");
}

}
}
}


2017-11-13
Muuhammed Ajmal comment

 Muuhammed Ajmal

Check this code

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test_projects;

import java.util.Scanner;

/*
*
* @author majmals007@gmail.com
*/
public class Patterns
{

public static void main(String[] args)
{

Scanner in = new Scanner(System.in);
// Scanner funtion is used to input values

int i,j,k,n,c;
String s,l;

System.out.println("Note:- Never type a decimal value instead of integer value\n\n");
/* Below this code is to give color to the text */

////////////////////////////////////////////////////////////////////////////
System.out.println("Type your favorite color code " );
System.out.print("Color's \n " + "\u001B[31m" + "RED ");
System.out.print("\u001B[32m" + "GREEN " );
System.out.print("\u001B[33m" + "YELLOW ");
System.out.print("\u001B[34m" + "BLUE " );
System.out.print("\u001B[35m" + "PURPLE" );
System.out.print("\u001B[30m \n");
l = in.nextLine();
if(l.equalsIgnoreCase("red")){s="\u001B[31m";}
else if(l.equalsIgnoreCase("green")){s="\u001B[32m";}
else if(l.equalsIgnoreCase("yellow")){ s="\u001B[33m";}
else if(l.equalsIgnoreCase("blue")){s="\u001B[34m";}
else if(l.equalsIgnoreCase("purple")){s="\u001B[35m";}
else { System.out.println("Choose a correct color");s=null;}
if(s==null)
{
System.err.println("Program Terminated");
}
else{
////////////////////////////////////////////////////////////////////////////



System.out.println("\u001B[36m Choose the pattern\u001B[30m");
System.out.println("1. String \n2. Numeric \n3. Symbols");
c = in.nextInt();
switch(c)
{
////////////////////////////////////////////////////////////////////////
// Printing String
case 1:
System.out.println("\u001B[30m"+"ASCII Code of Alphabets"+"\u001B[30m");
for(k=65;k<91;k++)
{
if(k==78){System.out.println("");}

System.out.print("\u001B[35m" +(char) k + " = " + "\u001B[34m" +k + " ; " );
}
System.out.println("\nEnter the value start from");
n = in.nextInt();
for(i=65;i<=(n);i++)
{
System.out.println("");
for(j=65;j<=i;j++)
{
System.out.print(" "+s+ (char)j + " " );
}
}
////////////////////////////////////////////////////////////////////////
break;
////////////////////////////////////////////////////////////////////////
// Printing Numerics
case 2:
System.out.println("Enter the number to print the pattern order");
n = in.nextInt();

for(i=1;i<=n;i++)
{
System.out.println("");
for(j=1;j<=i;j++)
{
System.out.print(" "+s+ j + " " );
}
}
////////////////////////////////////////////////////////////////////////
break;
////////////////////////////////////////////////////////////////////////
// Printing Symbols
case 3:
System.out.println("Enter the times to itrate");
n = in.nextInt();
System.out.println("Enter your favorite symbol to print pattern order");
char v = in.next().charAt(0);
for(i=1;i<=n;i++)
{
System.out.println("");
for(j=1;j<=i;j++)
{
System.out.print(" "+s+ v + " " );
}
}
////////////////////////////////////////////////////////////////////////
break;
////////////////////////////////////////////////////////////////////////
// Default Text
default:
System.err.println("Choose a correct Pattern");
}

}
}
}


2017-11-13
DAB comment

 DAB

He Bheem,
Check below code

int sum=0, num=50;

double avg=0;
for (int i=1; i<=num;i++)
{
sum+=i;
}
System.out.println("Sum of 50 integers are: "+ sum);

avg= sum/num;

System.out.println("Avg of 50 integers are: "+ avg);


2017-08-15
DAB comment

 DAB

He Rita,
Check belowcode

for (int l=0;l<=4;l++)
{
System.out.print(" ");
for(int z=l+1;z<=5;z=z+1)
{
System.out.print(z);
}
System.out.println("");
}


2017-08-15
DAB comment

 DAB

He Manal,
Check this code

int rows=5;
for(int o=1;o<=rows;o++)
{
for(int n=1;n<=rows-1;n++)
{
System.out.print("*");
}
for(int q=1;q<=1;q++)
{
System.out.print("z");
}
System.out.println(" ");
}


2017-08-15
Jitesh comment

 Jitesh

@Rita

int i, j;

for(i = 0; i <= 5; i++)
{
for (j = i; j <= 5; j++)
System.out.println(j);
System.out.println("------------------------------------------");
}


2017-03-26
neetu comment

 neetu

*
* * @
* @
@ *
@ * *
*

For odd number 3 5 7 ...


2017-01-28
bhim kumar comment

 bhim kumar

write a java program to accept any 50 integers and print the sum,product and average of the integer using for loop


2016-12-25
manal comment

 manal

hello ..
how do i solve a program that ask the user to enter an integer number n then prints n rows on the screen ,each row has (n-1)blanks followed by n "z" character
please i want the solution quickly ):


2016-12-10
Shubham comment

 Shubham

Rita, you can use this code:

public class Pattern{

public static void main(String []args)
{
for (int i=1;i<6;i++)
{
for (int j=i;j<6;j++)
{System.out.print(j);}
System.out.println(" ");
}
}
}


2016-12-09
Tesfay Tsehaye comment

 Tesfay Tsehaye

10 Q .........


2016-12-05
Tesfay Tsehaye comment

 Tesfay Tsehaye

10 Q .........


2016-12-05
Digvijay comment

 Digvijay

Rajeev u can see a similarity in the program that all the group of astrics are even in count and odd one is single .
Hope it will help u.


2016-11-05
Vishvesh comment

 Vishvesh

Write a program to take a number from the user and check if it is a number which is the product of two consecutive integers
Eg 12
3(3+1)=3*4=12


2016-09-07
bigram comment

 bigram

Hello,

For info,
This solution works with 2 for statements:
public static void main(String[] args) {
// TODO Auto-generated method stub

int cpt = 2;
String str = "";
for (int i = 1; cpt < 9 ; i ++){
str+=i;
System.out.print(str);
for (int j = 8 - cpt; j > 0 ; j--){
System.out.print("*");
}
System.out.println("");
cpt++;
}


}



2016-09-05
Reaksmey Lim comment

 Reaksmey Lim

12345
2345
345
45
5
Here is the code to display that above:
int line,c;
for(line=5; line>=1; line--){
for(c=6-line; c<=5; c++)
System.out.print(c);
System.out.println();
}


2016-06-23
Rajeev comment

 Rajeev

can you please tell me how to code this pattern.

this pattern will change as per the value of n provided by user. it was asked in my interview.

n=1:
*
n=2:
* *
* *
*
n=3:
* *
* *
* * * *
* *
*
n=4:
* *
* *
* *
* * * *
* *
* * * *
* *
*

and so on.. pls tell iam not getting


2016-06-21
rita comment

 rita

Type comment
12345
2345
345
45
5

how to code this?


2016-05-03
Android Example comment

 Android Example

very nice blog, i have also found one good link here.
<a href="http://androidexample.com/While_-_Do_While_-_For_Loop_Statements_In_Java/example.php?view=description&aid=148&article=162&mcat=2">Loop Statements In Java</a>


2016-01-08
q comment

 q

So when i solved all of them without looking, am i fine with for loops? Because i still dont feel very confident even thought i enjoy solving them.


2015-09-04
adc comment

 adc

cadcadc davadv


2015-03-12
Dara comment

 Dara

This method can be called to get the max value of the array. You need to pass an integer array to the method.
public static int getMax(int[] arr){
int max=arr[0];
for(int i=1;i<=arr.length-1;i++){
if(max<arr[i]) max=arr[i];

}
return max;
}

The below method can be used to get the min value of an array. It also accepts an integer array.
public int getMin(int[] arr){
int min=arr[0];
for(int i=1;i<=arr.length-1;i++){
if(min>arr[i]) min=arr[i];

}
return min;
}


2013-12-16
Kamoto Suma comment

 Kamoto Suma

By using for loop, please help you to create two functions to find the max and min values of the array.
Thanks


2013-12-16



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.