Download EXAMPLE: /* A Program to add N even positive numbers: Sum= 2+4

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Canonical normal form wikipedia , lookup

Parameter (computer programming) wikipedia , lookup

Addition wikipedia , lookup

Transcript
EXAMPLE:
/* A Program to add N even positive numbers: Sum= 2+4+6+...+2*N. The program
evaluate also the square root of the average of that Sum. The program uses the C
standard library header file "math.h" to evaluate the square root of the average of the
sum. We use a user-defined function "ADD_Even( )" to evaluate the sum Function
ADD_Even( ) has been invoked using call-by-value mechanism */
#include<stdio.h>
#include<math.h>
int ADD_Even(int, int); // Function's prototype
/* notice that the function declaration:
int ADD_Even(int M, int SUM); */
/* notice that you write function prototype without parameters if you want */
/* notice that the parameters in calling statement are dummy (as you notice the
declaration statement and calling statement in main function */
d
e
v
int main()
{
int N, sum=0, sumx=0;
double Avg, sqAvg;
printf ("Enter how many even numbers you need to add: \n");
scanf ("%d", &N);
o
r
p
sumx = ADD_Even(N, sum);
/* The above shows you the
p
A
calling statement in main*/
Avg = (double)sumx/N ;
sqAvg = sqrt(Avg) ;
printf ("\n");
printf ("\n\nResult:\n");
printf ("we added %d numbers\n", N);
printf ("sum= %d\n", sumx);
printf ("The average= %7.3f\n", Avg);
printf ("The square root of the average= %7.3f\n", sqAvg);
return 0;
}
//Function definition
int ADD_Even(int M, int SUM)
/* function declaration */
/* notice that the parameters in function are: M, SUM while the parameters in call
statement are: N, sum. Also there are no parameters in function prototype. In case you to
put parameters in function prototype then code as if it's written in function declaration. It
is important to have same number of parameters in function declaration as function call,
and should be one to one, type correspondent.
{
printf ("\nHere are the positive integers we added:\n");
for(int x=2 ; x<=2*M ; x +=2 )
{
printf ("%d ", x);
SUM += x;
}
return SUM;
}
Note the following:
1- Main program call function ADD_Even(N, sum); and assign the returned value SUM in
function to its name ADD.
2- The value of the name of the function (SUM) is assigned to variable sumx.
3- The main function will continue executing statements in sequence after the call statement.
4- Also, the input parameters in main which are ((N, sum) are passed by value from main as
in call stetement ADD_Even(N, sum) to normal function as in ADD_Even(int M,
int SUM).
5- Note also, values of N,sum ……..>…….passed by value to M, SUM in normal function.
The names are dummy variables.
p
A
o
r
p
d
e
v