Академический Документы
Профессиональный Документы
Культура Документы
<return_type><function_id>(<input_type 1>,
<input_type 2>,
<input_type 3>,
…);
return bal;
}
return bal;
}
User-defined Functions - Example
In the main function, read the values from the user and
call the function computeBalance to compute the final
balance.
int main(){
double bal, r;
int m;
scanf(“%lf %lf %d”, &bal, &r, &m);
bal = computeBalance(bal, r, m);
printf(“%.2f”, bal);
return 0;
}
Functions with no inputs
In general, it is possible to write function that takes no
input arguments, although it is very rarely useful.
<return_type><function_id> (void)
Functions with no output
C function also allows to return no output argument.
Functions with no output arguments are typically
known as procedures.
x = y*y; y
return x; x
}
result = square(x); x
return 0; result
}
Lexical Scoping - Example
int square(int y){ square
int x; variables local to square
x = y*y;
y
return x;
} x
main
int main(int a, int b){
a 10
int a=10, b=20;
b 20
swap(a,b);
printf(“%d %d”, a,b);
return 0;
}
Example
In the execution, the values from the main function are
passed into the swap function.
main
a 10
int main(int a, int b){
int a=10, b=20; b 20
swap(a,b);
printf(“%d %d”, a,b); swap(10, 20)
return 0;
}
Example
Inside the swap function, a temporary variable is
declared and is initialised to a
main
a 10
void swap(int a, int b){
int temp = a; b 20
a = b;
b = temp; swap(10, 20)
return; a 10
} b 20
temp 10
Example
After executing the statements, the values of a and b
inside the swap functions are changed, but not in the
main
main function.
a 10
int temp = a;
a = b; swap(10, 20)
b = temp; a 20
return;
b 10
}
temp 10
Example
At the return statement, the procedure is terminated
and does not return any value.
main
a 10
void swap(int a, int b){
int temp = a; b 20
a = b;
b = temp; swap(10, 20)
return; a 20
} b 10
temp 10
Example
The values of the variables in the main function remain
unchanged
main
Program output: 10 20
Macros
A simple operation can also be specified by a
preprocessing directive called a macro. Macros are
typically defined before any functions using #define.
rand()
1. Time-based seeding
// time(0) gets current time
srand((unsigned int) time(0));