java 1-2
java 1-2
Design and Implement a Java program to print the sum of the elements of the array with the
given below condition. If the array has 6 and 7 in succeeding orders, ignore 6 and 7 and the
numbers between them for the calculation of sum.
Eg1) Array Elements - 10,3,6,1,2,7,9
O/P: 22
[i.e. 10+3+9]
O/P:19
Eg3) Array Elements - 1,6,4,7,9
O/P:10
import java.util.Scanner;
int n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of array:");
n = sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();}
int sixPos=-1;
int sevenPos=-1;
int sum=0;
for(int i=0;i<arr.length;i++)
{
if(arr[i]==6)
{sixPos=i;
break;}}
for(int i=0;i<arr.length;i++)
{
if(arr[i]==7) sevenPos=i;
}
if(sevenPos==-1) sixPos=-1;
for(int i=0;i<arr.length;i++)
{
if(sixPos!=-1 && i>=sixPos && i<=sevenPos) continue;
sum+=arr[i];
}
System.out.println(sum);
}
}
Output:
Test 1 :
Test 2 :
Design and Implement a Java program that displays a menu with options 1. Add 2. Sub,
Based on the options chosen, read 2 numbers and perform the relevant operation. After
performing the operation, the program should ask the user if he wants to continue. If the user
presses y or Y, then the program should continue displaying the menu else the program
should terminate.
package fourd;
import java.util.*;
class calculator
{
public static void main(String a[])
{
int num1=0,num2=0,option,ex;
Scanner sc1 = new Scanner(System.in);
do
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter your choice from the following menu:");
System.out.println("1.Addition 2.Subtraction 3.Exit");
option = sc.nextInt();
if(option!=3){
System.out.println("Enter the first number");
num1=sc.nextInt();
System.out.println("Enter the second number");
num2=sc.nextInt();
}
else
break;
switch(option)
{
case 1:System.out.println("Addition of "+num1+" and
"+num2+" is "+(num1+num2));
break;
case 2:System.out.println("Subtraction of "+num1+" and
"+num2+" is "+(num1-num2));
break;
case 3: break;
}
}
Output: