Example Program 9.
Write a program to input n numbers and display the product of all the odd numbers.
import [Link].*;
class Product
{
//function to input n numbers and display the product of odd numbers
void displayProduct()
{
Scanner sc=new Scanner([Link]);
[Link]("Enter the number of inputs");
int n=[Link]();
int c=0;
int num,p=1;
for(int i=1;i<=n;i++)
{
[Link]("Enter a number ");
num=[Link]();
if(num%2==1)
{
c++;
p*=num;
}
}
if(c==0)
{
[Link]("There is no odd number present in the list");
}
else
{
[Link]("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 [Link].*;
class Greatest
{
//function to input n real nos and display the greatest number
void displayGreatest1()
{
Scanner sc=new Scanner([Link]);
[Link]
[Link]("Enter the number of inputs");
int n=[Link]();
[Link]("Enter the first number");
double num=[Link]();
double max=num;
for(int i=1;i<n;i++)
{
[Link]("Enter the next number");
num=[Link]();
max=num>max?num:max;
}
[Link]("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 [Link].*;
class Sum
{
//function to display the sum of -ve numbers, +ve even numbers and +ve odd numbers.
void displaySum()
{
Scanner sc=new Scanner([Link]);
int num,spo=0,spe=0,sng=0;
do
{
[Link]("Enter a number, press 0 to get output");
num=[Link]();
if(num<0)
{
sng+=num;
}
else if(num>0)
{
if(num%2==0)
{
spe+=num;
}
else
{
spo+=num;
}
[Link]
}
}while(num!=0);
[Link]("Sum of -ve numbers = "+sng);
[Link]("Sum of +ve even numbers = "+spe);
[Link]("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.
[Link]