Unit 1: C programming fundamentals to file handling
Problem Solving Techniques Laboratory notes · PTU syllabus (UGSEC2502)
On this page
Unit summary
This lab turns the theory of Problem Solving Techniques into working C programs. You progress from simple input/output and arithmetic to decisions, loops, functions, arrays, strings, pointers, structures and finally files.
The notes below give the logic and a model program for each family of lab exercises, plus the viva questions examiners ask most often.
After this unit you can
- Write, compile and run C programs and fix common errors
- Use conditions, loops and switch to solve classic lab problems
- Use functions, arrays, strings, pointers and structures in programs
- Read and write data files
PTU syllabus topics
- Basic I/O and arithmetic programs
- ASCII value and data type size programs
- conditional programs (largest/greater of numbers, even/odd, prime check)
- loop-based programs (multiplication tables, simple calculator using switch-case)
- function-based programs (largest of three, factorial, first 20 squares)
- matrix addition
- string functions (length, copy, compare, reverse)
- pointer-based programs
- structure/union memory demonstration
- student I-card using structures
- file read/write programs (employee details)
Topic 1
How to approach every lab program
- 1
Understand the problem
Inputs and expected output
- 2
Write the algorithm or flowchart
- 3
Type the program
Indent and comment it
- 4
Compile
gcc prog.c -o prog
- 5
Test
Normal, boundary and invalid inputs
- 6
Record in the practical file
Aim, code, output
Exam tip
In the practical exam you are marked on the program, the output and the viva. Keep a neat practical file with the aim, program and output for every experiment.
Example
Dry run before you type: for a program that finds the sum of digits of 123, trace it on paper. Pass 1: digit = 3, sum = 3, n = 12. Pass 2: digit = 2, sum = 5, n = 1. Pass 3: digit = 1, sum = 6, n = 0. The loop ends and prints 6.
Topic 2
Basic I/O, ASCII values and data type sizes
c#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
printf("ASCII value of %c = %d\n", ch, ch);
printf("int: %zu, float: %zu, double: %zu, char: %zu bytes\n",
sizeof(int), sizeof(float), sizeof(double), sizeof(char));
return 0;
}Printing a char with %d shows its ASCII code. sizeof gives the size of a type in bytes.
Example
Values to remember for the viva: 'A' is 65, 'a' is 97 and '0' is 48, so a lowercase letter is its uppercase letter plus 32. On a typical 32-bit or 64-bit compiler, sizeof(char) is 1, sizeof(int) is 4, sizeof(float) is 4 and sizeof(double) is 8 bytes.
Topic 3
Conditional programs
- Even or odd:
if (n % 2 == 0)→ even, else odd. - Largest of three: compare with nested if or
max = (a > b) ? (a > c ? a : c) : (b > c ? b : c); - Prime check: a number n > 1 is prime if no number from 2 to √n divides it.
cint n, i, isPrime = 1;
scanf("%d", &n);
if (n < 2) isPrime = 0;
for (i = 2; i * i <= n; i++)
if (n % i == 0) { isPrime = 0; break; }
printf(isPrime ? "Prime" : "Not prime");Example
Leap year: if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) — 2024 is a leap year, 1900 is not, and 2000 is.
Exam tip
Test boundary values such as 1900 and 2000.
Topic 4
Loop and switch programs
- Multiplication table:
for (i = 1; i <= 10; i++) printf("%d x %d = %d\n", n, i, n * i); - Simple calculator with switch:
cchar op; float a, b;
scanf("%f %c %f", &a, &op, &b);
switch (op) {
case '+': printf("%.2f", a + b); break;
case '-': printf("%.2f", a - b); break;
case '*': printf("%.2f", a * b); break;
case '/': if (b != 0) printf("%.2f", a / b); else printf("Divide by zero"); break;
default: printf("Invalid operator");
}Example
Sum of digits: while (n > 0) { sum += n % 10; n /= 10; } — for 472, the sum is 13.
Exam tip
Know the difference between break and continue.
Topic 5
Function programs
- Factorial using a function (iterative or recursive), largest of three using a function, and first 20 squares using a function that returns n × n.
clong factorial(int n) {
long f = 1;
for (int i = 2; i <= n; i++) f *= i;
return f;
}Example
Recursion traced: fact(4) returns 4 × fact(3) = 4 × 3 × fact(2) = 4 × 3 × 2 × fact(1) = 24. Each call waits for the next, and the base case if (n <= 1) return 1; stops the chain.
Exam tip
Every recursive function needs a base case. Without it the calls never end and the program crashes with a stack overflow.
Topic 6
Arrays and strings
- Matrix addition: read two m × n matrices and add them with nested loops:
c[i][j] = a[i][j] + b[i][j]; - String functions: use
strlen,strcpy,strcmpand a reverse (withstrrevor a manual swap loop).
c/* Reverse a string without strrev */
int len = strlen(s);
for (int i = 0; i < len / 2; i++) {
char t = s[i]; s[i] = s[len - 1 - i]; s[len - 1 - i] = t;
}Example
Palindrome check: copy the string, reverse the copy, and compare with strcmp — "madam" returns 0 (palindrome), "hello" does not.
Exam tip
strcmp returns 0 when strings are equal.
Topic 7
Pointers, structures, unions and files
- Pointer program: print a variable's value and address using
&and*; swap with pointers. - Structure vs union memory: print
sizeofof a struct and a union with the same members to show the difference. - Student I-card: a structure with name, roll number, course and address, printed in an ID-card layout.
- Employee file: write employee records with
fprintfto a file and read them back withfscanf.
cFILE *fp = fopen("emp.txt", "w");
fprintf(fp, "%d %s %.2f\n", id, name, salary);
fclose(fp);Example
Swap with pointers: void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; } called as swap(&x, &y) really swaps x and y.
Exam tip
Always check fopen for NULL before using a file.
Key terms
- Compiler
- Software that translates C source code into machine code
- Syntax error
- A mistake in the rules of the language, found at compile time
- Logical error
- A mistake in the logic, giving wrong output without an error message
- sizeof
- An operator that returns the size of a type or variable in bytes
- Practical file
- The record of aim, program and output for each experiment
Quick revision
- %d on a char prints its ASCII value.
- Test primes only up to √n.
- Always add break in each switch case and check divide by zero.
- Reverse a string by swapping from both ends.
- sizeof(struct) ≥ sum of members; sizeof(union) = largest member.
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 difference between a syntax error and a logical error?
- Q2.How do you print the ASCII value of a character?
- Q3.Why do we check divisors only up to √n in a prime program?
- Q4.What is the output of sizeof(char)?
- Q5.Why is fclose() needed?
- Q6.How is a structure different from a union in memory?
Long-answer questions
- Q1.Write a program to check whether a number is prime and explain its logic.
- Q2.Write a menu-driven calculator using switch-case.
- Q3.Write a program to add two matrices and display the result.
- Q4.Write a program to create a student I-card using a structure.
- Q5.Write a program to write and read employee details using a file.
Stuck on this unit?
Message SBS on WhatsApp for help with Problem Solving Techniques Laboratory, or to ask about studying BCA at Synetic.
