Control Structures and Loops
Programming in C тАУ Part 2: Control Structures and Loops
Class 12 ┬╖ Computer Science ┬╖ Unit 4: Programming in C
Normally a program runs from the first statement to the last. Control structures let it make decisions and repeat work. All programs below were compiled and run, and the outputs are real.
Navigation: тЖР Part 1: Fundamentals ┬╖ Part 2 ┬╖ Part 3: Arrays and Strings тЖТ
Table of Contents
- Types of Control Structures
- Decision Making: if, if...else, else if ladder
- switch Statement
- Loops: for, while, do...while
- Nested Loops and Patterns
- Jump Statements: break, continue, goto
- Common Number Programs
- Quick Revision Table
- Practice Questions
1. Types of Control Structures
A control structure decides the order in which statements are executed.
| Type | Meaning | C statements |
|---|---|---|
| Sequence | Statements run one after another (default) | Ordinary statements |
| Selection (decision) | One path is chosen depending on a condition | if, if...else, else if ladder, switch |
| Iteration (looping) | A block is repeated | for, while, do...while |
| Jump | Control is moved to another place | break, continue, goto, return |
2. Decision Making
2.1 Simple if
if (condition)
{
statements; /* runs only if the condition is true (non-zero) */
}
#include <stdio.h>
int main(void)
{
int marks;
printf("Enter your marks: ");
scanf("%d", &marks);
if (marks >= 40)
printf("You passed.\n");
return 0;
}
Sample run:
Enter your marks: 56
You passed.
2.2 if...else
if (condition)
statement 1; /* condition true */
else
statement 2; /* condition false */
#include <stdio.h>
int main(void)
{
int a;
printf("Enter a number: ");
scanf("%d", &a);
if (a % 2 == 0)
printf("%d is even\n", a);
else
printf("%d is odd\n", a);
return 0;
}
Sample run:
Enter a number: 17
17 is odd
#include <stdio.h>
int main(void)
{
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
if (a > b)
printf("%d is the greatest number\n", a);
else
printf("%d is the greatest number\n", b);
return 0;
}
Sample run:
Enter two numbers: 25 40
40 is the greatest number
2.3 else if ladder
Used when there are more than two choices. The conditions are tested from top to bottom, and the first true one runs. The rest are skipped.
if (condition 1) statement 1;
else if (condition 2) statement 2;
else if (condition 3) statement 3;
else default statement;
#include <stdio.h>
int main(void)
{
int a, b, c;
printf("Enter any three numbers: ");
scanf("%d %d %d", &a, &b, &c);
if (a > b && a > c)
printf("Largest number is %d\n", a);
else if (b > a && b > c)
printf("Largest number is %d\n", b);
else
printf("Largest number is %d\n", c);
return 0;
}
Sample run:
Enter any three numbers: 42 87 65
Largest number is 87
#include <stdio.h>
int main(void)
{
int eng, nep, comp, acc, eco, total;
float per;
printf("Enter marks of five subjects: ");
scanf("%d %d %d %d %d", &eng, &nep, &comp, &acc, &eco);
total = eng + nep + comp + acc + eco;
per = total / 5.0f; /* 5.0 keeps the decimal part */
printf("Total = %d, Percentage = %.2f\n", total, per);
if (eng >= 35 && nep >= 35 && comp >= 35 && acc >= 35 && eco >= 35) {
if (per >= 75)
printf("Distinction\n");
else if (per >= 60)
printf("First division\n");
else if (per >= 45)
printf("Second division\n");
else
printf("Third division\n");
} else {
printf("Failed\n");
}
return 0;
}
Sample run:
Enter marks of five subjects: 80 76 90 72 70
Total = 388, Percentage = 77.60
Distinction
Common mistakes: writing
if (a = 5)instead ofif (a == 5), and putting a semicolon right afterif (condition);, which makes theifdo nothing.
3. switch Statement
The switch statement chooses one block out of many by comparing one expression with several constant values. It is a neat alternative to a long else if ladder.
switch (expression)
{
case value1: statements; break;
case value2: statements; break;
default: statements;
}
Rules
- The expression must give an integer or character value (not
floator a string) - Each
casevalue must be a constant and must be unique breakends the case. Withoutbreak, execution "falls through" into the next casedefaultruns when no case matches. It is optional
#include <stdio.h>
int main(void)
{
int a, b, ch;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("1. Sum\n2. Difference\n3. Product\n");
printf("Enter your choice: ");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("Sum = %d\n", a + b);
break;
case 2:
printf("Difference = %d\n", a - b);
break;
case 3:
printf("Product = %d\n", a * b);
break;
default:
printf("Wrong choice\n");
}
return 0;
}
Sample run:
Enter two numbers: 12 5
1. Sum
2. Difference
3. Product
Enter your choice: 3
Product = 60
#include <stdio.h>
int main(void)
{
int day;
printf("Enter a number (1 for Sunday ... 7 for Saturday): ");
scanf("%d", &day);
switch (day) {
case 1: printf("Sunday\n"); break;
case 2: printf("Monday\n"); break;
case 3: printf("Tuesday\n"); break;
case 4: printf("Wednesday\n"); break;
case 5: printf("Thursday\n"); break;
case 6: printf("Friday\n"); break;
case 7: printf("Saturday\n"); break;
default: printf("Invalid day number\n");
}
return 0;
}
Sample run:
Enter a number (1 for Sunday ... 7 for Saturday): 3
Tuesday
Several cases sharing one block (the programmer deliberately leaves out break):
#include <stdio.h>
int main(void)
{
char ch;
printf("Enter a lowercase letter: ");
scanf(" %c", &ch);
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("%c is a vowel\n", ch);
break;
default:
printf("%c is not a vowel\n", ch);
}
return 0;
}
Sample run:
Enter a lowercase letter: e
e is a vowel
if...else vs switch
| Basis | if...else | switch |
|---|---|---|
| Tests | Any condition (ranges, relations, logic) | Only equality with constants |
| Data type | Any type | Integer or character only |
| Speed with many choices | Slower | Usually faster and neater |
| Fall-through | Not applicable | Happens without break |
4. Loops
A loop repeats a block of statements as long as a condition is true. Every loop needs three things:
- Initialization: the starting value of the counter
- Condition: a test that decides whether to continue
- Update: a change to the counter (increment or decrement), otherwise the loop never ends
4.1 for loop
for (initialization; condition; update)
{
statements;
}
Use it when the number of repetitions is known.
for (i = 1; i <= 5; i++)
| | |
| | +-- 3. runs after each pass
| +---------- 2. tested before each pass
+------------------ 1. runs once, at the start
#include <stdio.h>
int main(void)
{
int i;
for (i = 1; i <= 10; i++)
printf("%d ", i);
printf("\n");
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
#include <stdio.h>
int main(void)
{
int i, sum = 0;
printf("Even numbers from 1 to 20: ");
for (i = 2; i <= 20; i = i + 2) {
printf("%d ", i);
sum = sum + i;
}
printf("\nSum of even numbers = %d\n", sum);
return 0;
}
Output:
Even numbers from 1 to 20: 2 4 6 8 10 12 14 16 18 20
Sum of even numbers = 110
#include <stdio.h>
int main(void)
{
int i, c, sum = 0;
for (i = 1; i <= 10; i++) {
c = i * i * i;
sum = sum + c;
}
printf("Sum of cubes of first 10 numbers = %d\n", sum);
return 0;
}
Output:
Sum of cubes of first 10 numbers = 3025
#include <stdio.h>
int main(void)
{
int i, even = 0, odd = 0;
for (i = 1; i <= 50; i++) {
if (i % 2 == 0)
even = even + i;
else
odd = odd + i;
}
printf("Sum of even numbers (1 to 50) = %d\n", even);
printf("Sum of odd numbers (1 to 50) = %d\n", odd);
return 0;
}
Output:
Sum of even numbers (1 to 50) = 650
Sum of odd numbers (1 to 50) = 625
Correction: to print even numbers, either start from 2 and step by 2 (
i += 2), or testi % 2 == 0. Writingi + 2does not changei. Usei += 2ori = i + 2.
4.2 while loop
initialization;
while (condition)
{
statements;
update;
}
The condition is tested first. If it is false at the start, the body never runs. It is an entry-controlled loop. Use it when the number of repetitions is not known in advance.
#include <stdio.h>
int main(void)
{
int i = 2, count = 0;
while (i <= 100) {
printf("%4d", i);
i = i + 2;
count++;
if (count % 10 == 0)
printf("\n"); /* new line after every 10 numbers */
}
return 0;
}
Output:
2 4 6 8 10 12 14 16 18 20
22 24 26 28 30 32 34 36 38 40
42 44 46 48 50 52 54 56 58 60
62 64 66 68 70 72 74 76 78 80
82 84 86 88 90 92 94 96 98 100
#include <stdio.h>
int main(void)
{
int num;
char ename[20], eadd[30];
printf("How many employees? ");
scanf("%d", &num);
while (num > 0) {
printf("Enter name and address (one word each): ");
scanf("%19s %29s", ename, eadd);
printf("Name: %s, Address: %s\n", ename, eadd);
num = num - 1;
}
return 0;
}
Sample run:
How many employees? 2
Enter name and address (one word each): Ram Pokhara
Name: Ram, Address: Pokhara
Enter name and address (one word each): Sita Butwal
Name: Sita, Address: Butwal
4.3 do...while loop
initialization;
do
{
statements;
update;
} while (condition); /* note the semicolon */
The body runs first and the condition is tested afterwards, so the body runs at least once. It is an exit-controlled loop.
#include <stdio.h>
int main(void)
{
int i = 99;
do {
printf("%d ", i);
i = i - 2;
} while (i >= 1);
printf("\n");
return 0;
}
Output:
99 97 95 93 91 89 87 85 83 81 79 77 75 73 71 69 67 65 63 61 59 57 55 53 51 49 47 45 43 41 39 37 35 33 31 29 27 25 23 21 19 17 15 13 11 9 7 5 3 1
A menu program is a good use of do...while, because the menu must be shown at least once:
#include <stdio.h>
int main(void)
{
int choice;
do {
printf("\n1. Say hello\n2. Say goodbye\n3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
if (choice == 1)
printf("Hello!\n");
else if (choice == 2)
printf("Goodbye!\n");
} while (choice != 3);
return 0;
}
Sample run:
1. Say hello
2. Say goodbye
3. Exit
Enter your choice: 1
Hello!
1. Say hello
2. Say goodbye
3. Exit
Enter your choice: 2
Goodbye!
1. Say hello
2. Say goodbye
3. Exit
Enter your choice: 3
4.4 while vs do...while
| Basis | while | do...while |
|---|---|---|
| Type | Entry-controlled | Exit-controlled |
| Condition tested | Before the body | After the body |
| Minimum runs | 0 (may never run) | 1 (always runs once) |
| Semicolon after the condition | No | Yes |
| Best used when | Repetitions unknown, may be zero | The body must run at least once (menus, input validation) |
The next program makes the difference visible. The condition is false from the very beginning:
#include <stdio.h>
int main(void)
{
int i = 10;
while (i < 5) {
printf("while body executed\n"); /* never runs */
}
do {
printf("do-while body executed once\n"); /* runs once, then the test fails */
} while (i < 5);
return 0;
}
Output:
do-while body executed once
4.5 Which loop should I use?
| Situation | Best loop |
|---|---|
| Count is known (print 1 to 10) | for |
| Repeat until something happens (read until the user enters 0) | while |
| Must run at least once (menu, password retry) | do...while |
4.6 Infinite loops
A loop whose condition never becomes false runs forever. This happens when the update is missing or the condition is always true.
while (1) { /* runs forever until break */ }
for ( ; ; ) { /* runs forever until break */ }
5. Nested Loops and Patterns
A loop inside another loop is a nested loop. For each single pass of the outer loop, the inner loop runs completely. Nested loops are used for tables, matrices and patterns.
#include <stdio.h>
int main(void)
{
int r, k;
for (r = 1; r <= 5; r++) { /* outer loop: rows */
for (k = 10; k <= 50; k += 10) /* inner loop: columns */
printf("%d ", k);
printf("\n");
}
return 0;
}
Output:
10 20 30 40 50
10 20 30 40 50
10 20 30 40 50
10 20 30 40 50
10 20 30 40 50
#include <stdio.h>
int main(void)
{
int r, k;
for (r = 5; r >= 1; r--) {
for (k = 1; k <= r; k++)
printf("%d", r);
printf("\n");
}
return 0;
}
Output:
55555
4444
333
22
1
#include <stdio.h>
int main(void)
{
int r, k;
for (r = 1; r <= 5; r++) {
for (k = 1; k <= r; k++)
printf("* ");
printf("\n");
}
return 0;
}
Output:
*
* *
* * *
* * * *
* * * * *
How to work out a pattern: let the outer loop control the rows, and the inner loop control what is printed in each row. Then ask how the number of items changes from one row to the next.
6. Jump Statements
| Statement | Effect |
|---|---|
break | Leaves the nearest enclosing loop or switch immediately |
continue | Skips the rest of the current pass and goes to the next pass of the loop |
goto label; | Jumps to a statement marked with label: |
return | Leaves the current function (and may send back a value) |
break
#include <stdio.h>
int main(void)
{
int i;
for (i = 1; i <= 10; i++) {
if (i == 5)
break; /* leave the loop completely */
printf("%d ", i);
}
printf("\nLoop stopped when i = %d\n", i);
return 0;
}
Output:
1 2 3 4
Loop stopped when i = 5
continue
#include <stdio.h>
int main(void)
{
int num;
for (num = 1; num < 10; num++) {
if (num == 7)
continue; /* skip the rest of this round only */
printf("%d ", num);
}
printf("\n");
return 0;
}
Output:
1 2 3 4 5 6 8 9
goto
#include <stdio.h>
int main(void)
{
int marks;
retry:
printf("Enter marks (0 to 100): ");
scanf("%d", &marks);
if (marks < 0 || marks > 100) {
printf("Invalid marks, try again.\n");
goto retry; /* jump back to the label */
}
printf("Valid marks: %d\n", marks);
return 0;
}
Sample run:
Enter marks (0 to 100): 150
Invalid marks, try again.
Enter marks (0 to 100): -3
Invalid marks, try again.
Enter marks (0 to 100): 85
Valid marks: 85
gotois rarely used, because many jumps make a program hard to follow. Good programs use loops and functions instead.
Difference between break and continue
| Basis | break | continue |
|---|---|---|
| Action | Terminates the loop (or switch) completely | Skips only the current pass, and the loop carries on |
| Control moves to | The first statement after the loop | The next test (or update) of the loop |
| Used in | Loops and switch | Loops only |
| Example use | Stop searching once a value is found | Skip invalid or unwanted values |
7. Common Number Programs
These programs are asked again and again in exams. Learn the idea behind each one.
7.1 Reverse a number
Idea: take the last digit with % 10, add it to the reversed number after multiplying that number by 10, then remove the last digit with / 10.
#include <stdio.h>
int main(void)
{
int n, r, rev = 0;
printf("Enter a number: ");
scanf("%d", &n);
while (n > 0) {
r = n % 10; /* last digit */
rev = rev * 10 + r; /* add it to the reversed number */
n = n / 10; /* remove the last digit */
}
printf("Reverse number is %d\n", rev);
return 0;
}
Sample run:
Enter a number: 1234
Reverse number is 4321
7.2 Sum of digits
#include <stdio.h>
int main(void)
{
int n, r, sum = 0;
printf("Enter a positive number: ");
scanf("%d", &n);
if (n > 0) {
while (n > 0) {
r = n % 10;
sum = sum + r;
n = n / 10;
}
printf("The sum of the digits is %d\n", sum);
} else {
printf("It is not a positive number\n");
}
return 0;
}
Sample run:
Enter a positive number: 2345
The sum of the digits is 14
7.3 Palindrome number
A number is a palindrome if it reads the same forwards and backwards (121, 1331). Reverse it and compare with the original.
#include <stdio.h>
int main(void)
{
int n, original, r, rev = 0;
printf("Enter a number: ");
scanf("%d", &n);
original = n; /* keep a copy of the input */
while (n > 0) {
r = n % 10;
rev = rev * 10 + r;
n = n / 10;
}
if (original == rev)
printf("%d is a palindrome\n", original);
else
printf("%d is not a palindrome\n", original);
return 0;
}
Sample run:
Enter a number: 121
121 is a palindrome
7.4 Armstrong number
An Armstrong number equals the sum of its digits, each raised to the power of the number of digits. For three digits: 153 = 1┬│ + 5┬│ + 3┬│.
#include <stdio.h>
int main(void)
{
int n, original, r, sum = 0;
printf("Enter a 3-digit number: ");
scanf("%d", &n);
original = n;
while (n > 0) {
r = n % 10;
sum = sum + r * r * r; /* cube of each digit */
n = n / 10;
}
if (sum == original)
printf("%d is an Armstrong number\n", original);
else
printf("%d is not an Armstrong number\n", original);
return 0;
}
Sample run:
Enter a 3-digit number: 153
153 is an Armstrong number
7.5 Factorial
n! = 1 ├Ч 2 ├Ч 3 ├Ч ... ├Ч n, and 0! = 1.
#include <stdio.h>
int main(void)
{
int i, n;
unsigned long fact = 1;
printf("Enter a positive number: ");
scanf("%d", &n);
if (n > 0) {
for (i = n; i >= 1; i--)
fact = fact * i;
printf("The factorial of %d is %lu\n", n, fact);
} else {
printf("It is not a positive number\n");
}
return 0;
}
Sample run:
Enter a positive number: 5
The factorial of 5 is 120
7.6 Fibonacci series
Each term is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, ...
#include <stdio.h>
int main(void)
{
int i, n, a = 0, b = 1, next;
printf("How many terms? ");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
printf("%d ", a);
next = a + b;
a = b;
b = next;
}
printf("\n");
return 0;
}
Sample run:
How many terms? 10
0 1 1 2 3 5 8 13 21 34
7.7 Prime number check
A prime number has exactly two factors: 1 and itself. To test, try dividing by every number from 2 up to the number divided by 2. If any divides it exactly, it is not prime.
#include <stdio.h>
int main(void)
{
int i, num, isPrime = 1; /* assume prime until a divisor is found */
printf("Enter a number: ");
scanf("%d", &num);
if (num < 2)
isPrime = 0;
for (i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = 0;
break;
}
}
if (isPrime)
printf("%d is a prime number\n", num);
else
printf("%d is not a prime number\n", num);
return 0;
}
Sample run:
Enter a number: 29
29 is a prime number
7.8 Multiplication table
#include <stdio.h>
int main(void)
{
int i, n;
printf("Enter a number: ");
scanf("%d", &n);
for (i = 1; i <= 10; i++)
printf("%d x %2d = %3d\n", n, i, n * i);
return 0;
}
Sample run:
Enter a number: 7
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
7 x 9 = 63
7 x 10 = 70
7.9 Prime numbers up to 1000, and perfect squares
#include <stdio.h>
int main(void)
{
int i, j, count = 0;
for (j = 2; j <= 1000; j++) {
for (i = 2; i < j; i++) {
if (j % i == 0)
break; /* j has a divisor, so it is not prime */
}
if (i == j) { /* the inner loop ran to the end */
printf("%5d", j);
count++;
if (count % 10 == 0)
printf("\n");
}
}
printf("\n\nTotal prime numbers = %d\n", count);
return 0;
}
Output:
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463
467 479 487 491 499 503 509 521 523 541
547 557 563 569 571 577 587 593 599 601
607 613 617 619 631 641 643 647 653 659
661 673 677 683 691 701 709 719 727 733
739 743 751 757 761 769 773 787 797 809
811 821 823 827 829 839 853 857 859 863
877 881 883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997
Total prime numbers = 168
#include <stdio.h>
int main(void)
{
int s, t;
printf("Perfect squares from 100 to 500:\n");
for (s = 100; s <= 500; s++) {
for (t = 1; t * t <= s; t++) {
if (t * t == s)
printf("%d = %d x %d\n", s, t, t);
}
}
return 0;
}
Output:
Perfect squares from 100 to 500:
100 = 10 x 10
121 = 11 x 11
144 = 12 x 12
169 = 13 x 13
196 = 14 x 14
225 = 15 x 15
256 = 16 x 16
289 = 17 x 17
324 = 18 x 18
361 = 19 x 19
400 = 20 x 20
441 = 21 x 21
484 = 22 x 22
8. Quick Revision Table
| Topic | Key point |
|---|---|
if | Runs a block only when the condition is true |
if...else | Two-way choice |
else if ladder | Many choices; first true condition runs |
switch | Chooses by integer or character constant; needs break |
for | Entry-controlled; best for known counts |
while | Entry-controlled; may run 0 times |
do...while | Exit-controlled; runs at least once; ends with ; |
break | Exits the loop completely |
continue | Skips to the next pass |
goto | Jumps to a label; avoid it |
% and / in digit programs | % 10 gives the last digit; / 10 removes it |
9. Practice Questions
Short-answer questions
- What is a control structure? Name its types.
- Write the syntax of
if...elseand of theelse ifladder. - What is the use of
breakinside aswitch? What happens if it is missing? - What is a loop? Name the three parts every loop needs.
- Differentiate between
whileanddo...while. (NEB Q7) - Differentiate between
breakandcontinue. (NEB Q6) - What is a nested loop? Give one use.
- What is an infinite loop? How can it be created?
Long-answer questions
- Explain the control structures of C with examples. (NEB Q6)
- Explain the looping statements of C with syntax and examples. (NEB Q7)
- Differentiate between
if...elseandswitch. Explainswitchwith a program.
Programming questions (exam favourites)
- Write a program to find the largest of three numbers.
- Write a program to check whether a number is even or odd.
- Write a program to print the sum of the first 100 natural numbers.
- Write a program to print the multiplication table of any number.
- Write a program to reverse a number and check for a palindrome.
- Write a program to find the factorial of a number.
- Write a program to print the Fibonacci series up to 10 terms.
- Write a program to check whether a number is prime.
- Write a program to check whether a number is an Armstrong number.
- Write a program to find the sum of the digits of a number.
- Write a program to print this pattern for
nrows:
*
* *
* * *
* * * *
Predict the output
- How many times does
for (i = 0; i < 5; i++)run its body? - What is printed by
for (i = 1; i <= 5; i++) { if (i == 3) continue; printf("%d ", i); }? - What is printed if
breakreplacescontinuein question 2?
(Answers: 1) 5 times; 2) 1 2 4 5; 3) 1 2.)
Navigation: тЖР Part 1: Fundamentals ┬╖ Part 2 ┬╖ Part 3: Arrays and Strings тЖТ
Prepared for NEB Class 12 Computer Science exam revision.