To find the sum of the first ‘n’ natural numbers – while loop


Write a program in java to find the sum of  the first ‘n’ natural numbers.

import java.io.*;
class Natural
{
public static void main(String args[]) throws IOException
{
int n,sum=0,i=1;
BufferedReader br=new BufferedReader(new InputStreamReader (System.in));
System.out.println(“Enter the value of ‘n’ : “);
n=Integer.parseInt(br.readLine());
while(i<=n)
{
sum=sum+i;
i++;
}
System.out.println(“The sum of  first”+n+ “natural numbers:”+sum);
}
}

Output:

Enter the value of ‘n’ :
15
The sum of  first 15 natural numbers: 120

To check a is divisible by b


Write a program in java to check whether a is divisible by b.

import java.io.*;
class divisibile
{
public static void main(String args[])throws IOException
{
int a,b;
BufferedReader zm=new BufferedReader(new InputStreamReader (System.in));
System.out.println(“Enter the value of a”);
a=Integer.parseInt(zm.readLine());

System.out.println(“Enter the value of b”);
b=Integer.parseInt(zm.readLine());
if(a%b==0)
System.out.println(+a+” is divisible by”+b);
else
System.out.println(+a+” is  not divisible by”+b);
}
}

 

Output:

Enter a,b
12
5
12 is not divisible by 5

To input a Date and print in another format


Write a Program in Java to input a Date in ddmmyyyy 8-digit format and print it in:
1) dd/mm/yyyy format
2) dd, month name, yyyy format

Input: 12012018
Output:
12/01/2018
12 January, 2018

 

import java.io.*;

class Date_DDMMYY

{

public static void main(String args[])throws IOException

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

int l, y, d, m;

String dd, mm, yy;

//array storing the maximum days of every month

int maxdays[]={0,31,28,31,30,31,30,31,31,30,31,30,31};

//array storing the month names

String month[]={ “”, “January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December” };

System.out.print(“Enter any date in 8 digits (ddmmyyyy) format: “);

String date = br.readLine(); //inputting the date in String format

l = date.length(); //finding number of digits in the given input

if(l==8) //performing the task only when number of digits is 8

{

dd = date.substring(0,2); //extracting the day in String format

mm = date.substring(2,4); //extracting the month in String format

yy = date.substring(4); //extracting the year in String format

d = Integer.parseInt(dd); //day in Integer format

m = Integer.parseInt(mm); //month in Integer format

y = Integer.parseInt(yy); //year in Integer format

if((y%400==0) || ((y%100!=0)&&(y%4==0))) // condition for leap year

{

maxdays[2]=29;

}

/* checking whether the day, month and year are within acceptable range

i.e. there cannot be an input like 35012013 because 35/01/2013 is unacceptable*/

if(m<0 || m>12 || d<0 || d>maxdays[m] || y<0 || y>9999) // Performing Date  Validation

{

System.out.println(“The day, month or year are outside acceptable limit”);

}

else

{

/* First Part */

System.out.println(“Date in dd/mm/yyyy format = “+dd+”/”+mm+”/”+yy);

/* Second Part */

System.out.print(“Date in dd, month name, yyyy format = “+dd+” “+month[m]+”, “+yy);

}

}

else

System.out.println(“Wrong Input”);

}

}

 

Output:

Enter any date in 8 digits (ddmmyyyy) format: 12012018

Date in dd/mm/yyyy format = 12/01/2018

Date in dd, month name, yyyy format = 12 January, 2018

Frequency of each alphabet


Write a program to input a string (word). Convert it into lowercase letters. Count and print the frequency of each alphabet present in the string. The output should be given as:

Sample Input: Alphabets
Sample Output:
==========================
Alphabet             Frequency
==========================
a                              2
b                              1
e                              1
h                              1
l                               1
p                              1
s                              1
t                               1

import java.io.*;

class AlphaFrequency

{

public static void main(String args[])throws IOException

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.print(“Enter any string: “);

String s = br.readLine();

s=s.toLowerCase();                               //converting the string into lowercase

int l=s.length();                                    //finding the length of the string

char ch;

System.out.println(“Output:”);

System.out.println(“==========================”);

System.out.println(“Alphabet\tFrequency”);

System.out.println(“==========================”);

/* Counting frequency of alphabets begins below */

int count=0;

for(char i=’a’; i<=’z’; i++)

{

count = 0;

for(int j=0; j<l; j++)

{

ch=s.charAt(j);                         //extracting characters of the string one by one

if(ch==i)                               //first checking the whole string for ‘a’, then ‘b’ and so on

count++;            //increasing count of those aplhabets which are present in the string

}

if(count!=0)                    //printing only those alphabets whose count is not ‘0’

{

System.out.println(i+”\t\t”+count);

}

}

}

}

Enter any string: hai how are you

Output:

==========================

Alphabet         Frequency

==========================

a                      2

e                      1

h                      2

i                       1

o                      2

r                       1

u                      1

w                     1

y                      1

Write a program to input a word from the user and remove the duplicate characters present in it.


Write a program to input a word from the user and remove the duplicate characters present in it.

Example:

INPUT – abcabcabc
OUTPUT – abc

INPUT – javaforschool
OUTPUT – javforschl

INPUT – Mississippi
OUTPUT – Misp

Programs:

import java.io.*;

class RemoveDupChar

{

public static void main(String args[])throws IOException

{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.print(“Enter any word : “);

String s = br.readLine();

int l = s.length();

char ch;

String ans=””;

for(int i=0; i<l; i++)

{

ch = s.charAt(i);

if(ch!=’ ‘)

ans = ans + ch;

s = s.replace(ch,’ ‘); //Replacing all occurrence of the current character by a space

}

System.out.println(“Word after removing duplicate characters : ” + ans);

}

}

Output:

Example 1:
Enter any word : Mississippi
Word after removing duplicate characters : Misp

Example 2:
Enter any word : Attitude
Word after removing duplicate characters : Atiude

Encrypt a character


A simple encryption system uses a shifting process to hide a message. The value of the shift can be in the range 1 to 26.

For example a shift of 7 means that A = U, B =V,C = W, etc.i e.

Text : A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Code: U V W X Y Z A B C D E F G H I J K L M N O P Q R S T

Fist an extra space is added to the end of the string. To make things little more difficult, spaces within the original text are replaced with QQ before the text is encrypted. Double Q (QQ) was selected because no English word ends in Q or contains QQ.

Additionally the coded message is printed in blocks of six characters separated by spaces. The last block might not contain six characters. Write a program that takes the coded text (less than 100 characters), the shift value and prints the decoded original text.Your program must reject any non-valid value for shift and display an error message “INVALID SHIFT VALUE)”. Assume all characters are upper case. Test your program for the following data and some data that you have coded, using the rules given above:

 

SAMPLE DATA:

  1. INPUT:
    CODED TEXT : “UHINBY LKKQCH HYLKK”
    SHIFT : 7
    OUTPUT:
    DECODED TEXT : ANOTHER VALUE
  2. INPUT:
    CODED TEXT : “RUIJGG EVGGBK SAGG”
    SHIFT : 11
    OUTPUT:
    DECODED TEST : BEST OF LUCK
  3. INPUT:
    CODED TEXT : “DKSMMW NAMMUK QMM”
    SHIFT : 29
    OUTPUT:
    INVALID SHIFT VAULE

 

import java.io.*;

public class Decode

{

public static void main(String args[])throws IOException

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.print(“Enter Coded Text : “); // inputting coded text

String s = br.readLine();

int l = s.length();

s = s.toUpperCase(); // converting the coded text into Uppercase

s = s + ” “; // adding a space at the end

if(l>=100) // checking whether length of inputted code is less than 100

System.out.println(“!!! Invalid Length of Coded Text !!!”);

else

{

System.out.print(“Enter the Shift Value : “);

int shift = Integer.parseInt(br.readLine());

if(shift<1 || shift>26) // checking whether shift value is between 1 and 26

System.out.println(“!!! Invalid Shift Value !!!”);

else

{

int a, b;

char ch1, ch2;

String dec=””; //new String for storing the decoded text

for(int i=0; i<l; i++)

{

ch1 = s.charAt(i); // extracting characters one by one

ch2 = s.charAt(i+1); // extracting the next character

/*  after finding each character in ch1 and ch2

*Below we are adding shift value to the characters

* if ch1 = ‘A’ and shift = 7,

* then ch1 + shift – 1 will give us: ‘A’+7-1 = 65+7-1 = 71

* which is the ASCII value of ‘G’

*/

a = ch1 + shift – 1; // storing ASCII values after adding shift to the current character

b = ch2 + shift – 1; // storing ASCII values after adding shift to the next character

 

/* If the currrent character and the next character are both ‘Q’ then we have a ‘space’

* hence the ASCII value should be 32

*/

if((char)a == ‘Q’ && (char)b == ‘Q’)

{

a = 32;

i++;

}

 

/* If ASCII value after adding the shift becomes more than 90,

* then we subtract 26 from it, to make it circular,

* eg. ‘U’+7-1 = 85+7-1 = 91, but we want ‘A’ whose ASCII value is 65

* so 91-26 will give us 65

*/

if(a>90)

a = a – 26;

if(ch1 != ‘ ‘)

dec = dec + (char)a; // finally adding the decoded character to the new String

}

System.out.println(“Decoded Text : “+dec);

}

}

}

}

 

Output

Enter Coded Text : anu

Enter the Shift Value : 2

Decoded Text : BOV

Enter Coded Text : anu

Enter the Shift Value : 8

Decoded Text : HUB

Binary Search


import java.util.Scanner;

public class BinSearch

{   public static void main(String args[])

{    int c, first, last, middle, n, search, array[];

Scanner in = new Scanner(System.in);

System.out.println("Enter number of elements");

n = in.nextInt();

array = new int[n];

System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++)

array[c] = in.nextInt();

System.out.println("Enter value to find");

search = in.nextInt();

first  = 0;

last   = n - 1;

middle = (first + last)/2;

while( first <= last )

{

if ( array[middle] < search )

first = middle + 1;

else if ( array[middle] == search )

{

System.out.println(search + "found at location " + (middle + 1) + ".");

break;

}

else

last = middle - 1;

middle = (first + last)/2;

}

if ( first > last )

System.out.println(search + " is not present in the list.\n");

}

}

Linear Search / Sequential Search


to check if  an element is present in the given list, we compare key element (search element)  with every element in the list. If the number is found then display success otherwise the list doesn’t contain the element, that we are searching displays Search Unsuccessful.

import java.io.*;
public class LinearSearch{
public static void main(String args[]) throws IOException{
InputStreamReader read=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(read);
int a[]= new int[20];
int i, size, item, flag=0;
System.out.println(“Enter the size of the array:”);
size=Integer.parseInt(br.readLine());
System.out.println(“Enter the elements of the array:”);
for (i=0;i<size;i++){
a[i]=Integer.parseInt(br.readLine());
}
System.out.println(“Element to search:”);
item=Integer.parseInt(br.readLine());
for(i=0;i<size;i++){
if(item==a[i])
{
flag=1;
break;
}       }

if(flag==1)
System.out.println(item+”found in position”+(i+1));
else
System.out.println(“Search Unsuccessful”);

}}

 

Output:

Enter the size of the array:

5

Enter the elements of the array:

45

25

41

42

56

Element to search:

41

41 found in position 3

Design a class to overload a function compare()


Design a class Perform to overload a function  as follows:
(i) void compare (int, int)    – to compare two integer values and print the greater of the two integers.
(ii) void compare(char, char)  – to compare the numeric value of two characters and print with the higher numeric value.
(iii)void compare(String, String)  –  to compare the length of the two strings and print the longer of the two.

Answer:

class Perform
{
void compare(int m, int n)
{
if(m > n)
System.out.println(“The first number is greater”+m);
else
System.out.println(“The second  number is greater”+n);
}
void compare(char c, char d)
{
if(c > d)
System.out.println(“The first character is greater and the numeric  value”+(int)c);
else
System.out.println(“The second character is greater and the numeric  value”+(int)d);
}
void compare(String s1, String s2)
{
if(s1.compareTo(s2) > 0)
System.out.println(“The first string is longer”+s1);
else
System.out.println(“The second string is longer”+s2);
}

}

Program to check an alphabet using method


class Alphabet
{
 public void checkVowel(char ch)
{
if(ch==‘a’||ch==‘e’||ch==‘i’||ch==‘o’||ch==‘u’||ch==‘A’||ch==‘E’||ch==‘I’||ch==‘O’||ch==‘U’)
{
System.out.println(“Given alphabet “+ch+” is an Vowel”);
}
else if((ch>=‘a’&&ch<=‘z’)||(ch>=‘A’&&ch<=‘Z’))
System.out.println(“Given alphabet “+ch+” is Consonant”);
else
System.out.println(“Not an alphabet”);
}
public static void main(String[ ] arg)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println(“Enter a character : “);

char chr=(char)br.read();

checkVowel(chr);

}

}

Analyze the given code fragment


Analyze the given program segment and answer the following questions :
(i) Write the output of the code snippet.
(ii) How many times does the body of the loop gets executed?

for(int a=5; a<=20; a+=5)
{
if(a%3 == 0)
break;
else
if(a%5 == 0)
System.out.println(a);
continue;
}

answer :
(i) 5 10
(ii) 3 times

Working :

When a = 5,
if(a%3 == 0) is false
if(a%5 == 0) is true
so it prints ‘5’
Loop executed 1 time.

When a = 10,
if(a%3 == 0) is false
if(a%5 == 0) is true
so it prints ‘10’
Loop executed 2 times.

When a = 15,
if(a%3 == 0) is true
so, break is encountered and loop terminates.
Loop executed 3 times.

 

ISC Computer Science Practical – Marking pattern


ISC Computer science —  practical paper(30 marks)

Marking procedure for practical paper

Total Marks : 30

Algorithm : 3 marks

Program : 5 marks

Comments/Mnemonics code : 2 marks

Printed code that compiled correctly : 2 marks

Run the code and get correct output : 5 marks

Viva – 3 marks

Programs done in lab class throughout the year : 10 marks ( 5 from external examiner and 5 mark from your computer teacher)