# Functions in C program

Document Contents

### Introduction

In this post, we will learn how to write functions in a C program. A function is a block of code that performs a specific task for you upon invocation.  In order to make use of function, you have to do three steps.

The three steps are:

Declare Function.

Define the Function.

Invoke the function.

Lets see how to perform those steps with the help of simple C program. The sample program is to calculate Total, Average and Percentage of  subject marks of a student.

### Sample C Program:

```#include <stdio.h>
// Sample Program to calculate Total, Average and Percentage of
// subject marks

//Function prototypes as per the Question
float getStudentMarks(int n,int maxMarks);
float calculateAverage(int n,float total);

/*******************************
* Main method
********************************/
int main(){
// to hold n
int n;
float totalMarks=0.0;
float averageMarks=0.0;
float percentageOfMarks=0.0;
// max marks for each subject, usually 100.
int subjectMarksUpon=100;

printf("Enter number of subjects: \n");
scanf("%d", &n);
totalMarks=getStudentMarks(n,subjectMarksUpon);
averageMarks = calculateAverage(n,totalMarks);
percentageOfMarks = (totalMarks/(n * subjectMarksUpon)) * 100;

printf("\nTotal of %d subjects marks = %0.2f",n,totalMarks);
printf("\nAverage Marks = %.2f", averageMarks);
printf("\nPercentage = %.2f %%", percentageOfMarks);
return 0;
}

/*******************************
* getStudentMarks() method
********************************/
float getStudentMarks(int n,int maxMarks){
int i;
float marks=0.0;
float total=0.0;
for(i = 0; i < n; i++){
printf("Enter marks of each subject:\n");
scanf("%f", &marks);
printf("You entered = %.2f / %d \n",marks,maxMarks);
total += marks;
}
}

/*******************************
* calculateAverage() method
********************************/
float calculateAverage(int n,float total){
}

``` ### Program Run Output:

Enter number of subjects:

3

Enter marks of each subject:

56

You entered = 56.00 / 100

Enter marks of each subject:

78

You entered = 78.00 / 100

Enter marks of each subject: 88

You entered = 88.00 / 100

Total of 3 subjects marks = 222.00

Average Marks = 74.00

Percentage = 74.00 %