0% found this document useful (0 votes)
10 views33 pages

Week 9

A function is defined to calculate the kinetic energy of an element given its mass and speed. This function is used in a main program that gets mass and speed from the user as input and prints out the calculated kinetic energy. Another function is defined to check if a number is prime by testing for divisibility from 2 to the square root of the number. A main program uses this function to print all prime numbers from 2 to a number entered by the user.

Uploaded by

vanhoangdz2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views33 pages

Week 9

A function is defined to calculate the kinetic energy of an element given its mass and speed. This function is used in a main program that gets mass and speed from the user as input and prints out the calculated kinetic energy. Another function is defined to check if a number is prime by testing for divisibility from 2 to the square root of the number. A main program uses this function to print all prime numbers from 2 to a number entered by the user.

Uploaded by

vanhoangdz2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

C Programming

Introduction

week 9: Function
Lecturer : Cao Tuan Dung
Dept of Software Engineering
Hanoi University of
Technology
For HEDSPI Project
Functions
• a group of declarations and statements
that is assigned a name
– effectively, a named statement block
– usually has a value
• a sub-program
– when we write our program we always define a
function named main
– inside main we can call other functions
• which can themselves use other functions, and so
on…
Example: Square
double square(double a)
{ This is a function defined
return a * a; outside main
}

int main(void)
{
double num = 0.0, sqr = 0.0;

printf("enter a number\n");
scanf("%lf",&num);

sqr = square(num); Here is where we call


the function square
printf("square of %g is %g\n", num, sqr);

return 0;
}
Example: Square
double square(double a); /* nguyen mau ham */

int main(void)
{
double num = 0.0, sqr = 0.0;

printf("enter a number\n");
scanf("%lf",&num);

sqr = square(num);

printf("square of %g is %g\n", num, sqr);


Here is where we call
return 0; the function square
}
double square(double a)
{
return a * a;
}
Why use functions?
• Break your problem down into smaller
sub-tasks
– easier to solve complex problems
• generalize a repeated set of instructions
– we don’t have to keep writing the same thing
over and over
– printf and scanf are good examples…
• They make a program much easier to read
and maintain
Characteristics of
Functions
return-type name(argument-list)
{
local-declarations
statements
return return-value;
}
• When invoking a function call, we can include
function parameters in the parameter list.
• Declaring a function parameter is accomplished
by simply including the prototype of the
function in the parameter list
Exercise 9.1
• Write a function to calculate the
kinetic energy of the element
ke= mv2/2, for m is mass (kg) and v
is speed (m/s)
• Use this function in a program.
Solution
#include <stdio.h>
double kineticEnergy(double m, double v);
void main(){
double m, v;
do {
printf("Enter mass:"); scanf("%f",&m);
printf("Enter speed:"); scanf("%f",&v);
} while (m<0 && v <=0);
printf("Kinetic Energy of element is:%f",
kineticEnergy(m,v));
}
double kineticEnergy(double m, double v){
return m*v*v/2;
}
Improvement
#include <stdio.h>
double kineticEnergy(double m, double v);
double getMass() {
double m;
do {
printf("Enter mass:"); scanf("%f",&m);
if (m<0) printf("Wrong data input. Positive value required! \n
");
} while (m<0);
return m;
}
double getSpeed() {
double v;
do {
printf("Enter speed:"); scanf("%f",&v);
if (v<0) printf("Wrong data input. Positive value required!\n
");
} while (v<0);
return v;
}
// in main function
m=getMass(); v = getSpeed();
Exercise 9.2
1. Write a function is_prime that accepts a
positive integer and returns 1 if it’s a
prime number, and 0 otherwise.
prototype: int is_prime(int n);
2. Now write a program that gets a positive
integer from the user and prints all the
prime numbers from 2 up to that
integer.
Use the function from (1)!
Solution: function
int is_prime(int n)
{
int i = 0;

/* Check if any of the numbers 2, ... , n-1


divide it. */
for (i = 2; i <= sqrt(n); ++i)
{
if (n % i == 0)
{
return 0;
}
}
return 1;
/* If we got here - n is necessarily prime */
}
Solution: main program
int main(void)
{
int num = 0, i = 0;
/* Get input from user */
printf("enter a positive integer\n");
scanf("%d", &num);

printf("prime numbers up to %d:\n", num);


for (i = 2; i <= num; ++i)
{
if (is_prime(i))
{
printf("%d\n",i);
}
}
return 0;
}
New exercise ICT
• Redo the exercise: transform a number
from decimal to another base, by using
3 function with the following prototype:
– void printBinary(int n);
– void printOctal(int n);
- void printHexa(int n);
• Students are not allow to use printf
funtion with %o, %x to print octal and
hexa numbers.
Pass by value
• Function arguments are passed to
the function by copying their
values rather than giving the
function direct access to the actual
variables
• A change to the value of an
argument in a function body will not
change the value of variables in the
calling function
Exercise 9.3
• Write programs to setup these
following functions. Use them in a
main program
– A function to find the sum of the cube of
integers from 1 to n
– A function to list all submutiples of the
integer n
– A function to list the n first square
numbers
Solution: sum of cube and List of
submultiples
long sumcube(int n)
{
int i = 0;
long s=0;
for(i=1; i<=n; i++) s+=i*i*i; return s;
}
void printsubmultiples(int n)
{
int i;
for(i=2; i<n; i++)
if (n%i ==0) printf("%d ",i);
printf("\n");
}
Solution: n first perfect square
void printsquares(int n)
{
int i;
for(i=1; i<=n; i++)
printf("%d ",i*i);
printf("\n");
}
Exercise 9.4
• Write a program to calculate the worker’s
salary by a week. The average wage is
15000 VND for one hour working. And
workers have to do 40 hours a week. If
they work overtime, the money is paid
more 1.5 time for each hour.
• Data validation: A worker can not work
less than 10 hours or more than 65 hours
a week.
Solution:Salary Function
#include <stdio.h>
long salary(int hours)
{
if (hours >40)
return 15000*40+15000(hours-40)*3/2;
else return hours*40;
}
int nhapGioLam() {
int n1;
do {
printf("Enter number of working hours:");
scanf("%d",&n1);
} while (n1<10 || n1>=65);
return n1;
}
int main()
{
int n; n= nhapGioLam();
/* do {
printf("Enter number of working hours:");
scanf("%d",&n);
} while (n<10 || n>=65); */
printf("The salary you get:%ld\n",salary(n));
return 0;
}
Exercise 9.5
• Write the function
void printnchars(int ch, int n) to display a character for n
time.
a) Use this function to print “* right triangle” which has
edges of 5, 5.
b) Draw a square 9x9 of which the center is a blank
character. You should use the statement continue and the
nested loop here.
c) Write a function to get a character. Character must be in
alphabetical table or be digit. When user enter wrong
character, program ask them to re-enter until the valid
data is inputed or the number of wrong input depass 3.
a) Function returns the character get from users. In case of error, it
returns character #.
Solution
void printnchars(int ch, int n)
{
int i;
for(i = 0; i < n; i++)
printf("%c", ch);
}
BTVN K54
• Viết chương trình menu có các chức
năng sau, bắt buộc phải dùng hàm có
tham số phù hợp. (x và sai số)
• 1. Nhập giá trị x và sai số epsilon
• 2. Tính sin(x) theo thuật toán lặp chuối
Taylor – cài đặt dưới dạng lời gọi hàm
• 3. Tính sqrt(x) – dưới dạng hàm theo
phương pháp Newton
• 4. Tinh e mu x
• 5. Thoát.
sin(x)

double x1=x;
int i = 1;
do
{
lastsinx = sinx;
denominator = 2 * i * (2 * i + 1);
x1 = -x1 * x * x / denominator;
sinx = sinx + x1;
i = i + 1;
} while (epsilon <= fabs(sinx - lastsinx));
Goi y
• Cac ham nen co tham so: x va
epsilon
• Vi du: a= sinx(PI/2, 0.001);
• printf("%4.3f", emux(4,0.00001));
Bài tập bổ sung (BTVN2)
• Viết hàm xử lý cho phép thống kê số lần
xuất hiện của các ký tự nguyên âm (a,e,
u, i, y, o) trong dãy liên tục các ký tự
người dùng gõ từ bàn phím và đổi các ký
tự này sang dạng chữ Hoa.

• Sử dụng hàm này trong chương trình yêu


cầu người dùng nhập vào một đoạn văn
bản.
a) In ra số ký tự nguyên âm.
b) Highligh các ký tự này.
Exercise 9.6
• The formula for converting a temperature from
Fahrenheit to Celcius is C = 5/9(F-32)
• Write a function named celsius that accepts a
Fahrenheit temperature as an argument.
Function should return the temperature in
Celcius.
• Write a function that displays a table of the
Fahrenheit temperature to their Celsius
equivalents from a low value l to high value h.
the step s.
Exercise 12.6 (cont)
• Test these 2 functions by a program with the
expected output as the follows:
Tempt converter table
F C
5 X
10 Y
15
20
..
30 Z
Solution
// function to convert fahrenheit to celsius
double celsius(double);

int main() {
double fahr = 0;

printf("Fahrenheit\tCelsius\n");
while (fahr < 21) {
printf("%6.1f\t%6.1f\n", fahr, celsius(fahr);
fahr += 1;
}

return 0;
}

double celsius(double f) {
return 5 * (f - 32) / 9;
}
Exercise 12.7
• Given a positive number n which is
k-figure number. Write a function to
verify whether n has all figures being
odd numbers or even numbers.
Exercise
• The program Vietnamese Idol has 5 judges,
each of whom awards a score between 0
and 10 for each performer. Performer's final
score is determined by dropping the highest
and lowest score received, the averaging th
3 remaining scores. Write a program that
uses this method to calculate a contestant's
score using two following functions:
– void getJudgeData() should ask the user for a
judge's score, store it in a reference parameter
variable, and validate it.
– void calcScore() should calculate and display the
average score of performer.
Exercise: Leap Year
• Write an algorithm isLeapYear as a
function that determines whether a given
year is a leap year. Pass the year as a
parameter. A year is a leap year if
– It is a multiple of 4 but not a multiple of 100
OR
– It is a multiple of 400
– So, for example, 1996 and 2000 are leap
years, but 1900, 2002 and 2100 are not.
• Use this function in a program that asks
from user the month, year and return
the number of days of the month.
Bài tập bổ sung: Viện phí
• Chi phí bệnh viện của bệnh nhân gồm các khoản sau:
– Phí nội trú (150000 VND/ngày)
– Tiền thuốc: giá trị nguyên dương, lớn.
– Tiền phẫu thuật: (nếu có giá trị sẽ khác 0)
• Bệnh nhân có 3 loại thẻ bảo hiểm y tế sau:
– Gold(G): Chỉ cần thanh toán 30% chi phí
– Silver(S): Chỉ cần thanh toán 50% chi phí
– Citizen(C): Phải thanh toán 70% chi phí
• Thiết kế hàm hospitalFee với các tham số phù hợp để
tính số tiền bệnh nhân phải trả chỉ qua một lần gọi
hàm. Hàm vừa trả về tổng số tiền phải trả, vừa in ra
màn hình chi tiết các khoản thanh toán thành phần
của hóa đơn thanh toán. Chú ý giá trị các đối số
truyền vào hàm được nhập liệu ở chương trình chính,
không nhập liệu bên trong hàm.
Viện phí
• Sử dụng hàm trên để viết chương trình có giao diện
như sau
CHUONG TRINH TINH VIEN PHI
1. Thông tin bệnh nhân // Họ tên, loại thẻ bảo hiểm
và Thông tin khám chữa bệnh: //thông tin ngày nằm
viện,thuốc,..
2. Hóa đơn thanh toán viện phí //cho bệnh nhân hiện tại
3. Báo cáo thống kê
4. Thoát
• Trong đó chức năng báo cáo thống kê cần hiển
thị:
– Tổng số bệnh nhân (Chương trình cho phép nhập nhiều lần thông
tin) và số tiền trung bình một bệnh nhân phải trả.
– Số lượng thẻ bảo hiểm y tế đã khai báo cho mỗi loại G, S, C
– Số tiền lớn nhất mà bệnh nhân được hưởng từ bảo hiểm.

You might also like