MONITOR/DISPLAY
1 9
2 8
3 7
4 6
1
CS 159 - C Programming
Lecture 7
Announcements
Missed last lecture? Check Brightspace
Absences/Make up Work
• Watch lecture recordings
• Visit instructor office hours and discuss missed work
Accommodations
• Visit DRC section of Brightspace to schedule exams
• PTS (Purdue Testing Services) will accommodate you if you put in a request in advance
John Robinson (Major)
[email protected] Feasting with the Faculty –
JOIN US!!
• Windsor Dining Court:
LWSN B116J
Wednesdays at 12:30PM for
lunch
Office Hours:
Mon 10:00 - 11:30
Wed 2:00 - 3:30
3
Supplemental Instruction
Aidan Driscol
Tuesday’s Thursday’s
Sessions: 4:30-5:20 pm 4:30-5:20pm
HAMP 1113 HAMP 1113
Thursday’s
Office
12:00-1:00 pm
Hours:
ASC, WILY 215
4
Overview
This Week: Chapter 4
Functions
- Don’t use functions in lab this week or HW02
Lab 3
- Don’t use functions in lab this week
Homework 2 – 22 September 25
- - Don’t use functions in HW02
5
Lecture Quiz Time
6
Lecture Quiz Time
7
Lecture Quiz
Question 1
What is the value of u after this expression is run?
x = 0;
y = 0;
z = 0;
u = --x - y++ + z--;
A. 0
B. -1
C. -2
D. -3
End Result: x=-1, y=1, z=-1
9
Lecture Quiz
Question 2
10
End of Quiz
11
Selection by Calculation
Revise program to make it correct
#include <stdio.h>
Example Executions:
int main(void) Enter two integers: 5 8
{ Max value input is: 8
int factor1; Enter two integers: 9 6
int factor2; Max value input is: 9
Enter two integers: 10 3
int x;
Max value input is: 30
int y;
int max;
printf("Enter two integers:");
scanf("%d%d",&x,&y);
factor1 = x / y; factor1 = 10 / 10 = 1
factor2 = 10 / 10 = 1
factor2 = y / x;
factor1 = 3 % 2 = 1
factor1 = (factor1 + 2) % (factor1 + 1);
factor2 = 3 % 2 = 1
factor2 = (factor2 + 2) % (factor2 + 1); max = [1 * 10] + [1 * 10] = 20
max = factor1 * x + factor2 * y;
max = max / (factor1 + factor2); max = 20 / (1 + 1) = 10
printf("Max value input is: %d\n", max);
return 0;
}
12
What this would look like with selection?
#include <stdio.h>
int main(void) Preview of future code functions
{
int numOne;
int numTwo;
int max;
printf("Enter two integers:");
scanf("%d%d",&x,&y);
if(numOne >= numTwo)
{
max = numOne;
}
else
{
max = numTwo;
}
printf("Max value input is: %d\n", max);
return 0;
}
13
Selection by Calculation
Example 2
Example: Using what we now know about data types and expressions, given the total number of points earned during
a semester calculate the letter grade earned.
Enter total points earned: 470
Points Earned: 470
Grade Earned: A
Enter total points earned: 305
Points Earned: 305
Grade Earned: D
Enter total points earned: 415
Points Earned: 415
Grade Earned: B
Enter total points earned: 304
Points Earned: 304
Grade Earned: F
14
Selection by Calculation
Example 2
Solution:
#define A_MIN 470
#define B_MIN 415
#define C_MIN 360
#define D_MIN 305
int main()
{
int totalPoints; //TOTAL POINTS EARNED BY STUDENT
char courseGrade; //GRADE EARNED BY STUDENT
int gradePoints; //4 - A, 3 - B, 2 - C, 1 - D, 0 - F
printf("Enter total points earned: ");
scanf("%d", &totalPoints);
//gradePoints ADDS 0 OR 1 IN EACH EXPRESSION BELOW: After this
gradePoints = totalPoints / A_MIN; section
gradePoints += totalPoints / B_MIN; gradePoints will
gradePoints += totalPoints / C_MIN; = 0,1,2,3, or 4
gradePoints += totalPoints / D_MIN;
courseGrade = 'F' - gradePoints;
courseGrade -= totalPoints / D_MIN; //TO ACCOUNT FOR 'E'
printf("Points Earned: %d Grade Earned: %c\n", totalPoints, courseGrade);
return(0);
}
15
Selection by Calculation
Example 2
Solution:
#define A_MIN 470
#define B_MIN 415
#define C_MIN 360
#define D_MIN 305
int main()
{
int totalPoints; //TOTAL POINTS EARNED BY STUDENT
char courseGrade; //GRADE EARNED BY STUDENT
int gradePoints; //4 - A, 3 - B, 2 - C, 1 - D, 0 - F
printf("Enter total points earned: "); Test Input:
scanf("%d", &totalPoints);
370 200 500
//gradePoints ADDS 0 OR 1 IN EACH EXPRESSION BELOW:
gradePoints = totalPoints / A_MIN; = 370/470 0 200/470 0 500/470 1
gradePoints += totalPoints / B_MIN; += 370/415 0 200/415 0 500/470 2
gradePoints += totalPoints / C_MIN; += 370/360 1 200/360 0 500/470 3
gradePoints += totalPoints / D_MIN; += 370/305 2 200/305 0 500/470 4
courseGrade = 'F' - gradePoints;
= ‘F’ - 2 ‘D’ ‘F’ - 0 ‘F’ ‘F’ - 4 ‘B’
courseGrade -= totalPoints / D_MIN; //TO ACCOUNT FOR 'E'
= ‘F’ - 1 ‘C’ ‘F’ - 0 ‘F’ ‘F’ - 1 ‘A’
printf("Points Earned: %d Grade Earned: %c\n", totalPoints, courseGrade);
return(0);
}
16
Functions
Page 53
Why do we use functions?
Large problems can be broken down into understandable and manageable sub-problems
– Factoring – the identification of smaller tasks within the larger problem.
– A function should consist of a single specific task which is functionally cohesive.
– The process of factoring tasks into more manageable parts is known as top -down design.
Reusability. Once a function is defined, it
can be used over and over again in other
programs
– We already applied the idea in this
course, such as printf, scanf, functions
included in math.h, etc.
– We can also create personal and
project libraries that make developing
system easier
17
Functions
Why do we use functions?
We use functions to protect data
– Local data consist of data described in a function
– Local data are available only to the function and only while the
function is executing.
18
What is a function?
A function is a named block of code that performs a process within a program; an executable unit of
code, consisting of:
– A header (comments describing the function)
– Function name
– Return type and parameters
– Body that is designed to perform a task within a program.
In C, a program is made of one or more functions, one and only one of which must be called main function
19
Calling vs. Called functions
To be run, a function must first be called
– The function making the call is known as the calling function, e.g. main
function.
– The functions do not have to be called from main only. They may be called
from other functions.
– The function being called is the called function, e.g. printf, scanf function.
– When the called function completes its task, it returns control to the calling
function
20
Parameters
It is common that data needs to be exchanged between the calling and called
functions
– The act of sending (passing) data to a function as parameter passing.
– A function in C can have a return value, a side effect, or both.
– In C, a function is only capable of returning at most one value
21
Function Declaration and Definition
In C, functions must be both declared and defined.
The function declaration will appear in the global declaration section of the program
#include <stdio.h>
// Function declaration
int addTwo(int x, int y);
int main()
{
// Code and function calls
}
int addTwo(int x, int y) // Function Definition
{
// function code
}
22
Function Declaration
int addTwo(int x, int y);
The function declaration statement will tell the compiler:
– The type of value being return from the function. A function’s return type is also called that function’s type. If a
function does NOT return value, then it is a void function.
– The name of the function – follow same rules of naming variables
– The data being sent to the function – parameter list
– The number of parameters – as many as needed
– The type of each parameter
– The order of parameters
If a function does NOT have parameter, then an empty ( ) follows the function name, or you can put void inside (void)
The function definition contains the code needed to complete the task.
23
Basic Function Example
#include<stdio.h>
void welcome(void); // Function Declaration
int main()
{
welcome(); // function call
return 0;
}
/**********************************************************************
* Function Information
* Name of Function : welcome
* Function Return Type: void
* Parameters (list data type, name, and comment one per line): None
* Function Description: Displays the welcome message to the user
***********************************************************************
void welcome() // Function definition
{
printf(“\n\nWelcome to our program!\n”);
return; // It’s okay not having a return statement in a void function.
}
24
Compiler Looks For 3 Things
#include<stdio.h>
1. Declaration void welcome(void); // Function Declaration
int main()
{
2. Call welcome(); // function call
return 0;
}
/**********************************************************************
* Function Information
* Name of Function : welcome
* Function Return Type: void
* Parameters (list data type, name, and comment one per line): None
* Function Description: Displays the welcome message to the user
***********************************************************************
3. Definition void welcome() // Function definition
{
printf(“\n\nWelcome to our program!\n”);
return; // It’s okay not having a return statement in a void function.
}
25
4 Basic Function Designs
Page 55
1. No parameters, no return value
2. No parameters, yes return value
3. Yes parameters, no return value
4. Yes parameters, yes return value
Yes Parameters No Parameters
double x = pow(base, exponent) int x = rand();
Yes Return Value
printf(”Number: %d”, variable); welcome();
No Return Value
26
No Parameters and No Return Value
#include<stdio.h>
void welcome(); // Function Declaration
int main()
{
welcome(); // function call
return 0;
}
/**********************************************************************
* Function Information
* Name of Function : welcome
* Function Return Type: void
* Parameters (list data type, name, and comment one per line): None
* Function Description: Displays the welcome message to the user
***********************************************************************
void welcome() // Function definition
{
printf(“\n\nWelcome to our calculator program!\n”);
return; // It’s okay not having a return statement in a void function.
}
27
No Parameters and No Return Value
#include<stdio.h>
Declaration void welcome(); // Function Declaration
int main()
{
Call welcome(); // function call
return 0;
}
/**********************************************************************
* Function Information
* Name of Function : welcome
* Function Return Type: void
* Parameters (list data type, name, and comment one per line): None
* Function Description: Displays the welcome message to the user
***********************************************************************
Definition void welcome() // Function definition
{
printf(“\n\nWelcome to our calculator program!\n”);
return; // It’s okay not having a return statement in a void function.
}
28
No Parameters and No Return Value
#include<stdio.h>
void welcome(); // Function Declaration
int main()
{
welcome(); // function call
return 0;
}
/**********************************************************************
* Function Information
* Name of Function : welcome
* Function Return Type: void
* Parameters (list data type, name, and comment one per line): None
* Function Description: Displays the welcome message to the user
***********************************************************************
void welcome() // Function definition
{
printf(“\n\nWelcome to our calculator program!\n”);
return; // It’s okay not having a return statement in a void function.
}
29
No Parameters and No Return Value
#include<stdio.h>
void welcome(); // Function Declaration
int main()
{
welcome(); // function call
return 0;
}
/**********************************************************************
* Function Information
* Name of Function : welcome
* Function Return Type: void
* Parameters (list data type, name, and comment one per line): None
* Function Description: Displays the welcome message to the user
***********************************************************************
void welcome() // Function definition
{
printf(“\n\nWelcome to our calculator program!\n”);
return; // It’s okay not having a return statement in a void function.
}
30
No Parameters and No Return Value
#include<stdio.h>
/**********************************************************************
* Function Information
* Name of Function : welcome
* Function Return Type: void
* Parameters (list data type, name, and comment one per line): None
* Function Description: Displays the welcome message to the user
***********************************************************************
void welcome() // Function definition
{
printf(“\n\nWelcome to our calculator program!\n”);
return; // It’s okay not having a return statement in a void function.
}
int main()
{
welcome(); // function call
return 0;
}
31
No Parameters and Does Return Value
Calculator Program: New Function: Get Input
/*****************************************************************************
*
* Function Information
*
* Name of Function: getInput
*
* Function Return Type: int
*
* Parameters (list data type, name, and comment one per line): NONE
*
* Function Description: Accept and return the user integer input.
*
*****************************************************************************/
32
No Parameters and Does Return a Value
#include<stdio.h>
void welcome(); // Function Declaration
int getInput(void); // Function Declaration
int main(void)
{ //LOCAL VARIABLE DECLARATIONS
int operand1; //FIRST OPERAND ENTERED BY USER
int operand2; //SECOND OPERAND ENTERED BY USER
//EXECUTABLE STATEMENTS
welcome();
operand1 = getInput(); //THE ASSIGNMENT OPERATOR AWAITS THE
operand2 = getInput(); //VALUE RETURNED FROM getInput()
return(0);
}
33
No Parameters and Does Return a Value
#include<stdio.h>
void welcome(); // Function Declaration
int getInput(void); // Function Declaration
int main(void)
{ //LOCAL VARIABLE DECLARATIONS
int operand1; //FIRST OPERAND ENTERED BY USER
int operand2; //SECOND OPERAND ENTERED BY USER
//EXECUTABLE STATEMENTS
welcome();
operand1 = getInput(); //THE ASSIGNMENT OPERATOR AWAITS THE
operand2 = getInput(); //VALUE RETURNED FROM getInput()
return(0);
}
int getInput(void)
{
//LOCAL DECLARATIONS
int op; //USER'S OPERAND INPUT - ONLY VARIABLE AVAILABLE TO THIS FUNCTION
printf("Enter integer operand -> ");
scanf("%d", &op); Note: We have both the
prompt and the scanf() here
return(op);
}
34
Parameters - Yes, Return Value - Yes
/***************************************************************************
*
* Function Information
*
* Name of Function: calcRemainder
*
* Function Return Type: int
*
* Parameters (list data type, name, and comment one per line):
* 1. int op1 - FIRST OPERAND FOR REMAINDER CALCULATION
* 2. int op2 - SECOND OPERAND FOR REMAINDER CALCULATION
*
* Function Description: Returns the result of the modulus operator for
* two integer values.
*
***************************************************************************/
int calcRemainder(int op1, int op2)
{
int rem; //TEMPRORARY STORAGE OF REMAINDER
remain = op1 % op2;
return(remain);
}
35
Parameters - Yes, Return Value - Yes
#include<stdio.h>
void welcome(); // Function Declaration
int getInput(void); // Function Declaration
int calRemainder(int, int); // Function Declaration
int main(void)
{ //LOCAL VARIABLE DECLARATIONS
int operand1;
int operand2;
//EXECUTABLE STATEMENTS
welcome();
operand1 = getInput(); //THE ASSIGNMENT OPERATOR AWAITS THE
operand2 = getInput(); //VALUE RETURNED FROM getInput()
return(0);
}
// Header omitted due to space
int calcRemainder(int op1, int op2)
{
int rem; //TEMPRORARY STORAGE OF REMAINDER
remain = op1 % op2;
return(remain);
}
36
Parameters - Yes, Return Value - Yes
/***************************************************************************
*
* Function Information
*
* Name of Function: calcQuotient
*
* Function Return Type: int
*
* Parameters (list data type, name, and comment one per line):
* 1. int op1 - FIRST OPERAND FOR QUOTIENT CALCULATION
* 2. int op2 - SECOND OPERAND FOR QUOTIENT CALCULATION
*
* Function Description: Returns the result of the modulus operator for
* two integer values.
*
***************************************************************************/
int calcQuotient(int op1, int op2)
{
return(op1/op2);
}
37
Parameters - Yes, Return Value - Yes
#include<stdio.h>
void welcome(); // Function Declaration welcome, getInput, calcRemainder
int getInput(void); // Function Declaration Omitted due to space constraints
int calcRemainder(int, int); // Function Declaration
int calcQuotient(int x, int y); // Function Declaration
int main(void)
{ //LOCAL VARIABLE DECLARATIONS
int operand1;
int operand2;
//EXECUTABLE STATEMENTS
welcome();
operand1 = getInput(); //THE ASSIGNMENT OPERATOR AWAITS THE
operand2 = getInput(); //VALUE RETURNED FROM getInput()
return(0);
}
// Header omitted due to space
int calcQuotient(int op1, int op2)
{
return(op1/op2);
}
38
Parameters - Yes, Return Value - No
/***************************************************************************
*
* Function Information
*
* Name of Function: displayResults
*
* Function Return Type: void
*
* Parameters (list data type, name, and comment one per line):
* 1. int op1 - first operand for quotient and modulus calculation
* 2. int op2 - second operand for quotient and modulus calculation
* 3. int rem - result of modulus calculation
* 4. int quo - result of division calculation
*
* Function Description: Displays final result of calculator program.
*
***************************************************************************/
void displayResults(int op1, int op2, int rem, int quo)
{
printf("%d / %d = %d\n", op1, op2, quo);
printf("%d %% %d = %d\n", op1, op2, rem);
}
39
Calculator Program with functions
#include<stdio.h>
void welcome();
int getInput(void);
int calcRemainder(int, int);
int calcQuotient(int x, int y);
int displayResults(int, int, int, int);
int main(void)
{ //LOCAL VARIABLE DECLARATIONS
int operand1;
int operand2;
//EXECUTABLE STATEMENTS
welcome();
operand1 = getInput(); //THE ASSIGNMENT OPERATOR AWAITS THE
operand2 = getInput(); //VALUE RETURNED FROM getInput()
displayResults(operand1, operand2, calcRemainder(operand1, operand2), calcQuotient(operand1, operand2);
return(0);
}
40