AST 131 C Lec-7
AST 131 C Lec-7
AST 131 C Lec-7
May, 2018
ogramming with
WHAT IS C FUNCTION?
● A large C program is divided into basic building blocks
called C function. C function contains set of instructions
enclosed by “{ }” which performs specific operation in a C
program. Actually, Collection of these functions creates a C
program.
USES OF C FUNCTIONS:
● C functions are used to avoid rewriting same logic/code again
and again in a program.
● There is no limit in calling C functions to make use of same
functionality wherever required.
● We can call functions any number of times in a program and
from any place in a program.
● A large C program can easily be tracked when it is divided into
functions.
● The core concept of C functions are, re-usability, dividing a big
task into small pieces to achieve the functionality and to
improve understandability of very large C programs.
Example
#include<stdio.h>
// function prototype, also called function declaration
float square ( float x );
// main function, program starts from here
int main( )
{
float m, n ;
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
// function call
n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
}
Example
float square ( float x ) // function definition
{
float p ;
p=x*x;
return ( p ) ;
}
Another approach
#include<stdio.h>
float square ( float x );
int main( )
{
float m, n ;
printf ( "Enter some number for finding square \n");
scanf ( "%f", &m ) ;
// function call
square ( m ) ;
}
}
//Subprogram
int sos(int x[], int y[]){
int i, sum=0;
for(i=0; i<3; i++){
sum+=x[i]*y[i];
}
return sum;
}
Task 21.2
Write a C function factorial that inputs n and calculate n!.
Solution 21.2 (Factorial function)
#include <stdio.h>
unsigned long long int fact (unsigned int number);
int main(void)
{
unsigned i;
for (i=1; i<=10; ++i){
printf("%u!=%11u\n", i, fact(i));
}
}
Solution 21.2 cont…
unsigned long long int fact (unsigned int number)
{
unsigned counter; int prod=1;
for(counter=number; counter>=1; counter--)
{
prod*=counter;
}
return prod;
}
Problem
Write a program in C to find the sum of the series
1!/1+2!/2+3!/3+4!/4+5!/5 using the function.
Solution
#include <stdio.h>
int fact(int);
void main()
{
int sum;
sum=fact(1)/1+fact(2)/2+fact(3)/3+fact(4)/4+fact(5)/5;
printf("The sum of the series is : %d\n\n",sum);
}
Solution
int fact(int n)
{
int num=0,f=1;
while(num<=n-1)
{
f =f+f*num;
num++;
}
return f;
}
Task 21.3
Write a C function combination that inputs n and x, and
calculate combination of n and x
Solution 21.3 (Combination function)
#include <stdio.h>
unsigned long long int fact (unsigned int number);
int main(void)
{
unsigned i, n, x, ncx;
printf("Enter the value of n and x:");
scanf("%u %u", &n, &x);
ncx=fact(n)/(fact(x)*fact(n-x));
printf("The value of ncx is: %u", ncx);
}
Solution 21.3 cont…