C Programming Language OUTLINE Top-Down Design with Functions Selection Structures: if statement Nested if / else structures; Switch statement Practice
Jan 20, 2016
C Programming Language
OUTLINE
Top-Down Design with FunctionsSelection Structures: if statementNested if / else structures; Switch statementPractice
Top-Down Design with Functions
3
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.
4
Carefully following the software development methodis 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.
5
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.
6
Analysis
Problem Inputs - radius
Problem Outputs - area, circumference
Formulas
- area = PI * r * r- circumference = 2 * PI * r
7
#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);
}
8
#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);}
9
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
10
New problem: computing the area ofa 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:
11
Functions
Important concept in programming languages:- function represents a block of code whichbe reused again and again - procedural
abstraction
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
12
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 programstatement - execute the function code
Function called
Function returns
Function
13
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( )
14
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
15
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 aheader file
16
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”
17
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:
****************************************
18
...
/* 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
19
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.
20
In general, a function may be passed data by the calling code
- arguments and parameters
In general, a function may return results to the callingcode
- 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) )
21
In general, a function is defined with the followingformat:
data type function_name(parameter list){ local variables declarations; function code; return (value);}
Function definition comprises
- function heading
- function body
22
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();
void is the data typeof this function - does
not return a value
The argument list(void) indicates the
function has noarguments
The return is optionalif function does
not return a value
23
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.
24
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 name2. The data type of the function3. The function arguments
25
For a simple function, the function prototype hasthe 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 main3. function definition(s)
26
#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 orcalled by the statement
print_banner();
27
Local Variables
Each function can have variables declared inside it, these are local variables.
These variables do not have 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.
28
Functions with Input Arguments
Suppose we now want to change the program:
it should now print 5 rows of asterisks when itstarts and when it finishes, but print the original 2 line banner everywhere else.
We could write an additional function that prints 5rows of asterisks, or …
Could we somehow generalize print_banner()?
Could we make the same function do double duty?
29
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 “thistime” when we call it
N is information that the function needs to know
- it is the parameter for any call to print_banner()
30
Code for the Modified Function
To include parameters in a function, must modify thefunction 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_lines can be used inside the function just like a variable.
31
#include <stdio.h>int main(void){ print_banner(5); /* produce some output */ print_banner(2); /* produce final output */ print_banner(5); return(0);}
32
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
33
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.
34
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?
35
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.
36
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 evaluatesto type double
37
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) ;}
38
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
39
Selection Structures:if statement
41
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!
42
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 nested to any depth,
where “nested” means “put inside one another”.
43
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);
44
Selection Control of Flow
It is possible to alter the sequential flow of control usingselection (or conditional) statements.
Choose which of two
(or more) statements
to execute before
continuing
Choose whether or not
to skip a statement
before continuing
45
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.
46
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!
47
Conditional Flow Chart
if (x < 100)
x = x + 1 ;
y = y + 1;
48
Conditions
Within the parentheses () is a condition, also called a “logical” or “Boolean” expression.
It is made up of variables, constants, arithmetic expressions, and relational operators and …
A relational operator compares two values - the result is TRUE or FALSE
Examples:
(x < 30) - Is x less than 30?
(12 > y) - Is 12 greater than y?
49
Relational Operators
In Maths In C In English
< < Less Than
> > Greater Than
= == Equal To
<= Less Than or Equal To
>= Greater Than or Equal To
!= Not Equal To
50
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.
51
Examples
if (x < 100)
x = x + 1;
if (withdrawalAmount > balance)
printf( "Not enough money\n");
if (temperature > 98.6)
printf("You have a fever.\n");
if ( grade >= 60 ) printf( "Passed\n" );
52
Value of Conditional Expressions
The value of a conditional expression is either TRUE or FALSE.
C actually implements these “Boolean values” as integers:
- FALSE is 0 (and 0 is FALSE)- TRUE is 1 (and 1 is TRUE)
TRUE is also any other non-zero value …
Relational operators will always give 1 for TRUE(e.g. 4 < 7 evaluates to 1)
53
C does not have a Boolean type - use int instead!
E.g.
int senior_citizen;
...
senior_citizen = 1; /* equivalent to TRUE */
sets variable senior_citizen to TRUE
Better still
#define TRUE 1 if (senior_citizen) {
#define FALSE 0 ...
int senior_citizen; }
...
senior_citizen = TRUE;
54
Pitfall
Wrong!
if ( 0 <= x <= 10 ) {
printf ( "x is between 0 and 10. \n " ) ;
}
Right!
if ( 0 <= x && x <= 10 ) {
printf ( "x is between 0 and 10. \n " ) ;
}
55
Pitfall
Operators:
& is different from &&
| is different from ||
& and | are not used in this class, but are legal C
If used by mistake, no syntax error, but program may produce bizarre results
& and | are “bitwise” operators- they operate on the bits of
a memory cell
56
Pitfall
Do not use == or != with type double
- type double constants and variables are not stored as exact real number values, but only as approximations.
Using == and != only makes sense if the values being compared are exact, e.g. types int and char
But < , > , etc. are fine for use with double types.
57
Pitfall
Confusing equality (==) and assignment (=) operators
• Dangerous error– Does not ordinarily cause syntax errors!– Any expression that produces a value can be
used in control structures – Non-zero values are true, zero values are false.– Example using ==
if ( pay_code == 4 )
printf( "You get a bonus!\n" );
• Checks pay_code, if it is equal to 4 then a bonus is awarded.
58
– Example, replacing == with =
if ( pay_code = 4 )
printf( "You get a bonus!\n" );
– This sets pay_code to the value 4
• The value 4 is non-zero, so expression is true, and bonus awarded no matter what the pay_code is!
– Logic error, not a syntax error
Note: an assignment statement is an expression - its value is the value being assigned.
59
The World’s Last C Bug!
status = check_radar ( ) ;
if (status = 1) {
launch_nuclear_missiles ( ) ;
}
Using = instead of == is not a syntax error, so the compiler will not report any errors and the program can execute.
60
Quick Quiz
1. What are the values assigned?
foo = 7 < 0;bar = 8 != 3;
2. What does this do?
int foo, bar;foo = (bar = 6);
3. What does this do?
if (x = 7) printf(“x is equal to 7\n”);
4. What does this do?
x == PI * radius * radius;
61
“if” statement with two alternatives
if
– Only performs an action if the condition is true
if / else
– Specifies an action to be performed both when the condition is true, and when it is false.
if (condition)
statement_1;
else
statement_2;
Note indentation!
condition TRUE
condition FALSE
62
Example
if ( grade >= 60 )
printf( "Passed\n");
else
printf( "Failed\n");
if (balance >= withdrawal){
balance = balance - withdrawal;
}
else {
printf (“Insufficient Funds!\n”);
}
63
Example
if (x > y){
printf (“x is bigger\n”);
printf (“x is %f”, x);
}
else {
printf (“y is bigger\n”);
printf (“y is %f”, y);
}
64
• Nested if / else structures
– Test for multiple cases by placing if / else selection structures inside if/else selection structures!
– Once condition is met, rest of statements skipped
If student’s grade is greater than or equal to 90Print “A”
else If student’s grade is greater than or equal to 80 Print “B”else If student’s grade is greater than or equal to 70 Print “C” else If student’s grade is greater than or equal to 60 Print “D” else Print “F”
65
The switch statement
Useful when a variable or expression is tested for all the values it can assume and different actions are taken.
Convenient way of dealing with multiple alternatives.
66
Format
– Series of case labels and an optional default case
switch ( expression ){
case_1:
statements_1;
break;
case_2:
statements_2;
break;
default:
statements;
}
– break; exits from structure
Value of expression, whichmust be of type int or char,
is compared to each caselabel in turn. If a match is
found, statements associatedwith that case label are
executed until break statementencountered. Then the switch
construct is exited.
The default statement is a“catch-all” for no case labels
having a match.
67
Switch
Example:Program that figures interest on money that is held in a bank. The amount of interest that money earns depends on which type of account the money is in.
– 6 different types of accounts and they earn interest as follows:
account typeinterest earned1 -personal
financial2.3%
2 -personal homeowner
2.6%3 -personal gold 2.9%4 -small business 3.3%5 -big business 3.5%6 -gold business 3.8%
68
if (account_type == 1) interest = 2.3;
else if (account_type == 2) interest = 2.6; else if (account_type == 3)
interest = 2.9; else if (account_type == 4)
interest = 3.3; else if (account_type ==
5) interest = 3.5; else interest =
3.8;
Fragment with nested if / else structures
69
switch (account_value) {
case 1: interest = 2.3;
break;
case 2: interest = 2.6;
break;
case 3: interest = 2.9;
break;
case 4: interest = 3.3;
break;
case 5: interest = 3.5;
break;
case 6: interest = 3.8;
break;
default: interest = 0.0;
}
Fragment with switch statement
account_value is of type int
PRACTICE ( CONDITIONAL STATEMENTS)
70
71
C language program code for Leap Year
A classic example to demonstrate the nested if-else conditional scenarios of these languages.
The algorithm or logic for Leap year is basically that: 1. A year is a leap year if it is divisible by 4 but not by 100. 2. If a year is divisible by both 4 and by 100, then it can only be a leap year if it is also divisible by 400.
Going by the above logic, any year that is divisible by 400 must definitely be a leap year (because any number divisible by 400, is also divisible by 4)If a number is not divisible by 400, then we can check whether it is divisible by 100. If that is the case then it is definitely not a leap year (even if it is divisible by 4. this is as per condition no.1 above)After checking divisibility of the year by 400, and 100, lastly we can check whether the number is exactly divisible by 4. If it is, then its a leap year, else its not a leap year.
C language program code for Leap Year#include <stdio.h>
void main() {
int year;
system("clear");
printf("Enter the Year that you want to check : ");
scanf("%d", &year);
if(year % 400 == 0)
printf("%d is a Leap Year.", year);
else
if(year % 100 == 0)
printf("%d is not a Leap Year.", year);
else
if(year % 4 == 0)
printf("%d is a Leap Year.", year);
else
printf("%d is not a Leap Year", year);
printf("\nPress any key to Quit...\n"); system("/sbin/getkey");
}
72
Checking for Leap Year - untraditional approach or the Power of command line
Linux command line
Shell is not only your interface to Linux OS.
It is also a programming language (scripting language).
Some more Linux commands: pipe mechanism |
grep, wc, who, cal
Try these commands:
who
wc leapyear.c (option –l)
grep Leap leapyear.c
cal
cal 2013 cal –j 2012 cal –j 2013
cal 1752 (?????)
73
Checking for Leap Year - untraditional approach or the Power of command line
How about using Linux cal and grep commands to check if the year is leap or not leap?
cal 2 2000 | grep “ 29”
___________________________________________________
[ "`cal 2 1960 | grep 29`" != "" ] && echo 1960 is a leap year || echo 1960 is not a leap year
leapLinux:[ "`cal 2 $1 | grep ' 29'`" != "" ] && echo $1 is a leap year || echo $1 is not a leap year
___________________________________________________
74