# Flow of Control - Class 11 Computer Science - Chapter 6 - Notes, NCERT Solutions & Extra Questions

Renews every month. Cancel anytime

Your personal doubt-solving assistant

Chatterbot AI gives you 100% accurate answers to your questions in an instant.

## Notes - Flow of Control | Class 11 NCERT | Computer Science

### Comprehensive Flow of Control Class 11 Notes: Master Python Programming Concepts

### Understanding Flow of Control in Python

#### What is Flow of Control?

Flow of control refers to the order in which individual statements, instructions, or function calls of a program are executed or evaluated.

#### Importance in Programming

Understanding the flow of control is crucial as it allows a programmer to dictate how and when parts of the code are executed, ensuring the program runs efficiently and correctly.

### Sequence Control

#### Sequence Control in Python

In sequence control, statements are executed one after another in the order they appear. This is the simplest form of control flow, where Python executes one instruction after another until the end of the program is reached.

#### Example Code

```
### Program to print the difference of two input numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
diff = num1 - num2
print("The difference of", num1, "and", num2, "is", diff)
```

### Selection Control

#### Selection Control in Python

Selection control allows us to decide which statement to execute based on a condition. The primary tools in Python for selection control are the `if`

, `if..else`

, and `if..elif`

statements.

#### The If Statement

##### Syntax and Usage

```
if condition:
statement(s)
```

##### Example Code

```
age = int(input("Enter your age: "))
if age >= 18:
print("Eligible to vote")
```

#### The If..Else Statement

##### Syntax and Usage

```
if condition:
statement(s)
else:
statement(s)
```

##### Example Code

```
age = int(input("Enter your age: "))
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
```

#### Working with Nested If Statements

##### Syntax and Usage

Nested if statements are if statements inside other if statements. They allow for more complex decision-making.

##### Example Code

```
num = int(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
```

#### The Elif Statement

##### Syntax and Usage

The `elif`

statement, short for "else if," allows for multiple conditions to be checked sequentially.

```
if condition1:
statement(s)
elif condition2:
statement(s)
else:
statement(s)
```

##### Example Code

```
number = int(input("Enter a number: "))
if number > 0:
print("Number is positive")
elif number < 0:
print("Number is negative")
else:
print("Number is zero")
```

#### Practical Example: Simple Calculator

A practical example to illustrate the if..elif..else statement is creating a simple calculator.

```
val1 = float(input("Enter value 1: "))
val2 = float(input("Enter value 2: "))
op = input("Enter an operator (+, -, *, /): ")
if op == "+":
result = val1 + val2
elif op == "-":
result = abs(val1 - val2)
elif op == "*":
result = val1 * val2
elif op == "/":
if val2 != 0:
result = val1 / val2
else:
result = "Error! Division by zero."
else:
result = "Invalid operator"
print("The result is:", result)
```

### Indentation in Python

#### The Role of Indentation

Indentation is critical in Python as it defines the level of hierarchy in blocks of code. Unlike many other programming languages, Python uses indentation to represent the beginning and end of control structures like loops and conditionals.

#### Common Errors and Solutions

A common error is inconsistent use of tabs and spaces. Ensure that you use either spaces or tabs uniformly for indentation.

### Repetition (Looping) Constructs in Python

#### The For Loop

##### Syntax and Usage

```
for control-variable in sequence:
statements
```

##### Example Code

```
for letter in 'PYTHON':
print(letter)
```

#### Using the Range() Function

`range()`

generates a sequence of numbers, which can be used to control the number of loop iterations.

```
for num in range(5):
print(num)
```

#### The While Loop

##### Syntax and Usage

```
while test-condition:
statements
```

```
count = 1
while count <= 5:
print(count)
count += 1
```

#### Practical Example: Finding Factors of a Number

```
num = int(input("Enter a number to find its factors: "))
factor = 1
while factor <= num:
if num % factor == 0:
print(factor, end=' ')
factor += 1
```

### Break and Continue Statements

#### The Break Statement

Break statement immediately exits a loop, skipping the rest of the loop's body.

##### Example Code

```
for num in range(10):
if num == 7:
break
print(num)
```

#### The Continue Statement

Continue statement skips the remaining statements in the loop and jumps to the next iteration.

##### Example Code

```
for num in range(10):
if num == 3:
continue
print(num)
```

### Working with Nested Loops

#### Syntax and Usage

A nested loop is a loop within another loop.

```
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
```

#### Practical Example: Nested For and While Loops

```
num = 2
for i in range(2, 50):
j = 2
while j <= (i/2):
if i % j == 0:
break
j += 1
if j > (i/j):
print(i, "is a prime number")
```

#### Practical Example: Finding Prime Numbers

```
num = 2
for i in range(2, 50):
j = 2
while (j <= (i / 2)):
if (i % j == 0):
break
j += 1
if (j > i / j):
print(i, "is a prime number")
```

### Summary of Flow of Control in Python

The

`if`

statement is used for decision making.Looping constructs

`while`

and`for`

allow executing code repeatedly under some condition.The

`for`

statement iterates over a range of values or a sequence.The

`while`

statement continues to execute until its condition becomes false.The

`break`

statement immediately exits a loop, and the`continue`

statement skips the rest of the loop's body for the current iteration.Nested loops allow one loop to run inside another loop.

Understanding these concepts thoroughly will greatly enhance your programming skills in Python and make you proficient in developing complex algorithms and software solutions.

Here's a visualisation of flow of control showcasing sequential execution, selection through the `if..else`

statements, and repetition via loops.

```
graph TD
A[Start] --> B(Sequence Control)
B --> C[Selection Control if/else]
C --> D{Condition True?}
D --> |Yes| E[Execute Block of Code]
D --> |No| F[Skip Block]
E --> G{Repeat?}
F --> G
G --> |Yes| H[Repetition Control Loop]
H --> I[Loop Body Execution]
I --> J{Continue Loop?}
J --> |Yes| I
J --> |No| K[End]
G --> |No| K
```

With these notes, you should have a firm understanding of flow control in Python, enabling you to write more sophisticated and efficient code. Happy coding!

🚀 Learn more about *Notes* with Chatterbot AI

## Extra Questions - Flow of Control | NCERT | Computer Science | Class 11

💡 Have more questions?

Ask Chatterbot AI## NCERT Solutions - Flow of Control | NCERT | Computer Science | Class 11

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

Here is a Python program that takes the name and age of the user as input and checks if the user is eligible to apply for a driving license.

```
# Program to check driving license eligibility based on age
# Taking user input for name and age
name = input("Enter your name: ")
age = int(input("Enter your age: "))
# Checking eligibility
if age >= 18:
print(name + ", you are eligible to apply for a driving license.")
else:
print(name + ", you are not eligible to apply for a driving license.")
```

### Example Output

```
Enter your name: John Doe
Enter your age: 20
John Doe, you are eligible to apply for a driving license.
```

In this program:

We take the

**name**and**age**as input from the user.Use an

**if..else statement**to check if the age is greater than or equal to**18**.Print a message indicating whether the user is eligible to apply for a driving license.

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

Here's the Python function to print the multiplication table of a given number entered by the user:

```
def print_multiplication_table():
num = int(input("Enter a number to print its multiplication table: "))
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
```

You can call this function, and it will prompt you to enter a number and then print the multiplication table for that number from 1 to 10.

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

Here is a Python program that reads five numbers from the user and then prints the minimum and maximum of those numbers:

```
# Program to find the minimum and maximum of five numbers
# Taking input from the user
numbers = []
for i in range(5):
num = float(input(f"Enter number {i+1}: "))
numbers.append(num)
# Finding minimum and maximum
min_num = min(numbers)
max_num = max(numbers)
# Printing the results
print("The minimum number is:", min_num)
print("The maximum number is:", max_num)
```

### Key Points:

**Input Handling**: The program uses a loop to collect five numbers from the user.**Minimum and Maximum Functions**: The`min()`

and`max()`

functions are used to find the minimum and maximum numbers, respectively.**Output**: Finally, it prints the minimum and maximum numbers.

This program ensures that we correctly identify the smallest and largest numbers from a set of five user-provided inputs.

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

Here's a Python program to check if the year entered by the user is a leap year or not:

```
# Program to check if a year is a leap year or not
# Input: year to be checked
year = int(input("Enter a year: "))
# Logic to check if it's a leap year
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
```

### Explanation:

**Leap Year Rule**: A year is a leap year if:It is exactly divisible by 4

**and**not exactly divisible by 100**OR**It is exactly divisible by 400.

**Input**: The year to be checked (entered by the user).**Output**: Displays whether the year is a leap year or not.

Write a program to generate the sequence: $-5,10$, $-15,20,-25 \ldots .$. upto $\mathrm{n}$, where $\mathrm{n}$ is an integer input by the user.

Below is a Python program that generates the sequence `-5, 10, -15, 20, -25, ...`

up to `n`

where `n`

is an integer input by the user:

```
# Program to generate the sequence -5, 10, -15, 20, -25, ... upto n
n = int(input("Enter a number n: "))
# Initialize variables
term = -5
i = 1
# Generate the sequence
print("Generated sequence:", end=" ")
while abs(term) <= n:
print(term, end=", ")
term = -term + (5 * i)
i += 1
```

## Explanation

The

**input function**is used to accept an integer from the user.The loop continues until the absolute value of

`term`

is less than or equal to`n`

.The value of

`term`

is updated in each iteration:`-term`

flips the sign.`5 * i`

adds an increment of 5 on each iteration.

### Sample Output

```
Enter a number n: 30
Generated sequence: -5, 10, -15, 20, -25, 30
```

The sequence will continue to alternate signs and increment its absolute value by 5 on each iteration until the specified condition is met.

Write a program to find the sum of $1+1 / 8+$ $1 / 27 \ldots . .1 / \mathrm{n}^{3}$, where $\mathrm{n}$ is the number input by the user.

Here is a Python program to find the sum of $ 1 + \frac{1}{8} + \frac{1}{27} + \ldots + \frac{1}{n^3} $, where $ n $ is the number input by the user.

```
# Program to find the sum of 1 + 1/8 + 1/27 + ... + 1/n^3
def sum_of_series(n):
total_sum = 0
for i in range(1, n + 1):
total_sum += 1 / (i ** 3)
return total_sum
# Input from user
n = int(input("Enter the number n: "))
# Calculating the sum
result = sum_of_series(n)
# Displaying the result
print(f"The sum of the series for n = {n} is {result:.6f}")
```

This program defines a function `sum_of_series(n)`

that calculates the sum of the series. The user is prompted to enter a number $ n $, and the sum is calculated and displayed with 6 decimal precision.

Key points:

**Function definition**:`sum_of_series(n)`

calculates the sum.**User input**: The program takes an integer input from the user.**Loop**: A`for`

loop iterates from 1 to $ n $ and computes the term-wise sum.**Precision**: The result is printed with six decimal places.

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

Here is the code:

```
# Program to find the sum of digits of an integer number
# Function to calculate sum of digits
def sum_of_digits(n):
sum = 0
while n > 0:
digit = n % 10
sum += digit
n = n // 10
return sum
# Taking user input
number = int(input("Enter an integer number: "))
# Calculating the sum of digits
result = sum_of_digits(number)
# Displaying the result
print(f"The sum of the digits of {number} is {result}")
```

**Explanation:**

The

function calculates the sum of the digits of the number.`sum_of_digits`

The

**while loop**repeatedly extracts the last digit of the number usingand adds it to the sum.`n % 10`

The number is then

**floored**divided by 10 to remove the last digit.The process continues until there are no more digits left in the number.

The sum is then returned and printed.

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]

Here is a function in Python to check whether an input number is a palindrome or not:

```
def is_palindrome(number):
original = str(number)
reverse = original[::-1]
if original == reverse:
return True
else:
return False
# Example usage
num = int(input("Enter a number: "))
if is_palindrome(num):
print(f"{num} is a palindrome")
else:
print(f"{num} is not a palindrome")
```

This function ** is_palindrome** converts the input number to a string,

**reverses**the string, and then checks if the reversed string is equal to the original string. If they are equal, the function returns

`True`

, indicating that the number is a palindrome; otherwise, it returns `False`

.Write a program to print the following patterns:

i)

```
*
* * *
* * * * *
* * *
*
```

ii)

```
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
```

iii)

```
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
```

iv)

```
*
* *
* *
* *
*
```

Below are the Python programs to print each of the specified patterns:

### Pattern i

```
# Program i
rows = 3
for i in range(rows - 1, -1, -1):
print(" " * i + "* " * (rows - i))
for i in range(1, rows):
print(" " * i + "* " * (rows - i))
```

### Pattern ii

```
# Program ii
rows = 5
for i in range(1, rows + 1):
for j in range(rows, i, -1):
print(" ", end="")
for j in range(i, 0, -1):
print(j, end=" ")
for j in range(2, i + 1):
print(j, end=" ")
print()
```

### Pattern iii

```
# Program iii
rows = 5
for i in range(rows):
for j in range(2 * i):
print(" ", end="")
for j in range(1, rows - i + 1):
print(j, end=" ")
print()
```

### Pattern iv

```
# Program iv
rows = 5
n = rows // 2
for i in range(rows):
for j in range(rows):
if (i + j == n) or (j - i == n) or (i - j == n) or (i + j == (3 * n)):
print("*", end="")
else:
print(" ", end="")
print()
```

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.

Below is a Python program to find the grade of a student based on the percentage of marks obtained:

```
# Program to find the grade of a student based on percentage of marks
# Input: Percentage of marks obtained by the student
percentage = float(input("Enter the percentage of marks obtained: "))
# Determine the grade based on the given criteria
if percentage > 90:
grade = "A"
elif percentage >= 80:
grade = "B"
elif percentage >= 70:
grade = "C"
elif percentage >= 60:
grade = "D"
else:
grade = "E"
# Output: Display the grade
print(f"The grade of the student is: {grade}")
```

**Explanation**:

The program takes the percentage of marks obtained as input from the user.

It then compares the percentage against the given criteria using an

**if-elif-else**chain to determine the appropriate grade.Finally, it prints the grade of the student.

💡 Have more questions?

Ask Chatterbot AI