5
Exercise 3 Example> Write a C function that implements /* input : integer value n output : */ int f ( int n ) { int i, sum=0; for (i=1;i<=n;i++) sum+=i*i; return sum; } #include <stdio.h> int f(int); int main() { int x , square_sum; scanf(“%d”,&x); square_sum=f(x); printf(“%d\n”,square_sum); return 0; }

Exercise 3 Example> Write a C function that implements /* input : integer value n output : */ int f ( int n ) { int i, sum=0; for (i=1;i

Embed Size (px)

Citation preview

Page 1: Exercise 3 Example> Write a C function that implements /* input : integer value n output : */ int f ( int n ) { int i, sum=0; for (i=1;i

Exercise 3

Example> Write a C function that implements

/*input : integer value noutput : */int f ( int n ) { int i, sum=0; for (i=1;i<=n;i++) sum+=i*i; return sum;}

#include <stdio.h>

int f(int);

int main(){ int x , square_sum;

scanf(“%d”,&x); square_sum=f(x); printf(“%d\n”,square_sum);

return 0;}

Page 2: Exercise 3 Example> Write a C function that implements /* input : integer value n output : */ int f ( int n ) { int i, sum=0; for (i=1;i

1. Write a function integerPower(base, exponent) that returns the value of

base

For example, integerPower(3,4)=3*3*3*3. Assume that exponent is a positive, nonzero integer, and base is an integer. Function integerPower should use for to control the calculation. Do not use any math library functions.#include <stdio.h>

int integerPower(int, int);

int main(){ int b , e; scanf(“%d %d”,&b,&e); printf(“%d\n”,integerPower(b,e)); return 0;}

int integerPower(int base, int exponent){

// insert your code here

exponent

Page 3: Exercise 3 Example> Write a C function that implements /* input : integer value n output : */ int f ( int n ) { int i, sum=0; for (i=1;i

2.(a) Write a function fact that takes a nonnegative integer as a parameter and

returns its factorial value. Function prototype : int fact(int n);

(b) Write a function e that estimates the value of the mathematical constant e by using the formula : ( You cannot add unlimitedly. Give your own limitation for the number of values to add. (e.g. Use 8) ). Prototype: double compute_e();

(c) Write a function ex that takes a floating-point value x as a paramenter and computes the value of by using the formula.

Function prototype: double compute_ex(double x);

(d) Write a program that takes x as a keyboard input and prints as an output.

Page 4: Exercise 3 Example> Write a C function that implements /* input : integer value n output : */ int f ( int n ) { int i, sum=0; for (i=1;i
Page 5: Exercise 3 Example> Write a C function that implements /* input : integer value n output : */ int f ( int n ) { int i, sum=0; for (i=1;i

3. Write a C program that gets an arbitrary number of positive integer values from keyboard and prints the smallest value and the biggest value. To end keyboard input, give -1 as an input. For example,

Key board Input :13711255423196-1

Output :2 55