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.
No comments:
Post a Comment