Computer Science · Chapter 4
Study notes aligned to the official NEB syllabus.
Grade 11 introduced the C language, its data types, operators, decisions, loops, arrays and strings. This chapter takes C further, into the tools that let us write larger and better organized programs: functions that break a problem into manageable pieces, recursion and storage classes that control how those pieces run and how long variables live, structures and unions that group different kinds of data together, pointers that work directly with memory, and files that let a program store data permanently on disk. These are the ideas that separate small exercises from real, reusable programs.
A C program is a set of instructions written in the C language and executed in sequence. Every C program has a main() function where execution begins, uses header files included with #include to bring in ready made features, and ends each statement with a semicolon. Data are held in variables of a declared data type (int, float, char, double), decisions are made with if...else and switch, and repetition is done with for, while and do...while loops. A minimal program looks like this:
#include <stdio.h>
int main() {
int a = 5, b = 3;
printf("Sum = %d", a + b);
return 0;
}
A function is a self contained block of statements that performs a specific, well defined task. Breaking a program into functions makes it shorter (because repeated work is written once), easier to read, easier to test and easier to reuse. Working with a function involves three parts.
The function prototype (declaration) appears before main() and tells the compiler the function's name, the type it returns and the types of its parameters, so the compiler can check calls to it:
int add(int, int); // prototype
The function call is where the function is used, passing the actual values (arguments):
result = add(5, 3); // call
The function definition contains the actual body, and the return statement sends a value back to the caller and ends the function:
int add(int x, int y) { // definition
return x + y; // return statement
}
A complete example:
#include <stdio.h>
int add(int, int); // prototype
int main() {
int s = add(5, 3); // call
printf("Sum = %d", s);
return 0;
}
int add(int x, int y) { // definition
return x + y; // return
}