Introduction to C Programming

Report 2 Downloads 353 Views
Chapter 5

CS12 - Computer Programming 1

Chapter 5

1

Objectives • Understand the concept of functions in C • Learn and include function prototype and function definition in C program • Know what is global/external and local variables, when to include them in C program • Appreciate the purpose of parameter passing and how it works in C program • Learn and understand how to incorporate functions in program for validation check

CS12 - Computer Programming 1

Chapter 5

2

Why functions are used in C?  to avoid writing the same instructions repeatedly  make it easier to organize programs and keep track of what they were doing  each subroutine (function) could be written and checked out more or less independently  the variables in each subroutine were protected from inadvertent tampering by other subroutines

CS12 - Computer Programming 1

Chapter 5

3

The Structure of Functions There are three program elements involved in using a function: 1. The function definition – The function itself is referred to as function definition

2. The call to the function - The function is called by main() by using its name including the parenthesis that following the name

3. The function prototype - A function is declared in a similar way at the beginning of a program before it is called CS12 - Computer Programming 1

Chapter 5

4

Local Variables - Functions which are known only within that function and other functions are not allowed to use them - Also known as automatic variables - The length of time a variable lasts is called lifetime.

CS12 - Computer Programming 1

Chapter 5

5

Functions that Return a Value - A function that uses no arguments but returns a value is a slightly more complicated kind of function: a function that returns a value.

CS12 - Computer Programming 1

Chapter 5

6

Using Arguments to Pass Data to a Function  The mechanism used to convey information to a function is the argument  In the function definition, a variable name could be placed in the parentheses CS12 - Computer Programming 1

Chapter 5

7

Passing Multiple Arguments  We can pass as many arguments as we like to function  The value of the first actual argument in the calling program is assigned to the first formal argument in the function, and the value of the second actual argument is assigned to the second formal argument CS12 - Computer Programming 1

Chapter 5

8

‘Void’ type functions  A function returns a single result, but a void type function does not return anything (but does something, a sub-program)! Example (void): Printing Cards #include <stdio.h> void printcard(int); int main(){ int c1, c2, c3, c4, c5; printcard(c1); printcard(c2); printcard(c3); printcard(c4); printcard(c5); } CS12 - Computer Programming 1

void printcard(int cardnum){ if(cardnum==1) Printf("A“); else if(cardnum>=2 && cardnum