0% found this document useful (0 votes)
49 views5 pages

Java Labs 2.0: Looping Techniques

The document contains 14 programming exercises on loops and patterns in Java. It introduces while, do-while, and for loops, and provides examples to print numbers, check for palindromes, calculate sums of digits, and print various patterns using nested loops. It also covers taking input from the keyboard and includes exercises to find the largest of three numbers, calculate a square root, and get the sum of digits of a given number by accepting input. The final exercises are to print a multiplication table for a given number and implement a basic calculator using switch statements.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views5 pages

Java Labs 2.0: Looping Techniques

The document contains 14 programming exercises on loops and patterns in Java. It introduces while, do-while, and for loops, and provides examples to print numbers, check for palindromes, calculate sums of digits, and print various patterns using nested loops. It also covers taking input from the keyboard and includes exercises to find the largest of three numbers, calculate a square root, and get the sum of digits of a given number by accepting input. The final exercises are to print a multiplication table for a given number and implement a basic calculator using switch statements.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Omar Mukhtar University Faculty of Engineering

Dept. of Computer Engineering


Albeida , Libya
Instructor: Mrs. Krishna Kumari Ganga

Advanced Programming 1: Lab sheet 2

Loops

1. program to print numbers from 1 to 9


class NumDisplay {
public static void main(String arg[]) {
[Link]( “1”);
[Link]( “2”);
[Link]( “3”);
[Link]( “4”);
[Link]( “5”);
[Link]( “6”);
[Link]( “7”);
[Link]( “8”);
[Link]( “9”);
}
}
2. program to print numbers from 1 to 9 using while loop
class WhileLoop {
public static void main(String arg[]) {
int i=1;
while(i<10) {
[Link]( i);
i++;
}
}
}
3. program to print numbers from 1 to 9 using do while loop
class DoLoop {
public static void main(String arg[]) {
int i=15;
do {
[Link]( i);
i++;
} while(i<10);
}
}
Note: The difference between while loop and do while loop is the while loop executes the statements only when
the condition is satisfied. But do while executes the statements for the first time before checking the condition
4. Program to check whether the number is palindrome or not using while loop
Palindrome: A number which will be the same if we read backward of forward
Ex: 121, 34543, 26862
class palind {
public static void main(String a[ ]) {
int n,temp, m, rev = 0;
n = 2335332;
temp = n;
while( temp > 0 ) {
m = temp % 10;
rev = ( rev * 10 ) + m;
temp = temp / 10;
}
if( rev == n )
[Link]("The number "+ n + " is a palindrome" );

Advanced Programming Using Java - Prepared by: Krishna Kumari Ganga


else
[Link]("The number "+ n + " is not a palindrome" );
}
}
5. Program to Find the Sum of the Digits of a Number using while loop
class DigitAdd {
public static void main(String args[]) {
int temp,sum=0;
int num=12345;
[Link]("The number is:" +num);
while ( num > 0 ) {
temp = num % 10;
num = num / 10;
sum = sum + temp;
}
[Link]("The sum of the digits of the above number is:" +sum);
}
}
6. program to print numbers from 1 to 9 using for loop
class ForLoop {
public static void main(String arg[]) {
//int i=1;
//while(i<10)
for(int i=1;i<10;i++) {
[Link]( i);
//i++;
}
}
}
7. program to print the below pattern
* * * *
class ForLoop1 {
public static void main(String arg[]) {
for(int i=1;i<=4;i++) {
[Link]( “* ”);
}
[Link]( );
}
}
8. program to print the below pattern
* * * *
* * * *
* * * *
* * * *
class ForLoop2 {
public static void main(String arg[]) {
for(int i=1;i<=4;i++) {
[Link]( “*”);
}
[Link]( );
for(int i=1;i<=5;i++) {
[Link]( “*”);
}
[Link]( );
for(int i=1;i<=5;i++) {
[Link]( “*”);
}

Advanced Programming Using Java - Prepared by: Krishna Kumari Ganga


[Link]( );
for(int i=1;i<=4;i++) {
[Link]( “* ”);
}
[Link]( );

}
}

9. program to print the below pattern


* * * *
* * * *
* * * *
* * * *
class ForLoop3
{
public static void main(String arg[])
{
For(int i=1;i<=4;i++)
{ //nested for loop
for(int j=1;j<=4;j++)
{
[Link]( “*”);
}
[Link]( );
}
}
}

10. program to print the below pattern


*
* *
* * *
* * * *
class ForLoop4 {
public static void main(String arg[]) {
for(int i=1;i<=4;i++) {
for(int j=1;j<=i; j++) {
[Link]( “*”);
}
[Link]( );
}
}
}

11. program to print the below pattern


1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
class ForLoop5 {
public static void main(String arg[]) {
for(int i=1;i<=4;i++) {
for(int j=1;j<=4;j++) {
[Link]( j+ “ “);
}
[Link]( );

Advanced Programming Using Java - Prepared by: Krishna Kumari Ganga


}
}
}

12. program to print the below pattern


1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
class ForLoop6 {
public static void main(String arg[]) {
for(int i=1;i<=4;i++) {
for(int j=1;j<=4;j++) {
int k= i+j-1;
if (k>4)
[Link]( k-4+” “);
else
[Link]( k+” “);
}
[Link]( );
}
}
}
13. Write a program to display the following pattern by using for loops?
* * * *
* * *
* *
*
14. Write a program to display the following pattern by using for loops
* * * * *
* *
* *
* *
* * * * *

Advanced Programming Using Java - Prepared by: Krishna Kumari Ganga


Taking Input from the Keyboard

1. Program to find the biggest of the three numbers by taking the input from keyboard
public class Biggest {
public static void main(String a[])throws IOException {
DataInputStream dts=new DataInputStream([Link]);
[Link]("Enter the first number");
int x=[Link](dts. readLine());
[Link]("Enter the second number");
int y=[Link](dts. readLine());
[Link]("Enter the third number");
int z=[Link](dts. readLine());
if (x>y && x>z)
[Link]("The biggest number is "+x);
else if (y>z && y>x)
[Link]("The biggest number is "+y);
else
[Link]("The biggest number is "+z);

}
2. Program to find the square root of a number by taking the input from keyboard
class Sqrt {
public static void main(String a[])throws IOException {
DataInputStream dts=new DataInputStream([Link]);
[Link]("enter number to find squaroot");
int m=[Link](dts. readLine());
[Link]("square root of "+ m + " = "+[Link](m));
}
}
3. Program to find the sum of digits of a given number by taking the input from keyboard
class DigitAdd1{
public static void main(String args[])throws IOException{
int temp,sum=0;
DataInputStream dts=new DataInputStream([Link]);
[Link]("enter number to get the sum of digits");
int num=[Link](dts. readLine());
[Link]("The number is:" +num);
while ( num > 0 ){
temp = num % 10;
num = num / 10;
sum = sum + temp;
}
[Link]("The sum of the digits of the above number is:" +sum);
}
}

4. Write a program to print the multiplication table of a given number?

5. Write a program to implement the Basic Functionality of a Calculator using Switch?

Best of luck

Advanced Programming Using Java - Prepared by: Krishna Kumari Ganga

Common questions

Powered by AI

To modify the program to print hash (#) symbols instead of asterisks while maintaining the loop structure, you would replace every instance of System.out.print("*") with System.out.print("#"). This simple substitution will alter the character being printed while preserving the existing loop logic .

Initializing variables outside the loop in the palindrome-checking program is significant because these variables hold necessary states that persist across all iterations. For instance, 'rev' retains the accumulated reverse number, and 'temp' starts with the full input number that it continuously reduces. If they were initialized inside the loop, they would reset with each iteration, preventing the logic needed to correctly determine if the number is a palindrome .

When designing a program to find the square root of a numerical input in Java, considerations include managing user input effectively—ensuring the program handles non-numeric inputs gracefully and avoids runtime errors. Using exception handling is critical to intercepting parsing errors from wrong formats. Additionally, after obtaining the input value, the program should leverage Java's Math.sqrt() for precise calculations and ensure that any necessary rounding or formatting is applied before outputting the result. Consideration for performance and efficiency when handling large numbers may also be important .

To print a defined numeric pattern via a 'for loop', the process involves nested loops. The outer loop manages the number of lines, while the inner loop controls the sequence of numbers or characters printed on each line. For instance, to print a repeating sequence of numbers from 1 to 4 across multiple lines, the outer loop might iterate over lines, and the inner loop runs from 1 to 4 to print the sequence on each line .

The program to find the biggest of three numbers in Java uses conditional statements to compare the numbers. It implements a series of 'if-else' conditions to evaluate different scenarios: first checking if the first number is greater than the other two; if not, the second condition checks if the second number is greater than the third; otherwise, it defaults to the third number being the greatest. These comparisons ensure the program correctly determines and outputs the largest number .

In the Java program to check if a number is a palindrome, the modulus operator (%) is used to extract the last digit of the number. By dividing the number by 10 and capturing the remainder with %, the program obtains the last digit, which is then used to reconstruct the number in reverse order. This operation is repeated in a loop to process all digits .

Using a DataInputStream for reading keyboard input adds complexity by requiring explicit management of exceptions and data parsing. Each read operation involves potential IOExceptions, necessitating try-catch blocks or throws declarations. Additionally, since input is read as a string and often needs conversion (e.g., to integers), there is an added layer of complexity involving parsing methods like Integer.parseInt(), increasing the error handling and type management developers must implement compared to higher-level classes like Scanner .

The program reads a number as a string input using the DataInputStream and then converts it to an integer using Integer.parseInt(). Once converted to an integer, the while loop processes each digit by using the modulus operator to extract digits and the division operator to reduce the number for subsequent iterations, summing the digits until the number is reduced to zero .

The logic behind using nested loops to display a matrix-like pattern involves an outer loop controlling the number of rows and an inner loop controlling the number of repetitions per row. The outer loop iterates over each row, while the inner loop handles each element within the row. This allows for the structured output of elements in a grid or matrix format, where you can manipulate how many symbols or numbers appear per row and column .

The main difference between a 'while loop' and a 'do-while loop' in Java is the point at which the condition is evaluated. In a 'while loop', the condition is checked before the loop body is executed, which means if the condition is false initially, the loop body may not execute at all. In contrast, a 'do-while loop' evaluates the condition after the execution of the loop body, meaning that the loop body will always execute at least once, regardless of whether the condition is true or false initially .

You might also like