First Week Examples

Adapted from D. Milicic..

Some general remarks on compilation

Use an editor (for example, emacs) to create a C source code file foo.c.

Compile the source file by issuing the command cc foo.c in an xterm window. If there are no errors in your code, this creates a binary a.out. You execute the binary by issuing the command a.out in an xterm window.

If you want to name the binary foo, compile the source with the command cc foo.c -o foo . You execute this binary by issuing the command foo in an xterm window.


Loops


Compile and run the attached examples. Modify them and study the output.

The text between /* and */ is a comment. Put your name, the date, and program title in the first comment of your program.


First Programs


/**********************************************************
A. Treibergs                                          1-9-6
Week 1 First example: Program to say hello
hello.c 
**********************************************************/

#include <stdio.h>
#include <stdlib.h>


int 
main(void) 
{
   printf("Hello!\n");
   return(EXIT_SUCCESS);
}



/**********************************************************
A. Treibergs                                          1-9-6
Week 1 Second example: Program to say hello^3
hello.c 
**********************************************************/
#include <stdio.h>
#include <stdlib.h>

int 
main(void) 
{
   printf("Hello!\n");
   printf("Hello!\n");
   printf("Hello!\n");
   return(EXIT_SUCCESS);
}



For Loop



/**********************************************************
A. Treibergs                                          1-9-6
Week 1 Third example: Program to say hello ten times
hello2.c 
**********************************************************/
#include <stdio.h>
#include <stdlib.h>

int 
main(void) 

{
   int i;

   for(i=1;i <= 10; i=i+1) 
   {
       printf("%d. Hello!\n",i);
   }
   return(EXIT_SUCCESS);
}



Floating point numbers, input and output



/************************************************************************
A.Treibergs                                                  Jan. 9, 2006
First Week Example Four: Enter a radius and compute the area of a circle
circle.c
************************************************************************/

#include <stdio.h>
#include <stdlib.h>

int 
main(void) 

{
   float radius, area, Pi;
   
   Pi = 3.14159;

   printf("Enter the radius of the circle\n");
   scanf("%f", &radius);

   area = Pi * radius * radius;
   
   printf("The area of a circle whose radius is %f is %f.\n",radius,area);
   
   return(EXIT_SUCCESS);
}



Some tips


Comments:
/* This is a comment. */
Formatting with the printf command: