Python,C,C++ and JAVA programs for CBSE, ISC, B.Tech and I.T Computer Science and MCA students

The Programming Project: October 2021

Friday, October 29, 2021

Recurring Deposit Calculator: ICSE Class X

Recurring Deposit Calculator || Program ICSE Class X
To boost the savings among the people of small and middle income groups, there are recurring (or cumulative) time deposit schemes in banks and post offices. Under this scheme, an investor deposits a fixed amount (in multiples of 5) every month for a specified number of months (usually, in multiples of 3) and on expiry of this period (called maturity period), he gets the amount deposited by him together with the interest (usually, compounded quarterly at a fixed rate) due to him. The amount received by the investor on the expiry of the specified period is called maturity value. The rate of interest is revised from time to time.

ENTER THE AMOUNT DEPOSITED PER MONTH:

ENTER THE TOTAL PERIOD IN MONTHS:

ENTER THE RATE OF INTEREST (PER ANNUM):

Sunday, October 17, 2021

CBSE CLASS XI CHAPTER 6: Flow Control

CBSE CLASS XI CHAPTER 6: Flow Control Solved

Summary

• The if statement is used for selection or decision making.

• The looping constructs while and for allow sections of code to be executed repeatedly under some condition.

• for statement iterates over a range of values or a sequence.

• The statements within the body of for loop are executed till the range of values is exhausted.

• The statements within the body of a while are executed over and over until the condition of the while is false.

• If the condition of the while loop is initially false, the body is not executed even once.

• The statements within the body of the while loop must ensure that the condition eventually becomes false; otherwise, the loop will become an infinite loop, leading to a logical error in the program.

• The break statement immediately exits a loop, skipping the rest of the loop’s body. Execution continues with the statement immediately following the body of the loop. When a continue statement is encountered, the control jumps to the beginning of the loop for the next iteration.

• A loop contained within another loop is called a nested loop.

 

1. What is the difference between else and elif construct of if statement?

To check or implement condition(s) in a program "if statement" is used. Depending upon the situation, single or multiple if statement can be used. If there is only two possibilities ( either a number is even or odd) if else can be used. The else construct will come into play if the "if" construct condition fails: For example,

if n is even:

    workings

else: # if n is not even then it must be odd

    workings 

But if there are multiple possibilities ( remainder on dividing by 5 ) then instead of using multiple "if" statement, elif construct is used. It allows to check the next block of "elif" construct if the current "if" or "elif" condition fails. There can be only one else statement based on a particular if statement, while there can be multiple elif statement for a particular elif statement.

if n%5 == 1:

    n = 5k+1

elif n%5 == 2

    n = 5k+2

elif n%5 == 3

    n = 5k+3

elif n%5 == 4

    n = 5k+4

else

    n is divisible by 5

2. What is the purpose of range() function? Give one example.

3. Differentiate between break and continue statements using examples.

4. What is an infinite loop? Give one example.

5. Find the output of the following program segments:

(i)         a = 110

            while a > 100:

                print(a)

                a -= 2

OUTPUT: 

110    

108    

106    

104    

102    

(ii) for i in range(20,30,2):

        print(i)

OUTPUT: 

20    

22

24

26

28

(iii)     country = 'INDIA'

          for i in country:

            print (i)

OUTPUT:

I

N

D

I

A

(iv) 

i = 0
sum = 0
while i < 9:
    if i % 4 == 0:
        sum = sum + i
    i = i + 2
print (sum)

OUTPUT: 12

(v)

for x in range(1,4):
    for y in range(2,5):
        if x * y > 10:
            break
        print (x * y)

OUTPUT:

2

3

4

4

6

8

6

9

(vi)

var = 7
while var > 0:
    print ('Current variable value: ', var)
    var = var -1
    if var == 3:
        break
    else:
        if var == 6:
            var = var -1
            continue
print ("Good bye!")

OUTPUT:

Current variable value:  7

Current variable value:  5

Current variable value:  4

Good bye!

Programming Exercises

1. Write a program that takes the name and age of the user as input and displays a message whether the user is eligible to apply for a driving license or not.

(the eligible age is 18 years).

userName = str(input("Enter your name:"))
userAge = int(input("Enter your age in years:"))
if userAge >= 18:
    print(userName,"is eligible for driving license.")
else:
    print(userName,"is not eligible for driving license.")

   

2. Write a function to print the table of a given number. The number has to be entered by the user.


numb = int(input("Enter a positive integer:"))
if numb < 0:
    print("You must enter a positive number.")
else:
    for i in range(1,11,1):
        print(numb,"X",i,"=",numb*i)


3. Write a program that prints minimum and maximum of five numbers entered by the user.

listNumbers = []
minValue = 0.0
maxValue = 0.0
for i in range(5):
    print("Enter a real number:")
    listNumbers.append(float(input()))
for i in listNumbers:
    if i < minValue:
        minValue = i
    elif i > maxValue:
        maxValue = i
    else:
        continue
print("The minimum and maximum numbers are:",minValue,"and",maxValue)

4. Write a program to check if the year entered by the user is a leap year or not.

leap = False
year = int(input("Enter the year:"))
if (year%400==0):
    leap = True
elif (year%100==0):
    leap = False
elif (year%4==0):
    leap = True
else:
    leap = False
if (leap):
    print(year,"is a leap year")
else:
    print(year,"is not a leap year")
       


5. Write a program to generate the sequence: –5, 10,–15, 20, –25…….. up to n, where n is an integer input by the user.

termsOfSeries = int(input("Enter the value of n:"))
for i in range(termsOfSeries):
    if i%2 == 0:
        if i == termsOfSeries-1:
            print(-5*(i+1),end=" ")
        else:
            print(-5*(i+1),end=",")
    else:
        if i == termsOfSeries-1:
            print(5*(i+1),end=" ")
        else:
            print(5*(i+1),end=",")

           
       

6. Write a program to find the sum of 1+ 1/8 +1/27......1/n3, where n is the number input by the user.

sumOfSeries = 0.0
termsOfSeries = int(input("Enter the value of n:"))
for i in range(termsOfSeries):
    sumOfSeries += 1/(i+1)**3
for i in range(termsOfSeries):
    if i == termsOfSeries -1:
        print("1/{}".format(int((i+1)**3))," = ",sumOfSeries,end="")
    else:
        print("1/{}".format(int((i+1)**3)),end=" + ")




7. Write a program to find the sum of digits of an integer number, input by the user.

number = int(input("Enter an integer:"))
temp = number
if temp < 0:
    temp *= -1
sumOfDigits = 0
while temp > 0:
    remainder = temp % 10
    temp = temp // 10
    sumOfDigits += remainder
print("Sum of the digits of {} is {}".format(number,sumOfDigits))


8. Write a function that checks whether an input number is a palindrome or not.

[Note: A number or a string is called palindrome if it appears same when written in reverse order also. For example, 12321 is a palindrome while 123421 is not a palindrome]

number = int(input("Enter a positive integer:"))
#finding the length of the original number
counter = len(str(number))
temp = number
revNumber = 0
#reversing the number
while temp > 0:
    remainder = temp % 10
    temp = temp // 10
    revNumber += remainder*int((10**(counter-1)))
    counter -= 1
if(number == revNumber):
    print(number,"is a palindrome number.")
else:
    print(number,"is not a palindrome number.")


9. Write a program to print the following patterns:


I have modified the program a bit.

choice = 1
while choice == 1 or choice == 2 or choice == 3 or choice == 4:
    choice = int(input("Enter your choice (1/2/3/4 any other integer to exit):"))
    if choice == 1:
        n = int(input("Enter the number of lines (must be odd):"))
        uspace = n // 2
        lspace = 1
        for i in range(n):
            # printing upper half
            if i <= n // 2:
                for j in range(n):
                    if j < uspace or j >= n-uspace: # printing blank from the from and end
                        print(" ",end=" ")
                    else:
                        print("*",end=" ")
                print()
                uspace -=1
            #printing lower half
            else:
                for j in range(n):
                    if j < lspace or j >= n-lspace: # printing blank from the from and end
                        print(" ",end=" ")
                    else:
                        print("*",end=" ")
                print()
                lspace +=1
    elif choice == 2:
        n = int(input("Enter the number of lines:"))
        space = n-1
        # forms a matrix of size n x (2n-1)
        for i in range(n):
            startIndex = i+1
            rowIndexLeft = startIndex
            rowIndexRight = 1
            for j in range(2*n-1):
                if j < space or j >= (2*n-1)-space:
                    print(" ",end=" ")
                else:
                    #middle element is always 1 for each row
                    if j == (2*n-1) // 2:
                        print("1",end=" ")
                    #elements to the left of middle element
                    elif j < (2*n-1) // 2:
                        print(rowIndexLeft,end=" ")
                        rowIndexLeft -=1
                    #elements to the right of middle element
                    else:
                        print(rowIndexRight+1,end=" ")
                        rowIndexRight +=1  
            print()
            space -= 1
    elif choice == 3:
        n = int(input("Enter the number of lines:"))
        space = 0
        # forms a matrix of size n x n
        for i in range(n):
            startIndex = 1
            for j in range(n):
                if j < space:
                    print(" ",end=" ")
                else:
                    print(startIndex,end=" ")
                    startIndex +=1
            print()
            space +=1
    elif choice == 4:
        n = int(input("Enter the number of lines (must be odd):"))
        uspace = n // 2
        lspace = 1
        for i in range(n):
            # printing upper half
            if i <= n // 2:
                for j in range(n):
                    if j < uspace or j >= n-uspace: # printing blank from the from and end
                        print(" ",end=" ")
                    else:
                        if j == uspace or j == n-uspace-1:
                            print("*",end=" ")
                        else:
                            print(" ",end=" ")
                print()
                uspace -=1
            #printing lower half
            else:
                for j in range(n):
                    if j < lspace or j >= n-lspace: # printing blank from the from and end
                        print(" ",end=" ")
                    else:
                        if j == lspace or j == n-lspace-1:
                            print("*",end=" ")
                        else:
                            print(" ",end=" ")
                print()
                lspace +=1
    else:
        print("Program terminated:")


10. Write a program to find the grade of a student when grades are allocated as given in the table below. 

Percentage of Marks         Grade

Above 90%                        A

80% to 90%                       B

70% to 80%                       C

60% to 70%                       D

Below 60%                        E

Percentage of the marks obtained by the student is input to the program.

studentName = str(input("Enter your name:"))
percentMarks = float(input("Enter your percentage:"))
if percentMarks > 90:
    print("Grade obtained by {} : {}".format(studentName,"A"))
elif percentMarks >= 80 and percentMarks <= 90:
    print("Grade obtained by {} : {}".format(studentName,"B"))
elif percentMarks >= 70 and percentMarks < 80:
    print("Grade obtained by {} : {}".format(studentName,"C"))
elif percentMarks >= 60 and percentMarks < 70:
    print("Grade obtained by {} : {}".format(studentName,"D"))
else:
    print("Grade obtained by {} : {}".format(studentName,"E"))


Case Study-based Questions

Let us add more functionality to our SMIS developed in Chapter 5.

6.1 Write a menu driven program that has options to 

• accept the marks of the student in five major subjects in Class X and display the same.

• calculate the sum of the marks of all subjects. 

Divide the total marks by number of subjects (i.e. 5), calculate percentage = total marks/5

and display the percentage.

• Find the grade of the student as per the following criteria:

Criteria                                                             Grade

percentage > 85                                                  A

percentage < 85 && percentage >= 75              B

percentage < 75 && percentage >= 50              C

percentage > 30 && percentage <= 50              D

percentage <30                                                  Reappear

Let’s peer review the case studies of others based on the parameters given under “DOCUMENTATION TIPS” at the end of Chapter 5 and provide a feedback to them.








Wednesday, October 6, 2021

ICSE JAVA PROGRAMS 2018: SECTION B QUESTION 4

 

ICSE JAVA PROGRAMS 2018: SECTION B QUESTION 4

Programming for school students ( upper to middle/secondary school) PYTHON AND JAVA PROGRAMS

Design a Railway Ticket Class with the following description:

Instance Variables/Data Members:

String name                     : To store the name of the customer

String coach                     : To store the type of coach customer wants to travel

long mobno                     : To store customer’s mobile number

int amt                             : To store basic amount of ticket

int totalamt                     : To store the amount to be paid after updating the original amount

Member methods :

void accept () – To take input for name, coach, mobile number and amount.

void update() – To update the amount as per the coach selected

(extra amount to be added in the amount as follows)

Type of Coaches Amount

First_AC                  700

Second_AC              500

Third_AC                 250

sleeper                     None

void display() – To display all details of a customer such as name, coach, total amount and mobile number.

Write a main method to create an object of the class and call the above member

methods.


import java.util.Scanner;
public class ICSEJava{
    public static void main(String[] args) {
        RailwayTicket obj = new RailwayTicket();
        obj.accept();
        obj.update();
        obj.display();

    }
}
class RailwayTicket {
    public void display() {
        System.out.println("Passenger's name:"+name);    
        System.out.println("Travelling coach:"+coach); 
        System.out.println("Passenger's mobile no:"+mobileNumber); 
        System.out.println("Intial Amount:"+amount); 
        ifamount < totalAmount)
            System.out.println("Amount after upgradation:"+totalAmount); 
        else
            System.out.println("You have not opted for upgradation:");
    }
    public void update() {
        Scanner in = new Scanner(System.in);
        String choice;
        String temp;
        int counter = 0;
        System.out.println("Do you want to update your coach(Yes,No):");    
        choice = in.nextLine();
        if(choice.toUpperCase().equals("NO"))
            System.out.println("You have not opted for upgradation:");
        else if(choice.toUpperCase().equals("YES")){
            if (coach.equals("First_AC"))
                System.out.println("Cannot be upgraded:");
            else {
                int currentCoachPos = 0;
                int upgradeCoachPos = 0;
                System.out.println("Enter the coach name you want to upgrade:");
                temp = in.nextLine();
                while(!coach.equals(coachType[currentCoachPos++]));
                while(!temp.equals(coachType[upgradeCoachPos++]));
                if (currentCoachPos <= upgradeCoachPos)
                    if(currentCoachPos < upgradeCoachPos)
                        System.out.println("You are already in a higher class:");
                    else
                        System.out.println("You have opted to upgrade in the same class!:");
                else {
                    counter = 0;
                    while(!temp.equals(coachType[counter++]) && counter < 4);   
                    if(counter == 4 )
                        System.out.println("Invalid choice:");
                    else {
                        coach = coachType[counter-1];
                        totalAmount = amount + chargesForCoach[counter-1];
                    }   
                } 
            }
        }
        else {
            System.out.println("Invalid choice:");
        }
        in.close();
    }
    public void accept() {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter your name:");
        name = in.nextLine();
        System.out.println("Enter your coach type:(First_AC/Second_AC/Third_AC/Sleeper):");
        coach = in.nextLine();
        System.out.println("Enter your mobile number:");
        mobileNumber = in.nextLong();
        System.out.println("Enter your fare:");
        amount = in.nextInt();
        //in.close();
    }
    String name;
    String coach="Sleeper";
    long mobileNumber;
    int amount;
    int totalAmount;
    String[] coachType = {"First_AC","Second_AC","Third_AC","Sleeper"};
    int[] chargesForCoach = {700,500,250,0};
}

PYTHON CODE

class RailwayTicket:
    def display(self):
        print("Passenger's name:",self.__name)   
        print("Travelling coach:",self.__coach)
        print("Passenger's mobile no:",self.__mobileNumber)
        print("Intial Amount:",self.__amount)
        ifself.__amount < self.__totalAmount):
            print("Amount after upgradation:",self.__totalAmount); 
        else:
            print("You have not opted for upgradation:")
    def update(self):
        choiceOption = ""
        temp = ""
        choiceOption = str(input("Do you want to update your coach(Yes,No):"))
        if choiceOption.upper() == "NO":
            print("You have not opted for upgradation:")
        elif choiceOption.upper() == "YES":
            if self.__coach == "First_AC":
                print("Cannot be upgraded:")
            else:
                currentCoachPos = 0
                upgradeCoachPos = 0
                temp = str(input("Enter the coach name you want to upgrade:"))
                upgradeCoach = temp
                while(self.__coach != self.coachType[currentCoachPos]):
                    currentCoachPos +=1
                while(temp != self.coachType[upgradeCoachPos]):
                    upgradeCoachPos +=1
                if (currentCoachPos <= upgradeCoachPos):
                    if(currentCoachPos < upgradeCoachPos):
                        print("You are already in a higher class:")
                    else:
                        print("You have opted to upgrade in the same class!:")
                else:
                    counter = 0
                    while((temp != self.coachType[counter]) and counter < 4):
                        counter +=1
                    if counter == 4:
                        print("Invalid choice")
                    else:
                        self.__coach = self.coachType[counter-1]
                        self.__totalAmount = self.__amount + self.chargesForCoach[counter-1]
        else:
            print("Invalid choice:")

    def accept(self):
        self.__namestr(input("Enter your name:"))
        self.__coachstr(input("Enter your coach type:(First_AC/Second_AC/Third_AC/Sleeper):"))
        self.__mobileNumber = int(input("Enter your mobile number:"))
        self.__amount = float(input("Enter your fare:"))
    __name = ""
    __coach""
    __mobileNumber = 0
    __amount = float(0)
    __totalAmount = float(0)
    coachType = ["First_AC","Second_AC","Third_AC","Sleeper"]
    chargesForCoach = [700,500,250,0]
obj = RailwayTicket()
obj.accept()
obj.update()
obj.display()