Thursday, October 29, 2015

Socket - Client Code: udp_client.c

/* UDP client in the internet domain */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>




void
error (
    const char* msg
) {
    perror(msg);
    exit(0);
}



int
main (
    int        argc,
    char*    argv[])
{
    int                    sock;
    int                    n;
    unsigned int        length;
    struct sockaddr_in    server;
    struct sockaddr_in    from;
    struct hostent*        hp;
    char                buffer[1024];
   
    if (argc != 3) error("Usage: IP port\n");

    sock    = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) error("socket");

    server.sin_family    = AF_INET;
    server.sin_port        = htons(atoi(argv[2]));
    inet_aton(argv[1], &server.sin_addr);

    length            = sizeof(struct sockaddr_in);
    printf("Please enter the message: ");
    bzero(buffer,256);
    fgets(buffer,255,stdin);
    n                = sendto(sock,buffer, strlen(buffer),0,
                        (const struct sockaddr *)&server,length);
    if (n < 0) error("Sendto");
    n                = recvfrom(sock,buffer,256,0,(struct sockaddr *)&from, &length);
    if (n < 0) error("recvfrom");
    write(1,"Got an ack: ",12);
    write(1,buffer,n);
    close(sock);
    return 0;
}


Sockets - Server Code: udp_server.c

/* Creates a datagram server.  The port
   number is passed as an argument.  This
   server runs forever */

#include <sys/types.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <netdb.h>
#include <stdio.h>



void
error (
    const char* msg
) {
    perror(msg);
    exit(0);
}

const    int    BUF_SIZE    = 1024;


int
main (
    int        argc,
    char*    argv[]
) {
   int                    sock;
   int                    length;
   int                    n;
   socklen_t            fromlen;
   struct sockaddr_in    server;
   struct sockaddr_in    from;
   char                    buf[BUF_SIZE];

   if (argc != 2)    error("ERROR, no port provided\n");
  
   sock        = socket(AF_INET, SOCK_DGRAM, 0);
   if (sock < 0) error("Opening socket");

   length    = sizeof(server);
   bzero(&server, length);
   server.sin_family        = AF_INET;
   server.sin_addr.s_addr    = INADDR_ANY;
   server.sin_port            = htons(atoi(argv[1]));

   if (bind(sock,(struct sockaddr *)&server,length) < 0) error("binding");
   fromlen    = sizeof(struct sockaddr_in);
   for (;;) {
       n    = recvfrom(sock, buf, BUF_SIZE, 0, (struct sockaddr *)&from, &fromlen);
       if (n < 0) error("recvfrom");
       printf("Received a datagram: ");
       printf("%s\n", buf);
       n    = sendto(sock,"Got your message\n", 17, 0, (struct sockaddr *)&from, fromlen);
       if (n < 0) error("sendto");
   }
 }

Monday, October 19, 2015

More on Functions

https://www.dropbox.com/s/14d7yo2pmm8wzug/e121functions2.ppt?dl=0

Functions PowerPoint

https://www.dropbox.com/s/u2lhiweww96qjia/e121functions_1.ppt?dl=0

Bubble Sort with Functions

/* Bubble sort code with function */

#include <stdio.h>

#define MAX 1000000



int main()
{
    int array[MAX];
    int n,a,b,swap;
   
    printf("\n Enter number of elements\n");
    scanf("%d", &n);
    /* placed number of elements, n, in address &n */
   
    printf("\nEnter number of integers %d \n", n);
   
    for (a=0;a<n;a++)
    {
        scanf("%d",&array[a]);
       
        /* Input array elements into their address locations */
    }


    printf("\nSorted list in ascending order:\n");   
    sort(n,array); 
   
    printf("\n\n\nEnd Sort \n");
   
    return 0;
}

int sort(int num,int x[])
{   int a, b, j, swap;
   
    for (a=0;a<(num-1);a++)
    {
        for (b =0;b<num-a-1;b++)
        {
            if (x[b] > x[b+1]) /* For decreasing order use < */
            {
                swap=x[b];
                x[b]=x[b+1];
                x[b+1]=swap;
            }
        }
    }
    
    for (j=0;j<num;j++ )
    {
        printf("%d\n", x[j]);
    }
     
}

Bubble Sort Code

/* Bubble sort code */

#include <stdio.h>

#define MAX 1000000

int main()
{
      int array[MAX];
    int n,a,b,swap;

      printf("\n Enter number of elements\n");
      scanf("%d", &n);
     /* placed number of elements, n, in address &n */

     printf("\nEnter number of integers %d \n", n);

      for (a=0;a<n;a++)
        {
        scanf("%d",&array[a]);

        /* Input array elements into their address locations */
    }

      for (a=0;a<(n-1);a++)
     {
            for (b =0;b<n-a-1;b++)
           {
                  if (array[b] > array[b+1]) /* For decreasing order use < */
                  {
                    swap=array[b];
                    array[b]=array[b+1];
                    array[b+1]=swap;
                  }
            }
      }

      printf("Sorted list in ascending order:\n");

      for (a=0;a<n;a++ )
         {   
        printf("%d\n", array[a]);
    }

      return 0;
}

Traffic Light Blinking


Traffic Light Program

#include <stdio.h>

#include <wiringPi.h>

void red(void);
void yellow(void);
void green(void);

int main()
{
        /* set up the wiring pi library functions */
    wiringPiSetup();
    pinMode(0,OUTPUT);
    pinMode(1,OUTPUT);
    pinMode(2,OUTPUT);
    /* pinMode 0 is the GPIO_0 (GPIO Zero) pin that is */
    /* pin #7 on the header - green*/
    /* set up GPIO_0 as an output port (as opposed to input port *    /
    /*pinMode 1 is GPIO_1 yellow and pinMode 2 is GPIO_2 red */

    while(1)
    {

        green();
        delay(300);
        yellow();
        delay(300);
        red();       
        delay(300);

       
    }   
    return (0);
    /* Not necessay in C Code - main() returns 0 <--zero */
    /*at the termination of program */




}

void green(void)
{
    digitalWrite(0,HIGH);
    delay(700);
    digitalWrite(0,LOW);

}

void yellow(void)
{
    digitalWrite(1,HIGH);
    delay(700);
    digitalWrite(1,LOW);
}

void red(void)
{
    digitalWrite(2,HIGH);
    delay(700);
    digitalWrite(2,LOW);
}

Average and Standard Deviation Program

/* Average (mean) and standard deviation program */
/*      avg_std3.c                               */

#include <stdio.h>

#include <stdlib.h>

#include <math.h>
/* Require math.h to perform square-root and square calculations */
int
main(
){
    int i,j;
    int x[10];
    double sum,avg,sigma,sigma_sq;
    int *ptr;

    sum = 0;

    for(i=0;i<10;i++)
    {
        x[i]=i;
   
        /* ptr is assigned the value of the x[i] element address */
        ptr=&x[i];           
               
        /* notice for long printf() statements, close the " and open " on next line */
        printf("\nx[%d] = %d, at address using pointer *ptr %X, "
                "and using pointer ADDRESS operator &x[i] = %X\n",i,x[i],ptr,&x[i]);   
       
        /* taking a running average by using the variable, sum  */
        /* also using the pointer *ptr to 'point' to the value  */
        sum=sum+*ptr;
               
    }
   
    j=i;

    printf("\nSum = %f\n", sum);

    avg=sum/(i);
    printf("\nAverage = %f\n", avg);

    sum=0;
    for (i=0;i<10;i++)
    {
        /* the pow(a,b) = a^b using the math.h library */

        sum=sum+pow((x[i]-avg),2);
    }
   
    /*calculate the variance whichi is the square of the standard deviation, sigma_sq*/

    sigma_sq=sum/(i);

    /*take the square root of the variance to calculate the standard deviation, sigma*/

    /* sqrt(a) is the square root function using the math.h library */

    sigma=sqrt(sigma_sq); 


    printf("\nVariance sigma_sq = %f\n\n",sigma_sq);

    printf("\nStandard Deviation sigma = %f\n\n",sigma);

    /******************************************************************/
    /* to compile,                                                    */
    /*      gcc avg_std3.c -lm                                        */
    /*                                                                */
    /* the -lm links the math.h library to the program avg_std3.c     */
    /* during compile.                                                */
    /*                                                                */
    /* the program can be compiled in the 'me' directory              */
    /*                                                                */
    /* To execute, ./a.out                                            */
    /*                                                                */
    /* To name an executable named avg_std3:                          */
    /*      gcc avg_std3.c -o avg_std3 -lm                            */
    /******************************************************************/

    return(0);
}

Conditionals

https://www.dropbox.com/s/1bdvrq2shdt7szn/e121_conditionals.ppt?dl=0

Pointers PowerPoint

https://www.dropbox.com/s/5dmaebbeu1r2twg/pointers.ppt?dl=0

Program with Function

*Example of a program with functions*/
/*temperature conversion program*/

#include <stdio.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
double CelToFahr(double temp_cel);
double FahrToCel(double fahr_temp);

int main()
{
   int answer_1, dummy;
   double celsius, fahr;
   
   answer_1=TRUE;

  
   while(answer_1==TRUE) {
         printf("\nInput degrees Fahrenheit for conversion to Celsius(^z to exit):  \n");
      scanf("%lf",&fahr);
      celsius=FahrToCel(fahr);
      printf("\n%lf Celsius.\n\n",celsius);
     
      printf("\nAnother F to C conversion?  (0 to exit conversion):  \n");
      scanf("%d", &answer_1);
     }
   printf("\nDo you want to input degrees in Celsius for conversion? (yes=1)\n");
   scanf("%d",&answer_1);
 
      
       while(answer_1==TRUE) {
        printf("\n\nInput degrees Celsius for conversion to Fahrenheit (^z to exit):  \n");
        scanf("\n%lf",&celsius);
        fahr=CelToFahr(celsius);
          printf("\n%lf Fahrenheit.\n\n", fahr);
         
        }
   
   printf("End of program - enter any number to exit.\n");
   scanf("%d",&dummy);
}

double FahrToCel(double fahr_temp)
/* Function to convert Fahrenheit to Celsius */
{
   double cel_temp;
   cel_temp=(5.0/9.0)*(fahr_temp-32.0);
   return(cel_temp);
}

double CelToFahr(double temp_cel)
/* Function to convert Celsius to Fahrenheit */
{
   double temp_fahr;
   temp_fahr=(9.0/5.0)*temp_cel+32.0;;
   return(temp_fahr);
}

Program Without Function

/*Example of a program without functions*/
/*temperature conversion program*/
#include <stdio.h>
#include <math.h>
#define TRUE 1
#define FALSE 0

int main()
{
   int answer_1;
    double celsius;
    double fahr;
 

   answer_1=TRUE;
  
   while(answer_1==TRUE) {
      printf("\nInput degrees Fahrenheit for conversion to Celsius (^z to exit):  \n");
      scanf("%lf",&fahr);
      celsius=((fahr-32.0)*5.)/9.;
      printf("\n%lf Celcius\n\n", celsius);
      printf("\nAnother F to C conversion?  (0 to exit conversion):  \n");
      scanf("%d", &answer_1);
   }
   printf("\nDo you want to input degrees in Celsius for conversion? (yes=1)\n");
   scanf("%d", &answer_1);
   
    while(answer_1==TRUE) {
      printf("\n\nInput degrees Celsius for conversion to Fahrenheit (^z to exit):  \n");
      scanf("%lf",&celsius);
      fahr=(9.0/5.0)*celsius+32.0;
      printf("\n\n%lf Fahrenheit. \n\n",fahr);
      printf("\nAnother C to F conversion?  (0 to exit conversion):  \n");
      scanf("%d", &answer_1);
     }
  
   printf("\n\nEnd of program \n");
   return (0);
  
}
 

Inputting decimals, charagers, and strings

#include <stdio.h>
#include <string.h>

void main()
{
    int a, b;
    float c, d;
    double e, f;
    char g,h;

    char hello[10], cousin[10];

    a=10; b=12; c=10; d=12; e=10; f=12;

    g='H'; h='C';

     strcpy(hello, "Howzit");printf("\na=%d, b=%d, c=%f, d=%f \n", a,b,c,d);

    strcpy(cousin, "Cuz");

    printf("\na=%d, b=%d, c=%f, d=%f \n", a,b,c,d);
    printf("\ne=%f, f=%f\n",e,f);
   
    printf("\ng=%c, h=%c\n\n", g,h);

    printf("\nHello=%s, Cousin=%s\n\n",hello,cousin);

    printf("a= ");
    scanf("%d",&a);

    printf("\nb= ");
    scanf("%d", &b);

    printf("\n\n");printf("\na=%d, b=%d, c=%f, d=%f \n", a,b,c,d);

    printf("\na=%d \tb=%d \tc=%f \td=%f \n", a,b,c,d);

    printf("Input String hello:  ");
    scanf("%s",&hello);

    printf("Input String cousin:  ");
    scanf("%s", &cousin);


/*    scanf("Input Hello String=%s and Input Cousin String=%s", hello, cousin); */

/*    scanf("Input Hello String=%s and Input Cousin String=%s", hello, cousin); */
    printf("\n\nHello = %s \n",hello);

    printf("\nCousin = %s \n",cousin);

    printf("\n\n%s %s\n\n",hello,cousin);

    puts(hello);
    puts(cousin);


}

Using Pointers


USING POINTERS

This example program shows a pointer being used to swap between two floating point values. The actual manipulation of the floating point values is done within the function get_value, which doesn't have any parameters. I decided that I would do it by reassigning a pointer within the main program.

#include <stdio.h>

/* The pointer has to be declared here so that */
/* the function get_value can get access to it. */
float *my_point;

/* The floating point variables have to be */
/* declared here so that function display_values */
/* can access them.*/
float x = 36.3, y = -100.44;

int main ()
 { display_values();
   my_point = &x;    // Points to x
   get_value();
   my_point = &y;    // Points to y
   get_value();
   display_values();
   return 0;
 }

void get_value ()
 { float decimal_number;
   printf(\n "Please enter a number : \n");
   scanf(“%f”,decimal_number);
   *my_point = decimal_number;
 }

void display_values ()
 { printf("\nThe value of x is %f \n",x);
   printf("\nThe value of y is %f \n",y);
  
 }


The value of x is 36.3
The value of y is -100.44

Please enter a number : 2.1
Please enter a number : 3.1
The value of x is 2.1
The value of y is 3.1
_____________________________________________________________________________________________
I thought it might be interesting to see what the address of a variable is. Here I have declared three
unsigned long values together with a pointer that moves between them. In each case, the address that the pointer is pointed to is displayed.

#include <stdio.h>

int main ()
  { unsigned long a = 1, b = 2, c = 3, *p;

    p = &a;
    printf("\nThe address of a is %X\n",p);
    printf("\nThe value of a is %d\n",*p);

    p = &b;
    printf("\nThe address of b is %X\n",p);
    printf("\nThe value of b is %d\n",*p);

    p = &c;
    printf("\nThe address of c is %X\n",p);
    printf("\nThe value of c is %d\n",*p);
       
    return 0;
  }

The address of a is 0x3c27245e
The value of a is 1
The address of b is 0x3c27245a
The value of b is 2
The address of c is 0x3c272456
The value of c is 3
____________________________________________________________________________________________

This function is used to sort arrays of integers. The array itself is specified as a pointer. However, the routine doesn't know in advance how many elements the array will have, so that must also be passed across as an (ordinary) parameter.

void sort (*int array, int num_elements)
 { int i, j;
   int *temp;  /* Used in swopping array values */
   for (i = 0; i < num_elements; i++)
    for (j = 0; j < num_elements-1; j++)
     if (*(array+j) > *(array+j+1))
      { temp = *(array+j);
        *(array+j) = *(array+j+1);
        *(array+j+1) = temp;
      }
 }
You will see that the pointer to the array is simply declared as a pointer to an integer. You would have no way of knowing just by looking at the first line of the function that the pointer indicated an array rather than a simple integer (other than the fact that the pointer is called array, of course, which is something of a giveaway!)
The array elements are referred to using the pointer. *(array+j) refers to element array[j] etc.


Check out the program without functions:
Sorting an array would involve swapping the elements as necessary, until they are all in ascending or descending order. There are different sorting methods (called algorithms) and this worked example demonstrates what is probably the simplest sorting algorithm - Bubblesort.
Bubblesort is so-called as the largest elements of the array move gradually to the end like bubbles rising to the surface in a glass of fizzy drink. It is usually the slowest sorting algorithm (although it can take advantage of array elements which have been partially sorted already). The algorithm goes as follows:
Assume N is the number of elements in the array.

Go through the elements from 1 to N-1
   Look at the current element and the next one.
   Are they out of order? If so, swop them.
   At the end of the run, the largest element will have
        "bubbled" to the end of the array.
Repeat this process N times.
Here is the code. Go through it matching it line-by-line with the algorithm above.
#include <stdio.h>
int main ()
 { int x[11];     /* Set up an array of 11 values */
   x[0] = 74;  x[1] = 23;  x[2] = 91;  x[3] = 58;
   x[4] = 52;  x[5] = 60;  x[6] = 30;  x[7] = 19;
   x[8] = 28;  x[9] = 46;  x[10] = 37;

   int i,j;   /* These are used as loop variables */
   int temp;  /* Used in swopping the values */

   printf("\nBefore the sort, the values are \n");
   for (i = 0; i <= 10; i++)
     printf(“x[%d] = %d\n”,i,x[i]);

   for (i = 0; i < 11; i++)  /* Go through 10 times */
     for (j = 0; j < 10; j++)  /* Check all elements */
       if (x[j] > x[j+1])       /* except last */
         { temp = x[j];
           x[j] = x[j+1];
           x[j+1] = temp;
         }

   printf("\n\nAfter the sort, the values are \n");
   for (i = 0; i <= 10; i++)
     printf(“x[%d] = %d\n”,i,x[i]);
  
   return 0;
 }
Before the sort, the values are
74 23 91 58 52 60 30 19 28 46 37
After the sort, the values are
19 23 28 30 37 46 52 58 60 74 91

More on Functions


void function

void is a function that has no return value.

/* Prints a bad, I mean really bad, pun. */

#include <stdio.h>

main()
{
            print_pun();
            return 0;
            /* return 0 means end of program */
}

void print_pun(void)
{
            printf(“To C, or not to C:  That is the question. \n”);
}

General Form of Functions


return-type function name (parameters)
{
            declarations
            statements
}

The return type of a fucntion is the type of value that the function returns.  The following rules govern the return type:

·      Functions may not return arrays, but there are no other restrictions on the return type.
·      If the return type is omitted, the function is presumed to return a value type int.
·      Specifying the return type is void indicates that the function doesn’t return a value.

Local Variables
A variable declared in the body of a function is said to be local to the function.  In the following function, log is the local variable:


int log2(int n)
{
            int log = 0;  /* local variable */

            while (n>1) {
                        n /= 2;
            log++;
              }
            return log;
}

By default, local variables have the following properties:
·      Automatic storage duration.  The storage duration (or extent) of a variable is the portion of program execution during which storage for the variable exists.  Storage for a local variable is automatically allocated when the enclosing function is called and deallocated when the function returns, so the variable is said to have automatic storage duration.  A local variable doesn’t retain its value when its enclosing function returns.  When the function is called again, there is no guarantee that the variable will still have its old value.
·      Bock scope.  The scope of a variable is the portion of the program text in which the variable can be referenced.  A local variable has block scope:  It is visible from its point of declaration to the end of the enclosing function body only.  Since the scope of a local variable doesn’t extend beyond the function to which it belongs, other functions can use the same name for other purposes.

Global or External Variables
Passing  arguments is one way to transmit information to a function.  Functions can also communicate through global variables – variables that are declared outside the body of any function:

#include <stdio.h>
int x, y;  /* global variables */
double k, z; /* global variables */

main()
{
            declarations
            statements
}

return-type function name (parameters)
{
declarations
statements
}


The properties of global variables are different from those of local variables:
·      Static storage duration.  A value stored in a global variable wil stay there indefinitely until program termination.
·      File scope.  A global variable has file scope:  It is visible from its point of declaration to  the end of the enclosing file.  As a result, a global variable can be accessed by all functions that follow its declaration.

Pros and Cons of Global Variables

In most cases, it is better for functions to communicate through parameters rather than by sharing values.  Here’s why:
·      If we change a global variable during program modification, we’ll need to check every function in the same file to see how the change affects it.
·      If a global variable is assigned an incorrect value, it may be difficult to identify the guilty function.
·      Functions that rely on global variables are hard to reuse in other programs.  A function that depends on global variables is not self-contained.

Pre-Processor Directives
·      Macro definition.  The #define directive defines a macro; the #undef directive removes a macro definition.
·      File inclusion.  The #include directive causes the contents of a specified file to be included in a program.
·      Conditional compilation.  The #if, #ifdef, #ifndef, #elif, #else, and #endif directives allow blocks of text to be either included in or excluded from a program, depending on conditions that can be tested by the pre-processor.

Simple Macros

The definition of a simple macro has the form

            #define identifier  replacement-list

replacement-list is any sequence of C tokens:  It may include identifier, keyworkds, number, character constants, string literal, operators, and punctuation.  When it encounters a macro definition, the pre-processor makes anote that the identifier represents replacement-list .  Wherever identifier appears later in the file, the pre-processor substitutes replacement-list .

Don’t put any symbols in the macro definition – they’ll become part of the replacement list.  Putting the = symbol in a macro definition is a common error:

            #define N = 100  /*****WRONG!!!*****/

            #define N  100;  /*****WRONG!!! Semi-colon is not supposed to be used*****/

            #define N  100  /** CORRECT**/


Sample good macros:
            #define STR_LEN 80
            #define TRUE 1
            #define pi 3.14159
            #define CR ‘\r’
            #define MEM_ERR “Error:  not enough memory.”

Parameterized Macros

The definition of a parameterized macro has the form

            #define identifier (x1, x2, ..., xn)  replacement-list

Example:

            #define IS_EVEN(n)  ((n)%2==0)

So when
            if (IS_EVEN(i)) i++ ;

appears later in the program, the preprocessor will replace this line with:

            if (((n)%2==0)) i++ ;