NEB Class 12 Computer Science: Unit 4 - Programming in C [9 Marks]
Content Reference: Aligned with the Curriculum Development Centre (CDC) syllabus, NEB Board Examination pattern, and study resources from Readers Nepal.
Table of Contents
- 1. Review of C Fundamentals & Functions
- 2. Function Accessing (Call by Value)
- 3. Concept of Storage: Automatic & External
- 4. Concept of Recursion
- 5. Pointers in C
- 6. Structure and Union
- 7. Practice Questions & Board Exam Solutions
1. Review of C Fundamentals & Functions
C is a structured, procedure-oriented programming language created by Dennis Ritchie. Functions are self-contained code blocks designed to complete a specific task, promoting modular programming.
Types of Functions
- Library Functions: Pre-written functions included with C header files (e.g.,
printf(),scanf(),sqrt()). - User-Defined Functions: Custom functions created by programmers to solve specific sub-problems.
Function Essentials
- Prototype (Declaration): Informs the compiler about the function's name, parameters, and return type before it runs.
int multiply(int, int); - Definition: Contains the core code block executed during execution.
- Call: Executes the function from
main()or another function. - Return Statement: Passes a value back to the caller function.
2. Accessing a Function by Passing Values (Call by Value)
In Call by Value, a duplicate copy of the argument's data is sent to the function parameters. Modifying variables inside the function body does not affect the original variables in main().
#include <stdio.h>
// Function Prototype
void updateMarks(int score);
int main() {
int studentScore = 75;
printf("Original Score before call = %d\n", studentScore);
updateMarks(studentScore); // Call by Value
printf("Original Score after call = %d\n", studentScore); // Value stays 75
return 0;
}
void updateMarks(int score) {
score = score + 10; // Changes local copy only
printf("Updated Score inside function = %d\n", score);
}
3. Concept of Storage: Automatic & External
Storage classes determine where variables are saved, their default starting values, scope, and lifespan.
| Storage Specifier | Keyword | Storage Location | Default Value | Scope & Lifetime |
|---|---|---|---|---|
| Automatic | auto |
RAM (Stack) | Garbage Value | Local to its block; destroyed when block finishes. |
| External | extern |
RAM (Data Segment) | Zero (0) | Global; accessible across multiple functions and files. |
4. Concept of Recursion
Recursion is a programming approach where a function calls itself repeatedly until it satisfies a base terminating condition.
A. Factorial Program using Recursion
#include <stdio.h>
long int findFactorial(int n) {
if (n <= 1) {
return 1; // Base Case
}
return n * findFactorial(n - 1); // Recursive Step
}
int main() {
int number = 6;
printf("Factorial of %d = %ld\n", number, findFactorial(number));
return 0;
}
B. Fibonacci Series Program using Recursion
#include <stdio.h>
int getFibonacci(int term) {
if (term == 0) return 0; // Base Case 1
if (term == 1) return 1; // Base Case 2
return getFibonacci(term - 1) + getFibonacci(term - 2); // Recursive Step
}
int main() {
int totalTerms = 6, i;
printf("Fibonacci Series: ");
for (i = 0; i < totalTerms; i++) {
printf("%d ", getFibonacci(i));
}
printf("\n");
return 0;
}
5. Pointers in C
A pointer is a variable designed to hold the memory address location of another variable.
Key Operators:
&(Address-of Operator): Retrieves the memory address of a variable.*(Indirection / Dereference Operator): Reads or alters the value saved at a specific memory pointer address.
#include <stdio.h>
int main() {
int val = 50;
int *ptr = &val; // Assign address of val to pointer
printf("Value of val: %d\n", val);
printf("Memory Address of val (&val): %p\n", ptr);
printf("Value accessed via Dereferenced Pointer (*ptr): %d\n", *ptr);
*ptr = 100; // Altering value directly via memory address
printf("New value of val after dereference update: %d\n", val);
return 0;
}
6. Structure and Union
Comparison: Structure vs. Union
| Feature | Structure (struct) |
Union (union) |
|---|---|---|
| Keyword | struct |
union |
| Memory Space | Gives every member variable its own distinct memory block. | All member variables share a single memory block equal to the size of its largest member. |
| Member Access | All member values can be stored and accessed at the exact same time. | Only a single member holds a valid value at any moment. |
| Total Size | Equal to or greater than the sum of every member's size. | Equal to the size of its largest single member variable. |
Structure & Array of Structures Example
#include <stdio.h>
struct Book {
char title[40];
int pages;
float price;
};
int main() {
struct Book library[2]; // Array of structures for 2 books
for (int i = 0; i < 2; i++) {
printf("Enter title, pages, and price for Book %d:\n", i + 1);
scanf("%s %d %f", library[i].title, &library[i].pages, &library[i].price);
}
printf("\n--- Book Catalog ---\n");
for (int i = 0; i < 2; i++) {
printf("Book %d: %s | Pages: %d | Price: Rs. %.2f\n",
i + 1, library[i].title, library[i].pages, library[i].price);
}
return 0;
}
7. Practice Questions & Board Exam Solutions
Short Practice Questions
-
Differentiate between library functions and user-defined functions.
Answer: Library functions are built-in functions provided by C compilers (e.g.,printf(),sqrt()) accessed via header files. User-defined functions are written by programmers to perform custom routines within an application. -
What is the function of a return statement?
Answer: A return statement immediately terminates function execution and sends a calculated value back to the calling function. -
Explain Call by Value briefly.
Answer: It copies argument data values into function parameters. Changes inside the function do not alter the source variables in the calling routine. -
What is a pointer in C?
Answer: A pointer is a variable that stores a memory address location of another variable. Declared usingint *ptr;for integer types.
Sample NEB Board Exam Long Questions (8 Marks)
Question 1: Write a C program to generate the Fibonacci series up to 'n' terms using a recursive function. Explain recursion with its pros and cons.
#include <stdio.h>
// Recursive function declaration
int fibonacciTerm(int n) {
if (n == 0) return 0; // Base Case 1
if (n == 1) return 1; // Base Case 2
return fibonacciTerm(n - 1) + fibonacciTerm(n - 2); // Recursive Step
}
int main() {
int total, i;
printf("Enter number of terms for Fibonacci series: ");
scanf("%d", &total);
if (total <= 0) {
printf("Please enter a positive integer.\n");
} else {
printf("Fibonacci Sequence: ");
for (i = 0; i < total; i++) {
printf("%d ", fibonacciTerm(i));
}
printf("\n");
}
return 0;
}
Recursion Concept: Recursion occurs when a function calls itself to solve a smaller version of a problem. It requires a Base Case to stop execution and a Recursive Step to reduce problem size.
Advantages: Clean, elegant code for complex mathematical or tree-structure problems.
Disadvantages: Slower execution speed and higher stack memory usage due to overhead from repeated function calls.
Advantages: Clean, elegant code for complex mathematical or tree-structure problems.
Disadvantages: Slower execution speed and higher stack memory usage due to overhead from repeated function calls.
Question 2: Define Structure and Union in C. Explain their core differences with programmatic examples.
#include <stdio.h>
// Structure Example
struct StudentRecord {
int id;
float gpa;
};
// Union Example
union StudentData {
int id;
float gpa;
};
int main() {
struct StudentRecord s = {101, 3.8};
union StudentData u;
printf("--- STRUCTURE (Separate Memory Allocation) ---\n");
printf("ID: %d | GPA: %.2f\n", s.id, s.gpa);
printf("Size of Structure: %lu bytes\n\n", sizeof(struct StudentRecord));
printf("--- UNION (Shared Memory Allocation) ---\n");
u.id = 202;
printf("ID assigned: %d\n", u.id);
u.gpa = 3.9; // Overwrites ID memory
printf("GPA assigned: %.2f\n", u.gpa);
printf("ID value after GPA update (corrupted): %d\n", u.id);
printf("Size of Union: %lu bytes\n", sizeof(union StudentData));
return 0;
}