Example Program 9.
Write a program to input n numbers and display the product of all the odd numbers.
import java.util.*;
class Product
{
//function to input n numbers and display the product of odd numbers
void displayProduct()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of inputs");
int n=sc.nextInt();
int c=0;
int num,p=1;
for(int i=1;i<=n;i++)
{
System.out.println("Enter a number ");
num=sc.nextInt();
if(num%2==1)
{
c++;
p*=num;
}
}
if(c==0)
{
System.out.println("There is no odd number present in the list");
}
else
{
System.out.println("Product of odd numbers ="+p);
}
}
}
Example Program 10.
Write a program to input n real numeric constants from the user and display the greatest num-
ber.
import java.util.*;
class Greatest
{
//function to input n real nos and display the greatest number
void displayGreatest1()
{
Scanner sc=new Scanner(System.in);
YNotTheBest.in
System.out.println("Enter the number of inputs");
int n=sc.nextInt();
System.out.println("Enter the first number");
double num=sc.nextDouble();
double max=num;
for(int i=1;i<n;i++)
{
System.out.println("Enter the next number");
num=sc.nextDouble();
max=num>max?num:max;
}
System.out.println("Greatest Number="+max);
}
}
Example Program 11.
Write a program to display the sum of negative numbers, sum of positive even numbers and
the sum of positive odd numbers from a list of numbers inputted by the user. The list termi-
nates when the user enters 0.
import java.util.*;
class Sum
{
//function to display the sum of -ve numbers, +ve even numbers and +ve odd numbers.
void displaySum()
{
Scanner sc=new Scanner(System.in);
int num,spo=0,spe=0,sng=0;
do
{
System.out.println("Enter a number, press 0 to get output");
num=sc.nextInt();
if(num<0)
{
sng+=num;
}
else if(num>0)
{
if(num%2==0)
{
spe+=num;
}
else
{
spo+=num;
}
YNotTheBest.in
}
}while(num!=0);
System.out.println("Sum of -ve numbers = "+sng);
System.out.println("Sum of +ve even numbers = "+spe);
System.out.println("Sum of +ve odd numbers = "+spo);
}
}
The loop in the previous program is an example of a sentinel loop or a user-controlled loop. A
sentinel loop continues to process data until reaching a special value that signals the end.
The special value is called the sentinel. You can choose any value for the sentinel. The only re-
quirement is that it must be distinguishable from actual data values.
YNotTheBest.in