Control structures, arrays and strings — Unit 2 Notes (Programming for Problem Solving in C)

BCS101 · Unit 2

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.

Next — Page 2 — Conditions: relational and logical operators

1 of 20

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.

ExpressionReads asValue when a = 5, b = 3
a > ba greater than b1
a == ba equal to b0
a != ba not equal to b1
a > 0 && b > 0both positive1
a < 0 || b < 0at least one negative0
!(a > b)not (a greater)0

Next — Page 3 — if and if-else

2 of 20

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.

Next — Page 4 — else-if ladder and nested if

3 of 20

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);
}

Next — Page 5 — switch-case

4 of 20

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
Pointswitchelse-if ladder
TestsEquality with constants onlyAny condition, including ranges
Expression typeint or charAny type
Duplicate labelsNot allowedNot applicable
SpeedJump table, often fasterSequential tests

Next — Page 6 — conditional operator and goto

5 of 20

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.

Next — Page 7 — loops overview

6 of 20

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.

Next — Page 8 — while loop with dry run

7 of 20

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
Iterationnn % 10sum
147222
24779
34413
exit013

Next — Page 9 — do-while loop

8 of 20

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);
Pointwhiledo-while
Condition testedBefore the bodyAfter the body
Minimum executions01
SemicolonNot after the closing braceRequired after while(cond)
Typical useUnknown count, may skipMenus, 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.

Next — Page 10 — for loop and its variations

9 of 20

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. 1.Initialisation runs once, before the first test.
  2. 2.Condition is tested before every iteration.
  3. 3.Body executes when the condition is true.
  4. 4.Update runs after the body, then back to step 2.

Next — Page 11 — nested loops and pattern printing

10 of 20

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");
}

Next — Page 12 — break, continue and exit

11 of 20

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 */

Next — Page 13 — one-dimensional arrays

12 of 20

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.

Next — Page 14 — array traversal: sum, maximum, search

13 of 20

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.

Next — Page 15 — sorting: bubble and selection

14 of 20

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
CompareArray after
5 > 1 swap1 5 4 2
5 > 4 swap1 4 5 2
5 > 2 swap1 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.

Next — Page 16 — two-dimensional arrays and matrices

15 of 20

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.

Next — Page 17 — strings: storage and input

16 of 20

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.

Four ways to hold "Hi"
char s1[10] = "Hi";                 /* H i \ + 7 unused */
char s2[] = "Hi";                   /* size 3            */
char s3[3] = {'H', 'i', '\'};      /* explicit          */
char *s4 = "Hi";                    /* pointer to literal */
  • 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).

Next — Page 18 — string library functions

17 of 20

Page 18

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 2

18. String Library Functions (string.h)

FunctionPurposeReturns
strlen(s)Characters before '\'Length, excluding the terminator
strcpy(d, s)Copy s into dAddress of d
strcat(d, s)Append s to dAddress of d
strcmp(a, b)Compare alphabetically0 equal, <0 a first, >0 b first
strrev(s)Reverse in place (non-standard)Address of s
strstr(a, b)Find b inside aAddress 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.

Next — Page 19 — string programs without the library

18 of 20

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.

Next — Page 20 — errors and revision checklist

19 of 20

Page 20

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 2

20. Frequent Errors and Revision Checklist

MistakeEffect
= instead of == in a conditionCondition always true
Semicolon after for(...)Empty body, loop does nothing
Missing break in switchUnintended fall-through
Index up to n instead of n − 1Reads past the array
Missing '\' in a char arraystrlen and printf read garbage
continue before i++ in whileInfinite 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?

Next — Unit 3 — Functions, recursion and storage classes

20 of 20

Continue in this subject