Control structures, arrays and strings notes — Unit 2
Free unit-wise study notes on control structures, arrays and strings for Programming for Problem Solving in C, Semester 1 of B.Tech — Computer Science & Engineering — key concepts, examples, important questions and a revision checklist for semester exams.
Twenty hand-written sheets on decisions, loops, arrays and strings — the unit that carries the most programming marks in the first semester. Each sheet pairs the syntax with a dry run, so you can predict output instead of memorising code.
Notebook — 20 pages
Page 1
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
1. Why Control Structures Exist
Without control statements a program is a straight line: every statement runs once, in order. Real problems need choices and repetition, and structured programming allows exactly three ways to arrange them.
Sequence
Statements execute one after another, top to bottom.
Selection
A condition decides which block runs: if, if-else, switch.
Iteration
A block repeats while a condition holds: while, do-while, for.
Page 2
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
2. Conditions — Relational and Logical Operators
C has no boolean type in C89. A condition evaluates to an int: 1 for true, 0 for false. Any non-zero value counts as true, which is the source of several classic bugs.
Expression
Reads as
Value when a = 5, b = 3
a > b
a greater than b
1
a == b
a equal to b
0
a != b
a not equal to b
1
a > 0 && b > 0
both positive
1
a < 0 || b < 0
at least one negative
0
!(a > b)
not (a greater)
0
Page 3
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
3. if and if-else
Both forms, side by side
if (marks >= 40)
printf("Pass\n");
if (n % 2 == 0)
printf("Even\n");
else
printf("Odd\n");
Braces are optional for a single statement but required for a block — always write them.
No semicolon after if (cond); a stray one makes the body an empty statement.
else always binds to the nearest unmatched if, whatever your indentation suggests.
Page 4
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
4. else-if Ladder and Nested if
Grade from marks
if (m >= 90) printf("O");
else if (m >= 80) printf("A");
else if (m >= 70) printf("B");
else if (m >= 40) printf("C");
else printf("F");
Order matters: test the narrowest range first, or every mark above 40 prints C.
Exactly one branch of a ladder executes — the first true one.
A nested if is an if inside another if; use it when the second test only makes sense if the first passed.
Nested — largest of three
if (a > b) {
if (a > c) printf("%d", a);
else printf("%d", c);
} else {
if (b > c) printf("%d", b);
else printf("%d", c);
}
Page 5
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
5. switch — case Statement
Simple calculator
switch (op) {
case '+': printf("%d", a + b); break;
case '-': printf("%d", a - b); break;
case '*': printf("%d", a * b); break;
case '/':
if (b != 0) printf("%d", a / b);
else printf("Cannot divide by zero");
break;
default: printf("Invalid operator");
}
switch versus else-if ladder
Point
switch
else-if ladder
Tests
Equality with constants only
Any condition, including ranges
Expression type
int or char
Any type
Duplicate labels
Not allowed
Not applicable
Speed
Jump table, often faster
Sequential tests
Page 6
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
6. Conditional Operator and goto
Ternary operator
big = (a > b) ? a : b;
printf("%s\n", (n % 2 == 0) ? "Even" : "Odd");
/* nested — readable only in small doses */
grade = (m >= 80) ? 'A' : (m >= 40) ? 'C' : 'F';
?: is the only ternary (three-operand) operator in C.
It is an expression, so it can appear inside printf or an assignment.
goto label; jumps unconditionally; the label sits in the same function.
Accepted use of goto: breaking out of deeply nested loops on an error.
Page 7
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
7. Loops — The Three Forms
while
Entry controlled
Test first, then body
Body may run zero times
do-while
Exit controlled
Body first, then test
Body runs at least once
for
Entry controlled
Init, test, update in one line
Best when count is known
Every correct loop has three parts, whichever form you choose: an initialisation, a condition that eventually becomes false, and an update that moves towards it. A missing update is the definition of an infinite loop.
Page 8
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
8. while Loop
Sum of digits of a number
int n = 472, sum = 0;
while (n > 0) {
sum = sum + n % 10; /* last digit */
n = n / 10; /* drop it */
}
printf("%d", sum); /* 13 */
Dry run — trace every iteration
Iteration
n
n % 10
sum
1
472
2
2
2
47
7
9
3
4
4
13
exit
0
—
13
Page 9
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
9. do-while Loop
Menu that must appear once
int choice;
do {
printf("1 Add 2 View 3 Exit: ");
scanf("%d", &choice);
/* handle the choice here */
} while (choice != 3);
Point
while
do-while
Condition tested
Before the body
After the body
Minimum executions
0
1
Semicolon
Not after the closing brace
Required after while(cond)
Typical use
Unknown count, may skip
Menus, input validation
With i = 10 and the condition i < 5, while prints nothing while do-while prints once. That single difference is the whole comparison question.
Page 10
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
10. for Loop and Its Variations
Standard and unusual forms
for (i = 1; i <= 5; i++) printf("%d ", i); /* 1 2 3 4 5 */
for (i = 10; i >= 1; i -= 2) printf("%d ", i); /* 10 8 6 4 2 */
for (i = 0, j = 9; i < j; i++, j--) { } /* two counters */
for (;;) { break; } /* infinite, exited by break */
1.Initialisation runs once, before the first test.
2.Condition is tested before every iteration.
3.Body executes when the condition is true.
4.Update runs after the body, then back to step 2.
Page 11
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
11. Nested Loops and Pattern Printing
Right-angled triangle of stars
for (i = 1; i <= 4; i++) {
for (j = 1; j <= i; j++)
printf("* ");
printf("\n");
}
/* *
* *
* * *
* * * * */
Outer loop counts rows, inner loop counts columns in that row.
Total iterations of the inner body = sum of the inner counts, not rows × columns, when the inner limit depends on i.
The newline belongs to the outer loop; putting it inside the inner loop breaks every pattern question.
Multiplication table 1–3
for (i = 1; i <= 3; i++) {
for (j = 1; j <= 3; j++)
printf("%4d", i * j);
printf("\n");
}
Page 12
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
12. break, continue and exit
break
Leaves the innermost loop or switch immediately.
continue
Skips the rest of this iteration and goes to the next test/update.
exit(0)
Ends the whole program; needs stdlib.h.
Output prediction
for (i = 1; i <= 5; i++) {
if (i == 3) continue;
if (i == 5) break;
printf("%d ", i);
}
/* prints 1 2 4 */
Page 13
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
13. One-Dimensional Arrays
An array is a collection of elements of the same type stored in contiguous memory, reached by a single name and an index that starts at 0.
Declaration, initialisation, access
int marks[5]; /* 5 ints, values garbage */
int a[5] = {10, 20, 30, 40, 50}; /* full initialisation */
int b[5] = {1, 2}; /* rest become 0 */
int c[] = {4, 8, 12}; /* size inferred as 3 */
printf("%d", a[0]); /* first element, 10 */
printf("%d", a[4]); /* last element, 50 */
Valid indices are 0 to size − 1; a[5] in the example above is out of bounds.
C does not check bounds — an out-of-range write corrupts other memory silently.
The array name alone stands for the address of its first element.
Page 14
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
14. Array Traversal — Sum, Maximum, Search
Three standard loops
int sum = 0;
for (i = 0; i < n; i++) sum += a[i];
float avg = (float) sum / n;
int big = a[0];
for (i = 1; i < n; i++) if (a[i] > big) big = a[i];
int pos = -1; /* linear search for key */
for (i = 0; i < n; i++)
if (a[i] == key) { pos = i; break; }
Initialise the maximum with a[0], never with 0 — that fails for all-negative data.
Cast before dividing for the average, or integer division loses the fraction.
Linear search: worst case n comparisons; binary search needs sorted data and takes about log₂n.
Page 15
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
15. Sorting — Bubble and Selection
Bubble sort, ascending
for (i = 0; i < n - 1; i++)
for (j = 0; j < n - 1 - i; j++)
if (a[j] > a[j + 1]) {
t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
}
Bubble sort pass 1 on 5 1 4 2
Compare
Array after
5 > 1 swap
1 5 4 2
5 > 4 swap
1 4 5 2
5 > 2 swap
1 4 2 5
After each pass the largest remaining element is in place, which is why the inner limit shrinks by i. Selection sort instead finds the minimum of the unsorted part and swaps it into position — same O(n²) cost, far fewer swaps.
Page 16
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
16. Two-Dimensional Arrays and Matrices
Declaration and matrix addition
int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
s[i][j] = a[i][j] + b[i][j];
m[i][j] — first index is the row, second the column; both start at 0.
Stored in row-major order: m[0][0], m[0][1], m[0][2], m[1][0] …
Addition needs identical orders; multiplication needs columns of A = rows of B.
Multiplication uses three nested loops, with sum reset to 0 before the innermost one.
Page 17
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
17. Strings — Storage and Input
A string in C is a char array terminated by the null character '\ '. The terminator is what every library function looks for, so a char array without it is not a string.
scanf("%s", name) stops at the first space and needs no & (an array name is already an address).
For a full line use fgets(name, sizeof name, stdin) — gets() has no length limit and is removed from modern C.
Print with printf("%s", name) or puts(name).
Page 18
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
18. String Library Functions (string.h)
Function
Purpose
Returns
strlen(s)
Characters before '\ '
Length, excluding the terminator
strcpy(d, s)
Copy s into d
Address of d
strcat(d, s)
Append s to d
Address of d
strcmp(a, b)
Compare alphabetically
0 equal, <0 a first, >0 b first
strrev(s)
Reverse in place (non-standard)
Address of s
strstr(a, b)
Find b inside a
Address of match, or NULL
strlen("Hello") is 5, but the array needs 6 bytes.
s1 = s2 does not copy a string; only strcpy does.
if (s1 == s2) compares addresses; use strcmp(s1, s2) == 0 for content.
The destination must be large enough — strcat into a full array overflows it.
Page 19
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
19. String Programs Without the Library
Length, reverse and palindrome check
int len = 0;
while (s[len] != '\ ') len++; /* own strlen */
for (i = 0, j = len - 1; i < j; i++, j--) {
char t = s[i]; s[i] = s[j]; s[j] = t; /* reverse */
}
int pal = 1; /* palindrome */
for (i = 0, j = len - 1; i < j; i++, j--)
if (s[i] != s[j]) { pal = 0; break; }
Counting vowels: compare against 'a','e','i','o','u' in both cases, or use tolower() from ctype.h.
Counting words: increment when the current character is not a space and the previous one was.
'A' is 65 and 'a' is 97, so s[i] − 32 converts lower case to upper case.
Page 20
Wink Notes
B.Tech CSE — 1st Semester
Programming for Problem Solving in C
— Unit - 2 —
20. Frequent Errors and Revision Checklist
Mistake
Effect
= instead of == in a condition
Condition always true
Semicolon after for(...)
Empty body, loop does nothing
Missing break in switch
Unintended fall-through
Index up to n instead of n − 1
Reads past the array
Missing '\ ' in a char array
strlen and printf read garbage
continue before i++ in while
Infinite loop
Can you compare while and do-while in four points with an example?
Can you dry run a nested loop and predict the exact printed pattern?
Can you write bubble sort and show pass 1 on given data?
Can you explain why strcmp is needed instead of ==?
Can you write your own strlen, strrev and palindrome check?