UNIT – 3
THESE NOTES ARE FOR EXAM PREPARATION
1. Problems on Numbers
Working with numbers is a fundamental aspect of computer programming, serving as an excellent
training ground for developing logical thinking, problem decomposition, and algorithmic skills. These
classic problems involve manipulating the digits and properties of integers to determine specific
characteristics, such as whether a number is a palindrome, prime, or perfect. Solving these
challenges requires a solid understanding of basic arithmetic operations, conditional logic, and, most
importantly, the skillful use of loops to perform repetitive calculations. Mastering these number-
based problems builds a strong foundation for tackling more complex algorithmic tasks.
• Extracting Digits of a Number:
• Right to Left: This is the most common method. In a loop, use the modulo operator
(% 10) to get the last digit, and then use integer division (/ 10) to remove the last
digit. Repeat until the number becomes zero.
• Left to Right: This is more complex. One approach is to first find a power of 10 that is
just larger than the number (e.g., for 123, find 100). Then, you can get the first digit
by dividing (123 / 100 = 1) and use the modulo operator to get the remainder (123 %
100 = 23) for the next iteration.
• Palindrome Number:
• A palindrome is a number that reads the same forwards and backwards (e.g., 121,
353).
• The standard algorithm involves reversing the number (by extracting digits from right
to left and building a new number) and then comparing the reversed number with
the original. If they are equal, the number is a palindrome.
• Prime Number:
• A prime number is a natural number greater than 1 that has no positive divisors
other than 1 and itself (e.g., 2, 3, 5, 7, 11).
• To check if a number n is prime, you can iterate from 2 up to the square root of n.
If n is divisible by any number in this range, it is not prime. If the loop completes
without finding any divisors, the number is prime.
• Prime Factors:
• These are the prime numbers that, when multiplied together, produce the original
number (e.g., the prime factors of 12 are 2, 2, and 3).
• The algorithm involves repeatedly dividing the number by the smallest possible
prime (starting with 2). For example, for 12, divide by 2 to get 6; divide 6 by 2 to get
3; 3 is prime, so you stop.
• Amicable Numbers:
• A pair of numbers is amicable if the sum of the proper divisors of one number is
equal to the other number, and vice versa. (A proper divisor is any divisor of a
number, excluding the number itself).
• Example: The proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110, which
sum to 284. The proper divisors of 284 sum to 220. Thus, (220, 284) is an amicable
pair.
• Perfect Number:
• A positive integer that is equal to the sum of its proper positive divisors (e.g., 6,
because its proper divisors 1, 2, and 3 sum to 6).
• The algorithm requires finding all proper divisors of a number and summing them
up, then comparing the sum to the original number.
• Armstrong Number:
• An n-digit number that is equal to the sum of its digits raised to the power of n (e.g.,
153 is an Armstrong number because it has 3 digits, and 1³ + 5³ + 3³ = 1 + 125 + 27 =
153).
• The algorithm first requires counting the number of digits (n). Then, in a separate
loop, it extracts each digit and adds its nth power to a running total.
• Factorial:
• The factorial of a non-negative integer n, denoted by n!, is the product of all positive
integers less than or equal to n (e.g., 5! = 5 × 4 × 3 × 2 × 1 = 120). By definition, 0! =
1.
• This is typically calculated using a loop that iterates from 1 to n, multiplying each
number into an accumulator variable.
• Converting Number from One Base to Another:
• Any Base to Decimal (Base 10): To convert a number from a base b to decimal, you
multiply each digit by b raised to the power of its position (starting from 0 on the
right) and sum the results.
• Decimal to Any Base: To convert a decimal number to a base b, you repeatedly take
the modulo (% b) of the number to get the next digit, and then perform integer
division (/ b) to update the number. The digits are generated in reverse order.
2. Statistics on a Sequence of Numbers
A very common task in programming is to process a sequence of numbers to compute basic statistics
like the maximum, minimum, sum, and average. When the length of the sequence is unknown
beforehand, a sentinel-controlled loop is an ideal solution. This approach reads numbers one by one
until a special "sentinel" value (e.g., -1) is entered, signaling the end of the input. The key to
efficiency is to calculate these statistics "on the fly" using only a few variables, without needing to
store the entire sequence in an array, which saves a significant amount of memory.
• Important Points:
• Sentinel Controlled Repetition: The loop continues as long as the input value is not
equal to the sentinel value. This is a type of indefinite repetition.
• Using a few Variables: The core idea is to maintain running totals and comparisons.
You only need variables for the current input, a counter, a sum, and variables to hold
the current maximum and minimum.
• Calculating Sum and Average: Initialize sum = 0 and count = 0 before the loop. Inside
the loop, for each valid input, update sum += input and count++. The average is sum
/ count, calculated after the loop terminates.
• Finding Maximum and Minimum: Initialize max and min to the first input value. For
every subsequent input, compare it to the current max and min, updating them if
the new number is larger or smaller, respectively.
3. C Language: Advanced Control Flow
Beyond basic if statements and for/while loops, the C language provides more sophisticated control
structures to handle complex decision-making and give programmers finer control over program
flow. The else-if ladder and the switch-case statement allow for elegant multi-way branching,
providing cleaner alternatives to deeply nested ifs. Additionally, statements
like break and continue offer the ability to alter the standard execution path within loops, allowing a
programmer to exit a loop early or skip to the next iteration. These tools are essential for writing
clear, efficient, and well-structured code.
• else-if Ladder:
• This is a chain of if-else statements used to test a series of conditions in sequence.
• As soon as a condition evaluates to true, its corresponding block of code is executed,
and the rest of the ladder is skipped.
• An optional final else block at the end acts as a default case if none of the preceding
conditions are met.
• It is used for checking conditions based on ranges or different, unrelated expressions.
• switch-case Statement:
• A multi-way decision statement that provides an efficient alternative to a long else-
if ladder, specifically when checking a single integer or character variable against a
list of constant values.
• It evaluates an expression and then "jumps" to the case label that matches the
expression's value.
• The break statement is crucial; without it, execution will "fall through" to the next
case.
• A default case can be included to handle any values not explicitly covered by
a case label.
• Increment/Decrement Operators (++, --):
• These are unary operators that add 1 to or subtract 1 from their operand.
• Pre-increment/decrement (++x, --x): The variable is changed first, and then its new
value is used in the expression.
• Post-increment/decrement (x++, x--): The variable's current value is used in the
expression, and then the variable is changed.
• They are commonly used as concise shortcuts in loops and other expressions.
• break and continue Statements:
• break: When encountered inside a loop (for, while, do-while) or a switch statement,
it immediately terminates the statement. Program control transfers to the statement
immediately following the terminated loop or switch. It is used to exit a loop early
based on some condition.
• continue: When encountered inside a loop, it skips the remaining statements in the
current iteration and immediately proceeds to the next iteration. For for loops, it
moves to the update step; for while and do-while loops, it moves to the condition
check.