C++ Functions for Basic Calculations
C++ Functions for Basic Calculations
Exercise 1
Solution :
#include <stdio.h>
main()
{
/* Prototypes of the called functions */
float AVERAGE(float X, float Y);
/* Local variables */
float A,B;
/* Treatments */
Enter two numbers:
scanf("%f %f", &A, &B);
The arithmetic mean of %.2f and %.2f is %.4f
A, B, AVERAGE(A, B));
return 0;
}
Exercise 2
Write two functions that calculate the value XNfor a real value X (typedouble) and a
positive integer value N (type int):
Write a program that tests the two functions using values read from the keyboard.
Solution :
#include <stdio.h>
main()
{
/* Prototypes of the called functions */
double EXP1(double X, int N);
void EXP2(double *X, int N);
/* Local variables */
double A;
int B;
/* Treatments */
printf("Enter a real number X: ");
scanf("%lf", &A);
printf("Enter the positive exponent N: ");
scanf("%d", &B);
/* a */
printf("EXP1(%.2f , %d) =%f\n", A, B, EXP1(A,B));
/* b */
/* As the initial value of A is lost upon calling */
For EXP2, you need to share the display if you want. */
/* display the value of A before and after the call ! */
printf("EXP2(%.2f , %d) = ", A, B);
EXP2(&A, B);
printf("%f\n",A);
return 0;
}
Note: This EXP2 solution automatically respects the case where N=0.
Exercise 3
Write a MIN function and a MAX function that determine the minimum and the maximum.
of two real numbers.
Write a program using the MIN and MAX functions to determine the minimum and the
maximum of four real numbers entered from the keyboard.
Solution:
#include <stdio.h>
main()
{
/* Prototypes of the called functions */
double MIN(double X, double Y);
double MAX(double X, double Y);
/* Local variables */
double A,B,C,D;
/* Treatments */
Enter 4 real numbers:
scanf("%lf %lf %lf %lf", &A, &B, &C, &D);
printf("The minimum of the 4 reals is %f\n",
or else
/*
double MIN(double X, double Y)
{
return (X<Y) ? X : Y;
}
Exercise 4
Write the function WRITE_ARRAY with two parameters ARRAY and N that displays N components of the
table TAB of type int.
Example:
The table T read in the example above will be displayed by the call:
WRITE_TAB(T, N);
43 55 67 79
Solution :
void WRITE_ARRAY (int *ARRAY, int N)
{
Displaying the components of the table
while(N)
{
printf("%d ", *TAB);
TAB++;
N--;
}
Exercise 5
Write the function SUM_ARRAY that calculates the sum of the N elements of an array ARRAY of
typeint. N and TAB are provided as parameters; the sum is returned as a result.
you typelong.
Solution :
long SOMME_TAB(int *TAB, int N)
{
/* Local variables */
long SOMME = 0;
/* Calculation of the sum */
while(N)
{
SOMME += *TAB;
TAB++;
N--;
}
return SUM;
}