Functions, continued
Download
Report
Transcript Functions, continued
Introduction to Computers and
Programming
Class 18
Functions
Professor Avi Rosenfeld
Admin Todo List
• Review HW #3 (with functions)
• Problems with HW #4
• HW #5
#include <iostream.h>
#include <stdio.h>
int GPA(char);
void main()
{
int count = 0, total = 0, tempcredit;
char tempgrade;
for (int i = 0; i < 5; i++)
{
printf("Type grade #%d followed by a credit value\n", i + 1);
cin >> tempcredit >> tempgrade;
total+=GPA(tempgrade);
count+=tempcredit;
printf("You typed %c and %d\n", tempgrade, tempcredit);
}
printf("Your GPA for your %d credits is %.2f\n", total, float(total)/count);
}
int GPA (char x)
{
if (x == 'a' || x == 'A')
return 4;
if (x == 'b' || x == 'B')
return 3;
if (x == 'c' || x == 'C')
return 2;
if (x == 'd' || x == 'D')
return 1;
return 0;
}
Telephone Program
• Function to convert one letter
What is the prototype
• How would the main function use it?
• How do you know how many functions to
write?
Prime Number Example
int IsPrime(int number)
{
/* Test all numbers less than the one passed in */
/* Of course we don't test 1
*/
for(int index = 2; index < number; index++)
{
if( (number % index) == 0 )
{
/* Found a divisor, return right away */
return 0;
}
}
/* If we got this far, it must be prime */
return 1;
}
Main Function
void main()
{
int num = 0;
printf("Please enter value: ");
scanf("%d", &num);
/* We will print 1 right away: that's always true */
printf("Prime numbers <= %d: 1 ", num);
/* Loop through all the numbers less than this and print the primes */
for(int index = 2; index <= num; index++)
{
if( IsPrime(index) == 1 )
{
printf("%d ", index);
}
}
printf("\n");
}
Boolean Functions
bool IsPrime(int number)
{
/* Test all numbers less than the one passed in */
/* Of course we don't test 1
*/
for(int index = 2; index < number; index++)
{
if( (number % index) == 0 )
{
/* Found a divisor, return right away */
return false;
}
}
/* If we got this far, it must be prime */
return true;
}