760 likes | 818 Views
C Programming Language. OUTLINE Top-Down Design with Functions Selection Structures: if statement Nested if / else structures; Switch statement Practice. Top-Down Design with Functions. Developing Programs Approaches:
E N D
C Programming Language OUTLINE Top-Down Design with Functions Selection Structures: if statement Nested if / else structures; Switch statement Practice
Developing Programs Approaches: 0. From square one - blank screen! But can still use existing information - system documentation - to help us before coding. 1. Re-using code from previous programs. 2. Using functions from libraries (sqrt, cos, log). 3. Building your own functions for reuse. Code reuse - “Why reinvent the wheel?” - extremely important concept.
Carefully following the software development method is extremely important - it generates useful system documentation before coding, e.g. description of data requirements, solution algorithm Use system documentation to develop outline program before the actual coding. E.g. data requirements data declarations initial algorithm and refinements comments Then add C statements under relevant comments, even replacing some comments with C statements which perform the required action.
Adapting existing programs Extending the solution of an old problem to solve another. Example: Suppose we have program to calculate the area and circumference of a circle, given its radius.
Analysis Problem Inputs - radius Problem Outputs - area, circumference Formulas - area = PI * r * r - circumference = 2 * PI * r
#include <stdio.h> #define PI 3.14159 int main(void) { double radius; /* input - radius of a circle */ double area; /* output - area of a circle */ double circum; /* output - circumference */ /* Get the circle radius */ /* Calculate the area */ /* Assign PI * radius * radius to area. */ /* Calculate the circumference */ /* Assign 2 * PI * radius to circum. */ /* Display the area and circumference */ return (0); }
#include <stdio.h> #define PI 3.14159 int main() { double radius; /* input - radius of a circle */ double area; /* output - area of a circle */ double circumf; /* output - circumference */ /* Get the circle radius */ printf("Enter radius> "); scanf("%lf", &radius); /* Calculate the area */ area = PI * radius * radius; /* Calculate the circumference */ circumf = 2 * PI * radius; /* Display area & circumf */ printf("The area is %.4f\n", area); printf("The circumf is %.4f\n", circumf); return (0); }
New problem: Calculate the price per square inch of a circular pizza given its size (diameter) and its cost. Build on solution to previous problem. Analysis Problem Inputs - diameter, cost Problem outputs - price_psqi Other variables - radius, area Formulas - radius = diameter / 2 - area = PI * r * r - price per square inch = price / area
New problem: computing the area of a flat washer. Strategy: This problem has a sub-problem - Calculate the area of a disk The total algorithm: - Calculate the area of the outer disk - Calculate the area of the inner disk - Subtract Solve the Sub-Problem Find the area of a disk:
Functions Important concept in programming languages: - function represents a block of code which be reused again and again - proceduralabstraction In-built C library functions and programmer-defined functions. Functions: - Break the problem up into smaller parts. - More easily reason about what the program will do - Let us write code once and use it many times - Centralize changes
Functions (or “procedures” or “subroutines”) allow you to “visit” a block of code, use it and then “return”. (The function may be elsewhere in your own program, or may be code in another file altogether.) Invoke or call a function by writing its name in program statement - execute the function code Function called Function Function returns
Some C Functions We have already seen and used several functions: int main (void) { ... return (0); Function definition for main( ) } printf (“format string", print_list); scanf (“format string", &input_list); Function arguments (parameters) Calls to the functions printf( ) and scanf( )
Library functions Pre-written functions are commonly packaged in "libraries” Every standard C compiler comes with a set of standard libraries Remember #include <stdio.h> ? – Tells the compiler you intend to use the “standard I/O library” functions – printf and scanf are in the standard I/O library – So are lots of other I/O related functions There are (many) other useful functions in other libraries
C has a large mathematical function library #include <math.h> To use library functions. you must #include the correct header files: - I/O (printf, scanf, ...) — stdio.h - Utility functions (exit, ...) — stdlib.h - Math functions (sin, sqrt, ...) — math.h … Known as a header file
Programmer-defined functions We can write our own functions and then call them just like we call library functions. - Identify a “sub-problem” that has to be solved in your program - represent by a function - Choose a name to represent “the solution of that problem by code” - function name - Write that solution code (only once) - function body - Whenever you see that same sub-problem again, use the function name to say “go to that code now to take care of this problem, and don’t come back until you’re done”
Example of a programmer-defined function Suppose we are writing a program that displays many messages on the screen, and… we would like to display two rows of asterisks (‘*’s) to separate sections of output: ******************** ********************
... /* produce some output */ ... /* print banner lines */ printf("********************\n"); printf("********************\n"); /* produce more output */ ... /* print banner lines */ printf("********************\n"); printf("********************\n"); /* produce even more output */ ... /* print banner lines */ printf("********************\n"); printf("********************\n"); ... It is correct C code. It fulfills the problem specification, i.e. gives the desired result
But what if we wanted to - change the number of rows of asterisks? - change the number of asterisks in a row? - use hyphens instead of asterisks? - print the date with each separator? These changes are much easier to make with a function - all the necessary code is localized within the function. We can put the code to display two rows of asterisks in a function.
In general, a function may be passed data by the calling code - arguments and parameters In general, a function may return results to the calling code - functions have a data type E.g. Remember the function main int main(void) The int is telling the compiler that main “returns” an integer type result (via return(0) )
In general, a function is defined with the following format: data type function_name(parameter list) { local variables declarations; function code; return (value); } Function definition comprises - function heading - function body
Anatomy of a Simple Function Template for defining a simple function - functions which do not “return” a value nor have arguments void function_name(void){ /* local variable declarations */ /* code */ } It is invoked with the statement function_name(); The argument list (void) indicates the function has no arguments void is the data type of this function - does not return a value The return is optional if function does not return a value
Our Function void print_banner(void){ /* local variable declarations */ /* code */ printf(“****************\n”); printf(“****************\n”); } It is invoked with the statement print_banner(); Empty ( ) is required when a parameter-less (void) function is called.
Function Prototypes Just like constants and variables, function must be declared before it is used. One way is to insert a function prototype before the main function. A function prototype specifies 1. The function name 2. The data type of the function 3. The function arguments
For a simple function, the function prototype has the format void function_name(void); For our print_banner function, the prototype is void print_banner(void); The order of statements is 1. function prototype(s) 2. function main 3. function definition(s)
#include <stdio.h> void print_banner(void); int main(void) { /* produce some output */ ... /* print banner lines */ print_banner(); /* produce more output */ ... /* print banner lines */ print_banner(); /* produce even more output */ ... /* print banner lines */ print_banner(); /* produce final output */ ... return (0) ; } void print_banner(void){ printf(“****************\n”); printf(“****************\n”); } The function is invoked or called by the statement print_banner();
Local Variables Each function can have variables declared inside it, these are local variables. These variables do nothave any meaning outside of the function Several functions can have variables with the same name - they are different variables because they are local to each function. Each time you call a function, you get new copies of each local variable - old values cannot be carried over! They start un-initialized.
Functions with Input Arguments Suppose we now want to change the program: it should now print 5 rows of asterisks when it starts and when it finishes, but print the original 2 line banner everywhere else. We could write an additional function that prints 5 rows of asterisks, or … Could we somehow generalize print_banner()? Could we make the same function do double duty?
Can we Generalize? Can we modify the function so that instead of print two rows of asterisks it will: print N rows of asterisks where N is the number of rows that we want “this time” when we call it N is information that the function needs to know - it is the parameter for any call to print_banner()
Code for the Modified Function To include parameters in a function, must modify the function prototype and function header to include a parameter list - a function may have one or more parameters. The parameter list must specify the data type and name for each parameter (rather like a data declaration) data type function_name(parameter list) The function print_banner will start off this way: void print_banner(int num_lines) { ... num_lines is the “parameter” of the function. num_linescan be used inside the function just like a variable.
#include <stdio.h> int main(void) { print_banner(5); /* produce some output */ print_banner(2); /* produce final output */ print_banner(5); return(0); }
The parameter list is a comma separated list of variables names with their types Parameters act like local variables except that they are initialized with the values that the function was called with. Distinguish between (formal) parameters and (actual) arguments. - The values passed to the function are called arguments. E.g. void print_banner (int num_lines) { print_banner(5); parameter argument
Note that arguments do not need to be numeric values. - may be a constant, variable or expression, as long as data type is correct. E.g. instead of print_banner(5); we may also have print_banner(count); where we have previously declared count to be of type int and assigned it a value of 5.
Functions with Input Arguments and Single Result Passing results back from a function to the caller Specification: Write a function that, given the radius, computes the area of a circle with that radius. What should the function do with the result?
Returned Values Parameters are a way for the calling code to “send data” to the function. The new concept, return values, are the opposite - a way for the function to send data back to the calling code.
To allow a result to be returned from a function, must modify the function prototype and function header to include the data type of the result. data type function_name(parameter list) E.g. double circle_area(double r) { return(3.14 * r * r); } Expression evaluates to type double
Multiple Parameters A function may have more than one parameter. Arguments must match parameters in number, order, and type E.g. double num, answer; num = 3.9; answer = scale(7, num); ... double scale(int factor, double number) { return(factor * number) ; }
A Function with Local Variables E.g. double CircleArea(double r) { double rsquared, area; rsquared = r * r ; area = 3.14 * rsquared ; return(area); }
Practice - Functions CtoF.c flat_washer.c print_banner2.c print_banner.c test_banner.c
Selection Structures: if statement
Compound statements Possible to group a “block” of simple statements together so that they are treated as a compound statement. The format of a compound statement is { statement1 ; statement2 ; ... } Used to indicate sequential control of flow. E.g. the body of a function is a compound statement!
You may use a compound statement anywhere that a single statement may be used. Anywhere that a statement is allowed in C, any kind of statement can be used. A compound statement can contain any number of statements (including zero). Among other things, these principles imply that compound statements can be nestedto any depth, where “nested” means “put inside one another”.
Control of Flow “Control of flow” means controlling the order in which statements are executed. Until now, flow has been sequential - the next statement executed is the next one that appears, in order, in the C program. int i = 1; i = i + 1; printf(“%d”, i);
Selection Control of Flow It is possible to alter the sequential flow of control using selection (or conditional) statements. Choose which of two (or more) statements to execute before continuing Choose whether or not to skip a statement before continuing
Conditional Execution Selection statements allow the computer to choose an execution path depending on the value of a variable or expression - conditional execution: – if the withdrawal is more than the bank balance, then print an error. – if today is my birthday, then add one to my age. – if it’s a 08:30 class, then prop your eyelids open; otherwise chew your finger nails while you wait for lunch.
Conditional ("if") Statement The simplest conditional statement is the “if” statement - test if a condition is true or false. if (condition) statement; The statement is executed if the condition is true. Otherwise, the statement is skipped (i.e. not executed). This if statement has a single alternative, but possible to have have two or more alternatives. Later! Note indentation!
Conditional Flow Chart if (x < 100) x = x + 1 ; y = y + 1;
Conditions Within the parentheses () is a condition, also called a “logical” or “Boolean” expression. It is made up of variables, constants, arithmetic expressions, andrelational operators and … A relational operatorcompares two values - the result is TRUE or FALSE Examples: (x < 30) - Is x less than 30? (12 > y) - Is 12 greater than y?
Relational Operators In MathsIn CIn English < < Less Than > > Greater Than = == Equal To <= Less Than or Equal To >= Greater Than or Equal To != Not Equal To
Examples of Conditional Expressions air_temperature > 80.0 98.6 <= body_temperature marital_status == ’M’ divisor != 0 Such expressions are used in if statements and numerous other places in C.