Unit 1: C programming implementation
Software Lab-I (Programming in C) notes · PTU syllabus (BSIT105/BSBC105)
On this page
- Unit summary
- How to approach every lab program
- Data types, scope and formatted and unformatted I/O
- Operators including bitwise operators
- Decision-making programs
- Loop and switch programs
- Function and recursion programs
- Preprocessor directives and header files
- Arrays and string functions
- Pointers and file creation and editing
- Key terms
- Quick revision
- Important questions
Unit summary
This lab puts Programming in C into practice: keywords and identifiers, data types and scope, formatted and unformatted I/O, all operator families including bitwise, decision-making constructs, loops, functions and recursion, preprocessor directives and header files, arrays and string functions, pointers, and creating and editing files. Each section gives the logic and a model program, with viva questions examiners ask most often.
After this unit you can
- Write programs using data types, operators and formatted and unformatted I/O
- Use decision-making constructs and loops
- Write functions, recursive functions and preprocessor macros
- Use arrays, strings, pointers and files
PTU syllabus topics
- Keywords and identifiers
- variable/constant data types and scope
- formatted and non-formatted I/O
- arithmetic/logical/conditional/assignment/bitwise operators
- decision-making constructs (switch, if-else, nested if)
- loops (while, do-while, for)
- function definition/declaration/parameterization/recursion
- preprocessor directives
- standard header files
- array declarations and string functions
- pointer declarations
- file creation and editing
Topic 1
How to approach every lab program
A methodical approach saves time in the lab and in the practical exam, and the viva usually tests whether you understand your own 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
Planning before coding: for "find the largest of three numbers", first note the inputs (a, b, c) and output (largest), write a short algorithm, then code it, and test with (5, 9, 2), (7, 7, 3) and negative numbers.
Exam tip
Always test with normal, boundary and unusual inputs, and be ready to explain each line in the viva.
Topic 2
Data types, scope and formatted and unformatted I/O
Scope decides where a variable can be used: local variables exist only inside their block or function; global variables are declared outside all functions and are available everywhere.
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
Scope in a program: int count = 0; declared above main is global and can be used in every function; int i; declared inside main is local to main. Using getchar() reads one character without a format code, while scanf("%c", &ch) reads it with one.
Exam tip
Mention the four storage classes: auto, register, static and extern.
Topic 3
Operators including bitwise operators
c#include <stdio.h>
int main(void) {
int a = 12, b = 10; /* 1100 and 1010 in binary */
printf("a & b = %d\n", a & b); /* 8 (1000) */
printf("a | b = %d\n", a | b); /* 14 (1110) */
printf("a ^ b = %d\n", a ^ b); /* 6 (0110) */
printf("~a = %d\n", ~a); /* -13 */
printf("a << 1 = %d\n", a << 1); /* 24 */
printf("a >> 2 = %d\n", a >> 2); /* 3 */
int max = (a > b) ? a : b; /* conditional operator */
printf("max = %d\n", max);
return 0;
}- Scope: a variable declared inside a block is local to it; a variable declared outside all functions is global.
Topic 4
Decision-making programs
Decision-making programs check conditions with if, if-else, nested if or switch and choose what to print.
- 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) printf("Leap year"); else printf("Not a leap year"); — 2024 is a leap year, 1900 is not, and 2000 is.
Exam tip
Test boundary values — 1900 and 2000 are the classic leap-year test cases.
Topic 5
Loop and switch programs
Loops repeat a block: for (count known), while (condition checked first) and do-while (runs at least once). break exits a loop or switch; continue skips to the next iteration.
- 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 n = 472 the loop adds 2, 7 and 4, giving sum = 13.
Exam tip
Know the difference between while and do-while: do-while always runs at least once.
Topic 6
Function and recursion programs
A recursive function calls itself with a smaller problem until it reaches a base case.
- 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
Recursive factorial: int fact(int n) { if (n <= 1) return 1; return n * fact(n - 1); } — fact(5) calls fact(4), fact(3), fact(2) and fact(1), and returns 5 × 4 × 3 × 2 × 1 = 120.
Exam tip
Without a base case, recursion never stops and the program crashes with a stack overflow.
Topic 7
Preprocessor directives and header files
Lab programs use #include for standard and user header files and #define for constants and macros.
c#include <stdio.h>
#include "area.h" /* user header containing: #define PI 3.14159 */
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int main(void) {
printf("Square of 5 = %d\n", SQUARE(5));
printf("Max = %d\n", MAX(7, 3));
#ifdef PI
printf("Area of circle r = 2: %.2f\n", PI * SQUARE(2));
#endif
return 0;
}Example
A user header file: save #define PI 3.14159 in area.h, then in the main program write #include "area.h" and printf("%.2f", PI * r * r); — for r = 2 the output is 12.57.
Exam tip
Keep the user header file in the same folder as the program.
Topic 8
Arrays and string functions
Array programs use loops to read, process and print elements; string programs use string.h functions or loops that stop at '\0'.
- 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 with strrev (or a loop), and compare with strcmp. For "madam" the result is 0, so it is a palindrome; for "hello" it is not.
Exam tip
If strrev is not available in your compiler, reverse the string with a loop from both ends.
Topic 9
Pointers and file creation and editing
File programs open a file with fopen, write or read with fprintf/fscanf or fputc/fgetc, and close it with fclose.
- 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
Counting characters in a file: open the file in "r" mode and run while ((ch = fgetc(fp)) != EOF) count++; — the program prints the number of characters, then closes the file.
Exam tip
Check if (fp == NULL) after fopen and print an error message if the file cannot be opened.
Key terms
- Compiler
- Software that translates C source code into machine code
- Bitwise operator
- Operator working on individual bits
- Macro
- Name replaced by text before compilation
- Pointer
- Variable holding an address
- Practical file
- Record of aim, program and output for each experiment
Quick revision
- %d on a char prints its ASCII value; sizeof gives sizes.
- Bitwise &, |, ^, ~, <<, >>; conditional operator.
- Always add break in switch cases; test primes up to √n.
- Recursion needs a base case; macros need brackets.
- Strings end with '\0'; always fclose() files.
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 output of 12 & 10?
- Q2.Distinguish local and global variables.
- Q3.Why should macro arguments be parenthesised?
- Q4.Write the recursive formula for factorial.
- Q5.How do you append to an existing file?
- Q6.What does the * operator do in a declaration and in an expression?
Long-answer questions
- Q1.Write a program to demonstrate arithmetic, relational, logical and bitwise operators.
- Q2.Write a menu-driven calculator using switch-case.
- Q3.Write recursive programs for factorial and Fibonacci series.
- Q4.Write a program to reverse a string and check whether it is a palindrome.
- Q5.Write a program to create a file, write records into it and read them back.
Stuck on this unit?
Message SBS on WhatsApp for help with Software Lab-I (Programming in C), or to ask about studying B.Sc IT at Synetic.
