Examples of Loops: Part 1
Learn about the ‘for’ and ‘while’ loops in more detail with the help of the examples in this lesson.
We'll cover the following...
We'll cover the following...
Coding example: 62
In the following example, we will take inputs from the users and add negative numbers only. Let’s take a look at the code first. If you want to rerun the code, write java main in the terminal:
import java.util.Scanner;
/*
accept any 5 number and print the sum of only negative numbers
*/
public class main {
static int num, sum = 0;
static int controllingNumber = 1;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter any 5 number: ");
while (controllingNumber <= 5){
num = sc.nextInt();
if(num < 0){
sum += num;
}
controllingNumber++;
}
System.out.println("The sum of only negative numbers: " + sum);
}
}