| Functions What is functions? We have meet Main at the beginning of this tutorial. Main can be thought of as the master function. In C programming there is only 1 Main function. Inside Main there can be as many functions as possible to do other processing required by the main function. For example let say a calculator program: int Main() { 1. Function to display character on LCD. 2. Function to read number entered by user. 3. Function to perform addition. 4. Function to perform subtraction. 5. Function to perform multiplication. 6. Function to perform division. } In order to create a function, we need to write the function name inside the main program, for example function to display character on the Computer Screen: int Main() { void Display(); // we called function Display } Remember that we just need to write the name of the function in the Main program. We can then write the function code outside the Main Program. For example: int Main() { void Display(); // we called function Display } void Display() { printf(“Displaying numbers : %d \n", a); } when the program run, the Main program will process the Display function. Example program that read numbers, sum it and display the total value: #include <stdio.h> main() { int total; int sum(); //sum function name for(;;) { printf("Enter all numbers seperated by spaces, end with 0 and press Enter\n"); total = sum(); printf("Sum of the numbers is %d\n", total); // getchar(); // getchar(); } } int sum(void) { int number, isum = 0; scanf("%d", &number); while(number !=0) { isum += number; scanf("%d", &number); } return(isum); } Explanation of the program code : In the Main function, variable Total will get the total value of the number calculated by function sum(). After the sum() function has finish calculating, the C keyword return(isum) will pass the total number to Main function and display it onto the Computer Screen. Next Page >> |