0% found this document useful (0 votes)
10 views

IP-04-Function and struct

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

IP-04-Function and struct

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Function and struct

Inst. Nguyễn Minh Huy

Fundamentals of Programming - Nguyễn Minh Huy 1


Contents
 Function.
 Multiple--file project.
Multiple
 struct..
struct

Fundamentals of Programming - Nguyễn Minh Huy 2


Function
 Problem with repeated code:
 Consider a program:
 Enter 3 positive integers a, b, c >= 0.
 Compute and print S = a! + b! + c!.
 Identify repeated code.
 Disadvantages of repeated code:
 Time and cost.
 Changes  fix multiple places.

 Write once, reuse everywhere.

Fundamentals of Programming - Nguyễn Minh Huy 3


Function
 Function solution:
Define F(x)
true S1 = F(a)
a>0 S1 = S1 * a
a=a-1
false
true S2 = F(b)
x>0 T=T*x
true x=x-1
b>0 S2 = S2 * b false S3 = F(c)
b=b-1
false
S = S1 + S2 + S3
true
c>0 S3 = S3 * c
c=c-1
false

S = S1 + S2 + S3

Fundamentals of Programming - Nguyễn Minh Huy 4


Function
 C/C++ function:
 A named block of statements.
 Can be called:
 From anywhere in program.
 With different arguments.
 Function structure:
 Prototype: declaration. Prototype
 Function name. Input
Output
 Arguments. Name
 Return type.

 Identification.
 Body: implementation.
Body

Fundamentals of Programming - Nguyễn Minh Huy 5


Function
 C/C++ function:
 Declaration (prototype):
<Return type> <Function name>( <Arguments> );
<Return type>: int,
int, float, char, …, void (no return).
float calcGPA
calcGPA(( float literature, float math );
void printResult
printResult(( );
 Implementation (body):
<Return type> <Function name>( <Arguments> )
{
[Statements]
[return <value>
<value>;]
;]
}
 Calling:
<Function name>( <Arguments> );
float gpa = calcGPA
calcGPA(( 7.0, 8.5 );
Fundamentals of Programming - Nguyễn Minh Huy 6
Function
 C/C++ function:
// Function declaration. // Function implementation.
long long factorial
factorial(( int n ); long long factorial
factorial(( int n )
{
int main
main()
() long long s = 1;
{ for ( ; n > 0; n--
n--))
// Declare and input a, b, c. s = s * n;
return s;
// Function calls. }
S1 = factorial( a );
S2 = factorial( b );
S3 = factorial( c );

S = S1 + S2 + S3;
}

Fundamentals of Programming - Nguyễn Minh Huy 7


Function
 Passing arguments:
 Pass--by-
Pass by-value:
 Argument values are passed to function.
 Function receives only the COPY.
 Real arguments are UNCHANGED.
 Arguments are: variables, constant, expressions.
float calcGPA
calcGPA(( float lit, float math ) int main
main()
()
{ {
lit = lit * 2; float a, b, gpa;
gpa;
math = math * 3;
return (lit + math) / 5; gpa = calcGPA
calcGPA(( a, b ));;
} gpa = calcGPA
calcGPA(( 6, 8.5 ));;
gpa = calcGPA
calcGPA(( a + 1, b ));;
// a, b are UNCHANGED.
}

Fundamentals of Programming - Nguyễn Minh Huy 8


Function
 Passing arguments:
 Pass--by-
Pass by-reference (C++):
 Real arguments are passed to function.
 Function receives the original ones.
 Real arguments can be CHANGED.
 Arguments are variables only.
 Syntax: &<argument>.
float calcGPA
calcGPA(( float &lit
&lit,, float math ) int main
main()()
{ {
lit = lit * 2; float a, b, gpa;
gpa;
math = math * 3;
return (lit + math) / 5; gpa = calcGPA
calcGPA(( a, b)
b);;
} // a is CHANGED.
gpa = calcGPA
calcGPA(( 6, 8.5 ));; //wrong
gpa = calcGPA
calcGPA(a
(a + 1, b)b);; //wrong
}
Fundamentals of Programming - Nguyễn Minh Huy 9
Function
 Passing arguments:
 Notes:
 Use pass-
pass-by-
by-reference to return values.
 Function with multiple return values.
void input
input(( float &lit
&lit,, float &math ) int main
main()
()
{ {
printf(“Enter
printf (“Enter literature = “); float a, b;
scanf(“%f”,
scanf (“%f”, &
&lit
lit);
); float gpa;
gpa;
printf(“Enter
printf (“Enter math = “);
scanf(“%f”,
scanf (“%f”, &
&math
math); ); // a, b are UPDATED.
} input(a, b);
void calcGPA
calcGPA(( float lit, float math, float &gpa )
{ // gpa are UPDATED.
lit = lit * 2; calcGPA(a,
calcGPA (a, b, gpa);
gpa);
math = math * 3; }
gpa = (lit + math) / 5;
}
Fundamentals of Programming - Nguyễn Minh Huy 10
Function
 Scope:
 Existing area of variables and functions.
 Global scope: across program.
 Local scope: only in declaration block.
 Function has global scope.
 Variable:
 Global variable: declared outside functions (includes main() ).
 Can be used across program.
 Local variable: declared inside a block.
 Can be used only in the block.

Fundamentals of Programming - Nguyễn Minh Huy 11


Function
 Scope:
float S; // Global declarations.
int compute();

int main()
{
int a = S + compute(); // Local variable in main.
while (a > 0)
{
int b = S + compute(); // Local variable in loop.
}
}

int compute()
{
int y = S * 2; // Local variable in function.
}

Fundamentals of Programming - Nguyễn Minh Huy 12


Contents
 Function.
 Multiple--file project.
Multiple
 struct..
struct

Fundamentals of Programming - Nguyễn Minh Huy 13


Multiple--file project
Multiple
 How do we organize a book?
 Cannot write in one paper!!
 Split into chapters.
 Summary at first.
 Chapter contents follow.

Fundamentals of Programming - Nguyễn Minh Huy 14


Multiple--file project
Multiple
 Organize C/C++ project:
 Like a book:
 Chapters ~ source code files.
 Summary ~ main() function.
 How to connect multiple source code files?

// File main.cpp // File io.cpp // File compute.cpp


int main() void input() int compute1()
{ { {
input(); } }
compute1();
compute2(); void output() int compute2()
output(); { {
} } }

Fundamentals of Programming - Nguyễn Minh Huy 15


Multiple--file project
Multiple
 Header file:
 Connect source files across project.
 Make code on a file “see” code on another file.
 File extension .h
.h..
 Usage:
 Create header file .h for source file .cpp.
cpp.
 File .h contains only declaration (global variables/functions).
 File .cpp contains implementation of functions.
 To let A.cpp “see” code in B.cpp
 A.cpp #include “B.hB.h””

Fundamentals of Programming - Nguyễn Minh Huy 16


Multiple--file project
Multiple
 Header file:
// File main.cpp // File io.h // File compute.h
#include “io.h” // Function declaration // Function declaration
#include “compute.h” void input(); int compute1();
void output(); int compute2();
int main()
{
input();
compute1(); // File io.cpp // File compute.cpp
compute2(); #include “io.h” #include “compute.h”
output(); void input() int compute1()
} { {
} }
void output() int compute2()
{ {
} }

Fundamentals of Programming - Nguyễn Minh Huy 17


Multiple--file project
Multiple
 Divide--conquer a project:
Divide
 How to eat a cow?
 Split into small parts.
 Eat each parts.
 How small is small?
 Can be chewed.
 Organize a project:
 Split into functions and files.
 Implement each function.
 Should be < 30 statements.

Fundamentals of Programming - Nguyễn Minh Huy 18


Multiple--file project
Multiple
 Program breakdown tree:
 Enter 3 positive integers a, b, c >= 0.
 Compute and print S = a! + (b + 1)! + (c + 2)!.
Program

Input Compute Output

Input
Factorial
positive int

Fundamentals of Programming - Nguyễn Minh Huy 19


Multiple--file project
Multiple
// File process1.h // File process2.h
void input(int &a, int &b,int &c); void input_num(int x);
long compute(int a, int b, int c); long factorial(int n);
void output(long result);
// File main.cpp // File process1.cpp // File process2.cpp
#include “process1.h” #include “process1.h” #include “process2.h”
#include “process2.h” #include <stdio.h>
int main() void input(int &a, int &b,int &c) void input_num(int &x)
{ { {
int a, b, c; input_num(a); do {
long S; input_num(b); printf(“Positive integer = “);
input_num(c); scanf(“%d”, &x);
input(a, b, c); } } while (x < 0);
S = compute(a, b, c); long compute(int a, int b, int c) }
output(S); {
} return factorial(a) + long factorial(int n)
factorial(b+1) + factorial(c+ 2); {
} long S = 1;
void output(long result) for ( ; n > 0; n--)
{ S = S * n;
printf(“S = %ld”, result); return S;
} }
Fundamentals of Programming - Nguyễn Minh Huy 20
Contents
 Function.
 Multiple--file project.
Multiple
 struct..
struct

Fundamentals of Programming - Nguyễn Minh Huy 21


struct
 Organize program data:
 Student information:
 Student id.
 Student name.
 Literature, math.
 Write program:
 Enter information of a student.
 Print student information with computed gpa
gpa..
 Identify the inconvenience?

Fundamentals of Programming - Nguyễn Minh Huy 22


struct
 C/C++ struct:
struct:
 Combine data into one place.
 Compound data-
data-type.
 Declaration:
// Syntax 1: // Syntax 2:
struct <struct name> typedef struct
{ {
<struct member 1>; <struct member 1>;
<struct member 2>; <struct member 2>;
… …
}; } <struct name>;

Fundamentals of Programming - Nguyễn Minh Huy 23


struct
 C/C++ struct:
struct:
 struct variable: struct Student
struct <struct name> <variable>; {
char id[9];
// With typedef struct or C++ char name[50];
<struct name> <variable>; float literature;
float math;
};

int main()
{
struct Student s1;
Student s2; // C++
}

Fundamentals of Programming - Nguyễn Minh Huy 24


struct
 C/C++ struct:
struct:
 Initialization:
struct <struct name> <variable> = int main()
{ // In declaration order. {
<member 1 value>, struct Student s =
<member 2 value>, {
… “24127001”,
}; “Nguyen Van A”,
7.5,
struct <struct name> <variable> =
8.0
{ // C99 standard.
};
.<member name> = <value>,

s.literature = 5.5;
};
}
 Access struct member:
<variable> . <member name>.
name>.

Fundamentals of Programming - Nguyễn Minh Huy 25


struct
 C/C++ struct:
struct: void add1(
add1( struct Student s )
{
 Passing arguments: s.literature++;
s.literature ++;
 Pass-by-
Pass- by-value: s.math++;
s.math ++;
}
 Pass a copy.
void add2
add2(( Student &s )
 Unchanged. {
 Pass--by-
Pass by-reference (C++). s.literature++;
s.literature ++;
s.math++;
s.math ++;
 Pass the real one.
}
 Can be changed. int main
main()()
{
struct Student s1, s2;
add1( s1 );
add2( s2 );
// s1 unchanged.
// s2 changed.
}

Fundamentals of Programming - Nguyễn Minh Huy 26


struct
 C/C++ struct:
struct:
 struct assignment:
 All struct members are copied.
 Array members are copied too!
struct Student s1 = { .name = “minh”, .literature = 8.0 };
struct Student s2 = s1;

s2: Student s1: Student


name Copy name
m i n h \0 m i n h \0
literature literature
Copy
8 8

Fundamentals of Programming - Nguyễn Minh Huy 27


Summary
 Function::
Function
 A named block of statement can be called anywhere.
 Function structure:
 Prototype: name, arguments, return type.
 Body: implementation.
 Passing arguments:
 pass-by-
pass- by-value.
 pass--by-
pass by-reference (C++).

 Multiple--file project:
Multiple
 Program ~ book:
 main() ~ summary.
 source files ~ chapters.

Fundamentals of Programming - Nguyễn Minh Huy 28


Summary
 Multiple--file project:
Multiple
 Header file .h: connect code across source files.
 Program breakdown tree:
 Split program into files and functions.
 Based on levels of abstraction and reusability.

 struct::
struct
 Compound data-
data-type.
 Combine data into one place.
 Assignment: all members are copied.

Fundamentals of Programming - Nguyễn Minh Huy 29


Practice
 Practice 4.1:
Write C/C++ program to find prime numbers:
(organize in functions and multiple-
multiple-file project)
- Enter a positive integer N (re
(re--enter if invalid).
- Print all prime numbers <= N.
Input format:
Enter a positive integer = 11
Output format:
#1 = 2
#2 = 3
#3 = 5
#4 = 7
#5 = 11
There are 5 prime numbers.
Fundamentals of Programming - Nguyễn Minh Huy 30
Practice
 Practice 4.2:
Write C/C++ program to simulate a calculator as follow:
(organize in functions and multiple-
multiple-file project)
- Enter two integers.
- Enter an operator (+, -, *, /, %).
- Perform the operator on two integers and print result.
Input format:
Enter two integers = 7 5
Enter an opertor (+, -, *, /, %) = +
Output format (no error):
Result = 12
Output format (divided-
(divided-by-
by-zero error):
Error: divided by zero.

Fundamentals of Programming - Nguyễn Minh Huy 31


Practice
 Practice 4.3:
Write C/C++ program to classify a triangle:
(organize in functions and multiple-
multiple-file project)
- Enter 3 positive real numbers a, b, c (re (re--enter if invalid).
- Check if a, b, c can forms a triangle.
- If yes, print the triangle type.
(normal, right, isosceles, right-
right-isosceles, equilateral).
Input format:
Enter 3 positive real numbers = 3 4 5
Output format (can form a triangle):
Can form a triangle.
Right triangle.
Output format (cannot form a triangle):
Cannot form a triangle!
Fundamentals of Programming - Nguyễn Minh Huy 32
Practice
 Practice 4.4:
Write C/C++ program to simulate a menu as follow:
(organize in functions and multiple-
multiple-file project):
- Print the menu:
1. Practice 4.1.
2. Practice 4.2.
3. Practice 4.3.
4. Exit.
Selection (1-4):

- Enter an integer for your selection.


- Selection 1
1--3:
+ Execute the selected practice.
+ Go back to menu.
- Selection 4: exit program.

Fundamentals of Programming - Nguyễn Minh Huy 33


Practice
 Practice 4.5:
Write C/C++ program to operate on fractions:
(organize in functions and multiple-
multiple-file project):
- Declare struct to represent a fraction.
- Enter 2 fractions.
- Perform the following operations on 2 fractions and print result:
add, multiply, inverse, reduce.

Fundamentals of Programming - Nguyễn Minh Huy 34


Practice
 Practice 4.6:
Write C/C++ program to operate on students:
(organize in functions and multiple-
multiple-file project):
- Declare struct to represent a student (stated in the lesson).
- Enter a students.
- Print GPA and their rank:
+ Excellent: GPA >= 8.5.
+ Good: GPA >= 7.0.
+ Fair: GPA >= 5.0.
+ Failed: GPA < 5.0.

Fundamentals of Programming - Nguyễn Minh Huy 35


Practice
 Practice 4.7:
Write C/C++ program to operate on triangle:
(organize in functions and multiple-
multiple-file project):
- Declare structs to represent point (x, y) and triangle (3 points).
- Enter information of a triangle.
- Compute and print triangle perimeter.
- Find and print triangle centroid
centroid..

Fundamentals of Programming - Nguyễn Minh Huy 36


Practice
 Practice 4.8:
Write C/C++ program to operate on date:
(organize in functions and multiple-
multiple-file project):
- Declare struct to represent date (day, month, year).
- Enter two date d1 and d2.
- Check if d1 is latest than d2 and print result.
- Print tomorrow date of d1.
- Print yesterday date of d2.

Fundamentals of Programming - Nguyễn Minh Huy 37


Practice
 Practice 4.9 (*):
Write compile command for the following projects:
Simple project Simple project Complex project
with multiple folders with external libraries project 1 uses project 2
project/ project/ project/
bin/ bin/ lib/
src/ lib/ libA/
subfolder/ libA/ libB/
libB/ subproject1/
src/ bin/
subfolder/ src/
subfolder1/
subproject2/
bin/
src/
subfolder2/

Fundamentals of Programming - Nguyễn Minh Huy 38

You might also like