NCERTCh 6Free

Flow of Control

🎓 Class 11📖 Computer Science📖 10 notes🧠 15 Q&A⏱️ ~15 min

Flow of ControlStudy Notes

NCERT-aligned · 10 notes · 3 shown free

6.1 INTRODUCTION

Explanation

6.1 INTRODUCTION

The concept of flow of control in programming refers to the order in which individual statements, instructions, or function calls are executed or evaluated. In the initial chapters, students learn about the sequence structure where statements are executed one after another in the order they appear. This is analogous to a bus carrying children to school following a fixed route, moving from one milestone to the next without deviation. The bus driver has no choice but to follow the road to reach the destination. Similarly, in sequence execution, the program runs statements from the beginning to the end without any branching or repetition. Flow of control is fundamental to programming as it determines how a program behaves and responds to different inputs or conditions. To implement complex logic, programming languages provide control structures that alter the flow of execution. Python supports two primary control structures: selection and repetition. Selection allows the program to choose between different paths based on conditions, while repetition enables executing a set of statements multiple times. Proper indentation is crucial in Python as it defines the blocks of code and controls the flow of execution. Unlike many other languages that use curly braces, Python uses indentation as a syntactical element, making code more readable and less prone to errors related to block definition. This chapter introduces these concepts with examples and flowcharts, helping students understand how to control the execution flow in Python programs effectively.

  • Flow of control defines the order of execution of statements in a program.
  • Sequence is the simplest flow where statements execute one after another.
  • Control structures like selection and repetition alter the flow based on conditions or loops.
  • Python uses indentation to define blocks of code, which affects flow of control.
  • Understanding flow of control is essential for writing complex and efficient programs.
  • This chapter covers selection, repetition, break and continue statements, and nested loops.
  • 📌 Flow of Control: The order in which individual statements are executed in a program.
  • 📌 Sequence: Execution of statements one after another in the order they appear.
  • 📌 Control Structures: Constructs that alter the flow of execution in a program.

6.2 SELECTION

Explanation

6.2 SELECTION

Selection, also known as decision making, allows a program to choose between different paths based on conditions. This is essential when a program needs to perform different actions depending on the input or state. The if statement is the fundamental selection construct in Python. The section begins with a real-life example of choosing a pen priced at ₹10 among many options, illustrating the need to select based on conditions. Similarly, digital maps offer multiple routes, and the user selects one based on preferences like shortest distance or least traffic. The syntax of the if statement in Python is: if condition: statement(s) If the condition evaluates to True, the indented statements under the if block are executed. Otherwise, they are skipped. The if..else statement provides two alternative paths: if condition: statement(s) else: statement(s) This allows the program to execute one block if the condition is true and another if it is false. For multiple conditions, Python provides the if..elif..else construct, allowing chaining of conditions. Examples include checking if a number is positive, negative, or zero, or displaying messages based on traffic signal colors. A practical example is modifying the difference program to always output a positive difference by selecting which number to subtract from which. The section also introduces nested if statements, where an if or else block contains another if statement, providing finer control. Proper indentation is critical to define the blocks belonging to each condition. The section concludes with a program to create a simple calculator performing addition, subtraction (positive difference), multiplication, and division with error handling for division by zero and invalid operators.

  • Selection allows programs to choose different execution paths based on conditions.
  • The if statement executes a block only if its condition is true.
  • The if..else statement provides two alternative blocks depending on the condition.
  • The if..elif..else construct allows multiple conditions to be checked sequentially.
  • Nested if statements enable conditions within conditions for complex decision making.
  • Indentation defines the scope of statements under each condition in Python.
  • 📌 Selection: Decision making in programming to choose between alternatives.
  • 📌 if statement: Executes code block if a condition is true.
  • 📌 if..else statement: Executes one of two blocks based on a condition.

6.3 INDENTATION

Explanation

6.3 INDENTATION

Indentation in Python is a fundamental syntactical element that defines blocks of code. Unlike many other programming languages that use curly braces ({ }) to group statements, Python uses leading whitespace (spaces or tabs) at the beginning of a lin

Practice QuestionsFlow of Control

Includes NCERT exercise questions with answers

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

Answer:

The 'else' construct in an if statement is used to specify a block of code that will execute if the condition(s) in the if and elif statements are false. It acts as a default case. The 'elif' (else if) construct allows checking multiple conditions sequentially. If the first if condition is false, the program checks the elif condition(s) one by one. If any elif condition is true, its block executes, and the rest are skipped. Else is used only once at the end, while multiple elifs can be used between if and else.

Explanation:

In an if-elif-else ladder, the program evaluates conditions from top to bottom. 'elif' allows multiple conditions to be checked in sequence, whereas 'else' handles all cases not covered by if or elif. For example: if condition1: # block1 elif condition2: # block2 else: # block3 If condition1 is false and condition2 is true, block2 runs. If both are false, block3 runs.

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

Answer:

The range() function is used to generate a sequence of numbers. It is commonly used in for loops to iterate over a sequence of numbers. The function can take one, two, or three arguments: start, stop, and step. It generates numbers from start (inclusive) to stop (exclusive), incremented by step. Example: for i in range(1, 5): print(i) This will print numbers 1, 2, 3, 4.

Explanation:

range() helps in creating a list of numbers without manually writing them. It is efficient and widely used in loops. The default start is 0, and default step is 1 if not provided. Example with all parameters: range(2, 10, 2) generates 2, 4, 6, 8.

EasyNCERT
Q3.3. Differentiate between break and continue statements using examples.

Answer:

Break and continue are control statements used inside loops. - break: Terminates the loop immediately and transfers control to the statement following the loop. - continue: Skips the current iteration and moves to the next iteration of the loop. Example of break: for i in range(5): if i == 3: break print(i) # Output: 0 1 2 Example of continue: for i in range(5): if i == 3: continue print(i) # Output: 0 1 2 4

Explanation:

In the break example, when i becomes 3, the loop stops entirely. In the continue example, when i is 3, the print statement is skipped for that iteration, but the loop continues with i=4.

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

Answer:

An infinite loop is a loop that never terminates because its condition always remains true. It keeps executing indefinitely unless externally interrupted. Example: while True: print("This loop runs forever")

Explanation:

In the example, the condition 'True' is always true, so the loop never ends. Infinite loops are generally undesirable unless intentionally used for specific purposes like servers waiting for requests.

EasyNCERT
Q5.5. Find the output of the following program segments: (i) a = 110 while a > 100: print(a) a -= 2 (ii) for i in range(20,30,2): print(i) (iii) country = 'INDIA' for i in country: print (i) (iv) i = 0; sum = 0 while i < 9: if i % 4 == 0: sum = sum + i i = i + 2 print (sum) (v) for x in range(1,4): for y in range(2,5): if x * y > 10: break print (x * y) (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!")

Answer:

(i) Code: a = 110 while a > 100: print(a) a -= 2 Output: 110 108 106 104 102 Explanation: Starts at 110, prints and decrements by 2 until a <= 100. (ii) Code: for i in range(20,30,2): print(i) Output: 20 22 24 26 28 Explanation: range(20,30,2) generates numbers from 20 to 28 stepping by 2. (iii) Code: country = 'INDIA' for i in country: print(i) Output: I N D I A Explanation: Iterates over each character in the string and prints it. (iv) Code: i = 0 sum = 0 while i < 9: if i % 4 == 0: sum = sum + i i = i + 2 print(sum) Output: 8 Explanation: Values of i: 0,2,4,6,8 (since i increments by 2) Only i values divisible by 4 (0,4,8) are added to sum. Sum = 0 + 4 + 8 = 12 but note i increments inside loop, careful with indentation. But as per code, i increments by 2 each time, sum adds i if i%4==0. So i=0 (sum=0), i=2 (no add), i=4 (sum=4), i=6 (no add), i=8 (sum=12) Print sum = 12 (v) Code: 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 8 Explanation: For each x, y iterates from 2 to 4. If product > 10, inner loop breaks. Prints product otherwise. (vi) Code: 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 Good bye! Current variable value: 5 Good bye! Current variable value: 4 Good bye! Current variable value: 3 Explanation: - Starts with var=7 - Prints var, decrements var - If var==6, decrements var again and continues (skips print "Good bye!") - If var==3, breaks loop - Otherwise prints "Good bye!" Stepwise: var=7: print var=7, var=6, var==6 true, var=5, continue (skip "Good bye!") var=5: print var=5, var=4, var!=3 or 6, print "Good bye!" var=4: print var=4, var=3, var!=6, print "Good bye!" var=3: print var=3, var=2, var==3 triggers break, loop ends.

Explanation:

Detailed explanation is provided above for each sub-part showing how the loops and conditions work to produce the output.

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

Answer:

To find the sum of digits of an integer number input by the user, follow these steps: 1. Take the integer input from the user. 2. Initialize a variable sum to 0. 3. Use a loop to extract each digit of the number: - Find the last digit by taking the remainder when divided by 10 (digit = number % 10). - Add this digit to sum. - Remove the last digit by integer division by 10 (number = number // 10). 4. Repeat until the number becomes 0. 5. Print the sum. Example Python code: ```python number = int(input("Enter an integer number: ")) sum_digits = 0 while number > 0: digit = number % 10 sum_digits += digit number = number // 10 print("Sum of digits is:", sum_digits) ``` This program correctly computes the sum of digits of the input number.

Explanation:

The program extracts each digit from the number by repeatedly taking the remainder when divided by 10, adds it to a running total, and then removes the last digit by integer division. This process continues until all digits are processed, resulting in the sum of digits.

EasyNCERT
Q7.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]

Answer:

To check whether a number is a palindrome: 1. Take the input number from the user. 2. Store the original number in a variable. 3. Reverse the number by extracting digits and constructing the reversed number. 4. Compare the reversed number with the original number. 5. If both are equal, the number is a palindrome; otherwise, it is not. Example Python code: ```python number = int(input("Enter a number: ")) original_number = number reversed_number = 0 while number > 0: digit = number % 10 reversed_number = reversed_number * 10 + digit number = number // 10 if original_number == reversed_number: print("The number is a palindrome.") else: print("The number is not a palindrome.") ``` This program correctly identifies whether the input number is a palindrome.

Explanation:

The program reverses the number by extracting digits and building the reversed number. Then it compares the reversed number with the original number to determine if it is a palindrome.

EasyNCERT
Q8.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) * * * * * * * *

Answer:

To print the given patterns, write separate code blocks for each pattern: (i) Pattern: ``` * *** *** *** *** ``` This can be printed by: - Print '*' once in first line. - Then print '***' four times in next four lines. Example code: ```python print("*") for _ in range(4): print("***") ``` (ii) Pattern: ``` 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 ``` Explanation: - For each line i from 1 to 5: - Print descending numbers from i down to 1. - Then print ascending numbers from 2 up to i. Example code: ```python for i in range(1, 6): for j in range(i, 0, -1): print(j, end=' ') for j in range(2, i+1): print(j, end=' ') print() ``` (iii) Pattern: ``` 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 ``` Explanation: - For each line i from 5 down to 1: - Print numbers from 1 up to i. Example code: ```python for i in range(5, 0, -1): for j in range(1, i+1): print(j, end=' ') print() ``` (iv) Pattern: ``` * * * * * * * ``` Explanation: - Print '*' seven times, each on a new line. Example code: ```python for _ in range(7): print("*") ``` These programs will print the required patterns as specified.

Explanation:

Each pattern is printed by nested loops controlling the number and order of elements printed per line. The logic for ascending and descending sequences is implemented using appropriate ranges in loops.

MediumNCERT