Unit 2: Input/output and control statements
Problem Solving Techniques notes · PTU syllabus (UGSEC2501)
On this page
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
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 %i | Signed decimal integer |
| %u | Unsigned integer |
| %f | Float (printf), %lf for double in scanf |
| %e and %g | Exponential and shortest form |
| %c | Single character |
| %s | String |
| %x and %o | Hexadecimal and octal |
| %ld | Long integer |
| %p | Pointer (address) |
| %% | Prints the percent sign |
printf formatting options
| Effect | |
|---|---|
| %5d | Width 5, right aligned |
| %-5d | Width 5, left aligned |
| %05d | Pad with zeros: 00042 |
| %.2f | Two digits after the decimal point |
| %8.3f | Width 8, three decimals |
| %+d | Show the sign |
| \n \t | Newline and tab inside the format string |
- 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".
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;
}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.
Topic 3
Decision making: if, if–else and switch
Forms of the if statement
| Syntax | |
|---|---|
| Simple if | if (cond) { … } |
| if–else | if (cond) { … } else { … } |
| Nested if | An if inside another if |
| else–if ladder | if … else if … else if … else |
| Conditional operator | cond ? 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;
}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");
}- 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
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");
}Topic 4
Loops: while, do–while and for
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
- 1
Initialisation — executed once
- 2
Condition is tested
- 3
If true — body executes
- 4
Update (increment)
- 5
Condition tested again
- 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);Choosing a loop
| Use when | |
|---|---|
| for | The number of repetitions is known |
| while | Repetition depends on a condition that may be false at the start |
| do–while | The 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.
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 stars | Inner loop runs i times |
| Number pyramid | Spaces loop then number loop |
| Floyd's triangle | A counter increases across rows |
| Multiplication tables | Outer loop for the number, inner for the multiplier |
| Prime numbers in a range | Outer 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.
Topic 6
break and 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);
}- 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
- Q1.What is the use of & in scanf?
- Q2.Differentiate between getchar() and scanf("%c").
- Q3.Write the syntax of the for loop.
- Q4.Differentiate between while and do–while.
- Q5.What is fall-through in switch?
- Q6.Differentiate between break and continue.
- Q7.What is the output of printf("%5.2f", 3.14159)?
- Q8.When is a do–while loop preferred?
- Q9.How many times does the inner statement run in two nested loops of 5 and 3 iterations?
- Q10.Why is gets unsafe?
Long-answer questions
- Q1.Explain formatted and unformatted input and output functions with examples.
- Q2.Explain the decision statements of C with examples and flowcharts.
- Q3.Write a menu-driven program using switch.
- Q4.Explain the loops of C and write a program for the sum of digits and the Fibonacci series.
- Q5.Write programs to print triangle patterns using nested loops.
- 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.
