§ — — Computer Programming 1
A function is a self-contained section of code that performs a specific task. Functions are the primary tool for breaking large programs into manageable pieces (top-down design).
Advantages of using functions:
Tells the compiler the function name, return type, and parameter types before use.
return_type function_name(parameter_type_list);
// Examples:
int ccmit(int bsit, int bscs);
void ccmit();
float ccmit(float x, float y);
return_type function_name(parameter list) {
local variable declarations;
statements;
return value;
}
// Example:
double twice(double x) {
return 2.0 * x;
}
If return type is void, the function returns no value.
Local variables:
Global variables:
Arguments are passed as copies — changes inside the function do not affect the original.
void funct_sample(int y) {
y *= 3;
printf("New value of y: %d", y); // prints 15
}
main() {
int n = 5;
printf("n before call: %d", n); // 5
funct_sample(n);
printf("n after call: %d", n); // still 5 — unchanged
}
To allow a function to modify a variable in the caller, pass the address using &. Inside the function, use * to access the value at that address.
&variable — "the address of variable"*pointer — "the value at the address held by pointer"void compute_rating(float midterm, float final, float *rating) {
*rating = (midterm + final) / 2;
}
main() {
float mid, fin, fin_grd;
scanf("%f", &mid);
scanf("%f", &fin);
compute_rating(mid, fin, &fin_grd);
printf("Final rating = %f", fin_grd);
}
&fin_grd passes the address. *rating = ... stores a value directly into that memory location, so the change is visible in main() after the call.
ProReviewer — locked
Drills, code labs, and full solutions.
ProReviewer — locked
Drills, code labs, and full solutions.
ProReviewer — locked
Drills, code labs, and full solutions.
Try calling add() with different numbers, or write a new function that multiplies two values.
Done with this module? Track it — your progress shows on the subject list.
Up next
Lesson 7: String, Character, and Math Functions→←Previous: Lesson 5: Arrays