1 Summary

  • Several toy examples for beginners

2 Calculate the sum of two integers a and b.

  • There is only one main function
  • Remember to declare function add if it is behind the fuction that calls it. No requirement of the declaration otherwise.
  • Note the form of function’s declaration
#include <stdio.h>
//  This is the main program
int main()
{   
    int a,b,sum;
    int add(int x,int y);
    a=10;
    b=24;
    sum=add(a,b);
    printf("sum= %d\n",sum);
    return 0;
}

/* This function calculates the sum of x and y   */
int add(int x,int y)
{   int  z;
    z=x+y;
    return(z);
}

3 Calculate partial sum of number series

3.1 Calculate the series of odds, sum = +3+5+7+...+20

  • There is a key word while to deal with loop
  • Think about how to break or early break the loop
int main()
{
    // sum = 1+3+5+7+...+20
    int t,sum;
    sum = 0;
    t = 1;
    while(t<=20){
        sum += t;
        t += 2;
    }
    printf("1+3+5+7+...+ 20 =  %d\n",sum);

    return 0;
}

3.2 Calculate the sum of factorials, sum = 1!+2!+3!+…+8!

  • There is a key word for to deal with loop
  • Think about how to break or early break the loop
int main()
{
    // sum = 1!+2!+3!+...+8!
    int i;
    long t,sum;
    sum = 0;
    t = 1;
    for(i=1;i<=8;i++){
        sum += t;
        t *= i+1;
    }
    printf("1!+2!+3!+...+ 8! =  %ld\n",sum);
    return 0;
}

3.3 Calculate sum = 1/2+3/4+5/8+7/16+...

  • Declare variable clearly. Understand variable’s mean by the name.
int main()
{
    // sum = 1/2+3/4+5/8+7/16+...
    double denominator,numerator,sum;
    sum = 0.0;
    numerator = 1.0;
    denominator = 2.0;
    while(numerator/denominator>=1e-6){
        sum += numerator/denominator;
        numerator += 2.0;
        denominator *= 2;
    }
    printf("1/2+3/4+5/8+7/16+... =  %f\n",sum);
    return 0;
}

4 Problem

  • Think about how to approximate \(\sin(x)\). It can be written as the series \(\sin(x) = x/1-x^3/3!+x^5/5!-x^7/7!+\cdots\). Thus, we can approximate \(\sin(x)\) by partial sum of this sequence with a given precision, say \(1e-6\).