This collection of 30 C programming loops exercises is designed to sharpen your skills across all difficulty levels, from Beginner to Advanced.
Each exercise includes a Practice Problem, Hint, Solution code, and detailed Explanation, ensuring you don’t just copy code, but genuinely understand how and why it works.
What You’ll Practice
These exercises provide practice problems and challenges to master the following core topics:
- Loops: Basic and advanced use of for, while, and do-while, including Nested Loops for patterns and matrices.
- Control Flow: Conditional Logic (if/else), Multi-way Branching (switch), and loop control (break/continue).
- Core Concepts: Problems involving Factorials, Fibonacci Sequence, GCD, LCM, Prime numbers, Palindromes, and more.
Use Online C Compiler to solve exercises.
+ Table Of Contents (28 Exercises)
Table of contents
- Exercise 1: Positive, Negative, or Zero
- Exercise 2: Simple Calculator
- Exercise 3: Print Numbers 1 to 10
- Exercise 4: Print odd numbers from 1 to 20
- Exercise 5: Reverse Count
- Exercise 6: Sum of First N Integers
- Exercise 7: Sum Of All Even Numbers
- Exercise 8: Multiplication Table
- Exercise 9: Vowel or Consonant
- Exercise 10: Factorial
- Exercise 11: Do-While Menu
- Exercise 12: Count Digits
- Exercise 13: Reverse a Number
- Exercise 14: Check for Palindrome
- Exercise 15: Skip Even Numbers
- Exercise 16: Power of a Number
- Exercise 17: Solid Rectangle Pattern
- Exercise 18: Right-Angled Triangle (Numbers)
- Exercise 19: Inverted Right-Angled Triangle (Asterisks)
- Exercise 20: Print Multiplication Tables
- Exercise 21: Smallest and Largest
- Exercise 22: Check for Prime
- Exercise 23: Print Primes in Range
- Exercise 24: GCD (Greatest Common Divisor)
- Exercise 25: Armstrong Number
- Exercise 26: Pyramid Pattern
- Exercise 27: Generate Fibonacci
- Exercise 28: Print All Factors of a Number
Exercise 1: Positive, Negative, or Zero
Practice Problem: Write a C program that takes a number as input and uses an if-else if-else chain to classify and print whether the number is Positive, Negative, or Zero.
+ Hint
You will need two distinct comparison checks: one for being greater than 0 and another for being less than 0. If both fail, the number must be 0.
+ Show Solution
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num > 0) {
printf("%d is a Positive number.\n", num);
} else if (num < 0) {
printf("%d is a Negative number.\n", num);
} else {
printf("The number is Zero.\n");
}
return 0;
}Code language: C++ (cpp)
Explanation:
This uses a multi-way decision structure.
- The first
ifchecks the most common case:num > 0. - If the first check is false, the
else ifchecks the second case:num < 0. This is more efficient than checking all possibilities separately. - If both the
ifand theelse ifconditions are false, the finalelseblock is executed, correctly identifying the number as zero.
Exercise 2: Simple Calculator
Practice Problem: Write a C program that Implement a basic calculator that takes two floating-point numbers and a character operator (+, -, *, /) as input. Use a switch statement to perform the corresponding arithmetic operation and display the result.
Expected Output:
Enter operator (+, -, *, /): +
Enter two operands: 10 20
10.00 + 20.00 = 30.00
+ Hint
The switch statement should evaluate the character variable holding the operator. Remember to include a default case for handling invalid operators and a check to prevent division by zero.
+ Show Solution
#include <stdio.h>
int main() {
char op;
double n1, n2;
printf("Enter operator (+, -, *, /): \n");
scanf(" %c", &op); // Note the space before %c to handle whitespace
printf("Enter two operands: \n");
scanf("%lf %lf", &n1, &n2);
switch (op) {
case '+':
printf("%.2lf + %.2lf = %.2lf\n", n1, n2, n1 + n2);
break;
case '-':
printf("%.2lf - %.2lf = %.2lf\n", n1, n2, n1 - n2);
break;
case '*':
printf("%.2lf * %.2lf = %.2lf\n", n1, n2, n1 * n2);
break;
case '/':
if (n2 != 0) {
printf("%.2lf / %.2lf = %.2lf\n", n1, n2, n1 / n2);
} else {
printf("Error: Division by zero is not allowed.\n");
}
break;
default:
printf("Error: Invalid operator.\n");
}
return 0;
}Code language: C++ (cpp)
Explanation:
The switch statement is ideal for selecting one of many code blocks to execute.
- The expression being evaluated is the operator variable
op. - Each
caselabel ('+','-', etc.) corresponds to a possible value ofop. - The
breakkeyword is crucial; it terminates theswitchstatement after a case is handled, preventing fall-through into the next case. - The
/case includes anif-elsestatement to prevent the program from crashing on division by zero. - The
defaultcase catches any operator that wasn’t matched by the specific cases.
Exercise 3: Print Numbers 1 to 10
Practice Problem: Write a C program that uses a for-loop to print all integers from 1 up to and including 10, each on a new line.
Expected Output:
1
2
3
4
...
10
+ Hint
A for loop has three parts: Initialization, Condition, and Update. Set the counter to start at 1, loop as long as the counter is less than or equal to 10, and increment the counter by 1 in each step.
+ Show Solution
#include <stdio.h>
int main() {
int i;
// i=1 (Initialization); i<=10 (Condition); i++ (Update/Iteration)
for (i = 1; i <= 10; i++) {
printf("%d\n", i);
}
return 0;
}Code language: C++ (cpp)
Explanation:
The for loop is the best choice when the number of iterations is known beforehand.
- Initialization (
i = 1): The counteristarts at 1. This happens once. - Condition (
i <= 10): The loop continues as long asiis less than or equal to 10. - Body:
printf("%d\n", i);prints the current value ofi. - Update (
i++): After the body executes,iis incremented by 1. The process repeats from step 2.
Exercise 4: Print odd numbers from 1 to 20
Practice Problem: Write a C program to print odd numbers between 1 and 20 using a do...while loop.
Expected Output:
1 3 5 7 9 11 13 15 17 19
+ Hint
A do...while loop guarantees at least one execution. Start from 1 and increase the number by 2 on each iteration to directly reach the next odd number.
+ Show Solution
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d ", i);
i += 2;
} while (i <= 100);
return 0;
}Code language: C++ (cpp)
Explanation:
Unlike for and while, this do while loop runs the body first before checking the condition. Here, i begins at 1, and after each print, it is incremented by 2 to move to the next odd number. The loop continues until i becomes greater than 100.
Exercise 5: Reverse Count
Practice Problem: Write a C program that uses a while loop to print numbers starting from 10 down to 1.
Expected Output:
10
9
8
7
...
1
+ Hint
Start a counter variable at 10. The while loop’s condition should check if the counter is greater than or equal to 1. Inside the loop, don’t forget to decrement the counter.
+ Show Solution
#include <stdio.h>
int main() {
int count = 10;
while (count >= 1) {
printf("%d\n", count);
count--; // Decrement the counter
}
return 0;
}Code language: C++ (cpp)
Explanation:
The while loop is suitable when you need a loop to continue based on a condition, and the number of repetitions isn’t fixed or is harder to determine initially.
- The variable
countis initialized to 10. - The loop checks the condition:
count >= 1. - If true, the number is printed, and
countis decremented (count--). - The loop repeats until
countbecomes 0, making the condition false and terminating the loop
Exercise 6: Sum of First N Integers
Practice Problem: Write a C program to calculate the sum of all natural numbers from 1 to N using a for loop.
Given:
int N = 5;Code language: C++ (cpp)
Expected Output:
The sum of numbers from 1 to 5 is: 15
+ Hint
You’ll need an sum variable, initialized to 0, to hold the running total. In each iteration of the loop, add the current iteration number to the sum variable.
+ Show Solution
#include <stdio.h>
int main() {
int N = 5, i;
long long sum = 0; // Use long long for potentially large sums
for (i = 1; i <= N; i++) {
sum += i; // Equivalent to: sum = sum + i;
}
printf("The sum of numbers from 1 to %d is: %lld\n", N, sum);
return 0;
}Code language: C++ (cpp)
Explanation:
- A
long longtype is used forsumto ensure it can hold the result for large values of N without integer overflow. - The
forloop iterates from i=1 up to i=N. - In the loop body,
sum += i;updates the sum by adding the current value ofito the running total. When the loop finishes,sumholds the final result.
Exercise 7: Sum Of All Even Numbers
Practice Problem: Write a C program to calculate the sum of all even numbers from 1 to 20.
Expected Output:
Sum of even numbers = 110
+ Hint
- You’ll need an sum variable, initialized to 0, to hold the running total.
- In each iteration of the loop, add the current even number to the sum variable.
- Note: Even numbers are multiples of 2. Either check each number with
(i % 2 == 0)or incrementiby 2 directly.
+ Show Solution
#include <stdio.h>
int main() {
int sum = 0;
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) {
sum += i;
}
}
printf("Sum of even numbers = %d", sum);
return 0;
}Code language: C++ (cpp)
Explanation:
The loop runs from 1 to 20. Each time, it checks if i is even. If true, it adds the number to sum. At the end, the total is printed, which will be 110.
Exercise 8: Multiplication Table
Practice Problem: Write a C program to print the multiplication table of a given integer N from 1 × N up to 10 × N using loop.
Given:
int num = 2;Code language: C++ (cpp)
Expected Output:
--- Multiplication Table for 2 ---
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
...
2 x 10 = 20
+ Hint
Use a for loop that iterates 10 times. Inside the loop, the output should be formatted as: Number x Multiplier = Result.
+ Show Solution
#include <stdio.h>
int main() {
int num = 2, i;
printf("--- Multiplication Table for %d ---\n", num);
for (i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", num, i, num * i);
}
return 0;
}Code language: C++ (cpp)
Explanation:
A for loop is used to handle the 10 iterations needed for the standard multiplication table.
- The loop counter
iacts as the multiplier, going from 1 to 10. - Inside the loop, the
printfstatement calculates the product (num * i) and neatly formats the output for the user, clearly showing the factors and the result.
Exercise 9: Vowel or Consonant
Practice Problem: Write a C program to read a single alphabet character from the user and determine if it is a vowel (a, e, i, o, u, or their uppercase counterparts) or a consonant using a switch statement.
Expected Output:
Enter an alphabet character: A
A is a Vowel.
+ Hint
The switch statement should check the input character. List all 10 possible vowel characters as separate case labels. Use the default case to handle all other characters as consonants.
+ Show Solution
#include <stdio.h>
int main() {
char ch;
printf("Enter an alphabet character: \n");
// Using %c to read a single character
scanf(" %c", &ch);
switch (ch) {
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
printf("%c is a Vowel.\n", ch);
break;
default:
printf("%c is a Consonant.\n", ch);
}
return 0;
}Code language: C++ (cpp)
Explanation:
This illustrates switch fall-through.
- The cases for both lowercase and uppercase vowels are stacked without a
breakin between them. For example, if the input is'a', the code executes the block under'U'(which is the first block with abreak). - This structure allows multiple case labels to execute the same block of code, efficiently grouping all 10 vowels.
- The
defaultcase handles any other character, which we assume here to be a consonant (though you could add logic to check it’s actually a letter first).
Exercise 10: Factorial
Practice Problem: Write a C program to calculate and print the factorial of a non-negative integer N (e.g., 5!=5×4×3×2×1=120) using a loop.
Given:
int N = 5;Code language: C++ (cpp)
Expected Output:
Factorial of 5 is 120.
+ Hint
Use a loop that starts at 1 and goes up to N. You’ll need an accumulator variable, initialized to 1, which you will multiply by the loop counter in each iteration.
+ Show Solution
#include <stdio.h>
int main() {
int N = 5, i;
long long factorial = 1; // Start at 1 for multiplication
if (N < 0) {
printf("Error: Factorial is not defined for negative numbers.\n");
} else {
// Calculate factorial
for (i = 1; i <= N; i++) {
factorial *= i; // Equivalent to: factorial = factorial * i;
}
printf("Factorial of %d is %lld.\n", N, factorial);
}
return 0;
}Code language: C++ (cpp)
Explanation:
Factorial is a product, so the accumulator (factorial) is initialized to 1.
- An initial
ifcheck handles the invalid case of a negative number. - The
forloop iterates from 1 up to N. - The line
factorial *= i;accumulates the product. If N is 5, thefactorialvariable changes like this:1→1×2→2×3→6×4→24×5=120. - The
long longtype is used forfactorialbecause factorials grow very quickly and exceed the capacity of a standardint.
Exercise 11: Do-While Menu
Practice Problem: Write a C program to create a simple menu-driven program that displays options (“1. Greet”, “2. Say Goodbye”, “3. Exit”). Use a do-while loop and a switch statement to repeatedly show the menu and process the user’s choice until they select the ‘Exit’ option.
Expected Output:
The area of a circle with radius 5.00 is 78.54
+ Hint
The do-while loop is perfect because you want the code block (displaying the menu) to execute at least once before checking the exit condition. The exit condition should be based on the user’s choice being equal to 3.
+ Show Solution
#include <stdio.h>
int main() {
int choice;
do {
printf("\n--- Menu ---\n");
printf("1. Greet\n");
printf("2. Say Goodbye\n");
printf("3. Exit\n");
printf("Enter your choice (1-3): ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Hello! Welcome to the program.\n");
break;
case 2:
printf("Goodbye! Have a nice day.\n");
break;
case 3:
printf("Exiting program. Thank you!\n");
break; // Required to exit switch, not do-while
default:
printf("Invalid choice. Please enter 1, 2, or 3.\n");
}
} while (choice != 3); // Loop continues UNTIL choice is 3
return 0;
}Code language: C++ (cpp)
Explanation:
This combines control flow structures for interactive programs.
do { ... } while (condition): The code inside thedoblock executes first. The condition (choice != 3) is checked after the first run.- The
switchstatement inside the loop handles the different menu options. - The loop continues as long as
choiceis not equal to 3. Once the user enters 3, theswitchhandles the exit message, and thewhilecondition becomes false, terminating the entire loop and ending the program.
Exercise 12: Count Digits
Practice Problem: Write a C program that uses a while loop to count the number of digits in a given number (e.g., 1234 has 4 digits).
Given:
int num = 12568;Code language: C++ (cpp)
Expected Output:
The number of digits in 12568 is: 5
+ Hint
In each iteration of the while loop, divide the number by 10 using integer division (num = num / 10). This effectively removes the last digit. Continue looping until the number becomes 0.
+ Show Solution
#include <stdio.h>
int main() {
int num = 12568, count = 0;
// Handle the case where the input is 0 separately
if (num == 0) {
count = 1;
}
int temp = num; // Use a temporary variable to preserve the original number
while (temp > 0) {
temp = temp / 10;
count++;
}
printf("The number of digits in %d is: %d\n", num, count);
return 0;
}Code language: C++ (cpp)
Explanation:
This program uses a loop to repeatedly strip off the last digit of the number.
temp = temp / 10: Because this is integer division in C, 123/10 results in 12, 12/10 results in 1, and 1/10 results in 0.count++: The counter increases once for every digit removed.- The loop continues as long as
temp > 0, ensuring that every digit contributes one count before the number is fully reduced to 0.
Exercise 13: Reverse a Number
Practice Problem: Write a C program to reverse a given number (e.g., 1234 becomes 4321).
Given:
int num = 1234;Code language: C++ (cpp)
Expected Output:
Original number: 1234
Reversed number: 4321
+ Hint
- Use the modulo operator (
% 10) to extract the last digit. Then, use this digit to build the reversed number. - Finally, remove the last digit from the original number (
num = num / 10).
+ Show Solution
#include <stdio.h>
int main() {
int num = 1234, reversed = 0, remainder;
int originalNum = num; // Keep the original number for output
while (num != 0) {
remainder = num % 10; // 1. Get the last digit
reversed = reversed * 10 + remainder; // 2. Append it to reversed number
num /= 10; // 3. Remove the last digit
}
printf("Original number: %d\n", originalNum);
printf("Reversed number: %d\n", reversed);
return 0;
}Code language: C++ (cpp)
Explanation:
This is a classic loop-based digit manipulation problem. The while loop continues until the original number is reduced to 0.
- Extraction:
remainder = num % 10isolates the right-most digit. - Construction:
reversed = reversed * 10 + remainderis the key. Multiplyingreversedby 10 shifts all existing digits one place to the left, making room to add the newremainderin the units place. - Reduction:
num /= 10(integer division) removes the digit that was just processed.
Exercise 14: Check for Palindrome
Practice Problem: Write a C program to determine if a given integer is a Palindrome (a number that reads the same forwards and backwards, e.g., 121 or 9009).
Given:
int num = 121;Code language: C++ (cpp)
Expected Output:
121 is a PALINDROME number
+ Hint
This exercise combines the logic from Exercise 11 (Reverse a Number). Calculate the reverse of the input number and then use an if-else statement to compare the reversed number with the original number.
+ Show Solution
#include <stdio.h>
int main() {
int num = 121, reversed = 0, originalNum;
originalNum = num; // Store the original value
// Logic to reverse the number
while (num > 0) {
reversed = reversed * 10 + (num % 10);
num /= 10;
}
// Control flow check
if (originalNum == reversed) {
printf("%d is a PALINDROME number.\n", originalNum);
} else {
printf("%d is NOT a palindrome number.\n", originalNum);
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The original number is stored in
originalNumbefore the loop modifies thenumvariable. - The
whileloop calculates thereversedversion of the number (exactly as in Exercise 12). - Finally, the
if-elsestatement acts as the control flow decision: iforiginalNumequalsreversed, the condition is true, and it’s a palindrome; otherwise, it is not
Exercise 15: Skip Even Numbers
Practice Problem: Write a C program to print all odd numbers between 1 and N using a single for loop and the continue keyword to skip the even numbers.
Given:
int n = 20;Code language: C++ (cpp)
Expected Output:
Odd numbers from 1 to 20:
1 3 5 7 9 11 13 15 17 19
+ Hint
Loop through every number from 1 to N. Inside the loop, use an if statement to check if the current number is even (i % 2 == 0). If it is, execute the continue statement.
+ Show Solution
#include <stdio.h>
int main() {
int N = 20, i;
printf("Odd numbers from 1 to %d:\n", N);
for (i = 1; i <= N; i++) {
// Control flow check for even numbers
if (i % 2 == 0) {
continue; // Skips the rest of the loop body for even numbers
}
// This line only executes if 'i' is ODD
printf("%d ", i);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
The continue keyword alters control flow within a loop by skipping the current iteration and immediately moving to the next one (i.e., the loop update expression).
- The loop iterates through all numbers.
- When an even number is encountered (
i % 2 == 0),continueis executed. This causes the program to jump directly toi++, skipping theprintfstatement for that even number. - The
printfstatement is only reached wheniis an odd number.
Exercise 16: Power of a Number
Practice Problem: Write a C program to calculate x raised to the power y (xy) where x (base) and y (exponent) are integers input by the user. Do this without using the built-in pow() function, relying only on a loop. Assume y is non-negative.
Given:
int base = 5, exponent = 3;Code language: C++ (cpp)
Expected Output:
5^3 = 125
+ Hint
- Start an accumulator variable (
result) at 1. - Use a
forloop that iteratesytimes. In each iteration, multiply theresultby the basex. Handle the edge case wherey=0(any number to the power of 0 is 1).
+ Show Solution
#include <stdio.h>
int main() {
int base = 5, exponent = 3, i;
long long result = 1; // Use long long for potentially large results
// Control flow: Handle x^0 case
if (exponent == 0) {
result = 1;
} else {
// Loop runs 'exponent' number of times
for (i = 1; i <= exponent; i++) {
result *= base; // Equivalent to: result = result * base;
}
}
printf("%d^%d = %lld\n", base, exponent, result);
return 0;
}Code language: C++ (cpp)
Explanation:
This solution uses a loop to perform repeated multiplication.
- Initialization:
resultstarts at 1 because multiplying x by 1 y times gives xy. if-elseControl: The program first checks for the edge case where theexponentis 0.- Loop: The
forloop runs exactlyexponenttimes. In each iteration, the base is multiplied into theresult. For example, 23:- i=1:
resultbecomes 1×2=2 - i=2:
resultbecomes 2×2=4 - i=3:
resultbecomes 4×2=8
- i=1:
long longis used forresultto prevent overflow, as powers can grow very large very quickly.
Exercise 17: Solid Rectangle Pattern
Practice Problem: Write a C program that uses nested for-loops to print a solid rectangle pattern of asterisks (*) with 4 rows and 4 columns.
Given:
int rows = 4, col = 4;Code language: C++ (cpp)
Expected Output:
****
****
****
****
+ Hint
- The outer loop controls the rows (running R times). The inner loop controls the columns (running C times).
- The inner loop prints the
*and then the outer loop finishes its iteration by printing a newline character (\n).
+ Show Solution
#include <stdio.h>
int main() {
int rows = 4, cols = 4, i, j;
// Outer loop for rows
for (i = 1; i <= rows; i++) {
// Inner loop for columns (prints stars in a single row)
for (j = 1; j <= cols; j++) {
printf("*");
}
printf("\n"); // Move to the next line after a row is complete
}
return 0;
}Code language: C++ (cpp)
Explanation:
Nested loops are essential for 2D patterns.
- Outer loop (
i): Iterates R times, representing each row. - Inner loop (
j): Iterates C times. In each iteration, it prints one*without a newline, building a single row horizontally. - Newline:
printf("\n");is placed outside the inner loop but inside the outer loop. This ensures that after a complete row of C stars is printed, the cursor moves to the beginning of the next line.
Exercise 18: Right-Angled Triangle (Numbers)
Practice Problem: Write a C program to print a right-angled triangular pattern where each row prints increasing numbers, up to the row number (e.g., Row 3 prints 1 2 3).
Given:
int rows = 3;Code language: C++ (cpp)
Expected Output:
1
1 2
1 2 3
+ Hint
The outer loop (rows) goes from 1 to N. The inner loop (columns) should print numbers starting from 1 and going up to the current row number (Rowindex).
+ Show Solution
#include <stdio.h>
int main() {
int N = 3, i, j;
// Outer loop controls rows (1 to N)
for (i = 1; i <= N; i++) {
// Inner loop controls columns (prints 1 up to current row number i)
for (j = 1; j <= i; j++) {
printf("%d ", j); // Print the column index 'j'
}
printf("\n");
}
return 0;
}Code language: C++ (cpp)
Explanation:
The key here is setting the correct termination condition for the inner loop.
- Outer Loop Variable (
i): Determines how many numbers will be printed in the current row. - Inner Loop Condition:
j <= i. This ensures that the inner loop runs i times. For example, wheni=3, the inner loop runs for j=1,2,3. - Output: The inner loop prints the counter
jitself, resulting in the sequence 1,1 2,1 2 3, and so on
Exercise 19: Inverted Right-Angled Triangle (Asterisks)
Practice Problem: Write a C program to print an inverted right-angled triangular pattern of asterisks. Decide the number of rows. (e.g., if N=4: ****,***,**,*).
Given:
int rows = 3;Code language: C++ (cpp)
Expected Output:
number of rows (N): 3
***
**
*
+ Hint
The number of asterisks in Row i should be N−i+1. You can simplify this by setting the outer loop to start at N and decrement to 1, and having the inner loop run equal to the current row index.
+ Show Solution
#include <stdio.h>
int main() {
int N = 3, i, j;
// Outer loop starts at N and decrements
for (i = N; i >= 1; i--) {
// Inner loop prints stars equal to the current row index 'i'
for (j = 1; j <= i; j++) {
printf("*");
}
printf("\n");
}
return 0;
}Code language: C++ (cpp)
Explanation:
This demonstrates reversing the iteration of the outer loop.
- Outer Loop Initialization:
i = N. Starting at N ensures the first row has the maximum length. - Outer Loop Update:
i--. The row count decreases in each iteration. - Inner Loop Condition:
j <= i. Sinceidecreases from N to 1, the number of stars printed in the inner loop also decreases from N to 1, creating the inverted triangle.
Exercise 20: Print Multiplication Tables
Practice Problem: Write a C program to print multiplication tables for numbers 1 to 10, each from ×1 to ×10.
Expected Output:
Table of 1
1 x 1 = 1
1 x 2 = 2
....
1 x 10 = 10
Table of 2
2 x 1 = 2
2 x 2 = 4
...
2 x 10 = 20
....
Table of 10
10 x 1 = 10
10 x 2 = 20
....
10 x 10 = 100
+ Hint
- Use two loops: outer loop for the base number (1…10).
- Inner loop for multipliers (1…10).
- Consider a blank line between tables for readability.
+ Show Solution
#include <stdio.h>
int main() {
for (int n = 1; n <= 10; n++) {
printf("Table of %d\n", n);
for (int i = 1; i <= 10; i++) {
int product = n*i;
printf("%2d x %2d = %3d\n", n, i, product);
}
printf("\n");
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Use an outer loop to choose the base number
nfrom 1 to 10. Inside it, run an inner loopi = 1..10and printn x i = n*i, using fixed field widths to keep columns aligned. - After finishing a table for one
n, print a blank line for readability. The two dimensions (base and multiplier) naturally map to nested loops.
Exercise 21: Smallest and Largest
Practice Problem: Write a C program that asks the user for the number of integers (N) they will enter. Then, read those N integers and use a single loop to determine and display the smallest and largest values.
Expected Output:
How many numbers will you enter (N)? 3
Enter the numbers:
123 567 894
Largest number entered: 894
Smallest number entered: 123
+ Hint
- Initialize the
smallestvariable to a very large number and thelargestvariable to a very small number (or simply initialize both to the first number entered by the user). - Update them in the loop using
ifstatements.
+ Show Solution
#include <stdio.h>
int main() {
int N, num, i;
int smallest, largest;
printf("How many numbers will you enter (N)? \n");
scanf("%d", &N);
printf("Enter the numbers:\n");
for (i = 1; i <= N; i++) {
scanf("%d", &num);
// Initialize smallest and largest with the very first number
if (i == 1) {
smallest = num;
largest = num;
continue; // Skip the rest of the checks for the first number
}
// Update smallest and largest using control flow
if (num < smallest) {
smallest = num;
}
if (num > largest) {
largest = num;
}
}
printf("\nLargest number entered: %d\n", largest);
printf("Smallest number entered: %d\n", smallest);
return 0;
}Code language: C++ (cpp)
Explanation:
- Initialization: The
if (i == 1)block ensures thatsmallestandlargestare correctly set to the value of the first input number. Thecontinuejumps past the update checks for this first iteration. - Loop Updates: Inside the loop, two separate
ifstatements (notif-else) independently check if the current inputnumis smaller than the currentsmallestor larger than the currentlargest. If a number meets the condition, the corresponding variable is updated.
Exercise 22: Check for Prime
Practice Problem: Write a C program to determine if a number is a Prime number (a number greater than 1 that is only divisible by 1 and itself). Use a loop and the break statement to optimize the check.
Given:
int N = 31;Code language: C++ (cpp)
Expected Output:
31 is a PRIME number
+ Hint
You only need to check for divisibility from i=2 up to the square root of N. If N is divisible by any number in this range, it’s not prime, and you can immediately exit the loop using break.
+ Show Solution
#include <stdio.h>
#include <stdbool.h> // For using the boolean type
#include <math.h> // For the sqrt() function
int main() {
int N = 31, i;
bool isPrime = true;
// 0 and 1 are not prime numbers
if (N <= 1) {
isPrime = false;
} else {
// Loop from 2 up to the square root of N
for (i = 2; i <= sqrt(N); i++) {
if (N % i == 0) {
isPrime = false;
break; // Optimization: Found a factor, no need to check further
}
}
}
if (isPrime) {
printf("%d is a PRIME number.\n", N);
} else {
printf("%d is NOT a prime number.\n", N);
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Initialization: A
boolflagisPrimeis set totrue(optimistically assuming the number is prime). - Optimization: The
forloop checks only up to square root of N because if N has a factor greater than square root of N
, it must also have a factor smaller than square root of N
.
break: If a divisor is found (N % i == 0),isPrimeis set tofalse, and thebreakkeyword immediately terminates theforloop, saving processing time.
Exercise 23: Print Primes in Range
Practice Problem: Write a C program that uses nested loops to print all the prime numbers within a given range, specified by a start limit and an end limit.
Given:
int start = 10, end = 20;Code language: C++ (cpp)
Expected Output:
Prime numbers between 10 and 20 are:
11 13 17 19
+ Hint
Use an outer loop (for loop) to iterate through every number in the range. Use an inner loop (another for loop) to check the primality of the current number (as done in previous Exercise).
+ Show Solution
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
int main() {
int start = 10, end = 20, num, i;
bool isPrime;
printf("Prime numbers between %d and %d are:\n", start, end);
// Outer loop iterates through every number in the range
for (num = start; num <= end; num++) {
if (num <= 1) {
continue; // Skip 0 and 1
}
isPrime = true;
// Inner loop checks primality of 'num'
for (i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break; // Found a factor, not prime
}
}
if (isPrime) {
printf("%d ", num);
}
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
This exercise demonstrates use of nested loops and the continue keyword.
- Outer Loop: The
for (num = start; ...)loop ensures every number in the specified range is tested. continue:if (num <= 1) { continue; }is used to skip 0 and 1 and immediately jump to the next iteration of the outer loop, preventing unnecessary checks.- Inner Logic: The inner loop implements the same primality test as Exercise 15. If
isPrimeremainstrueafter the inner loop finishes, the number is printed.
Exercise 24: GCD (Greatest Common Divisor)
Practice Problem: Write a C program to find the Greatest Common Divisor (GCD) (or Highest Common Factor, HCF) of two positive integers using an iterative approach (Euclidean algorithm is best, but a simple loop iteration is sufficient for this exercise).
Given:
int num1 = 10, num2 = 30;Code language: C++ (cpp)
Expected Output:
GCD of 10 and 30 is: 10
+ Hint
Use a for loop that iterates from 1 up to the smaller of the two numbers. Inside the loop, check if the current loop counter i divides both numbers evenly. The last value of i that satisfies this condition is the GCD.
+ Show Solution
#include <stdio.h>
int main() {
int num1 = 10, num2 = 30, i, gcd = 1;
// Loop runs up to the smaller of the two numbers
int limit = (num1 < num2) ? num1 : num2;
for (i = 1; i <= limit; i++) {
// Check if i divides both num1 AND num2 evenly
if (num1 % i == 0 && num2 % i == 0) {
gcd = i; // Store this factor; it will be the greatest one found
}
}
printf("GCD of %d and %d is: %d\n", num1, num2, gcd);
return 0;
}Code language: C++ (cpp)
Explanation:
- The loop iterates through all possible common factors starting from 1.
- Conditional Check:
if (num1 % i == 0 && num2 % i == 0)ensures thatidivides both numbers evenly. - Accumulation:
gcd = iupdates thegcdvariable every time a common factor is found. Because the loop iterates in increasing order, the last value stored ingcdwill necessarily be the largest (Greatest) Common Divisor.
Exercise 25: Armstrong Number
Practice Problem: Write a C program to check if an integer is an Armstrong number (a number that is equal to the sum of the cubes of its digits, e.g., 153=13+53+33=1+125+27=153). Note: This definition is for 3-digit numbers. For simplicity, assume a 3-digit input.
Given:
int num = 153;Code language: C++ (cpp)
Expected Output:
153 is an ARMSTRONG number.
+ Hint
Use the same digit extraction logic as in reverse number Exercise, but instead of constructing the reversed number, accumulate the cube of each extracted digit into a sum variable. Compare the final sum with the original number.
+ Show Solution
#include <stdio.h>
int main() {
int num = 153, originalNum, remainder, sum = 0;
originalNum = num; // Store the original value
while (num > 0) {
remainder = num % 10; // Extract the last digit
// Add the cube of the digit to the sum
// remainder * remainder * remainder is the cube
sum = sum + (remainder * remainder * remainder);
num /= 10; // Remove the last digit
}
// Control flow check
if (originalNum == sum) {
printf("%d is an ARMSTRONG number.\n", originalNum);
} else {
printf("%d is NOT an Armstrong number.\n", originalNum);
}
return 0;
}Code language: C++ (cpp)
Explanation:
This program extends the digit-by-digit processing loop by introducing the cube calculation.
- Digit Extraction Loop: The
whileloop extracts digits using the modulo operator (% 10) and removes them using integer division (/ 10). - Summation: Inside the loop,
sumacts as the accumulator, adding the cube of theremainder(remainder * remainder * remainder) in each step. - Final Check: After the loop finishes and all digits have been processed, the
if-elsestatement compares the finalsumwith the preservedoriginalNumto determine if it is an Armstrong number.
Exercise 26: Pyramid Pattern
Practice Problem: Write a C program to print a full pyramid (isosceles triangle) pattern of asterisks. The pattern must be centered. Decide the number of rows N.
Given:
int N = 3;Code language: C++ (cpp)
Expected Output:
number of rows (N): 3
*
***
*****
+ Hint
This requires three parts in the inner loop:
- A loop to print spaces for indentation: (
N - i) spaces in rowi. - A loop to print stars: (
2×i−1) stars in row
+ Show Solution
#include <stdio.h>
int main() {
int N = 3, i, j;
for (i = 1; i <= N; i++) {
// 1. Loop to print leading spaces
for (j = 1; j <= N - i; j++) {
printf(" ");
}
// 2. Loop to print stars
// Number of stars is always 2*i - 1
for (j = 1; j <= 2 * i - 1; j++) {
printf("*");
}
printf("\n");
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Outer Loop (
i): Controls the row number (from 1 to N). - First Inner Loop: Prints
N - ispaces. As i increases (we move down the pyramid), the number of leading spaces decreases, shifting the center outward. - Second Inner Loop: Prints
2 * i - 1stars. The number of stars increases by 2 in each row (e.g., 1,3,5,7,…), which is the characteristic of a full pyramid.
Exercise 27: Generate Fibonacci
Practice Problem: Write a C program to print the first n terms of the Fibonacci sequence.
Given:
int N = 9;Code language: C++ (cpp)
Expected Output:
0 1 1 2 3 5 8 13 21
+ Hint
Handle small n first. Maintain two variables (a, b) for the last two terms; print a, then advance with c = a + b, shift a = b, b = c in a loop.
+ Show Solution
#include <stdio.h>
int main() {
int n = 9;
if (n <= 0) { return 0; }
long long a = 0, b = 1;
for (int i = 1; i <= n; i++) {
printf("%lld ", a);
long long c = a + b;
a = b;
b = c;
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
We iterate n times, always printing the current term (a) before advancing. The rolling update keeps only two previous terms in memory, making this approach simple and efficient. Using a 64-bit type delays overflow for moderate n.
Exercise 28: Print All Factors of a Number
Practice Problem: Write a C program to print all its positive factors of integer n.
Given:
int N = 10;Code language: C++ (cpp)
Expected Output:
1 2 5 10
+ Hint
Loop from 1 to n and print i whenever n % i == 0. For a faster variant, loop to i*i <= n and print factor pairs; but the simple full loop is clearer.
+ Show Solution
#include <stdio.h>
int main() {
int n = 10;
if (n <= 0) { printf("Enter a positive integer.\n"); return 0; }
for (int i = 1; i <= n; i++) {
if (n % i == 0) printf("%d ", i);
}
printf("\n");
return 0;
}Code language: C++ (cpp)
Explanation:
We check each candidate from 1 through n for exact divisibility. Whenever the remainder is zero, that candidate is a factor and gets printed. This O(n) approach is straightforward for teaching loops; later, you can optimize using i*i <= n and printing factor pairs.

Leave a Reply