Set array elements to 1 if Prime
- Program which will set the array element a[i] to 1 if i is prime, and to 0 if i is not prime.
Program
import
java.util.Scanner;
public class
PrimeArray {
private static
Scanner sc;
public static void
main(String[] args) {
int
limit,value;
PrimeArray ob=new
PrimeArray();
sc=new
Scanner(System.in);
int[]
number=new int[1000];
System.out.println("Enter
the number of elements in the array:");
limit=sc.nextInt();
System.out.println("Enter
the elements of the array:");
for(int
i=0;i<limit;i++) {
number[i]=sc.nextInt();
}
for(int
i=0;i<limit;i++) {
value=ob.checkPrime(number[i]);
number[i]=value;
}
System.out.println("Array
after re-setting:");
for(int
i=0;i<limit;i++) {
System.out.println(number[i]);
}
}
public int
checkPrime(int num) {
int
flag=0;
for(int
i=1;i<=num;i++) {
if(num%i==0)
{
flag++;
}
}
if(flag==2)
{
return 1;//is
prime
}
else {
return 0;//is
not prime
}
}
}
Output
Enter
the number of elements in the array:
5
Enter
the elements of the array:
19
4
7
3
23
Array
after re-setting:
1
0
1
1
1
- Program to count the number of vowels in a given string.
Program
import
java.util.Scanner;
public class
CountVowels {
private static
Scanner sc;
public static void
main(String[] args) {
int
flag=0,count=0;
sc=new
Scanner(System.in);
System.out.println("Enter
the String:");
String str=sc.nextLine();
for(int
i=0;i<str.length();i++) {
if((str.charAt(i)=='a')||(str.charAt(i)=='A')||(str.charAt(i)=='e')||(str.charAt(i)=='E')||
(str.charAt(i)=='i')||(str.charAt(i)=='I')||(str.charAt(i)=='o')||(str.charAt(i)=='O')||
(str.charAt(i)=='u')||(str.charAt(i)=='U')) {
count++;
flag=1;
}
}
if(flag==0)
{
System.out.println("There
are no vowels in the string.");
}
else {
System.out.println("The
string contains "+count+" vowels.");
}
}
}
Output
Enter
the String:
Count
the number of vowels.
The
string contains 8 vowels.
No comments:
Post a Comment