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

Loops Solutions

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 3

LOOPS SOLUTIONS

sigmacourse872@gmail.com
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;

sigmacourse872@gmail.com
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.

sigmacourse872@gmail.com
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