Functions
Functions
P r o g r a m m i n g - f u n c t i o n s
M o d u l a r p r o g r a m m i n g a n d
F u n c t i o n s
Lengthier programs
• Prone to errors
• tedious to locate and correct the errors
To overcome this
Programs broken into a number of smaller
logical components, each of which serves a
specific task.
• Debugging is easier
• Build library
User-defined functions
Written by the user(programmer)
statement1;
statement2;
.
.
.
return(value_computed);
}
4/9/2025 CSE 1001 Department of CSE 9
Defining a Function
Name (function name)
• You should give functions descriptive names
• Same rules as variable names, generally
Return type
• Data type of the value returned to the part of the program that activated (called)
the function.
Parameter list (parameter_definition)
• A list of variables that hold the values being passed to the function
Body
• Statements enclosed in curly braces that perform the function’s operations(tasks)
int main()
{
calculateSquare(5);
calculateSquare(25);
return 0;
}
• Void main()
•{
• Sum(); // calling
•}
dispPattern(); // prototype
int main(){
printf(“fn to display a line of stars\n”);
dispPattern();
return 0;
}
dispPattern(){
int i;
for (i=1;i<=20 ; i++)
printf( “*”);
4/9/2025 } CSE 1001 Department of CSE 65
Function with No Arguments but A return value
int readNum(void); // prototype
int main(){
int c;
printf(“Enter a number \n”);
c=readNum();
printf(“The number read is %d“,c);
return 0;
}
int readNum(){
int z;
scanf(“%d”,&z);
return(z);
}
4/9/2025 CSE 1001 Department of CSE 66
Fn with Arguments/parameters & No return values
void dispPattern(char ch); // prototype
int main(){
printf(“fn to display a line of patterns\n”);
dispPattern(‘#’);
dispPattern(‘*’);
dispPattern(‘@’);
return 0;
}
void dispPattern(char ch ){
int i;
for (i=1;i<=20 ; i++)
printf(“%c”,ch);
}
4/9/2025 CSE 1001 Department of CSE 67
Function with Arguments/parameters & One return
value
int fnAdd(int,int);
int main(){
int a,b,c;
printf(“\nEnter numbers to be added\n”);
scanf(“%d %d”,&a,&b);
c=fnAdd(a,b);
printf(“Sum is %d “, c);
return 0;
}
int fnAdd(int x, int y ){
int z;
z=x+y
return(z);
68
}
4/9/2025 CSE 1001 Department of CSE
Extra Problems…
Write appropriate functions to
1. Find the factorial of a number ‘n’.
2. Reverse a number ‘n’.
3. Check whether the number ‘n’ is a palindrome.
4. Generate the Fibonacci series for given limit ‘n’.
5. Check whether the number ‘n’ is prime.
6. Generate the prime series using the function written
for prime check, for a given limit.