0% found this document useful (0 votes)
3 views66 pages

Lecture4 Functions

This document is a lecture on functions in C programming, covering topics such as top-down design, defining and calling functions, and recursive functions. It emphasizes the advantages of using functions for code management and reusability, and provides examples of function declarations, prototypes, and the use of standard libraries. Additionally, it discusses the Make utility for automating the building process of larger programs.

Uploaded by

giaphonghoang123
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views66 pages

Lecture4 Functions

This document is a lecture on functions in C programming, covering topics such as top-down design, defining and calling functions, and recursive functions. It emphasizes the advantages of using functions for code management and reusability, and provides examples of function declarations, prototypes, and the use of standard libraries. Additionally, it discusses the Make utility for automating the building process of larger programs.

Uploaded by

giaphonghoang123
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

VIETNAM ACADEMY OF SCIENCE AND TECHNOLOGY

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF HANOI

BASIC PROGRAMMING
Lecture 4: Functions

Dr. NGUYEN Hoang Ha


Dr. NGUYEN Minh Huong
Dr. TONG Si Son
Dr. PHAN Thanh Hien

ĐO TẠO NGHIÊN ỨU SÁNG TO


1
Possible to write thousands lines of
code with mixed structures?

How to organize a big program?

2
Agenda

▪ Top-down design
▪ Defining functions
▪ Calling functions
▪ Recursive functions
▪ The Make utility
▪ Practical time

3
Top-down Design

▪ Large problems:
▪ Highly complex
Problem
▪ Heavy computation Task 1
▪ Hard to implement •Sub Task
•Sub Task

▪ Break the problem down into tasks and tasks


•Sub Task

down into subtasks Task 2

▪ Less complex
•Sub Task
•Sub Task

▪ Lighter computation
▪ Easy to implement
Task 3
▪ Eventually Sub Tasks become manageable and
implementable in C
4
Top-down Design in Programming

▪ Function: a group of statements performing specific tasks


▪ Two or more commands
▪ Has a name to be reused
▪ Goal: divide and conquer

5
Advantages of Functions

▪ Keep the main program smaller 🡪 easier to read and


modify
▪ Enhance
▪ Code management
▪ Reusability
▪ Readability: make main program smaller, focus on big points
▪ Reduce
▪ Repetition code
▪ Risks of error/bug
▪ Ease: writing, reading, debugging the code
6
Structure of Functions
Parameter 1
Parameter 2
Function Return result

Parameter 3

Function
Function name
return_type parameters

int add (int x, int y)


Function
{
body
return (x+y);

};

▪ Number of arguments: zero to any


▪ Return type: void or any datatype 7
Types of Functions in C

▪ Build-in functions:
▪ Found in standard libraries
▪ Eg:
▪ printf(), scanf() in <stdio.h>
▪ sqrt(), pow() in <math.h>
▪ User-defined functions
#include <stdio.h>
void functionName()
{
... .. ...
}
int main()
{

... .. ...

functionName();

... .. ... 8
}
Standard Libraries

▪ Common libraries
Header file Descriptions
stdio.h Input/Output functions
conio.h Console Input/Output functions
stdlib.h General utility functions
math.h Mathematics functions
string.h String functions
ctype.h Character handling functions
time.h Date and time functions
float.h Limits of float types
limits.h Size of basic types
wctype.h Functions to determine the type contained in wide character data.

▪ All of standard libraries:


[Link]
9
Defining Functions

10
Function Declaration

▪ Function must be declared before invoked


▪ Syntax:
return_type function_name (parameter_list){
body of the function
}

11
Function Declaration (cont’)

▪ Choose a meaningful function name


▪ Convention: should be a verb, using _ to separate words
▪ Define a contract
▪ Inputs
▪ Arguments – choose type and name, none 🡪 void
▪ Will the function change the parameter’s value?
▪ Output
▪ Only one ; by convention, 0 means good
▪ Only one: datatype, void means nothing.
▪ Body: set of statements (in different structures)
▪ Function cannot be defined in another function
12
E.g. of a Simple Function
#include <stdio.h>

//The definition of a very simple function returning nothing - void


void say_hello()
{
printf("Hello from a function\n");
}

//Every program in C must have 01 main() function as the entry


int main()
{
/*calling function*/
say_hello();
return 0;
}

13
E.g. of another Simple Function
#include <stdio.h>
int addition (int num1, int num2)
{
int sum;
sum = num1+num2;
return sum;
}

int main ()
{
int var1, var2;
printf("Enter number 1: ");
scanf("%d",&var1);
printf("Enter number 2: ");
scanf("%d",&var2);

/* Calling the function here */


int res = addition(var1, var2);
printf ("Output: %d", res);

return 0;
}
14
Function prototype
▪ Think of function as a backbox 🡪 as a function consumer,
sometimes programmers do not need to look at function
body
Parameter 1
Parameter 2
Function Return result

Parameter 3

▪ Declare prototype (header) of function:


return_type function_name (parameter_list);

15
Declare Function with Prototype

#include <stdio.h>

//Firstly declare function prototype


void say_hello ();

int main()
{
//calling function, even when not yet define it
say_hello ();
return 0;
}

//Declare full function after invoking it at the main()


void say_hello ()
{
printf ("Hello from a function\n");
}
16
Function Declared in Separate Files

▪ A big program shoud not be written in a single file


▪ Follow “divide and conquer” mindset
▪ Request to use existing code from outer file by using C
processing directive #include

17
E.g. of Function in a Separate File

File say_hello.h File main.c


#include <stdio.h> #include "say_hello.h"

//Declare function in a separate file int main()

void say_hello() {

{ //calling function declared in say_hello.h

printf("Hello from a function\n"); say_hello();


return 0;
}
}

18
Header File (*.h) and
Implementation File (*.c)
▪ Function creators want to hide code body
▪ Blackbox mindset: separate template and implementation code
▪ Security purposes 🡪 Do not ship the body code, but only function
prototype (in *.h files) and binary code (in *.dll and/or *.lib)
▪ A library is often written in two files
▪ *.h for prototypes
▪ *.c for body of functions 🡪 compiled into binary files (*.dll or *.lib)

19
E.g. of Function in 02 Files

File say_hello.h File say_hello.c


#ifndef SAY_HELLO_H #include <stdio.h>
#define SAY_HELLO_H //implementation of the function
//Function prototype void say_hello()
void say_hello(); {
#endif printf("Hello from a function\n");
}

File main.c
#include ”say_hello.h”
//calling the function
int main() Compile with gcc
{
gcc .\say_hello.c .\main.c -o test_function
say_hello();
}
20
Calling Functions

21
Function Using

▪ before calling functions


▪ Use #include <header_file> for standard libs
▪ Use #include “header_file” for user-defined libs

▪ Call (invoke) by:


▪ Write function name
▪ Provide parameter values if required:
▪ E.g.:
▪ printf("Hello world");
▪ double result = pow(2,3);//pow(2,e) is called function call

22
Calling a Function

▪ Calling a function means running the code in its body


▪ Function is defined 🡪 memory is occupied. But if it is not
called, the code never runs.
▪ To call:
▪ Use its name
▪ Followed by () with values for parameters if any.
▪ C programming has two parameter passing schemes:
▪ call by value
▪ call by pointer (studied later in session 6).

23
Call by Value

▪ The caller passes the value to the function


▪ If the parameter (argument) is a number 🡪 trivial
▪ If the parameter is a variable 🡪 the cloned of the variable is
passed to the function 🡪 function can not modify the original
variable

24
Call by Value Demo
#include <stdio.h>

void double_num(int num){


num *=2;
printf("Inside function, the num is %d\n", num);
}

int main()
{
int my_number = 10;
double_num(my_number);

printf("After calling a_number, my_number is still %d\n", my_number);


return 0;
}

25
Using const in Function Prototype

▪ Using const keyword for each parameter 🡪 add a


constraint to the body: impossible to change the value of
parameter (even the copied version)
▪ Like constant variable declaration
void say_hello (const int times)
{
for(int i=0;i<=times;i++)
printf("Hello from a function\n");
}

▪ Will discuss on const when study call by pointer

26
Recursive Functions

27
Recursive Function

▪ Recursive is the process of repeating in a self-similar way


▪ Recursive function in C: the body consists of statement
invoking the name of function itself.
▪ When writing a recursive function, must define an exit
condition to avoid infinite loop

28
Factorial Function in
Recursive Format
#include<stdio.h>
int find_factorial(int n)
{
//Factorial of 0 is 1
if(n==0)
return(1);

//Function calling itself: recursion


return(n*find_factorial(n-1));
}
int main()
{
int num, fact;
printf("\nEnter any integer number:");
scanf("%d",&num);

//Calling our user defined function


fact =find_factorial(num);

//Displaying factorial of input number


printf("\nfactorial of %d is: %d",num, fact);
return 0;
29
}
Factorial Function in
Non-Recursive Format
#include<stdio.h>
int find_factorial(int num)
{
if(num<=0)
printf("\n Invalid Number! ");
else{
int fact=num;
int i=1;
while(i<num){
fact=fact*i;
i++;
}
printf("\n Factorial = %ld",fact);
}
}
int main()
{
int num, fact;
printf("\nEnter any integer number:");
scanf("%d",&num);

//Calling our user defined function


fact =find_factorial(num);

//Displaying factorial of input number


printf("\nfactorial of %d is: %d",num, fact);
return 0;
}
30
Recursive Function
Pros vs. Cons

Pros Cons
• Simpler to write • Consume more memory
• Easier to debug • Risk to infinite loop
• Code is short

31
The Make Utility

32
Context - A Project Structure
gcc –o hello_program .\main.o .\say_hello.o

gcc –c .\main.c hello_program.exe gcc –c .\say_hello.c

main.o say_hello.o

[Link] say_hello.h say_hello.cpp


33
Motivation

▪ Small programs 🡪 all in one single cpp file


▪ Bigger programs 🡪 modularize into functions, files
▪ Many lines of code
▪ Multiple programmers
▪ Multiple components
▪ Manual building is laborious
▪ How to automate the building process?

34
A Make file

▪ “makefile” is put at the folder of source files


hello_program: say_hello.o main_say_hello.c
gcc -o hello_program say_hello.o main_say_hello.c

say_hello.o: say_hello.c
gcc -c say_hello.c

▪ To compile the whole project ,just type ”make”

35
Makefile rule

▪ Each section consists of 2 lines


▪ Outputfile: inputfile1, inputfile2 …
▪ Compiling command
▪ Example:
hello_program: say_hello.o main_say_hello.c
gcc -o hello_program say_hello.o main_say_hello.c

say_hello.o: say_hello.c
gcc -c say_hello.c

36
Practical time

37
The "Void" Function (Menu System)
Concept: Functions don't always calculate numbers. Sometimes they perform actions, like displaying User Interfaces (UI).

Scenario: A game menu.

38
The "Void" Function (Menu System)
#include <stdio.h>

// This function returns NOTHING (void), it just prints text


void print_menu() {
printf("\n=== GAME MENU ===\n");
printf("1. Start Game\n");
printf("2. Load Save\n");
printf("3. Settings\n");
printf("4. Exit\n");
printf("=================\n");
}

int main() {
int choice = 0;

// We can reuse the menu printing logic easily


print_menu();
printf("Select an option: ");
scanf("%d", &choice);

if (choice == 1) {
printf("Starting game...\n");
} else {
printf("Quitting...\n");
}

return 0;
}

39
The "Call by Value" Experiment
Goal: Understand that functions cannot change variables in main directly (without pointers).

Task: Write a function try_to_change that attempts to update a score, and observe why it fails
(demonstrating the "Copy" mechanism explained in Lecture 4).

40
The "Call by Value" Experiment
#include <stdio.h>

void try_to_change(int score) {


printf(" [Inside Function] Original value: %d\n"
, score);
score = 100; // Change the COPY
printf(" [Inside Function] New value: %d\n"
, score);
}

int main() {
int my_score = 50;

printf("[Main] Before calling function: %d\n"


, my_score);

// Pass my_score to the function


try_to_change(my_score);

// Check if it changed
printf("[Main] After calling function: %d\n"
, my_score);

return 0;
}

41
"Call by Value" Visualization (The
Broken Swap)
Concept: This is the most important concept in Lecture 4. In C, variables are copied into functions. The function cannot change
the original variable (yet).

Scenario: Trying to swap two bank account balances.

42
"Call by Value" Visualization (The
Broken Swap)
#include <stdio.h>

// Attempting to swap two numbers


void swap_money(int a, int b) {
int temp = a;
a = b;
b = temp;
printf(" [Inside Function] Account A: %d, Account B: %d (Swapped!)\n"
, a, b);
}

int main() {
int acct1 = 1000;
int acct2 = 50;

printf("[Main] Before: Account A: %d, Account B: %d\n"


, acct1, acct2);

// CALL BY VALUE: C sends COPIES of 1000 and 50 to the function.


swap_money(acct1, acct2);

// The originals in main are UNTOUCHED.


printf("[Main] After: Account A: %d, Account B: %d (No Change!)\n"
, acct1, acct2);

return 0;
}

43
Pattern Printer

Goal: Practice functions that perform an action (printing)


without returning a value.
Task: Write a function print_triangle that accepts an integer
height and prints a pyramid of stars.

44
Pattern Printer
#include <stdio.h>

// Function Prototype
void print_triangle(int height);

int main() {
int h;
printf("Enter height: ");
scanf("%d", &h);

print_triangle(h); // Call the void function


return 0;
}

// Function Definition
void print_triangle(int height) {
for (int i = 1; i <= height; i++) {
// Print stars
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n"); // New line after each row
}
}

45
Recursive Sum (Sum of 1 to N)
Task: Write a recursive function sum_n that calculates the sum of all numbers
from 1 to n.
Logic: sum(5) = 5 + sum(4) ... sum(1) = 1.

46
Recursive Sum (Sum of 1 to N)
#include <stdio.h>

int sum_n(int n);

int main() {

int num = 5;

printf("Sum of 1 to %d is: %d\n", num, sum_n(num));

return 0;

int sum_n(int n) {

// Base case: Stop when we reach 1 (or 0)

if (n == 0) return 0;

// Recursive step: n + sum of (n-1)

return n + sum_n(n - 1);

47
Recursion (Fibonacci Sequence)

Goal: Practice the "divide and conquer" mindset using


recursion (Function calling itself).
Task: Write a recursive function fibonacci(n) that returns the
n-th number in the Fibonacci sequence (0, 1, 1, 2, 3, 5, 8...).
Logic: fib(n) = fib(n-1) + fib(n-2).

48
Recursion (Fibonacci Sequence)
#include <stdio.h>

// Function Prototype
int fibonacci(int n);

int main() {
int n = 6;
int result = fibonacci(n);
printf("The %dth Fibonacci number is: %d\n"
, n, result);
return 0;
}
// Recursive Definition
int fibonacci(int n) {
// Base Case 1: if n is 0, return 0
if (n == 0) return 0;
// Base Case 2: if n is 1, return 1
if (n == 1) return 1;

// Recursive Step: call itself twice


return fibonacci(n - 1) + fibonacci(n - 2);
}

49
Recursion (The Power Function)
Concept: A function calling itself to solve a smaller version of the problem.

Scenario: Calculating xn (x to the power of n) without using pow().

● Logic: 23 is the same as 2×22


● Base case: Any number to the power of 0 is 1.

50
Recursion (The Power Function)
#include <stdio.h>

int power(int base, int exponent) {


// 1. Base Case (The Stop Sign)
if (exponent == 0) {
return 1;
}

// 2. Recursive Step
// 2^3 = 2 * power(2, 2)
return base * power(base, exponent - 1);
}

int main() {
int x = 2;
int n = 3;
printf("%d to the power of %d is %d\n", x, n, power(x, n));
return 0;
}

51
The "Max" Finder

Concept: Function with return value and parameters.


Task: Write a function find_max that takes three integers as
input and returns the largest one.

52
The "Max" Finder
#include <stdio.h>

// 1. Prototype
int find_max(int a, int b, int c);

int main() {
int x, y, z;
printf("Enter three numbers: ");
scanf("%d %d %d", &x, &y, &z);

// 2. Call
int max = find_max(x, y, z);
printf("The largest number is: %d\n", max);
return 0;
}

// 3. Definition
int find_max(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
return max;
}

53
Temperature Converter
Concept: Functions with float and mathematical logic.
Task: Write a function to_fahrenheit that accepts a float (Celsius) and
returns a float (Fahrenheit).
Formula:
F=(C×1.8)+32

54
Temperature Converter
#include <stdio.h>

float to_fahrenheit(float celsius);

int main() {

float c;

printf("Enter temperature in Celsius: ");

scanf("%f", &c);

printf("%.2f Celsius is %.2f Fahrenheit.\n"


, c, to_fahrenheit(c));

return 0;

float to_fahrenheit(float celsius) {

// Note: We use 1.8, not 9/5. Because in C, 9/5 is 1 (integer division)!

return (celsius * 1.8) + 32;

55
The Boolean Function (Prime
Checker)
Goal: Practice returning a value (0 or 1) to represent
logic/truth, acting as a "black box" that answers a question.
Task: Write a function check_prime that takes an integer as
input and returns 1 if the number is prime, and 0 if it is not.

56
The Boolean Function (Prime
Checker)
#include <stdio.h>

// Function Prototype
int check_prime(int n);

int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);

// Call the function inside the if statement


if (check_prime(num) == 1) {
printf("%d is a Prime number.\n", num);
} else {
printf("%d is NOT a Prime number.\n", num);
}
return 0;
}

// Function Definition
int check_prime(int n) {
if (n <= 1) return 0; // 0 and 1 are not prime

// Check divisors from 2 to n/2


for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return 0; // Found a divisor, so it's not prime
}
}
return 1; // No divisors found, it is prime
}
57
Numerical Integration (Riemann
Sum)
Concept: Calculating the area under a curve. Since computers can't do symbolic integration
(like ∫x2dx) easily without heavy libraries, we approximate it by summing up many small
rectangles.

58
Numerical Integration (Riemann
Sum)
#include <stdio.h>
#include <math.h>

// The mathematical function: f(x) = x^2


double f(double x) {
return x * x;
}

int main() {
double a = 0.0; // Start limit
double b = 2.0; // End limit
int n = 1000; // Number of rectangles (steps)

double dx = (b - a) / n; // Width of each rectangle


double total_area = 0.0;

for (int i = 0; i < n; i++) {


// Calculate height of the rectangle at current x
double current_x = a + i * dx;
double height = f(current_x);

// Area = height * width


total_area += height * dx;
}

printf("Approximate area under x^2 from %.1f to %.1f is: %.4f\n"


, a, b, total_area);
// Actual math answer is 2.6667

return 0;
}
59
Linear Algebra
Topic: Matrix Addition
Concept: Matrices are fundamental in engineering. In C, a Matrix is represented perfectly by a 2D
Array. This example adds two 2×2 matrices.

60
Linear Algebra
#include <stdio.h>

int main() {
int rows = 2, cols = 2;

// Matrix A
int A[2][2] = {
{1, 2},
{3, 4}
};

// Matrix B
int B[2][2] = {
{5, 6},
{7, 8}
};

// Matrix C (Result)
int C[2][2];

printf("Result of A + B:\n");

// Nested loops to traverse rows and columns


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// Linear Algebra logic: C_ij = A_ij + B_ij
C[i][j] = A[i][j] + B[i][j];

printf("%d\t", C[i][j]);
}
printf("\n"); // New line after every row
}

return 0;
} 61
Physics (Mechanics)
Topic: Free Fall Simulation
Concept: Simulating the height of an object dropped from a tower over time until it hits
the ground.

● Formula: h=h0−0.5×g×t2

62
Physics (Mechanics)
#include <stdio.h>

#define G 9.81 // Gravity constant

int main() {
double initial_height = 100.0; // Meters
double current_height = initial_height;
double time = 0.0;
double time_step = 0.5; // Update every 0.5 seconds

printf("Time(s) \t Height(m)\n");
printf("------------------------\n");

// Loop until the object hits the ground (height <= 0)


while (current_height > 0) {
printf("%.1f \t\t %.2f\n", time, current_height);

time += time_step;

// Physics formula implementation


current_height = initial_height - 0
(.5 * G * time * time);
}

printf("Impact! The object hit the ground around %.1f seconds.\n"


, time);

return 0;
}

63
Probability & Statistics
Topic: Calculating Standard Deviation
Concept: Calculating how "spread out" a set of grades is. This requires two passes: one to
find the Mean (Average), and one to find the Variance.

64
Probability & Statistics
#include <stdio.h>
#include <math.h> // Required for sqrt() and pow()

float calculate_mean(float data[], int n) {


float sum = 0.0;
for (int i = 0; i < n; i++) {
sum += data[i];
}
return sum / n;
}

int main() {
float grades[] = {75.0, 80.0, 95.0, 60.0, 85.0};
int n = 5;

// Step 1: Calculate Mean


float mean = calculate_mean(grades, n);

// Step 2: Calculate Variance


float sum_deviation = 0.0;
for (int i = 0; i < n; i++) {
// (x - mean)^2
sum_deviation += pow(grades[i] - mean, 2);
}

// Step 3: Standard Deviation = sqrt(variance)


float variance = sum_deviation / n;
float std_dev = sqrt(variance);

printf("Mean Grade: %.2f\n", mean);


printf("Standard Deviation: %.2f\n", std_dev);

return 0;
}
65
Practical time

1. Write a function to compute average of two numbers


2. Write a program calling above function to compute
average of 4 numbers.

66

You might also like