The Programming Project: Programming
Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Saturday, October 2, 2021

ICSE JAVA PROGRAMS 2019: SECTION B QUESTION 9 SOLVED

 

ICSE JAVA PROGRAMS 2019: SECTION B QUESTION 9

Programming for school students ( upper to middle/secondary school)

A tech number has even number of digits. If the number is split in two equal halves, then the square of the sum of these halves is equal to the number itself. Write a program to generate and print all four digits tech numbers.



JAVA CODE

public class ISCJava{
       public static void main(String[] args) {
       final int j = 2;
       int counter;
       int lastTwoDigit;
       int firstTwoDigit;
       int temp;
       forint i = 1000 ; i < 10000 ; i++) { // looping through all 4-digits
              counter = 0;
              lastTwoDigit = 0;
              firstTwoDigit = 0;
              temp = i;
              // extracting the last two digit
              while ( counter < j) {
                     lastTwoDigit += (temp%10)*(int)Math.pow(10,counter);
                     counter++;
                     temp /= 10;
                     }
              // extracting the first two digit
              counter = 0;
              while ( counter < j) {
                     firstTwoDigit += (temp%10)*(int)Math.pow(10,counter);
                     counter++;
                     temp /= 10;
                     }
              ifi ==  (int)Math.pow(firstTwoDigit+lastTwoDigit,2))
                     System.out.println(i+" is a tech number.");
              }
       }
}

PYHTON CODE
#PROGRAM TO PRINT ALL 4 DIGITS TECH NUMBER
j = 2
for i in range(9000): #total number of 4 digits number are 9000
    counter = 0
    lastTwoDigit = 0
    firstTwoDigit = 0
    temp = i+1000
    numb = temp
    #extracting the last two digit
    while counter < j:
        lastTwoDigit += int(temp%10*int((10**counter)))
        temp /= 10
        temp = int(temp)
        counter +=1
    #extracting the last two digit
    counter = 0
    while counter < j:
        firstTwoDigit += int(temp%10*int((10**counter)))
        temp /= 10
        temp = int(temp)
        counter +=1
    #print(firstTwoDigit,"last",lastTwoDigit,numb)
    if numb == int((firstTwoDigit+lastTwoDigit)**2):
        print(numb," is a tech number.")

Friday, October 1, 2021

ICSE JAVA PROGRAMS 2019: SECTION B QUESTION 8 SOLVED

 

ICSE JAVA PROGRAMS 2019: SECTION B QUESTION 8

Programming for school students ( upper to middle/secondary school)

Write a program to input s sentence and convert it into uppercase and display the total number of words starting with letter 'A'.

Example:

INPUT: Advancement and application of Information Technology are ever changing.

OUTPUT: ADVANCEMENT AND APPLICATION OF INFORMATION TECHNOLOGY ARE EVER CHANGING.

Number of word(s)starting with A is/are: 4




JAVA CODE

import java.util.Scanner;
public class ISCJava{
       public static void main(String[] args) {
       String sentence;
       int counterStartingA = 0;
       Scanner in = new Scanner(System.in);
       System.out.println("Enter your sentence:");
       sentence = in.nextLine();
       System.out.println();
       System.out.println("OUTPUT:");
       System.out.println("ORIGINAL STATEMENT:");
       System.out.println(sentence);
       System.out.println();
       System.out.println("AFTER CHANGING TO UPPER CASE:");
       for(int i =0isentence.length();i++) {
              char c = sentence.charAt(i);
              if(c >= 'a' && c <= 'z') {
                     c -= 32;
                     System.out.print(c);
              }
              else
              System.out.print(c);   
       }
       //counting number of words staring with A
       System.out.println();
       for(int i =0isentence.length(); i++) 
              if (sentence.charAt(i) == 'A' || sentence.charAt(i) == 'a') {
                     if(i==0)
                            counterStartingA++; 
                     else if(sentence.charAt(i-1) == ' ')
                            counterStartingA++;
              }
       System.out.println("Number of word(s)starting with A is/are: "+counterStartingA);
       in.close();
       }
}


PYTHON CODE

counterStartingA = 0
sentence = str(input("Enter the sentence: "))
print("OUTPUT:")
print("ORIGINAL STATEMENT:")
print(sentence)
print("AFTER CHANGING TO UPPER CASE:")
for i in range(len(sentence)):
    c = (sentence[i])
    if (c >= 'a' and c <= 'z'):
        t = ord(c) -32
        print(chr(t),end="")
    else:
        print(c,end="")
for i in range(len(sentence)):
    if sentence[i] == 'A' or sentence[i] == 'a':
        if i == 0:
            counterStartingA +=1
        elif sentence[i-1] == ' ':
            counterStartingA +=1
print()
print("Number of word(s)starting with A is/are:",counterStartingA)

ICSE JAVA PROGRAMS 2019: SECTION B QUESTION 7 SOLVED

ICSE JAVA PROGRAMS 2019: SECTION B QUESTION 7

Programming for school students ( upper to middle/secondary school)

Design a class to overload a function series() as follows:

(a) void series (int x, int n) - To display the sum of the series given below:

x+x2+x3+........+xn

(b) void series (int p) - To display the following series:

0, 7, 26, 63, ........ upto p terms

(c) void series () - To display the sum of the series given below

&frac12 + 1⁄3 +&frac14 +.......+1⁄10


import java.util.Scanner;
public class ISCJava{
       public static void main(String[] args) {
       Scanner in = new Scanner(System.in);
       Series obj = new Series();
       int choice;
       System.out.println("Enter your choice(1/2/3):");
       choice = in.nextInt();
       switch(choice){
              case 1:
              int xn;
              System.out.println("Enter the value of x:");
              x = in.nextInt();
              System.out.println("Enter the value of n:");
              n = in.nextInt();
              obj.series(x,n);
              break;
              case 2:
              int p;
              System.out.println("Enter the value of p:");
              p = in.nextInt();
              obj.series(p);
              break;
              case 3:
              obj.series();
              break;
              default:
              System.out.println("Wrong Choice:");
       }
       in.close();
       }
}
class Series {
       public void series(int xint n) {
              for (int i = 1; i<= n ;i++)
                     sumOfSeries += Math.pow((double)x,(double)i);
              System.out.println("Sum of the series is:"+sumOfSeries);
       }
       public void series(int p) {
              System.out.println("The series is");
              for(int i = 1; i<= p; i++)
                     if (i != p)
                            System.out.print((int)Math.pow(i, 3)-1+",");
                     else
                            System.out.println((int)Math.pow(i, 3)-1);       
       }
       public void series() {
              for (int i = 2; i<= 10 ;i++)
                     sumOfSeries += (1.0/i);
              System.out.println("Sum of the series is:"+sumOfSeries);
       }
       Series() {
              this.sumOfSeries = 0.0;
       }
       private double sumOfSeries;
}
       
PYTHON CODE
Note: Function overloading is not available in Python.

class Series:
    def seriesOne(self,x,n):
        for i in range(n):
            i +=1
            self.__sumOfSeries += x**i
        print("Sum of the series is:",self.__sumOfSeries)
    def seriesTwo(self,p):
        for i in range(p):
            i +=1
            if i<p:
                print(i**3-1end =",")
            else:
                print(i**3-1end =" ")
    def seriesThree(self):
        for i in range(9):
            i +=2
            self.__sumOfSeries += (1.0/(i+1))
        print("Sum of the series is:",self.__sumOfSeries)
    def __init__(self):
       self.__sumOfSeries = 0
    __sumOfSeries = float(0)
# main program    
obj = Series()
try:
    N = int(input("Enter your choice(1/2/3):"))
    if N > 3:
        print("Your choice in invalid")   
    elif N==1:
        x = int(input("Enter the value of x:"))
        n = int(input("Enter the value of n:"))
        obj.seriesOne(x,n)
    elif N==2:
        p = int(input("Enter the value of p:"))
        obj.seriesTwo(p
    else:
        obj.seriesThree()    
except ValueError as e:
    print("Your choice is invalid")

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))



Monday, September 9, 2013

Random Quotes

Program to print a random quote from a set of  quotes stored in a file "Quotes.txt" such that the quotes will not be repeated unless all the quotes are exhausted.




import java.util.*;
import java.io.*;
public class MathsQuoteOfDay
{
public static void main(String[] args) throws IOException
{
int n=0,input,j=0,nq=0,k;
boolean flag=true;
FileReader fr = new FileReader("Quotes.txt");
BufferedReader br = new BufferedReader(fr);
String S;
while(( S=br.readLine() ) != null)
n++;
fr.close();
Quotes Q = new Quotes(n);
int[] qIndex = new int[60];
FileReader fr1 = new FileReader("Quotes.txt");
BufferedReader br1 = new BufferedReader(fr1);
while(( S=br1.readLine() ) != null)
Q.setQuotes(S);
fr1.close();
/*FileOutputStream fout1 = new FileOutputStream("Data.txt");
        DataOutputStream out1 = new DataOutputStream(fout1);
        out1.close();*/
FileInputStream fi = new FileInputStream("Data.txt");
        DataInputStream i = new DataInputStream(fi);
        int l;
        boolean EOF =false;
        while(!EOF)
        {
        try {
        qIndex[j] =i.readInt();
        //System.out.println(qIndex[j]);
        j++;
        }catch (EOFException e) {
        EOF=true;
        }
        }
        i.close();
        //j=j-1;
        //System.out.println("J=>>>>>>>>>"+j);
        //for(int t=0; t<j;t++)
        //System.out.println("Array"+qIndex[t]);
        if(j!=0 && j!=n)
        {
        boolean match=true;
        boolean find=false;
        int t;
        do
        {
        find=false;
        t = (int)(Math.random()*n);
        //System.out.println("Random value is"+t);
        for(int m=0;m<j;m++)
        {
        if(t==qIndex[m])
        find=true;
        }
        if(find==true)
        match=false;
        else
        match=true;
        }while(match==false);
        FileOutputStream fout = new FileOutputStream("Data.txt",true);
        DataOutputStream out = new DataOutputStream(fout);
        out.writeInt(t);
        //System.out.println("Ought to be 9"+t);
        System.out.println("");
        System.out.println(" "+Q.getQuotes(t));
        System.out.println("");
        out.close();
        }
        else
        {
        int t;
        //System.out.println("Exhausted");
        t = (int)(Math.random()*n);
        FileOutputStream fo = new FileOutputStream("Data.txt");
        DataOutputStream o = new DataOutputStream(fo);
        o.writeInt(t);
        System.out.println("");
        System.out.println(" "+Q.getQuotes(t));
        System.out.println("");
        o.close();
        }
                }
}
class Quotes
{
Quotes()
{
}
Quotes(int n)
{
quotes = new String[n];
q=0;
}
public void setQuotes(String S)
{
quotes[q++]=S;
}
public String getQuotes(int ran)
{
return (quotes[ran]);
}
private String[] quotes;
private int q;
}

Sunday, September 8, 2013

Simple Java Program to Demonstrate ArrayList and use of gc()

Inherit the STUDENT Class(Program here http://thecprojectt.blogspot.in/2013/09/simple-java-program-to-demonstrate.html)  and override the input method so as to input the department of each student. Search and display a sorted list of students one department or students based on scoring criteria. Create an arraylist of students and remove a student based on scoring criteria and then call gc() and check for free memory



import java.util.*;
public class ListStudent
    {
    public static void main(String[] args)
    {
      int[] mdays={31,28,31,30,31,30,31,31,30,31,30,31};
int[] ldays={31,29,31,30,31,30,31,31,30,31,30,31};
int ch,k=0,n;
String d1;
boolean lp,fg=true;
Runtime r = Runtime.getRuntime();
    Scanner in = new Scanner(System.in);
    Course co = new Course();
    extendStudent[] students = new extendStudent[6];
    for(int i=0;i<6;i++)
    students[i]=new extendStudent();
    ArrayList<extendStudent> L = new ArrayList<extendStudent>();
    System.out.println("Courses available are Graduation, PG and PhD with 3,2 and 1 seats respectively:");
    String choice1="";
        do
    {
   
    System.out.println("\n Enter the course name:");
    String S = in.next();
    if(co.getCourse(S).equals("XX"))
    {
    System.out.println("Invalid course:");
    continue;
    }
    if(co.getSeat(S)>co.getSeatLimit(S))
    {
    System.out.println("Seats for the course "+S+" is exhausted:");
    continue;
    }
      System.out.println("Enter the Record for student :"+(k+1));
      students[k].setCourse(S);
    students[k].inputData();
    L.add(students[k]);
    k++;
    System.out.println(" Want to add another record yes/no:");
    choice1 = in.next();
    }while("YES".equalsIgnoreCase(choice1));
    n=k;
    System.out.println(" Intial List Size is: "+L.size());
    System.out.println("Press 1 to display Records of all STUDENTS:");
    System.out.println("Press 2 to see the result of all STUDENTS:");
    ch = in.nextInt();
    switch(ch)
    {
    case 1:
    for(int i=0;i<L.size();i++)
    L.get(i).displayAll();
    break;
    case 2:
        for(int i=0;i<L.size();i++)
        L.get(i).resultBuild();
        break;
        default:
        System.out.println("Wrong choice:");
        break;
        }
        System.out.println(" Intial List Size is: "+L.size());
        System.out.println(" Total free memory is: "+r.freeMemory()+" Bytes");
        System.out.println(" Want to search by Admission Date(dd/mm/yyyy)? yes/no:");
        String choice = in.next();
        if("YES".equalsIgnoreCase(choice))
        {
        int d=0,m=0,y=0;
         
          do {
fg=true;
int i=0;
int j=0;

String temp ="";
System.out.println("Enter the admission date(dd/mm/yyyy):");
d1=in.next();
while(d1.charAt(i)!='/' && i<d1.length())
{
if(0 <= d1.charAt(i)-48 && d1.charAt(i)-48 <= 9 )
{
temp=temp+d1.charAt(i);
i++;
j++;
}
else
{
System.out.println("Incorrect format:");
i++;
fg=false;
break;
}
} //d extraction
//System.out.println("Temp="+temp+"I="+i+"J="+j+"fg="+fg);
  if(fg==true && j<=2 && d1.charAt(i)=='/' && j >0 )
{
j=0;
d = Integer.valueOf(temp);
i=i+1;
temp="";
while(d1.charAt(i)!='/' && i<d1.length() )
{
if(0 <= d1.charAt(i)-48 && d1.charAt(i)-48 <= 9 )
{
temp=temp+d1.charAt(i);
i++;
j++;
}
else
{
System.out.println("Incorrect format:");
i++;
//j++;
fg=false;
break;
}
} //m extraction
m = Integer.valueOf(temp);
}
//System.out.println("Temp="+temp+"I="+i+"J="+j+"fg="+fg);

if(fg==true && j<=2 && d1.charAt(i)=='/' && j >0 && m <=12 && 1<=m)
{
j=0;
//m = Integer.valueOf(temp);
//System.out.println(d);
i=i+1;
temp="";
while(i<d1.length())
{
if(0 <= d1.charAt(i)-48 && d1.charAt(i)-48 <= 9 )
{
temp=temp+d1.charAt(i);
i++;
j++;
}
else
{
System.out.println("Incorrect format:");
fg=false;
i++;
break;
//j++;

}
} //y extraction
}
//System.out.println("Temp="+temp+"I="+i+"J="+j+"fg="+fg);
if(fg==true && j==4)
{
y = Integer.valueOf(temp);
fg=true;
}//end of else of y
else
fg=false;
if(fg==true)
{
if(y%400==0)
    lp=true;
else if (y%100==0)
    lp=false;
else if (y%4==0)
    lp=true;
else
    lp=false;
   
if(lp==false)
{
if(d>mdays[m-1] || d < 1 )
{
System.out.println("Invalid d of a m:");
fg=false;
}
}//non-lp y checking
else
{
if(d>ldays[m-1] || d < 1)
{
System.out.println("Invalid d of a m:");
fg=false;
}
} //lp y checking
} // checking for vaild date in months
}while(fg==false);
d1="";
d1=d+"/"+m+"/"+y;
for(int i=0;i<L.size();i++)
        {
        if(L.get(i).searchByAdmissionDate().equals(d1))
        L.get(i).displayAll();
        }
       
}
        System.out.println("Press 1 to display Records on basis of Departments:");
    System.out.println("Press 2 to display Records on basis of Scoring Criteria:");
    ch = in.nextInt();
    switch(ch)
    {
    case 1:
    System.out.println("Enter the Department name:");
    String dept = in.next();
    for(int i=0;i<L.size();i++)
        if(L.get(i).deptName().equals(dept))
        {
        System.out.println("Department name: "+dept+" Student Name: "+L.get(i).getName());
        }
    break;
    case 2:
    System.out.println("Enter the cut-off percentage:");
    double per = in.nextDouble();
    extendStudent S = new extendStudent();
    for(int i=0;i<n-1;i++)
    {
    for(int j=0;j<n-i-1;j++)
    {
    if(L.get(j).getPercentage()<L.get(j+1).getPercentage())
    {
    S=L.get(j);
    L.set(j,L.get(j+1));
    L.set(j+1,S);
    }
    }
    }
    System.out.println(" Sorted List is:");
    for(int i=0;i<n;i++)
    {
    System.out.println("Department name: "+L.get(i).deptName()+" Student Name: "+L.get(i).getName()+" Percentage Marks: "+L.get(i).getPercentage());
      }
   
    System.out.println("List after imposing the cut-off percentage:");
    for(int i=0;i<L.size();i++)
    {
    if(L.get(i).getPercentage()>=per)
      System.out.println("Department name: "+L.get(i).deptName()+" Student Name: "+L.get(i).getName()+" Percentage Marks: "+L.get(i).getPercentage());
    else
    {
    L.remove(i);
    r.gc();
    }
    }
   
    break;
    default:
    System.out.println("Wrong choice:");
    break;
    }
        in.close();
        System.out.println(" List Size after elimination is: "+L.size());
       
        System.out.println(" Total free memory after removing unwanted objects: "+r.freeMemory()+" Bytes");
    }
    }
class StudentRecord
{

StudentRecord()
{
roll=0;
name="";
co="";
for(int i:marks)
marks[i]=0;
}
public String searchByAdmissionDate()
{
return (dte);
}
public String getName()
{
return name;
}
public void resultBuild()
{
int sum=0;
System.out.println("----------------------------------------------------");
System.out.println("Name :"+name);
System.out.println("Course :"+co);
System.out.println("Roll Number :"+roll);
System.out.println("----------------------------------------------------");
for(int i=0;i<5;i++)
{
System.out.println("Subject "+(i+1)+" "+marks[i]);
sum +=marks[i];
}
System.out.println("Total Marks: "+sum);
System.out.println("Percentage: "+sum/5);
percentage= sum/5;
System.out.println("");
}
public void inputData()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the name:");
name=in.nextLine();
System.out.println("Enter the roll number:");
roll=in.nextInt();
do {
flag=true;
int i=0;
int j=0;
String temp ="";
System.out.println("Enter the admission date(dd/mm/yyyy):");
dte=in.next();
while(dte.charAt(i)!='/' && i<dte.length())
{
if(0 <= dte.charAt(i)-48 && dte.charAt(i)-48 <= 9 )
{
temp=temp+dte.charAt(i);
i++;
j++;
}
else
{
System.out.println("Incorrect format:");
i++;
flag=false;
break;
}
} //day extraction
//System.out.println("Temp="+temp+"I="+i+"J="+j+"flag="+flag);
  if(flag==true && j<=2 && dte.charAt(i)=='/' && j >0 )
{
j=0;
day = Integer.valueOf(temp);
i=i+1;
temp="";
while(dte.charAt(i)!='/' && i<dte.length() )
{
if(0 <= dte.charAt(i)-48 && dte.charAt(i)-48 <= 9 )
{
temp=temp+dte.charAt(i);
i++;
j++;
}
else
{
System.out.println("Incorrect format:");
i++;
//j++;
flag=false;
break;
}
} //month extraction
month = Integer.valueOf(temp);
}
//System.out.println("Temp="+temp+"I="+i+"J="+j+"flag="+flag);

if(flag==true && j<=2 && dte.charAt(i)=='/' && j >0 && month <=12 && 1<=month)
{
j=0;
//month = Integer.valueOf(temp);
//System.out.println(day);
i=i+1;
temp="";
while(i<dte.length())
{
if(0 <= dte.charAt(i)-48 && dte.charAt(i)-48 <= 9 )
{
temp=temp+dte.charAt(i);
i++;
j++;
}
else
{
System.out.println("Incorrect format:");
flag=false;
i++;
break;
//j++;

}
} //year extraction
}
//System.out.println("Temp="+temp+"I="+i+"J="+j+"flag="+flag);
if(flag==true && j==4)
{
year = Integer.valueOf(temp);
flag=true;
}//end of else of year
else
flag=false;
if(flag==true)
{
if(year%400==0)
    leap=true;
else if (year%100==0)
    leap=false;
else if (year%4==0)
    leap=true;
else
    leap=false;
   
if(leap==false)
{
if(day>mdays[month-1] || day < 1 )
{
System.out.println("Invalid day of a month:");
flag=false;
}
}//non-leap year checking
else
{
if(day>ldays[month-1] || day < 1)
{
System.out.println("Invalid day of a month:");
flag=false;
}
} //leap year checking
} // checking for vaild date in months
}while(flag==false);
dte="";
dte=day+"/"+month+"/"+year;
System.out.println("Enter the marks:");
for(int i=0;i<5;i++)
{
System.out.println("Enter the marks in Subject:"+(i+1));
marks[i]=in.nextInt();
}
}
public void setCourse(String S)
{
co=S;
}
public void displayAll()
{
System.out.println("Roll No. = "+roll+" Name= "+name+" Course ="+co);
System.out.println("Admission date: "+dte);
for(int i=0;i<5;i++)
{
System.out.println("Marks in Subject "+(i+1)+"= "+marks[i]);
}
System.out.println("");
}
public double getPercentage()
{
return percentage;
}
private int roll;
private String name;
private String co;
private String dte;
private boolean flag=true;
private boolean leap;
private double percentage;
private int day;
private int month;
private int year;
int[] marks = new int[5];
int[] mdays={31,28,31,30,31,30,31,31,30,31,30,31};
int[] ldays={31,29,31,30,31,30,31,31,30,31,30,31};
}
class extendStudent extends StudentRecord
{
public extendStudent()
{
super();
Department="";
}
public void inputData()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the department:");
Department = in.nextLine();
super.inputData();
}
public String deptName()
{
return Department;
}
public double getPercentage()
{
return super.getPercentage();
}

private String Department;
}
class Course
{
Course()
{
seats=new int[3];
seats[0]=0;
seats[1]=0;
seats[2]=0;
}
public String getCourse(String S)
{
for(int i=0;i<3;i++)
if(S.equalsIgnoreCase(course[i]))
{
seats[i]++;
return course[i];
}
return "XX";
}
public int getSeat(String S)
{
for(int i=0;i<3;i++)
{
if(S.equalsIgnoreCase(course[i]))
return seats[i];
}
return -9;
}
public int getSeatLimit(String S)
{
for(int i=0;i<3;i++)
{
if(S.equalsIgnoreCase(course[i]))
return fixSeat[i];
}
return -9;
}
private static String[] course = {"Graduation", "PG", "PhD"};
private static int[] fixSeat={3,2,1};
private int[] seats;
}