The Programming Project

Sunday, September 26, 2021

ISC COMPUTER SCIENCE PRACTICAL SPECIMEN QUESTION PAPER 2021 QUESTION 1 : DATE AFTER

 


As per the given criteria we will first check the inputs before passing the variables to the constructor.

do {
           System.out.println("Enter the day number:");
           day = in.nextInt();
           if(day < 1 || day > 366)
                System.out.println("INVALID DAY:");
           System.out.println("Enter the year:");
           yr = in.nextInt();
           if(Integer.toString(yr).length() !=4)
                System.out.println("INVALID YEAR:");
           System.out.println("Enter the value of N:");
           N = in.nextInt();
           if(N < 1 || N > 100)
                System.out.println("INVALID DATA:");
       }while(day < 1 || day > 366 || Integer.toString(yr).length() !=4 ||  N < 1 || N > 100 );
       DaysCalculation obj = new DaysCalculation(dayyrN);

Now the main task of the program is to calculate the date in the format: Day: Month: Year
for given day ( 1<= day <= 366).
To this I have use the function obj.currentDay(); the logic is as follows:
I am assuming that the entered year is a non-leap year, the same goes for the leap-year.
Between to check a year is leap or not I have employed the method
private boolean checkLeap(int year)
which is easy to decode.
Now coming back to the main theme, suppose a user enters 70, 2017 and 50 as the input.
First we need to calculate the date of 70th day of the year 2017 and then the date after 50
days from the current date.
Since 2017 is a non-leap year, the months will have the following days:
private int[] mdays={31,28,31,30,31,30,31,31,30,31,30,31};
First we have to calculate the month in which the 70th day fall, for this add up the
elements of the array mdays starting from 0th position until the sum exceeds the day number 70.
So in our example, 31+28+31 = 90 > 70
So the 70th day of the year falls in the 3rd month.
This has been implemented by the following snippet of code:
if(checkLeap(year)) {
        sum += ldays[counter];
        whilesum  < dayNumber) {  
            monthCounter++;
            sum +=ldays[counter+1];
            counter++;
        }
    }
    else{
        sum += mdays[counter];
        whilesum  < dayNumber) {  
            monthCounter++;
            sum +=mdays[counter+1];
            counter++;  
        }
    }

Once we get the month, the next task is to calculate the day of the current month.
This is too easy, just subtract the day number ( 70th in our case ) from the
sum of the days of all the previous months.
In our case this will give 70-(31+28) = 11th day of the 3rd month.
    sum = 0;
    if(checkLeap(year))
        for(int i = 0i < monthCounteri++)
            sum +=ldays[i];
    else
        for(int i = 0i < monthCounteri++)
            sum +=mdays[i];
    int fdayNumber;
    fdayNumber = dayNumber
    fdayNumber -= sum;

Note fdayNumber is just a temporary variable to store the value of dayNumber.
After this we just need to print the day and month and year;

Now the next task is to find the day after 50 days, so the logic is as follows:
add the dayNumber and 50 ( 70 + 50 = 120 ) in our case. Check if this value crosses
365 ( for non-leap year), if so, subtract 365 from it and increment the year.
So now we have a day number and year so just call the function discussed above!

public void dateAfter() {
        dayNumber +=dayAfter;
        if(checkLeap(year)) {
            if(dayNumber > 366 ) {
                dayNumber -= 366;
                year++;
                }
            currentDay();   
            }
        else {
            if(dayNumber > 365) {
                dayNumber -= 365;
                year++;
                }
            currentDay();
        }   
    
    }  

JAVA CODE



import java.util.*;
public class ISC2021SpecimenQuestion1 {
    public static void main(String[] args) {
       int day;
       int yr;
       int N;
       Scanner in = new Scanner(System.in);
       do {
           System.out.println("Enter the day number:");
           day = in.nextInt();
           if(day < 1 || day > 366)
                System.out.println("INVALID DAY:");
           System.out.println("Enter the year:");
           yr = in.nextInt();
           if(Integer.toString(yr).length() !=4)
                System.out.println("INVALID YEAR:");
           System.out.println("Enter the value of N:");
           N = in.nextInt();
           if(N < 1 || N > 100)
                System.out.println("INVALID DATA:");
       }while(day < 1 || day > 366 || Integer.toString(yr).length() !=4 ||  N < 1 || N > 100 );
       DaysCalculation obj = new DaysCalculation(dayyrN);
       System.out.println("OUTPUT:");
       obj.currentDay();
       System.out.println("DATE AFTER "+N+" DAYS");
       obj.dateAfter();
       in.close();
    }  
}
class DaysCalculation {
    public void currentDay() {
    int counter = 0;
    int monthCounter = 0;
    int sum =0;
    if(checkLeap(year)) {
        sum += ldays[counter];
        whilesum  < dayNumber) {  
            monthCounter++;
            sum +=ldays[counter+1];
            counter++;
        }
    }
    else{
        sum += mdays[counter];
        whilesum  < dayNumber) {  
            monthCounter++;
            sum +=mdays[counter+1];
            counter++;  
        }
    }
    sum = 0;
    if(checkLeap(year))
        for(int i = 0i < monthCounteri++)
            sum +=ldays[i];
    else
        for(int i = 0i < monthCounteri++)
            sum +=mdays[i];
    int fdayNumber;
    fdayNumber = dayNumber
    fdayNumber -= sum;
    String s = fdayNumber%10 == 1 ? "st" : fdayNumber%10 == 2 ? "nd" : fdayNumber%10 == 3 ? "rd" : "th";
    if(fdayNumber >= 11 && fdayNumber <= 19)
        s"th";
    System.out.println(fdayNumber+s+" "+months[monthCounter]+" "+year); 
    }
    public void dateAfter() {
        dayNumber +=dayAfter;
        if(checkLeap(year)) {
            if(dayNumber > 366 ) {
                dayNumber -= 366;
                year++;
                }
            currentDay();   
            }
        else {
            if(dayNumber > 365) {
                dayNumber -= 365;
                year++;
                }
            currentDay();
        }   
    
    }  
    private boolean checkLeap(int year) {
        if(year%400==0)
           leap=true;
        else if (year%100==0)
           leap=false;
        else if (year%4==0)
           leap=true;
        else
           leap=false;
        return leap;
    }   
    DaysCalculation(int dayint yrint N) {
        this.dayNumber = day;
        this.year = yr;
        this.dayAfter =N;
    }
    private boolean leap;  
    private int dayNumber;
    private int year;
    private int dayAfter;
    private String[] months = {"January","Feburary","March","April","May","June","July","August","Sepetember","October","November","December"};
    private int[] mdays={31,28,31,30,31,30,31,31,30,31,30,31};
    private int[] ldays={31,29,31,30,31,30,31,31,30,31,30,31};  
}


Friday, September 24, 2021

COMPOUND INTEREST CACULATOR : PYTHON PROGRAMMING


If the principal is P and the rate of compound interest is r% per annum and the interest is compounded k times in a year, then the amount after n years is given by the formula


If k = 1, the interest is payable yearly, for k =2 the interest is payable half-yearly and for k=4 the interest is payable quarterly. Below is the program which uses above formula to calculate the final amount.

PYTHON CODE



principal = float(input("Enter the principal value:"))
rateOfInterest = float(input("Enter the rate of interest:"))
numberOfMonths = int((input("Enter the period in months:")))
frequency =int(input("Enter the number of times the the interest is compunded (yearly=1, half-yearly=2, quarterly =4,..):"))
finalAmount = 0.0
finalAmount += principal*(1+(rateOfInterest/frequency)/100)**(frequency*(numberOfMonths/12))
print("The final amount is"round(finalAmount,2))



ISC COMPUTER SCIENCE PRACTICAL SOLVED 2021 QUESTION 3: MATRIX - BOUNDARY ELEMENTS

 QUESTION 3:




JAVA CODE



import java.util.*;
public class ISC2021Question3 {
    public static void main(String[] args) {
          int M,N;
          Scanner in = new Scanner(System.in);
          System.out.println("Enter the NUMBER OF ROWS of the matrix:");
          M = in.nextInt();
          System.out.println("Enter the NUMBER OF COLOUMNS of the matrix:");
          N = in.nextInt();
          whileM <=2 || N >= 8) {
            System.out.println("OUT OF RANGE:");  
            System.out.println("Enter the NUMBER OF ROWS of the matrix:");
            M = in.nextInt();
            System.out.println("Enter the NUMBER OF COLOUMNS of the matrix:");
            N = in.nextInt();
          }
          Matrix obj = new Matrix(M,N);
          System.out.println("Enter the elements of the matrix:");
          obj.inputMatrix();
          System.out.println("ORIGINAL MATRIX:");
          obj.originalMatrix();
          System.out.println("REARRANGED MATRIX:");
          obj.matrixSort();
          in.close();
    }
}
class Matrix{
public void originalMatrix() {
    sumOFBoundaryElements(Mat);
}   
public void matrixSort() {
    int[] linearArray;
    int counter=0;
    linearArray = new int[row*coloumn];
    //getting the elements of the 2D array in a single dimension array
    for(int i=0;i<row;i++) 
          for(int j=0;j<coloumn;j++)
                linearArray[counter++] = Mat[i][j];
    //sorting the linear Array
    for(int k = 0k < counter-1;k++) {
        for(int l = 0l < counter-k-1l++ ) {
            if (linearArray[l+1] > linearArray[l]) {
                int temp = linearArray[l+1];
                linearArray[l+1] = linearArray[l];
                linearArray[l] = temp;
            }
        }
    }
    // getting elements after sorting in the 2D Array
    counter = 0;
    for(int i=0;i<row;i++) 
          for(int j=0;j<coloumn;j++)
                Mat[i][j] = linearArray[counter++];
    // finding the sum of boundary elements of the Sorted Array
    sumOFBoundaryElements(Mat);
}
private void sumOFBoundaryElements(int[][] X) {
    sumOfBoundaryElements = 0;
    for(int i=0;i<row;i++) 
          for(int j=0;j<coloumn;j++)
                 if(i== 0 || i == row-1 || j == 0 || j == coloumn-1
                       sumOfBoundaryElements += X[i][j];
    displayMatrix(Mat); 
    System.out.println("SUM OF BOUNDARY ELEMENTS:"+sumOfBoundaryElements);
    }

/*private void displayMatrix(int[][] X) {
    for(int i=0;i<row;i++) {
          for(int j=0;j<coloumn;j++)
                 System.out.print(X[i][j]+" ");
          System.out.println();
          }
    } */
// you can display the matrix by the method above
// but if you want to have a allined display use the method below
private void displayMatrix(int[][] X) {
    int MAX_MATRIX=0;
    for(int p=0;p<row;p++)
           for(int q=0;q<coloumn;q++)
                 if(MAX_MATRIX < X[p][q])
                        MAX_MATRIX = X[p][q];
    String s,element;
    s=Integer.toString(MAX_MATRIX);
    for(int i=0;i<row;i++) {
           for(int j=0;j<coloumn;j++) {
                element=Integer.toString(X[i][j]); 
                int tmp=element.length();
                while(tmp !=s.length()) {
                   element +=" ";
                   tmp++;
                }
                System.out.print(element+"  ");
            }
        System.out.println();
    }
}
public void inputMatrix() {
    Scanner in = new Scanner(System.in);
    for(int i=0;i<row;i++)
          for(int j=0;j<coloumn;j++)
                 Mat[i][j]=in.nextInt();
    }

Matrix(int Mint N){
    this.row = M;
    this.coloumn = N;
    Mat = new int[M][N];
    sumOfBoundaryElements = 0;
    }
    private int row;
    private int coloumn;
    private int[][] Mat;
    private int sumOfBoundaryElements;
      
}




Thursday, September 23, 2021

ISC COMPUTER SCIENCE PRACTICAL SOLVED 2021 QUESTION 2: STRING - COMMON WORDS FREQUENCY

 


Question 2

Write a program to accept a paragraph containing TWO sentences only. The sentences may be terminated by either ‘.’, ‘?’ or ‘!’ only. Any other character may be ignored. The words are to be separated by a single blank space and must be in UPPER CASE.

Perform the following tasks:

(a)    Check for the validity of the accepted paragraph for the number of sentences and for the terminating character.

(b)   Separate the two sentences from the paragraph and find the common words in the two sentences with their frequency of occurrence in the paragraph.

(c)    Display both the sentences separately along with the common words and their frequency, in the format given below:

Example 1

INPUT: IS IT RAINING? YOU MAY GET WET IF IT IS RAINING.

OUTPUT:   IS IT RAINING?

                        YOU MAY GET WET IF IT IS RAINING.

        COMMOM WORDS             FREQUENCY

                  IS                                                  2

                  IT                                                  2

                  RAINING                                2

 

Example 2

INPUT: INDIA IS MY MOTHERLAND AND I AM PROUD OF MY MOTHERLAND. ALL INDIANS ARE MY BROTHERS AND SISTERS.

OUTPUT:   INDIA IS MY MOTHERLAND AND I AM PROUD OF MY MOTHERLAND.

                        ALL INDIANS ARE MY BROTHERS AND SISTERS.

        COMMOM WORDS             FREQUENCY

                  MY                                               3

                  AND                                             2

 

Example 3

INPUT: ARE YOU COMING? I AM GETTING LATE.

OUTPUT:   ARE YOU COMING?

                        I AM GETTING LATE.

                        NO COMMON WORDS

Example 4

INPUT: AT LAST, THE TIGER WAS SAVED.

OUTPUT:   INVALID INPUT

SUMMMARY

I will definitely recommend not attempting this type of questions in your final exam. Below are few reasons to avoid problems based on Strings in general.

1. Numbers or Matrix problems are easy to handle, less cumbersome.

2. Logic for problems related to string are generally complicated and more complicated to implement in code.

3. More prone to error while coding.

4. Lengthy problems.

5. Testing need to be done very carefully with lots of valid input.

Now coming back to this problem, it is very unique and somewhat much lengthy compared to other "string problems" in various years.

I will discuss here the main logic of the program step by step.

In the main program I have taken the input and checked its validity accordingly. It is easy to understand and I am leaving that part.

Moving forward, the input contains two sentences which need to be separated and displayed. For this I have used the function public void sentenceExtractor()    it splits the string in two sentences.

The two sentences are stored in SentenceOne & sentenceTwo respectively.

After thet the logic is quite simple!( implementation is hard!)

Extract the words of each of the sentences ( achieved using the private String[] wordExtractor(String msgTemp)  function, used in many programs on this blog!) and store it somewhere.

Now notice that the number of common words cannot exceed the number of words in the first senctence. For example,

INPUT:  vi

Once you extract the words and store somewhere ( THIS, IS, MY, BLOG, ON, ISC, COMPUTER, PRACTICALS) and (PLEASE, SHARE, THIS, BLOG).

Now we need to compare this too String arrays by taking the first element (THIS)  from the first array and compare it to all the element in the second array. This will determine whether or not the word is common in both the sentences. This we have to do for each of the words in the first array. Obviously if there is some word which is present in the second sentence but not in the first one cannot be common!

Now once we collect all the common words, we need to find its frequency in the original sentence and display it!

But there will be one problem! it will cause repetition!

For example, if the input is IS IS RAINING? YOU MAY GET WET IF IT IS RAINING.

when you extract the words (IS,IS,RAINING) you don't know that IS is being repeated twice and is common! So you have to solve this issue too. Again its not that difficult but definitely time consuming. Below is the piece of the code in which to avoid duplicate printing, I have used a flag "duplicateflag" to check whether the common word has already printed or not!


for(int i=0;i<counter;i++) {
                  if(i>0) {
                      for(int j=0;j<i;j++)
                            if(commonWords[i].equals(commonWords[j]))
                                duplicateflag = true// duplicate found.
                  } // end of if
                  if(!duplicateflag)
                    System.out.println(" "+commonWords[i]+"    "+commonWordsFrequency[i]);
                duplicateflag = false;   // setting the flag again 
              }  // end of i-loop 

Another problem that you can face based on the technique of word extraction. As the words are separeted by a single space, we will be using that single space divider to extract the words. So if the input is like this: HEY THERE, ARE YOU PRACTISING ENOUGH! THERE AREN'T ENOUGH GOOD BLOGS.

The extracted words will be like (HEY, THERE, , ARE, YOU......) Now when you match with the words of the second sentence, you won't be getting THERE as a common word. Because you are comparing THERE, with THERE! So you need to be careful and check for this:

String truncate = "";       
                if(word_Storage[k].charAt(word_Storage[k].length()-1) < 'A' || word_Storage[k].charAt(word_Storage[k].length()-1) > 'Z'){
                    for(int l=0;l<word_Storage[k].length()-1;l++)
                        truncate += word_Storage[k].charAt(l);
                    word_Storage[k]=truncate;

Go through the code and try to understand the methods seperately! If you have any question comment below.

JAVA CODE

import java.io.*;
public class ISC2021Question2{
       public static void main(String[] argsthrows IOException{
               String Sentence;
               int k;
               BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
               do {
               k=0;
               System.out.println("Enter the sentence:");
               Sentence=br.readLine();
               ifSentence.charAt(Sentence.length()-1)!= '.' && Sentence.charAt(Sentence.length()-1)!= '?' && Sentence.charAt(Sentence.length()-1)!= '!')
                  System.out.println("INVALID INPUT:,TRY AGAIN");
               for(int i=0;i<Sentence.length();i++)   
                    if(Sentence.charAt(i)== '.' || Sentence.charAt(i) == '?' || Sentence.charAt(i)== '!')
                        k++;
                if(k!=2
                    System.out.println("INVALID INPUT:,TRY AGAIN");
                } while(k!=2 || (Sentence.charAt(Sentence.length()-1)!= '.' && Sentence.charAt(Sentence.length()-1)!= '?' && Sentence.charAt(Sentence.length()-1)!= '!'));
               SenetenceWordFrequency obj = new SenetenceWordFrequency(Sentence);
               obj.sentenceExtractor();
               System.out.println("OUTPUT:");
               obj.commonWordsFrequency();
               obj.display();
               br.close();
       }
}
class SenetenceWordFrequency{
       public void display() {
              boolean duplicateflag = false;    
              System.out.println(sentenceOne);
              System.out.println(sentenceTwo);
              System.out.println("WORD               FREQUENCY:");  
              for(int i=0;i<counter;i++) {
                  if(i>0) {
                      for(int j=0;j<i;j++)
                            if(commonWords[i].equals(commonWords[j]))
                                duplicateflag = true// duplicate found.
                  } // end of if
                  if(!duplicateflag)
                    System.out.println(" "+commonWords[i]+"    "+commonWordsFrequency[i]);
                duplicateflag = false;   // setting the flag again 
              }  // end of i-loop 
              if(frequencyflag == false)
              System.out.println("NO COMMON WORDS:");  
        }
        public void commonWordsFrequency(){
            boolean wordfrequencyflag;
            String[] wordsSentenceOne,wordsSentenceTwo,wordsSentenceFull;
            // creating space for the words to be stored
            wordsSentenceOne = new String[numberOFWordsInSentence(sentenceOne)];
            wordsSentenceTwo = new String[numberOFWordsInSentence(sentenceTwo)];
            wordsSentenceFull = new String[numberOFWordsInSentence(msg)];
            // storing the extracted words
            wordsSentenceOne = wordExtractor(sentenceOne);
            wordsSentenceTwo = wordExtractor(sentenceTwo);
            wordsSentenceFull = wordExtractor(msg);
            //maximum number of common words cannot exceed the number of words in the first sentence
            commonWords = new String[numberOFWordsInSentence(sentenceOne)];
            commonWordsFrequency = new int[numberOFWordsInSentence(sentenceOne)];
            for(int i=0;i<numberOFWordsInSentence(sentenceOne);i++){
                wordfrequencyflag = false;
                for(int j=0;j<numberOFWordsInSentence(sentenceTwo);j++){
                    if(wordsSentenceOne[i].equals(wordsSentenceTwo[j])) { // finding a common word
                        frequencyflag = true;
                        wordfrequencyflag = true;
                        break;
                    }
                } //end of j-loop
                int frequencyword = 0;
                if(wordfrequencyflag==true){ 
                    // if there is a common word find its frequency in the whole sentence
                    for(int k=0;k<numberOFWordsInSentence(msg);k++)
                        if(wordsSentenceOne[i].equals(wordsSentenceFull[k]))
                            frequencyword++;
                        //STORING THE COMMON WORDS AND THEIR FREQUENCY  
                        commonWords[counter] = wordsSentenceOne[i];
                        commonWordsFrequency[counter] = frequencyword;  
                        counter++;  
                } //end of if
            } //end of i-loop
        }
        private int numberOFWordsInSentenceString msg){
            int word_counter=0;
            for(int i=0;i<msg.length();i++)
              if(msg.charAt(i)== ' ')
                     word_counter++;
                word_counter +=1
            return (word_counter);
        }
        private String[] wordExtractor(String msgTemp) {
            int i;
            int word_counter =0;
            String[] word_Storage;
            //counting the number of words
            for(i=0;i<msgTemp.length();i++)
              if(msgTemp.charAt(i)== ' ')
                     word_counter++;
            // In any sentence, number of words is 1 greater than the number of spaces       
            word_counter +=1
            word_Storage = new String[word_counter];
            int k = 0;
            //extracting words
            for(i=0;i<msgTemp.length();i++) {
              word_Storage[k]="";
              while(msgTemp.charAt(i) != ' ' &&  i < msgTemp.length()-1) { 
                           word_Storage[k] +=msgTemp.charAt(i);
                           i++; 
                           }
                // if any special character except '.', '!' and '?' is used after a word
                // it need to be removed after the extraction
                String truncate = "";       
                if(word_Storage[k].charAt(word_Storage[k].length()-1) < 'A' || word_Storage[k].charAt(word_Storage[k].length()-1) > 'Z'){
                    for(int l=0;l<word_Storage[k].length()-1;l++)
                        truncate += word_Storage[k].charAt(l);
                    word_Storage[k]=truncate;   
                } // end of if      
                k++;

            } // end of i-loop
            return (word_Storage);
        }       
       public void sentenceExtractor() {
              for(int i=0;i<msg.length();i++) {
                if (sentenceSeparaterFlag == false) {
                while(msg.charAt(i) != '.' && msg.charAt(i) != '!' && msg.charAt(i) != '?' && i < msg.length()-1) { 
                             sentenceOne +=msg.charAt(i);
                             i++;
                        }
                        sentenceOne +=msg.charAt(i);
                        sentenceSeparaterFlag = true;
                        i++;
                    }       
                else{
                    while(i < msg.length()-1) { 
                        sentenceTwo +=msg.charAt(i);
                        i++;
                   }
                   sentenceTwo +=msg.charAt(i); 
                    }                       
                } // end of i-loop
        }
        SenetenceWordFrequency(String Sentence){
              msg=Sentence;
              sentenceOne = "";
              sentenceTwo = "";
              sentenceSeparaterFlag = false;
              frequencyflag = false;
              counter = 0;
        }
       private String msg;
       private String sentenceOne;
       private String sentenceTwo;
       private boolean sentenceSeparaterFlag;
       private boolean frequencyflag;
       private String[] commonWords
       private int[] commonWordsFrequency;
       private int counter;
}