π Lecture 5 β Conditional Statements and Logical Operators
π Overview: This lecture introduces the fundamental concept of decision-making in C++ programming. It explains how to use conditional statements like
ifandif/elseto control program flow based on conditions, introduces relational and logical operators, and demonstrates their application through practical examples and flow charts.
ποΈ Topics Covered
The lecture covers conditional statements (decision making), relational operators used in conditions, flow charting as a program design technique, the if/else structure for handling true/false conditions, logical operators (&&, ||, !) for combining multiple conditions, and two complete sample programs demonstrating these concepts. It concludes with programming tips for writing clear conditional code.
π Lecture Summary
Conditional Statements (Decision Making)
Every programming language provides a structure for decision making. In C, the primary decision-making structure is the if statement. It has a simple structure: if (condition) statement;. When the condition is true, the following statement (or block of statements) is executed. The condition is an expression that explains the condition on which a decision will be made.
To execute multiple statements when a condition is true, we group them using braces { } to form a block of statements. The structure becomes:
if (condition) {
statement1;
statement2;
// ...
}
Note that semi-colons are required after every C statement, while indentation is only a matter of style to improve readability.
π Definition β Relational operators: Operators used to compare two values, such as greater than (>), less than (<), equal to (==), greater than or equal to (>=), less than or equal to (<=), and not equal to (!=).
π Table of Relational Operators:
- Greater than:
>(e.g.,x > y) - Equal to:
==(e.g.,x == y) - Less than:
<(e.g.,x < y) - Greater than or equal to:
>=(e.g.,x >= y) - Less than or equal to:
<=(e.g.,x <= y) - Not equal to:
!=(e.g.,x != y) π Example:if (age1 > age2) cout << "Student 1 is older than student 2";β Ifage1(12) is greater thanage2(10), the message is displayed.
β οΈ Important Warning: Do not confuse the assignment operator (=) with the equal to operator (==). Writing if (x = 2) is not a syntax error but creates a logical error because the assignment returns a value, not a boolean true/false. Be very careful when using equality in if statements.
Flow Charting
A flow chart is a pictorial representation of a program using labeled geometrical symbols connected by arrows. It helps in correctly designing a program by visually showing the sequence of instructions. A programmer can trace and rectify logical errors by first drawing a flow chart and then simulating it.
The main flow chart symbols used:
- Start or Stop: Oval shape
- Process: Rectangle
- Decision: Diamond shape
- Flow Line: Arrow connecting symbols
- Continuation Mark: Small circle
The flow chart for the if structure shows the condition in a diamond shape, with one path (true) leading to the action and another path (false) bypassing it.
Sample Program 1
A program comparing ages of two students (Amer and Amara) demonstrates the usage of relational operators and conditional statements.
Key programming practices introduced:
- Initialization of variables: Assign an initial value (preferably 0 for integers) when declaring variables. This is a good programming practice. Example:
int x = 0; - Prompt user for input using
coutand read usingcin.
The program declares AmerAge and AmaraAge as int variables, prompts the user to enter both ages, and then uses if statements to compare them.
if (AmerAge > AmaraAge) {
cout << "Amer is older than Amara";
}
if (AmerAge < AmaraAge) {
cout << "Amer is younger than Amara";
}
π Important concept: When a single if condition is not sufficient for all cases (e.g., when ages are equal), additional if statements are needed to handle all possible outcomes.
If/else Structure
The if/else structure extends the if statement by allowing the programmer to specify a different block of statements to execute when the condition is false.
Structure:
if (condition) {
statement(s); // executed if condition is true
}
else {
statement(s); // executed if condition is false
}
Using this structure, the age comparison program becomes:
if (AmerAge > AmaraAge) {
cout << "Amer is older than Amara";
}
else {
cout << "Amer is younger than Amara";
}
π Critical insight: The else part executes for all cases other than the one stated in the if condition. In the age comparison, the else covers both "less than" and "equal to" conditions. So the message "Amer is younger than Amara" would display even if ages are equal, which is logically incorrect. The correct message should be "Amer is younger than or is of the same age as Amara" to accurately describe both alternative cases.
π‘ Why this matters: It is very important to check all the conditions while making decisions to ensure complete and logical results. Make sure that all cases are covered and there is no situation where the program does not respond or gives incorrect output.
Logical Operators
Complex decisions often depend on more than one condition. Logical operators allow combining multiple conditions.
The three logical operators:
&&(AND): Both conditions must be true for the combined expression to be true.||(OR): At least one condition must be true for the combined expression to be true.!(NOT/negation): Reverses the meaning of a condition (unary operator).
Truth Table:
| Expression 1 | Expression 2 | Exp1 && Exp2 | Exp1 || Exp2 |
|---|---|---|---|
| True | False | false | true |
| True | True | true | true |
| False | False | false | false |
| False | True | false | true |
π Definition β Short-circuit evaluation: An expression containing && or || is evaluated only until truth or falsehood is known. For example, in (age > 18) && (height > 6), evaluation stops immediately if age > 18 is false (since the entire expression becomes false).
π Example with ! (negation):
if (!(age > 18))
cout << "The age is less than 18";
Here, the cout statement executes when the original condition (age > 18) is false, because ! reverses false to true.
Operator precedence: && has higher precedence than ||. Both operators associate from left to right.
Sample Program 2
Problem: A shopkeeper gives 10% discount on all bills, but if the bill amount is greater than 5000, the discount is 15%. Calculate the payable amount.
Solution analysis:
- Declare three
doublevariables:amount,discount, andnetPayable - Initialize all to 0
- Prompt user for bill amount
- Use
if/elsestructure to check the amount
if (amount > 5000) {
discount = amount * (15.0 / 100);
netPayable = amount - discount;
}
else {
discount = amount * (10.0 / 100);
netPayable = amount - discount;
}
π Critical implementation detail: In the statement discount = amount * (15.0 / 100);, we write 15.0 instead of 15. If we write 15, the division 15 / 100 would be evaluated as integer division, truncating the result (0.15 becomes 0), making the entire calculation zero. Writing at least one operand in decimal form (like 15.0) ensures floating-point division. Variables must also be declared as float or double for correct decimal results.
π Example execution:
- Input: 6500
- Condition: 6500 > 5000 (true)
- Discount = 6500 * (15.0/100) = 6500 * 0.15 = 975
- Net Payable = 6500 - 975 = 5525
- Output: "The discount at the rate 15% is Rupees 975" and "The payable amount is Rupees 5525"
Tips
Practical programming tips for writing clean conditional code:
- Always put the braces in an
if/elsestructure - Type the beginning and ending braces before typing inside them
- Indent both body statements of an
ifandelsestructure - Be careful while combining conditions with logical operators
- Use
if/elsestructure instead of a number of single selectionifstatements
β Key Takeaways
Conditional statements are fundamental for creating programs that make decisions. The if statement executes code only when a condition is true, while if/else handles both true and false cases, reducing the need for multiple if statements. Relational operators (>, <, ==, >=, <=, !=) are used to form conditions, and one must never confuse = (assignment) with == (equality). For complex decisions, logical operators (&&, ||, !) combine multiple conditions, with && requiring both conditions true and || requiring at least one. Always initialize variables before use, use proper data types (float/double) for decimal calculations to avoid integer division issues, and ensure all possible cases are covered in your conditions to produce logically complete programs.
π§ Quick Revision Questions
- What is the difference between the
ifstatement and theif/elsestructure, and how does theelsepart handle conditions not explicitly stated in theifcondition? - Why does writing
15 / 100in C++ produce a different result than15.0 / 100, and how can this affect your calculations? - In the expression
(age > 18) && (height > 6), ifageis 15, willheight > 6ever be evaluated? Explain why. - What is the difference between the
=operator and the==operator, and why is using the wrong one a logical error rather than a syntax error? - Given two variables
x = 5andy = 10, determine the value of(x > y) || (x == 5)and explain using the truth table.
π Lecture 6 β Repetition Structure (Loop)
π Overview: This lecture introduces the concept of repetition structures in C++ programming, specifically the
whileloop. It explains how loops allow efficient execution of repeated tasks, demonstrates practical examples like summing integers and calculating factorials, and covers important concepts including overflow conditions, infinite loops, and flow chart representation.
ποΈ Topics Covered
The lecture covers repetition structures (loops) with detailed explanation of the while loop construct, overflow conditions in integer arithmetic, sample programs for summing integers and even numbers, infinite loops and their causes, properties of while loops including zero-or-more-time execution, flow chart representation of loop structures, and factorial calculation using loops.
π Lecture Summary
Repetition Structure (Loop)
Repetition is a fundamental concept in programming, mirroring real-world patterns like days repeating or payroll procedures applied to multiple employees. Without loops, summing numbers from 1 to 1000 would require an extremely long and impractical statement. Instead, we observe that each integer can be obtained by adding 1 to the previous integer, and we can repeat this process.
The while loop is a repetition structure in C/C++. The keyword while cannot be used as a variable name. Its syntax is:
while (logical expression) {
statement1;
statement2;
...
}
The logical expression must contain a relational or logical operator. While this expression is true, the statements inside the braces execute repeatedly. When it becomes false, control moves to the next statement after the loop. It is good practice to always use braces with while, even if only one statement follows, and to indent the code inside the loop for readability.
Overflow Condition
When summing integers, we can change the loop condition to calculate sums for any upper limit. However, integers have a fixed memory allocation (typically 32 bits on most PCs). If the sum exceeds what 32 bits can store, an overflow condition occurs. In overflow, either:
- A run-time error occurs (the compiler cannot detect this)
- Only the lower 32 bits are stored, discarding the extra bits, resulting in an incorrect value
Sample Program 1 β Generic Sum Calculator
To make the program reusable without modifying source code, we introduce a variable upperLimit and prompt the user for input:
int upperLimit;
cout << "Please enter the upper limit for which you want the sum ";
cin >> upperLimit;
while (number <= upperLimit) {
sum = sum + number;
number = number + 1;
}
cout << "The sum of first " << upperLimit << " integers is " << sum;
This approach eliminates the need to recompile the program for different limits.
π‘ Why this matters: Making programs interactive with user input is a crucial step toward creating flexible, reusable software.
Sample Program 2 β Sum of Even Numbers
To calculate the sum of even numbers only, we need to identify even numbers. A number is even if it is divisible by 2, meaning its remainder when divided by 2 is zero. C provides the modulus operator % to get the remainder.
if ((number % 2) == 0) {
sum = sum + number;
}
Alternatively, without the modulus operator, we can check: if ((2 * (number / 2)) == number) because integer division truncates decimals.
π Definition β Modulus Operator (%): Returns the remainder of integer division. For example, 5 % 2 equals 1, while 4 % 2 equals 0.
Infinite Loop
An infinite loop occurs when the condition in the while statement is always true. This happens if the variable used in the condition never changes value. For example, omitting the statement number = number + 1; inside the loop will cause the loop to execute forever because number never increments.
Properties of While Loop
The while loop may execute zero or more times. If the condition is false when first evaluated, the statements inside the loop body will not execute even once. For example, if upperLimit is 0, then number <= upperLimit is false initially, and the loop body is skipped entirely.
The loop terminates only when the condition is tested and found false. Ensure the loop has an adequate exit condition by modifying the control variable within the loop body.
Flow Chart
The structured flow chart for a while loop is:
- Draw a rectangle with "while" written in it
- Draw a line to the right to a diamond (decision symbol) containing the loop condition
- From the diamond, draw a downward line (true path) to rectangles representing the repeated processes
- From the last process, draw a line going back to the while/decision connection
- From the diamond, draw a line exiting to the right (false path) representing loop exit
Flow charts should be drawn before coding to plan the program logic.
Sample Program 3 β Factorial Calculation
The factorial of a number N is defined as: N Γ (N-1) Γ (N-2) Γ ... Γ 3 Γ 2 Γ 1
The program uses a loop that multiplies decreasing values of number:
int factorial = 1;
int number = 1;
cout << "Please enter the number for factorial ";
cin >> number;
while (number > 1) {
factorial = factorial * number;
number = number - 1;
}
cout << "The factorial is " << factorial;
The loop continues while number > 1, multiplying factorial by number and then decrementing number by 1 in each iteration.
β Key Takeaways
The while loop is a fundamental repetition structure that executes zero or more times based on a condition evaluated before each iteration. To avoid infinite loops, the control variable in the condition must change within the loop body. Overflow is a critical issue when dealing with large sums in fixed-size data types. Flow charts serve as essential planning tools before writing code. The modulus operator % is useful for conditional logic within loops, such as identifying even numbers.
π§ Quick Revision Questions
- What is the syntax of a
whileloop in C++ and what does each part mean? - What causes an overflow condition when summing integers, and what are the two possible outcomes?
- How can you determine if a number is even using the modulus operator in C++?
- What is an infinite loop and what programming mistake typically causes it?
- How many times will a
whileloop execute if its condition is false when first evaluated?
π Lecture 7 β Do-While Statement and for Statement
π Overview: This lecture introduces two important looping structures in C++: the do-while loop and the for loop. It explains when to use each type of loop, provides detailed examples, and covers increment/decrement operators essential for loop control. Understanding these concepts is fundamental for writing efficient repetitive code.
ποΈ Topics Covered
The lecture covers the do-while statement with a complete character guessing game example, the for statement with table printing and sum of squares programs, increment and decrement operators including pre/post variations, and compound assignment operators for concise code writing. It also provides important programming tips for avoiding common loop errors.
π Lecture Summary
Do-While Statement
We have seen that there may be certain situations when the body of while loop does not execute even a single time. This occurs when the condition in while is false. In while loop, the condition is tested first and the statements in the body are executed only when this condition is true. If the condition is false, then the control goes directly to the statement after the closed brace of the while loop. So we can say that in while structure, the loop can execute zero or more times. There may be situations where we may need that some task must be performed at least once.
For example, a computer program has a character stored from a-z. It gives to user five chances or tries to guess the character. In this case, the task of guessing the character must be performed at least once. To ensure that a block of statements is executed at least once, C provides a do-while structure. The syntax of do-while structure is as under:
do
{
statement(s);
}
while ( condition ) ;
Here we see that the condition is tested after executing the statements of the loop body. Thus, the loop body is executed at least once and then the condition in do while statement is tested. If it is true, the execution of the loop body is repeated. In case, it proves otherwise (i.e. false), then the control goes to the statement next to the do while statement.
Broadly speaking, in while loop, the condition is tested at the beginning of the loop before the body of the loop is performed. Whereas in do-while loop, the condition is tested after the loop body is performed. Therefore, in do-while loop, the body of the loop is executed at least once.
π‘ Why this matters: The do-while loop guarantees that user input or critical operations happen at least once before checking conditions, which is essential for interactive programs like games or data validation.
Example
Let's consider the example of guessing a character. We have a character in the program to be guessed by the user. Let's call it 'z'. The program allows five tries (chances) to the user to guess the character. We declare a variable tryNum to store the number of tries. The program prompts the user to enter a character for guessing. We store this character in a variable c.
We declare the variable c of type char. The data type char is used to store a single character. We assign a character to a variable of char type by putting the character in single quotes. Thus the assignment statement to assign a value to a char variable will be as c = 'a'. Note that there should be a single character in single quotes. The statement like c = 'gh' will be a syntax error.
Here we use the do-while construct. In the do clause we prompt the user to enter a character. After getting character in variable c from user, we compare it with our character i.e 'z'. We use if/else structure for this comparison. If the character is the same as ours then we display a message to congratulate the user else we add 1 to tryNum variable. And then in while clause, we test the condition whether tryNum is less than or equal to 5 (tryNum <= 5). If this condition is true, then the body of the do clause is repeated again. We do this only when the condition (tryNum <= 5) remains true. If it is otherwise, the control goes to the first statement after the do-while loop.
If guess is matched in first or second try, then we should exit the loop. We know that the loop is terminated when the condition tryNum <= 5 becomes false, so we assign a value which is greater than 5 to tryNum after displaying the message. Now the condition in the while statement is checked. It proves false (as tryNum is greater than 5). So the control goes out of the loop.
There is an elegant way to exit the loop when the correct number is guessed. We change the condition in while statement to a compound condition. This condition will check whether the number of tries is less than or equal to 5 AND the variable c is not equal to 'z'. So we will write the while clause as while (tryNum <= 5 && c != 'z' ); Thus when a single condition in this compound condition becomes false, then the control will exit the loop. Thus we need not to assign a value greater than 5 to variable tryNum.
The code of the improved program is:
#include <iostream.h>
main()
{
int tryNum = 0;
char c;
do
{
cout << "Please enter a character between a-z for guessing : ";
cin >> c;
if (c == 'z')
{
cout << "Congratulations, Your guess is correct";
}
else
{
tryNum = tryNum + 1;
}
}
while (tryNum <= 5 && c != 'z');
}
Output:
Please enter a character between a-z for guessing : g
Please enter a character between a-z for guessing : z
Congratulations, Your guess is correct
for Statement
Let's see what we do in a loop. In a loop, we initialize variable(s) at first. Then we set a condition for the continuation/termination of the loop. To meet the condition to terminate the loop, we affect the condition in the body of the loop. If there is a variable in the condition, the value of that variable is changed within the body of the loop. If the value of the variable is not changed, then the condition of termination of the loop will not meet and loop will become an infinite loop. So there are three things in a loop structure: (i) initialization, (ii) a continuation/termination condition and (iii) changing the value of the condition variable, usually the increment of the variable value.
To implement these things, C provides a loop structure known as for loop. This is the most often used structure to perform repetition tasks for a known number of repetitions. The syntax of for loop is:
for ( initialization condition ; continuation condition ; incrementing condition )
{
statement(s);
}
We see that a for statement consists of three parts. In initialization condition, we initialize some variable while in continuation condition, we set a condition for the continuation of the loop. In third part, we increment the value of the variable for which the termination condition is set.
Let's suppose, we have a variable counter of type int. We write for loop in our program as:
for (counter = 0; counter < 10; counter = counter + 1)
{
cout << counter << endl;
}
This for loop will print on the screen 0, 1, 2 .... 9 on separate lines. In for loop, at first, we initialize the variable counter to 0. And in the termination condition, we write counter < 10. This means that the loop will continue till value of counter is less than 10. In other words, the loop will terminate when the value of counter is equal to or greater than 10. In the third part of for statement, we write counter = counter + 1 this means that we add 1 to the existing value of counter. We call it incrementing the variable.
When the control goes to for statement first time, it sets the value of variable counter to 0, tests the condition (i.e. counter < 10). If it is true, then executes the body of the loop. In this case, it displays the value of counter which is 0 for the first execution. Then it runs the incrementing statement (i.e. counter = counter + 1). Thus the value of counter becomes 1. Now, the control goes to for statement and tests the condition of continuation. If it is true, then the body of the loop is again executed which displays 1 on the screen. The increment statement is again executed and control goes to for statement. The same tasks are repeated. When the value of counter becomes 10, the condition counter < 10 becomes false. Then the loop is terminated and control goes out of for loop.
The point to be noted is that, the increment statement (third part of for statement) is executed after executing the body of the loop. Thus for structure is equivalent to a while structure, in which, we write explicit statement to change (increment/decrement) the value of the condition variable after the last statement of the body. The for loop does this itself according to the increment statement in the for structure. There may be a situation where the body of for loop, like while loop, may not be executed even a single time. This may happen if the initialization value of the variable makes the condition false. The statement in the following for loop will not be executed even a single time as during first checking, the condition becomes false:
for (counter = 5; counter < 5; counter++)
{
cout << "The value of counter is " << counter;
}
Sample Program 1
Let's take an example to explain for loop. We want to write a program that prints the table of 2 on the screen. In this program, we declare a variable counter of type int. We use this variable to multiply it by 2 with values 1 to 10. For writing the table of 2, we multiply 2 by 1, 2, 3 .. up to 10 respectively and each time display the result on screen. So we use for loop to perform the repeated multiplication.
The code of the program:
#include <iostream.h>
main()
{
int counter;
for (counter = 1; counter <= 10; counter = counter + 1)
{
cout << "2 x " << counter << " = " << 2 * counter << "\n";
}
}
In the for statement, we initialize the variable counter to 1 as we want the multiplication of 2 starting from 1. In the condition clause, we set the condition counter <= 10 as we want to repeat the loop for 10 times. And in the incrementing clause, we increment the variable counter by 1. In the body of the for loop, we write a single statement with cout. In the first iteration where the value of counter is 1, the cout statement will display 2 x 1 = 2. After the execution of cout statement, the for statement will increment the counter variable by 1. When the value of counter is 11, the condition (counter <= 10) will become false and the loop will terminate.
Output:
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
To make the program generic and reusable, we use a variable instead of a hard-coded number. We prompt the user to enter the number for which they want a table. We store this number in the variable and then use it to write a table. We also allow the user to enter the number of multipliers up to which they want a table using a variable maxMultiplier.
#include <iostream.h>
main()
{
int counter, number, maxMultiplier;
cout << "Please enter the number for which you want a table : ";
cin >> number;
cout << "Please enter the multiplier up to which you want a table : ";
cin >> maxMultiplier;
for (counter = 1; counter <= maxMultiplier; counter = counter + 1)
{
cout << number << " x " << counter << " = " << number * counter << "\n";
}
}
Output:
Please enter the number for which you want a table : 7
Please enter the multiplier up to which you want a table : 8
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
Increment/decrement Operators
We have seen that in while, do-while and for loop we write a statement to increase the value of a variable. For example, we used the statements like counter = counter + 1; which adds 1 to the variable counter. This increment statement is so common that it is used almost in every repetition structure. The C language provides a unary operator that increases the value of its operand by 1. This operator is called increment operator and sign ++ is used for this. The statement counter = counter + 1; can be replaced with the statement counter++;
The statement counter++ adds 1 to the variable counter. There is also an operator -- called decrement operator. This operator decrements the value of its operand by 1. So the statements counter = counter - 1; and j = j - 1; are equivalent to counter--; and j--; respectively.
The increment operator is further categorized as pre-increment and post-increment. Similarly, the decrement operator as pre-decrement and post-decrement.
In pre-increment, we write the sign before the operand like ++j while in post-increment, the sign ++ is used after the operand like j++. If we are using only variable increment, pre or post increment does not matter. The difference of pre and post increment matters when the variable is used in an expression where it is evaluated to assign a value to another variable. If we use pre-increment (++j), the value of j is first increased by 1. This new value is used in the expression. If we use post-increment (j++), the value of j is used in the expression first. After that it is increased by 1. Same is the case in pre and post decrement.
π Definition β Pre-increment: The operator ++ placed before the variable. Example: x = ++j; If j = 5, after this expression, x = 6 and j = 6.
π Definition β Post-increment: The operator ++ placed after the variable. Example: x = j++; If j = 5, after this expression, x = 5 and j = 6.
The operators ++ and -- are used to increment or decrement the variable by 1. There may be cases when we are incrementing or decrementing the value of a variable by a number other than 1. For example, we write counter = counter + 5; or j = j - 4;. Such assignments are very common in loops, so C provides operators to perform this task in short. These operators are compound assignment operators: +=, -=, *=, /= and %=.
The use of these operators:
| Long Form | Short Form |
|---|---|
x = x + 4; | x += 4; |
x = x - 3; | x -= 3; |
x = x * 2; | x *= 2; |
x = x / 2; | x /= 2; |
x = x % 3; | x %= 3; |
Note that there is no space between these operators. These are treated as single signs. Be careful about the operator %=. This operator assigns the remainder to the variable. These operators are alternate in shorthand for an assignment statement.
Sample Program 2
Let's write a program using for loop to find the sum of the squares of the integers from 1 to n. Where n is a positive value entered by the user (i.e. Sum = 1Β² + 2Β² + 3Β² + ......+ nΒ²)
The code of the program:
#include <iostream.h>
main()
{
int i, n, sum;
sum = 0;
cout << "Please enter a positive number for sum of squares: ";
cin >> n;
for (i = 1; i <= n; i++)
{
sum += i * i;
}
cout << "The sum of the first " << n << " squares is " << sum << endl;
}
In the program we declared three variables i, n and sum. We prompted the user to enter a positive number. We stored this number in the variable n. Then we wrote a for loop. In the initialization part, we initialized variable i with value 1 to start the counting from 1. In the condition statement we set the condition i <= n (number entered by the user) as we want to execute the loop n times. In the increment statement, we incremented the counter variable by 1. In the body of the for loop we wrote a single statement sum += i * i;. This statement takes the square of the counter variable (i) and adds it to the variable sum. This statement is equivalent to sum = sum + (i * i);. Thus in each iteration the square of the counter variable (which is increased by 1 in each iteration) is added to the sum. After completing the for loop the cout statement is executed which displays the sum of the squares of number from 1 to n.
Output when the number 5 is entered:
Please enter a positive number for sum of squares: 5
The sum of the first 5 squares is 55
Tips
Comments should be meaningful, explaining the task. Don't forget to affect the value of loop variable in while and do-while loops. Make sure that the loop is not an infinite loop. Don't affect the value of loop variable in the body of for loop, the for loop does this by itself in the for statement. Use pre and post increment/decrement operators cautiously in expressions.
β Key Takeaways
The do-while loop guarantees at least one execution of the loop body because the condition is tested after the body executes, making it ideal for programs that require user input before checking. The for loop consolidates initialization, condition, and increment into a single line, making it the most commonly used loop for known repetition counts. Pre-increment (++j) increments the variable before using its value in an expression, while post-increment (j++) uses the current value first then increments. Compound assignment operators like += and *= provide concise shorthand for updating variables in loops. The lecture emphasizes writing generic code using variables instead of hard-coded constants to improve reusability and maintainability.
π§ Quick Revision Questions
- What is the key difference between a while loop and a do-while loop in terms of when the condition is tested?
- What are the three parts of a for loop statement, and in what order are they executed during each iteration?
- If
j = 5, what will be the values ofxandjafter executingx = ++j;versusx = j++;? - How does using a compound condition (
tryNum <= 5 && c != 'z') provide a more elegant way to exit the guessing game loop compared to manually setting tryNum to 6? - Write the equivalent short form using compound assignment operators for each:
counter = counter + 5;,total = total * 2;, andremainder = remainder % 3;
π Lecture 8 β Switch Statement
π Overview: This lecture introduces the switch statement as an efficient alternative to multiple if/else statements for multi-way decision making. It covers the break and continue statements, structured programming guidelines, and rules for flow charting, emphasizing the importance of single-entry-single-exit constructs for creating maintainable code.
ποΈ Topics Covered
The lecture covers the switch statement syntax and behavior, the break statement for controlling flow in switches and loops, the continue statement for skipping iterations, the goto statement and why it should be avoided, guidelines for structured programming, rules for structured programming/flow charting, and a sample program demonstrating salary deduction calculations using switch.
π Lecture Summary
Switch Statement
When a program must handle multiple conditions and execute different actions for each, using many separate if statements is computationally expensive because the processor must evaluate each condition. For example, in a payroll system or when converting student grades to descriptions (A=Excellent, B=Very Good, etc.), a more efficient approach is needed. The C language provides the switch structure, a multiple-selection construct designed for multi-way decisions.
π Definition β switch statement: A control structure that transfers control to one of several statement lists based on the value of an integer expression. π Syntax:
switch ( variable/expression )
{
case constant1 : statementList1 ;
case constant2 : statementList2 ;
...
case constantN : statementListN ;
default : statementList ;
}
β The switch variable must be an integer type (including char), and each case constant must be an integer constant. Compound conditions using && or || are not allowed.
The switch statement evaluates the expression, then looks for a matching case constant. When found, execution begins at that case and falls through all subsequent cases to the end of the switch block. This fall-through behavior means that if a user enters grade 'B', not only will "Very Good" print, but also "Good", "Poor", and "Fail" β unless controlled. To handle both uppercase and lowercase letters in grade input, cases can be stacked:
case 'A':
case 'a':
statements;
π‘ Why this matters: The fall-through behavior is a unique feature of switch; without proper control, it can cause serious logical errors.
Break Statement
The break statement interrupts the flow of control, forcing an immediate exit from the enclosing switch or loop. In a switch, break is placed after the statements of a case to prevent fall-through. When a matching case executes and its break is encountered, control jumps out of the entire switch statement.
π Definition β break statement: A statement that terminates the nearest enclosing loop or switch statement.
π Example: In a guessing game, if the user guesses the character 'z', we can use break to exit the loop:
if ( c == 'z' )
{
cout << "Great, Your guess is correct";
break;
}
continue Statement
The continue statement forces the immediate next iteration of a loop, skipping any remaining statements in the current iteration. It's useful when early parts of a loop body must execute every time, but later parts execute only conditionally.
π Definition β continue statement: A statement that skips the rest of the current loop iteration and proceeds to the next iteration.
β οΈ Important distinction: In while and do-while loops, the loop variable must be incremented/decremented before the continue statement to avoid infinite loops. In for loops, the increment step is built into the loop structure, so continue automatically triggers it before checking the condition.
goto Statement
The goto statement is an unconditional branch that can jump control to any labeled point in a program. While historically used in languages like COBOL and FORTRAN, goto leads to "spaghetti code" β programs with tangled, unpredictable execution paths that are nearly impossible to debug or modify.
π Definition β goto statement: An unconditional branch that transfers control to a labeled statement elsewhere in the program.
π‘ Why this matters: The lecture explicitly states, "Though goto is there in C language but we will not use it in our programs." Structured programming rejects goto in favor of sequences, decisions, and loops.
Guide Lines
Programs should minimize the use of break and continue in loops (though break is necessary in switch). These statements create multiple exit points, violating the single entry, single exit principle. Each module or construct should have exactly one entry point and one exit point, making execution flow predictable and code easier to understand, debug, and modify.
π Definition β single entry, single exit: A design principle where each program construct has exactly one way to enter and one way to leave, ensuring predictable control flow.
Rules for Structured Programming/Flow Charting
- Start simple: Draw a start symbol, a rectangle (process), and a stop symbol.
- Replace rectangles: Any rectangle can be replaced by two rectangles (splitting the problem).
- Replace with constructs: Any rectangle can be replaced by a structured construct (decision, loop, or multi-way decision).
- Repeat: Rules 2 and 3 can be applied repeatedly to decompose complex problems.
These rules ensure a top-down, modular approach where each part is manageable and the flow chart corresponds one-to-one with the code.
Sample Program
Problem: A company deducts fund from employee salaries as follows:
- Salary < 10,000: No deduction
- 10,000 β€ Salary < 20,000: Deduct Rs. 1,000
- Salary β₯ 20,000: Deduct 7% of salary
Solution: Use switch with salary / 10000 as the control expression. Integer division yields 0 (salary < 10,000), 1 (10,000β19,999), or 2+ (β₯20,000).
int salary;
float deduction, netPayable;
cout << "Please enter the salary : ";
cin >> salary;
switch ( salary / 10000 )
{
case 0 :
deduction = 0;
netPayable = salary;
break;
case 1 :
deduction = 1000;
netPayable = salary - deduction;
break;
default :
deduction = salary * 7 / 100;
netPayable = salary - deduction;
}
π Sample Output:
Please enter the salary : 15000
Net Payable (salary β deduction) = 15000 β 1000 = 14000
β Key Takeaways
The switch statement is a powerful, efficient alternative to multiple if/else chains for multi-way decisions involving integer values, but its fall-through behavior requires careful use of break statements to prevent logical errors. The break and continue statements can disrupt control flow in loops and should be minimized to maintain single-entry-single-exit design. The goto statement should never be used due to its tendency to create unmanageable spaghetti code. Structured programming relies on decomposing problems using sequences, decisions, and loops, with flow charts that follow four simple replacement rules to ensure modular, traceable code. Missing a break in a switch or forgetting to increment a loop variable before continue in while/do-while loops are common pitfalls that cause hard-to-find bugs.
π§ Quick Revision Questions
- What is the main advantage of using a switch statement instead of multiple if statements for multi-way decisions?
- What happens if you forget to include a break statement after a case in a switch?
- How does the continue statement behave differently in a while loop versus a for loop?
- Why should the goto statement be avoided in structured programming?
- In the sample salary deduction program, why is the switch expression
salary / 10000used instead ofsalaryitself?