### Computer Programming for Engineering Applica"ons Intro to

```9/24/13
Computer Programming for Engineering Applica4ons ECE 175 Intro to Programming Lecture Set Overview Modular Programming – Func4ons 9/24/13 ECE 175 2 Func4ons – Modular Programming Func4ons hide unnecessary details and hence, reduce complexity of the program Input parameters Output result Example: F
So far we have used the standardized func4ons of C language such as printf,
scanf, fprintf, fscanf
Func4ons make our program modular. Easier to debug and isolate errors Re-­‐use: We can reuse func4on we have wriTen in other programs Simplicity: simplify our code when a block of commands has to be repeated mul4ple 4mes within the main func4on 9/24/13 ECE 175 3 1
9/24/13
Func4on Declara4on Placement in your program Before the main func4on Usually at the top of your program right aXer the declara4ons for the pre-­‐processor Or can be placed at the boTom of your code, with a name declara4on at the top Input arguments – Data passed to the func4on Output arguments – Data returned from the func4on Syntax: data type function_name(data type var1, data type var2)
{
variable declarations;
statements;
return statement;
}
Argument list correspondence Number of arguments must be the same Ordering of arguments determines correspondence Each argument must be of a data type that can be assigned to the formal parameter 9/24/13 ECE 175 4 Example – Check if a 3-­‐tuple is a Pythagorean triple Problem Analysis Input: three integer numbers a, b, c Output: A binary decision (yes/no) Algorithm design Ini4al condi4on: Read three numbers from keyboard Checking condi4on: a^2 + b^2 = c^2 or b^2 + c^2 = a^2 or a^2 + c^2 = b^2 à outcome is a Pythagorean triple Modular design Func4on that computes x^y. Inputs: x, y Output: x^y 9/24/13 ECE 175 5 Func4ons with mul4ple inputs, one output Function name
Input arguments
Data type returned by the
function
Internal variable declaration
Returned value
9/24/13 long int power(int b, int n)!
{!
int i!
long int p=1 ;!
"!
"for (i = 1; i <= n; i++)!
" p=p*b;!
" !
" return p;!
}
ECE 175 6 2
9/24/13
Func4on Calling #include<stdio.h>!
long int power(int base , int n);!
!
int main(void)!
{
" !
int i, base=2; !
long int res;!
printf("Base\tPower\tResult\n");!
for (i=1; i<=10; i++)!
{!
res=power(base, i);!
printf("%d\t%d\t%ld\n", base, i, res);!
}!
return (0);!
}
9/24/13 ECE 175 7 Func4on Re-­‐use #include<stdio.h>!
long int power(int b, int n);!
!
int main(void)!
{!
int a, b, c;!
!
printf("Enter the values of a, b,c:");!
scanf("%d%d%d", &a, &b, &c);!
if (power(a,2)+power(b,2)==power(c,2) ||!
power(a,2)+power(b,2)==power(c,2) ||!
power(a,2)+power(b,2)==power(c,2))!
{!
printf("Values (%d, %d, %d) form a Pythagorean triple",
a,b,c);!
}!
else!
{!
printf("Values (%d, %d, %d) do not form a Pythagorean
triple", a,b,c);
!
}!
return(0);
!
}
9/24/13 ECE 175 8 Func4ons without Return Types (and statement…) #include<stdio.h>!
void print_rboxed(float r);!
!
int main(void)!
{!
"float real_n;!
"printf("Give me any real number:");!
"scanf("%f", &real_n); // scanning for a real!
"print_rboxed(real_n); // calling the print_rboxed function!
return(0);!
}!
!
void print_rboxed(float r)!
{ !
printf("***************\n");!
printf("*
*\n");!
printf("* %7.2f
*\n", r);!
printf("*
*\n");!
printf("***************\n");!
}!
!
9/24/13 ECE 175 9 3
9/24/13
Func4on data Each 4me a func4on is executed, an area of memory is allocated Local variables declared within the scope of the func4on The data area is lost when the func4on terminates It is recreated empty when the func4on is called again All the local variables have undeﬁned (random) value 9/24/13 ECE 175 10 Func4ons with no arguments void title(void)!
{!
printf("Power calculation tool\n\n");!
printf("Base\tPower\tResult\n");!
!
return;!
}!
9/24/13 int main(void)!
{
" !
int i, base=2; !
long int res;!
title();!
for (i=1; i<=10; i++)!
{!
res=power(base,i);!
printf("%d\t%d\t%ld\n", base, i, res);!
}!
return (0);!
}
ECE 175 11 Conversion Binary to Decimal, Decimal to Binary Problem statement: Write a C program that converts binary numbers to decimals. 9/24/13 ECE 175 12 4
9/24/13
Breaking down to elementary tasks Program analysis Input: A binary number Output: the converted number Algorithm design Ini4al condi4on: Read the number from keyboard Conversion from binary to decimal: compute number length. Divide by 10^(i-­‐1) to isolate the leXmost digit. Keep a sum of the leXmost digit 4mes 2^(i-­‐1). Subtract 10^i from binary number and con4nue un4l number is equal to zero. Modular design Func4on for binary to decimal and length of the number. User Interface Ask user for binary number or quit the conversion tool 9/24/13 ECE 175 13 Func4on for the Computa4on of the Number Length int numb_len(long int number)!
{!
int count=0; // digit counter initialized to
zero!
!
while(number!=0)!
{!
count++; // increase digit counter!
number=number/10; // divide by ten!
}!
return count; // return the length of the number!
}
9/24/13 ECE 175 14 Binary-­‐to-­‐decimal int bin_dec(long int number)!
// binary-to-decimal conversion!
{!
"int digit=0, i=0, dec=0;!
!
"for (i=numb_len(number); number!=0; i--)!
{ !
digit=number/pow(10,i-1);!
dec+=digit*pow(2,i-1); //2^i !
number=number-(digit*pow(10,i-1)); !
"
// number = number - 10^i!
} !
return dec;!
}
9/24/13 ECE 175 15 5
9/24/13
Interface #include<stdio.h>!
#include<math.h>!
int numb_len(long int number);!
int bin_dec(long int number);!
!
int main(void)!
{
" !
long int binary;!
char ans='y';!
!
while (ans!='n' && ans!='N')!
{!
printf("Enter the binary number you want to convert>");!
scanf("%ld",&binary);!
printf("(%ld)_2 equals (%d)_10\n", binary, bin_dec(binary));!
printf("Do you want to continue y/n?:");!
fflush(stdin);!
scanf("%c", &ans);!
}!
return (0);!
}
9/24/13 ECE 175 16 Another Version of the bin_dec Func4on int bin_dec(long int bin)!
// binary-to-decimal conversion!
{!
"int digit=0, i=0, dec=0;!
!
"while(bin!=0)!
{!
digit=bin%10; // compute the remainder with 10!
// to isolate the rightmost digit!
dec+=digit*pow(2,i); //2^i!
bin=bin/10; // integer division with 10!
i++;!
}!
return dec;!
}
9/24/13 ECE 175 17 Compu4ng Grade Sta4s4cs -­‐ Func4on Style Write a program that reads ﬁle “grades.txt” and prints the following on ﬁle “stats.txt” average, minimum, and maximum grade Input: grades.txt Output: stats.txt Constraints: Number of students is unknown Algorithm: AVE = SUM/# of students MIN = 100, if current # < MIN à MIN = current # MAX = 0, if current # > MAX à MAX = current # 9/24/13 ECE 175 18 6
9/24/13
Simpliﬁed main func4on #include <stdio.h>!
!
int max_grade(void);!
int min_grade(void);!
float average(void);!
!
int main(void)!
{
!
int low, high;!
float ave;!
!
ave=average();!
low=min_grade();!
high=max_grade();!
!
if (ave!=-1)!
printf("The average grade in the class is:%.1f\n", ave);!
if (low!=-1)!
printf("The minimum grade in the class is:%d\n", low); !
if (high!=-1)!
printf("The maximum grade in the class is:%d\n", high);!
return(0);!
}
9/24/13 ECE 175 19 Max Grade func4on int max_grade(void)!
{!
int n_st=0, max=0, grade;!
FILE *inp = fopen("grades.txt", "r"); // open grades.txt!
if (inp == NULL)!
{
!
printf("The input file does not exist\n"); !
max = -1;!
}!
else!
{
"
"
"!
while (fscanf(inp, "%d", &grade)!=EOF ) !
// while have not reached the end of file!
{!
n_st++;!
if (grade>max || n_st==1)!
max=grade; !
}!
fclose(inp); // close the file that inp points at!
}!
return max;!
}!
9/24/13 ECE 175 20 Min Grade func4on int min_grade(void)!
{!
int n_st=0, min=0, grade;!
FILE *inp = fopen("grades.txt", "r"); // open grades.txt
if (inp == NULL)!
{
!
printf("The input file does not exist\n"); !
min = -1;!
}!
else!
{
"
"
"!
while (fscanf(inp, "%d", &grade)!=EOF ) !
// while have not reached the end of file!
{!
n_st++;!
if (grade<min || n_st==1)!
min=grade; !
}!
fclose(inp); // close the file that inp points at!
}!
return min;!
}!
9/24/13 ECE 175 !
21 7
9/24/13
Average Grade func4on float average(void)!
{!
int n_st=0, grade;!
float sum=0, ave;!
!
FILE *inp = fopen("grades.txt", "r"); // open grades.txt !
if (inp == NULL)!
{
printf("The input file does not exist\n"); !
ave = -1;!
}!
else!
{
"
"
"!
while (fscanf(inp, "%d", &grade)!=EOF ) !
{!
n_st++;!
sum+=grade;!
}!
ave = sum/n_st;!
fclose(inp); // close the file that inp points at!
}!
return ave;!
9/24/13 ECE 175 22 }
8
```