You are on page 1of 7

Function in C program

1. 1. A large program in c can be divided to many subprogramThe subprogram posses a self


contain components and have well define purpose.The subprogram is called as a
functionBasically a job of function is to do somethingC program contain at least one function
which is main(). Classification of Function User define Library function function - main()
-printf() -scanf() -pow() -ceil()
2. 2. It is much easier to write a structured program where a large program can be divided into
asmaller, simpler task.Allowing the code to be called many timesEasier to read and updateIt
is easier to debug a structured program where there error is easy to find and fix
3. 3. 1: #include <stdio.h> Arguments/formal parameter Function names is cube2: Variable
that are requires is3: long cube(long x); long4: Return data type The variable to be passed
on5: long input, answer; is X(has single arguments)6: value can be passed to7: int
main( void ) function so it can perform the8: { specific task. It is called Actual parameters9:
printf(Enter an integer value: );10: scanf(%d, &input);11: answer = cube(input);12:
printf(nThe cube of %ld is %ld.n, input, answer);13: Output14: return 0;15: } Enter an
integer value:416:17: long cube(long x)18: { The cube of 4 is 64.19: long x_cubed;20:21:
x_cubed = x * x * x;22: return x_cubed;23: }
4. 4. C program doesnt execute the statement in function until the function is called.When
function is called the program can send the function information in the form of oneor more
argument.When the function is used it is referred to as the called functionFunctions often use
data that is passed to them from the calling functionData is passed from the calling function
to a called function by specifying the variables ina argument list.Argument list cannot be used
to send data. Its only copy data/value/variable that passfrom the calling function.The called
function then performs its operation using the copies.
5. 5. Provides the compiler with the description of functions that will be used later in the
program Its define the function before it been used/called Function prototypes need to be
written at the beginning of the program. The function prototype must have : A return type
indicating the variable that the function will be returnSyntax for Function Prototypereturn-type
function_name( arg-type name-1,...,arg-type name-n);Function Prototype Examples double
squared( double number ); void print_report( int report_number ); int
get_menu_choice( void);
6. 6. It is the actual function that contains the code that will be execute. Should be identical to
the function prototype.Syntax of Function Definitionreturn-type function_name( arg-type
name-1,...,arg-type name-n) ---- Function header{declarations;statements; Function
Bodyreturn(expression);}
7. 7. Function Definition Examples float conversion (float celsius) { float fahrenheit; fahrenheit =
celcius*33.8 return fahrenheit; }The function names is conversionThis function accepts
arguments celcius of the type float. The function return a float value.So, when this function is
called in the program, it will perform its task which is to convertfahrenheit by multiply celcius

8.
9.

10.

11.

12.

13.

14.

15.

16.

17.

with 33.8 and return the result of the summation.Note that if the function is returning a value,
it needs to use the keyword return.
8. Can be any of Cs data type: char int float longExamples:int func1(...) /* Returns a
type int. */float func2(...) /* Returns a type float. */void func3(...) /* Returns nothing. */
9. Function can be divided into 4 categories:A function with no arguments and no return
valueA function with no arguments and a return valueA function with an argument or
arguments and returning no valueA function with arguments and returning a values
10. A function with no arguments and no return value Called function does not have any
arguments Not able to get any value from the calling function Not returning any value There
is no data transfer between the calling function and called function. #include<stdio.h>
#include<conio.h> void printline(); void main() { printf("Welcome to function in C"); printline();
printf("Function easy to learn."); printline(); getch(); } void printline() { int i; printf("n");
for(i=0;i<30;i++) { printf("-"); } printf("n"); }
11. A function with no arguments and a return value Does not get any value from the calling
function Can give a return value to calling program #include <stdio.h> Enter a no: 46
#include <conio.h> int send(); You entered : 46. void main() { int z; z=send(); printf("nYou
entered : %d.",z); getch(); } int send() { int no1; printf("Enter a no: "); scanf("%d",&no1);
return(no1); }
12. A function with an argument or arguments and returning novalue A function has
argument/s A calling function can pass values to function called , but calling function not
receive any value Data is transferred from calling function to the called function but no data is
transferred from the called function to the calling function Generally Output is printed in the
Called function A function that does not return any value cannot be used in an expression it
can be used only as independent statement.
13. #include<stdio.h>#include<conio.h>void add(int x, int y);void main(){ add(30,15);
add(63,49); add(952,321); getch();}void add(int x, int y){ int result; result = x+y; printf("Sum of
%d and %d is %d.nn",x,y,result);}
14. A function with arguments and returning a values Argument are passed by calling
function to the called function Called function return value to the calling function Mostly used
in programming because it can two way communication Data returned by the function can be
used later in our program for further calculation.
15. #include <stdio.h> Result 85.#include <conio.h>int add(int x,int y); Result 1273.void
main() Send 2 integer value x and y to add(){ Function add the two values and send int z;
back the result to the calling function z=add(952,321); int is the return type of function
printf("Result %d. nn",add(30,55)); Return statement is a keyword and in printf("Result
%d.nn",z); bracket we can give values which we want to return. getch();}int add(int x,int y){ int
result; result = x + y; return(result);}
16. Variable that declared occupies a memory according to it sizeIt has address for the
location so it can be referred later by CPU for manipulationThe * and & OperatorInt x= 10
x Memory location name 10 Value at memory location 76858 Memory location addressWe
can use the address which also point the same value.
17. #include <stdio.h>#include <conio.h>void main(){ int i=9; & show the address of the
variable printf("Value of i : %dn",i); printf("Adress of i %dn", &i); getch();}

18. 18. #include <stdio.h>#include <conio.h>void main(){ int i=9; * Symbols called the value at
the address printf("Value of i : %dn",i); printf("Address of i %dn", &i); printf("Value at address
of i: %d", *(&i)); getch();}
19. 19. #include <stdio.h>#include <conio.h> int Value(int x) {int Value (int x); x = 1;int Reference
(int *x); } int Reference(int *x)int main() { *x = 1;{ } int Batu_Pahat = 2; int Langkawi =
2;Value(Batu_Pahat);Reference(&Langkawi); printf("Batu_Pahat is number
%dn",Batu_Pahat); printf("Langkawi is number %d",Langkawi);}Pass by referenceYou pass
the variable addressGive the function direct access to the variableThe variable can be
modified inside the function
20. 20. #include <stdio.h>#include <conio.h>void callByValue(int, int);void callByReference(int *,
int *);int main(){ int x=10, y =20; printf("Value of x = %d and y = %d. n",x,y); printf("nCAll By
Value function call...n"); callByValue(x,y); printf("nValue of x = %d and y = %d.n", x,y);
printf("nCAll By Reference function call...n"); callByReference(&x,&y); printf("Value of x = %d
and y = %d.n", x,y); getch(); return 0;}
21. 21. void callByValue(int x, int y){ int temp; temp=x; x=y; y=temp; printf("nValue of x = %d and
y = %d inside callByValue function",x,y);}void callByReference(int *x, int *y){ int temp;
temp=*x; *x=*y; *y=temp;}

Functions in C
1. 2. Functions A function is a self contained block of code that performs a particular task.
Any C program can be seen as a collection/group of these functions. A functions takes
some data as input, perform some operation on that data and then return a value. Any C
program must contain at least one function, which is main(). There is no limit on the
number of functions that might be present in a C program.
2. 3. For ex. main() { message(); printf(I am in main); } message() { printf(I am in
message); }
3. 4. Function Prototype All Identifiers in C must be declared before they are used. This is
true for functions as well as variables. For functions, the declarations needs to be done
before the first call of the function. A function declaration specifies the name, return type,
and arguments of a function. This is also called the function prototype. To be a prototype, a
function declaration must establish types for the functions arguments. Having the
prototype available before the first use of the function allows the compiler to check that the
correct number and types of arguments are used in the function call.
4. 5. The prototype has the same syntax as the function definition, except that it is
terminated by a semicolon following the closing parenthesis and therefore has no body.
Although, functions that return int values do not require prototypes, prototypes are
recommended.
5. 6. Function Definition General form of any function definition is: return-type functionname(argument declarations) { declarations and statements } Return-type refers to the

6.

7.

8.

9.
10.
11.

12.

data type of the value being returned from the function. If the return type is omitted, int is
assumed. The values provided to a function for processing are the arguments. The set
of statements between the braces is called as the function body.
7. Arguments Call by Value In C, all functions are passed by value by default. This
means that the called function is given the values of its arguments in temporary variables
rather than the originals. For ex. main() { int a=4,b=5; sum(a,b); printf(Sum = %d,a+b); }
sum(int a,int b) { a++; b++; printf(Sum = %d,a+b); }
8. Arguments Call by Reference When necessary, it is possible to arrange a function
which can modify a variable in a calling routine. The caller must provide the address of the
variable to be set (generally, a pointer to a variable), and the called function must declare the
parameter to be a pointer and access the variable indirectly through it. For ex: main() { int
a=4,b=5; sum(&a,&b); printf(Sum = %d,a+b); } sum(int *a,int *b) { (*a)++; (*b)++;
printf(Sum = %d,(*a)+(*b)); }
9. Recursion Recursion defines a function in terms of itself. It is a programming
technique in which a function calls itself. A recursive function calls itself repeatedly, with
different argument values each time. Some argument values cause the recursive method
to return without calling itself. This is the base case. Either omitting the base case or
writing the recursion step incorrectly will cause infinite recursion (stack overflow error).
10. Recursion to find the factorial of any number: int factorial(int x) { if(x<=1) return 1; else
return(x*factorial(x-1)); }
11. External Variables See the below example: main() { extern int a; printf(Value of a =
%d,a); } int a=5;Output: Value of a = 5
12. Scope Rules Example: int num1 = 100; //Global Scope static int num2 = 200; //File
Scope int main() { int num3 = 300; //Local Scope if(num2>num1) { int i=0; //Block Scope
printf(Value of i = %dn,i++); } printf(Value of num1 = %dn,num1); printf(Value of num2 =
%dn,num2); printf(Value of num3 = %dn,num3); }
13. Static Variables Example: static int min = 10; int setmax() { static int max = 100; return
++max; } main() { min++; printf(Value of max = %d, setmax()); printf(Value of max = %d,
setmax()); printf(Value of min = %d, min); }

Function in c
1. 1. C Programming Functions
2. 2. Introduction A function is a block of code performing a specific task which can be called
from other parts of a program. The name of the function is unique in a C Program and is
Global. It means that a function can be accessed from any location with in a C Program.
We pass information to the function called arguments specified when the function is called.
And the function either returns some value to the point it was called from or returns nothing.
3. 3. Program to find if the number is Armstrong or not #include<stdio.h> #include<conio.h> int
cube(int); void main() { clrscr(); int num, org, remainder,sum=0; printf("Enter any numbern");
scanf("%d",&num); org=num; while(num!=0) { remainder=num%10;

4.

5.

6.

7.

8.

9.

sum=sum+cube(remainder); num=num/10; } if(org==sum) { printf("nThe number is


armstrong"); } else { printf("nThe number is not armstrong"); } getch(); } int cube(int n) { int
qbe; qbe=n*n*n; return qbe; }
4. Second way: #include<stdio.h> int sum_cube_digits(int n) #include<conio.h> { int
sum_cube_digits(int); int rem ,sum=0; void main() { while(n!=0) clrscr(); { int num, org, f_call;
remainder=n%10; printf("Enter any numbern"); sum=sum+rem*rem*rem; scanf("%d",&num);
org=num; n=n/10; f_call=sum_cube_digits(num); } if(org==f_call) return sum; { printf("nThe
number is armstrong"); } } else { printf("nThe number is not armstrong"); } getch(); }
5. Third way: #include<stdio.h> #include<conio.h> int armstrong(int); void main() { clrscr(); int
num; printf("Enter any numbern"); scanf("%d",&num); armstrong(num); getch(); } int
armstrong(int n) { int remainder,sum=0,org; org=n; while(n!=0) { remainder=n%10;
sum=sum+remainder*remainder*remaind er; n=n/10; } if(org==sum) { printf("nThe number is
armstrong"); } else { printf("nThe number is not armstrong"); } return(0); }
6. Program to calculate factorial of a number. #include <stdio.h> #include <conio.h> int
calc_factorial (int); // ANSI function prototype void main() { clrscr(); int number; printf("Enter a
numbern"); scanf("%d", &number); calc_factorial (number);// argument number is passed
getch(); } int calc_factorial (int i) { int loop, factorial_number = 1; for (loop=1; loop <=i; loop++)
factorial_number *= loop; printf("The factorial of %d is %dn",i, factorial_number); }
7. Function Prototype int calc_factorial (int); The prototype of a function provides the basic
information about a function which tells the compiler that the function is used correctly or not.
It contains the same information as the function header contains. The only difference
between the header and the prototype is the semicolon ; there must the a semicolon at the
end of the prototype.
8. Defining a Function: The general form of a function definition is as follows: return_type
function_name( parameter list ) { body of the function } Return Type: The return_type is the
data type of the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void. Function Name:
This is the actual name of the function. The function name and the parameter list together
constitute the function signature. Parameters: A parameter is like a placeholder. When a
function is invoked, you pass a value to the parameter. This value is referred to as actual
parameter or argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain no
parameters. Parameter names are not important in function declaration only their type is
required Function Body: The function body contains a collection of statements that define
what the function does.
9. More about Function Function declaration is required when you define a function in one
source file and you call that function in another file. In such case you should declare the
function at the top of the file calling the function. Calling a Function: While creating a C
function, you give a definition of what the function has to do. To use a function, you will have
to call that function to perform the defined task. When a program calls a function, program
control is transferred to the called function. A called function performs defined task and when
its return statement is executed or when its function-ending closing brace is reached, it
returns program control back to the main program. To call a function, you simply need to

10.

11.

12.

13.

14.

15.

16.

pass the required parameters along with function name, and if function returns a value, then
you can store returned value.
10. For Example #include <stdio.h> #include <conio.h> int max(int num1, int num2); /*
function declaration */ int main () { int a = 100; int b = 200; /* local variable definition */ int ret;
ret = max(a, b); /* calling a function to get max value */ printf( "Max value is : %dn", ret );
return 0; } /* function returning the max between two numbers */ int max(int num1, int num2) {
int result; /* local variable declaration */ if (num1 > num2) result = num1; else result = num2;
return result; }
11. Local and global variables Local: These variables only exist inside the specific function
that creates them. They are unknown to other functions and to the main program. As such,
they are normally implemented using a stack. Local variables cease to exist once the
function that created them is completed. They are recreated each time a function is executed
or called. Global: These variables can be accessed by any function comprising the
program. They do not get recreated if the function is recalled. To declare a global variable,
declare it outside of all the functions. There is no general rule for where outside the functions
these should be declared, but declaring them on top of the code is normally recommended
for reasons of scope. If a variable of the same name is declared both within a function and
outside of it, the function will use the variable that was declared within it and ignore the global
one.
12. Function Arguments: If a function is to use arguments, it must declare variables that
accept the values of the arguments. These variables are called the formal parameters of the
function. The formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit. While calling a function, there
are two ways that arguments can be passed to a function: Call Type Description Call by value
This method copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have no effect on
the argument. Call by reference This method copies the address of an argument into the
formal parameter. Inside the function, the address is used to access the actual argument
used in the call. This means that changes made to the parameter affect the argument.
13. Fibonacci series in c using for loop #include<stdio.h> int main() { int n, first = 0, second =
1, next, c; printf("Enter the number of termsn"); scanf("%d",&n); printf("First %d terms of
Fibonacci series are :-n",n); for ( c = 0 ; c < n ; c++ ) { if ( c <= 1 ) next = c; else { next = first +
second; first = second; second = next; } printf("%dn",next); } return 0; }
14. Fibonacci series program in c using recursion #include<stdio.h> #include<conio.h> int
Fibonacci(int); main() { clrscr(); int n, i = 0, c; printf("Enter any numbern"); scanf("%d",&n);
printf("Fibonacci seriesn"); for ( c = 1 ; c <= n ; c++ ) { printf("%dn", Fibonacci(i)); i++; } return
0; } int Fibonacci(int n) { if ( n == 0 ) return 0; else if ( n == 1 ) return 1; else return
( Fibonacci(n-1) + Fibonacci(n-2) ); }
15. Factorial program in c using for loop #include <stdio.h> #include<conio.h> void main()
{ int c, n, fact = 1; printf("Enter a number to calculate it's factorialn"); scanf("%d", &n); for (c =
1; c <= n; c++) fact = fact * c; printf("Factorial of %d = %dn", n, fact); getch(); }
16. Factorial program in c using function #include <stdio.h> #include<conio.h> long
factorial(int); void main() { int number; long fact = 1; printf("Enter a number to calculate it's

17.

18.
19.
20.
21.

22.

factorialn"); scanf("%d", &number); printf("%d! = %ldn", number, factorial(number)); getch(); }


long factorial(int n) { int c; long result = 1; for (c = 1; c <= n; c++) result = result * c; return
result; }
17. Factorial program in c using recursion #include<stdio.h> #include<conio.h> long
factorial(int); void main() { int n; long f; printf("Enter an integer to find factorialn"); scanf("%d",
&n); if (n < 0) printf("Negative integers are not allowed.n"); else { f = factorial(n); printf("%d! =
%ldn", n, f); } getch(); } long factorial(int n) { if (n == 0) return 1; else return(n * factorial(n1)); }
18. Program to Find HCF and LCM
19. C program to find hcf and lcm using recursion
20. C program to find hcf and lcm using function
21. Program to sum the digits of number using recursive function #include <stdio.h>
#include<conio.h> int add_digits(int); void main() { int n, result; scanf("%d", &n); result =
add_digits(n); printf("%dn", result); getch(); } int add_digits(int n) { int sum = 0; if (n == 0)
{ return 0; } sum = n%10 + add_digits(n/10); return sum; }
22. Thank You Raj Kumar Tandukar rktandukar@hotmail.com

You might also like