0% found this document useful (0 votes)
8 views3 pages

Loops Solutions

Uploaded by

Piter Parker
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)
8 views3 pages

Loops Solutions

Uploaded by

Piter Parker
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
You are on page 1/ 3

LOOPS SOLUTIONS

[email protected]
Solution 1: Hello is printed 2 times.

Solution 2:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

int number;
int choice;
int evenSum = 0;
int oddSum = 0;

do {
System.out.print("Enter the number ");
number = sc.nextInt();

if( number % 2 == 0) {
evenSum += number;
} else {
oddSum += number;
}

System.out.print("Do you want to continue? Press 1 for yes or 0 for


no");
choice = sc.nextInt();

} while(choice==1);

System.out.println("Sum of even numbers: " + evenSum);


System.out.println("Sum of odd numbers: " + oddSum);
}
}
Solution 3:
import java.util.Scanner;

[email protected]
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num; // To hold number
int fact = 1; // To hold factorial

System.out.print("Enter any positive integer: ");


num = sc.nextInt();

for(int i=1; i<=num; i++) {


fact *= i;
}

System.out.println("Factorial: "+ fact);


}
}

Solution 4:
import java.util.*;
class MultiplicationTable {
public static void printMultiplicationTable(int number){
Scanner sc = new Scanner(System.in);
System.out.print("Enter number:");
int n = sc.nextInt();
for(int i=1; i<=10; i++) {
System.out.println(n + " * " + i + " = " + n*i);
}
}
public static void main(String s[]) {
printMultiplicationTable(5);
}
}

Solution 5:
Scope of variable is referred to the part of the program where the variable can be used.
In this program variable i is declared in the for loop. So scope of variable i is limited to the for
loop only that is between { and } of the for loop. There is a display statement after the for loop
where variable i is used which means i is used out of scope. This leads to compilation errors.

[email protected]
The program given will not run and give an error instead. To correct the program, the variable i
needs to be declared outside the for loop.

You might also like