This document discusses functions in C programming. It defines what a function is and explains that functions make programs easier to understand and maintain by breaking them into subprograms that perform specific tasks. It provides examples of function syntax, declaring and defining functions, and calling functions. It also discusses the differences between local and global variables and provides exercises for the reader to practice writing functions.
3. What is a function?
A large program in c can be divided to many
subprogram. The subprogram is called as a
function
A function is a block of code that performs a
specific task
Creating an application using function
makes it easier to understand, edit, check
errors etc.
A function is a set of statements that take
inputs, do some specific computation and
produces output
5. #include <iostream>
using namespace std;
int sum (int x, int y); //declaring function
int main()
{
int a = 10;
int b = 20;
int c = sum (a, b); //calling function
cout << c;
}
int sum (int x, int y) //defining function
{
return (x + y);
}
Declaring, Defining and Calling Function
6. Void Functions
A void function returns values by modifying one or more parameters rather than
using a return statement. For example:
8. Local Variable VS Global Variable
A local variable is a variable that is declared inside a
function. A global variable is a variable that is declared
outside all functions. A local variable can only be used in
the function where it is declared. A global variable can be
used in all functions.
10. EXERCISES 1
Write a program that calculates (Add, Subtract, Multiply,
Divide and Modulus) using functions.
11. EXERCISES 2
Write a program that If f(x) = x2+ 3x + 1, then find the values of f(0), f(1), f(2), f(3).
12. EXERCISES 3
Write a program that ask for three numbers, compare them and show the
maximum. Declare a function called max_three that compares the numbers and
returns the maximum. See the sample below.
13. EXERCISES 4
Write a function that uses n (integer) and prints out a triangle as the following
example
(for n = 5) :
14. EXERCISES 5
Write a program that calculate surface area and volume of cubes. You must be
using:
Local variabel for the side of a cube (int S) and
Void with two functions (surface area and volume).