Unit 2 of 4 · BCA Sem 1

Unit 2: Input/output and control statements

Problem Solving Techniques notes · PTU syllabus (UGSEC2501)

4 min read6 topics16 exam questions
On this page
  1. Unit summary
  2. Formatted input and output
  3. Unformatted input and output
  4. Decision making: if, if–else and switch
  5. Loops: while, do–while and for
  6. Nested loops
  7. break and continue
  8. Key terms
  9. Quick revision
  10. Important questions

Unit summary

Programs read data, make decisions and repeat actions. This unit covers formatted and unformatted input and output, the decision statements if, if–else and switch, the loops while, do–while and for, nested loops, and the jump statements break and continue.

After this unit you can

  • Use printf and scanf with format specifiers, width and precision
  • Use getchar, putchar, gets and puts
  • Write programs with if, if-else, nested if, else-if ladder and switch
  • Write programs with while, do-while, for and nested loops
  • Use break and continue

PTU syllabus topics

  • Formatted and unformatted input/output
  • while
  • do-while and for statements
  • nested loops
  • if-else
  • switch
  • break-continue statements
1

Topic 1

Formatted input and output

c#include <stdio.h>
int main(void) {
    int n; float f; char c;
    printf("Enter an integer, a real number and a character: ");
    scanf("%d %f %c", &n, &f, &c);
    printf("n = %d, f = %.2f, c = %c\n", n, f, c);
    return 0;
}

Format specifiers

Meaning
%d or %iSigned decimal integer
%uUnsigned integer
%fFloat (printf), %lf for double in scanf
%e and %gExponential and shortest form
%cSingle character
%sString
%x and %oHexadecimal and octal
%ldLong integer
%pPointer (address)
%%Prints the percent sign

printf formatting options

Effect
%5dWidth 5, right aligned
%-5dWidth 5, left aligned
%05dPad with zeros: 00042
%.2fTwo digits after the decimal point
%8.3fWidth 8, three decimals
%+dShow the sign
\n \tNewline and tab inside the format string
Key termsscanf rules
Address operator
Use & before every non-string variable — &n
Return value
Number of items read
Whitespace
%d and %f skip leading white space, %c does not — use " %c"
Strings
scanf("%s", name) stops at the first space
Reading with width
scanf("%4d", &n) reads at most 4 digits

Example

printf("%5.2f|%-6d|%06d", 3.14159, 42, 42) prints " 3.14|42 |000042".

2

Topic 2

Unformatted input and output

Character and string I/O functions

Description
getchar()Reads one character from the keyboard (waits for Enter)
putchar(c)Writes one character
getch() and getche()Read without Enter (conio.h, non-standard)
gets(str) and fgets(str, n, stdin)Read a line (use fgets — gets is unsafe)
puts(str)Writes a string and a newline
c#include <stdio.h>
int main(void) {
    char ch, name[30];
    printf("Press a key: ");
    ch = getchar();
    putchar(ch); putchar('\n');
    getchar();                       /* absorb the newline */
    printf("Name: ");
    fgets(name, sizeof name, stdin);
    puts(name);
    return 0;
}
ComparisonFormatted vs unformatted I/O
Formatted (printf, scanf)
Unformatted (getchar, putchar, gets, puts)

Data

Any data type

Characters and strings only

Control

Width, precision, alignment

No formatting

Speed

Slower

Faster

Example

Reading a full name: for the input "Ravi Kumar", scanf("%s", name) stores only "Ravi", because %s stops at the first space. fgets(name, 30, stdin) reads the whole line. getchar() reads one character and putchar(ch) prints one.

Exam tip

Avoid gets(): it does not check the size of the array. Use fgets() instead.

3

Topic 3

Decision making: if, if–else and switch

Flowchartif-else structure
YesNoStartCondition true ?Statements of the if blockStatements of the elseblockEnd

Forms of the if statement

Syntax
Simple ifif (cond) { … }
if–elseif (cond) { … } else { … }
Nested ifAn if inside another if
else–if ladderif … else if … else if … else
Conditional operatorcond ? a : b
c#include <stdio.h>
int main(void) {
    int marks;
    scanf("%d", &marks);
    if (marks >= 90)       printf("Grade A\n");
    else if (marks >= 75)  printf("Grade B\n");
    else if (marks >= 40)  printf("Grade C\n");
    else                   printf("Fail\n");
    return 0;
}
Flowchartelse-if ladder (grade)
YesNoYesNoYesNoStartRead marksmarks >= 90 ?Print "Grade A"marks >= 75 ?Print "Grade B"marks >= 40 ?Print "Grade C"Print "Fail"Stop

The switch statement

cswitch (choice) {
    case 1:  printf("Add\n");      break;
    case 2:  printf("Subtract\n"); break;
    case 3:  printf("Multiply\n"); break;
    default: printf("Invalid\n");
}
Key termsRules of switch
Expression type
int or char only
Case labels
Unique constants
break
Leaves the switch — without it execution falls through to the next case
default
Optional; runs when no case matches
Use
Menu-driven programs
Limitation
No ranges or float conditions
Comparisonif–else vs switch
if–else
switch

Conditions

Any relational or logical expression

Equality with constants only

Data types

Any

int or char

Speed and readability

Slower for many branches

Faster and cleaner

Ranges

Possible

Not possible

c/* simple calculator using switch */
char op; float a, b;
scanf("%f %c %f", &a, &op, &b);
switch (op) {
    case '+': printf("%.2f\n", a + b); break;
    case '-': printf("%.2f\n", a - b); break;
    case '*': printf("%.2f\n", a * b); break;
    case '/': if (b != 0) printf("%.2f\n", a / b); else printf("Divide by zero\n"); break;
    default:  printf("Invalid operator\n");
}
4

Topic 4

Loops: while, do–while and for

ComparisonLoop statements
Syntax
Test is made

while

while (cond) { … }

Before each iteration — entry-controlled

do–while

do { … } while (cond);

After each iteration — runs at least once

for

for (init; cond; update) { … }

Before each iteration — entry-controlled

ProcessWorking of the for loop
  1. 1

    Initialisation — executed once

  2. 2

    Condition is tested

  3. 3

    If true — body executes

  4. 4

    Update (increment)

  5. 5

    Condition tested again

  6. 6

    If false — loop ends

c/* multiplication table of n */
for (i = 1; i <= 10; i++)
    printf("%d x %d = %d\n", n, i, n * i);

/* sum of digits using while */
sum = 0;
while (n > 0) { sum += n % 10; n /= 10; }

/* menu repeated at least once */
do { printf("1.Add 2.Exit: "); scanf("%d", &ch); } while (ch != 2);
FlowchartReverse of a number using a while loop
YesNoStartRead nrev = 0n > 0 ?d = n mod 10rev = rev × 10 + dn = n / 10Print revStop

Choosing a loop

Use when
forThe number of repetitions is known
whileRepetition depends on a condition that may be false at the start
do–whileThe body must run at least once (menus, input validation)

Exam tip

Infinite loops — for(;;) or while(1) — need a break inside. A stray semicolon after for(…) or while(…) makes an empty loop.

Example

Choosing a loop: to print 1 to 10, use for (count known); to read numbers until the user enters 0, use while; to show a menu at least once, use do–while.

Exam tip

do–while always runs at least once.

5

Topic 5

Nested loops

A loop inside another loop: the inner loop completes all its iterations for every iteration of the outer loop.

c/* right-angled triangle pattern */
for (i = 1; i <= 4; i++) {
    for (j = 1; j <= i; j++)
        printf("* ");
    printf("\n");
}
*
* *
* * *
* * * *

Common patterns

Idea
Triangle of starsInner loop runs i times
Number pyramidSpaces loop then number loop
Floyd's triangleA counter increases across rows
Multiplication tablesOuter loop for the number, inner for the multiplier
Prime numbers in a rangeOuter loop for numbers, inner loop to test divisors

Example

Outer loop 3 times and inner loop 4 times — the inner body executes 3 × 4 = 12 times.

6

Topic 6

break and continue

Comparisonbreak vs continue
break
continue

Effect

Terminates the loop (or switch) at once

Skips the rest of this iteration and goes to the next

Used in

Loops and switch

Loops only

Example

Stop searching when found

Skip even numbers

cfor (i = 1; i <= 10; i++) {
    if (i == 5) break;        /* prints 1 2 3 4 */
    printf("%d ", i);
}
for (i = 1; i <= 10; i++) {
    if (i % 2 == 0) continue; /* prints 1 3 5 7 9 */
    printf("%d ", i);
}
Key termsRelated statements
goto
Jumps to a label — avoid, it breaks structured flow
return
Leaves the function
exit(n)
Ends the whole program

Example

Predict the output: for (i = 1; i <= 5; i++) { if (i == 3) continue; printf("%d ", i); } prints 1 2 4 5, because continue skips only that pass. Replacing continue with break prints 1 2, because break leaves the loop.

Key terms

Format specifier
Code such as %d that tells printf and scanf the data type
scanf
Standard function to read formatted input
getchar and putchar
Read and write one character
if–else
Two-way decision statement
switch
Multi-way selection on an integer or character value
while loop
Entry-controlled loop
do–while loop
Exit-controlled loop that runs at least once
Nested loop
Loop inside another loop
break
Statement that exits a loop or switch
continue
Statement that skips to the next loop iteration

Quick revision

  • printf/scanf: %d, %f, %c, %s; scanf needs &; width and precision with %5.2f.
  • getchar, putchar, gets/fgets, puts for unformatted I/O.
  • if, if–else, nested if, else–if ladder, switch (break, default).
  • for (known count), while (entry), do–while (at least once).
  • Nested loop body runs outer × inner times.
  • break leaves the loop; continue skips one iteration.

Important exam questions

Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).

Short-answer questions

  1. Q1.What is the use of & in scanf?
  2. Q2.Differentiate between getchar() and scanf("%c").
  3. Q3.Write the syntax of the for loop.
  4. Q4.Differentiate between while and do–while.
  5. Q5.What is fall-through in switch?
  6. Q6.Differentiate between break and continue.
  7. Q7.What is the output of printf("%5.2f", 3.14159)?
  8. Q8.When is a do–while loop preferred?
  9. Q9.How many times does the inner statement run in two nested loops of 5 and 3 iterations?
  10. Q10.Why is gets unsafe?

Long-answer questions

  1. Q1.Explain formatted and unformatted input and output functions with examples.
  2. Q2.Explain the decision statements of C with examples and flowcharts.
  3. Q3.Write a menu-driven program using switch.
  4. Q4.Explain the loops of C and write a program for the sum of digits and the Fibonacci series.
  5. Q5.Write programs to print triangle patterns using nested loops.
  6. Q6.Explain break and continue with examples.

Stuck on this unit?

Message SBS on WhatsApp for help with Problem Solving Techniques, or to ask about studying BCA at Synetic.

WhatsApp us