•
The C language was written in 1970 for the first UNIX system.
C Language
•In 1988, the American National Standards Institute (ANSI) adopted a ''new and improved'' version of C, known today as ''ANSI C''.
The C Programming Language -- ANSI C
Brian W. C. Kernighan & Dennis M. Ritchie
Prentice Hall, 1988
A First Program
#include
void main()
{
printf("\nHello World\n");
}
• Save the file in *.c extension.
• Use gcc command for compilation. Eg.
$ gcc hello.c
• A file called a.out will be created.
• Execute the programme simply by typing ./a.out
• As the result ''Hello World'' are printed out.
•The program will start from ''main'' function. The ''main'' function establishes the overall logic of the code.
•All C codes must have a ''main'' function.
•printf(), an output function from the I/O (input/output) library (defined in the file stdio.h)
–''\n'' prints a ''new line'' character, which brings the cursor onto the next line.
•The first statement ''#include < stdio.h>'‘. The ''.h'' files are by convention ''header files'' which contain definitions of variables and functions necessary for the functioning of a program.
Compilation
•Create a text file with editor and convention end with ''.c ''
•There are many C compilers around. The cc being the default Sun compiler. The GNU C compiler gcc is popular and available for many platforms.
•To Compile your program simply invoke the command cc. The command must be followed by the name of the (C) program :
cc program.c
•If compilation success, the output file called a.out
•It is more convenient to use a -o and filename in the compilation as in
cc -o program.exe program.c
•The output file called as the name following the "-o" argument instead of a.out .
•The C Compilation Model
–We will briefly highlight key features of the C Compilation model here
•C Compiler
–The C compiler translates source to assembly code. The source code is received from the preprocessor
•Assembler
–The assembler creates object code. On a UNIX system you may see files with a .o suffix (.OBJ on MSDOS) to indicate object code files
•Link Editor
–If a source file references library functions or functions defined in other source files the link editor combines these functions (with main()) to create an executable file. External Variable references resolved here also
•Some Useful Compiler Options
–Now that we have a basic understanding of the compilation model we can now introduce some useful and sometimes essential common compiler options
–-c
•Suppress the linking process and produce a .o file for each source file listed. Several can be subsequently linked by the cc command, for example:
cc file1.o file2.o ...... -o executable
–-llibrary
•Link with object libraries. This option must follow the source file arguments. The object libraries are archived and can be standard, third party or user created libraries. Probably the most commonly used library is the math library ( math.h). You must link in this library explicitly if you wish to use the maths functions (note do note forget to #include header file), for example:
cc calc.c -o calc -lm
–-Ldirectory
•Add directory to the list of directories containing object-library routines. The linker always looks for standard and other system libraries in /lib and /usr/lib. If you want to link in libraries that you have created or installed yourself (unless you have certain privileges and get the libraries installed in /usr/lib) you will have to specify where you files are stored, for example:
cc prog.c -L/home/myname/mylibs mylib.a
–-Ipathname
•Add pathname to the list of directories in which to search for #include files with relative filenames (not beginning with slash /).
•BY default, The preprocessor first searches for #include files in the directory containing source file, then in directories named with -I options (if any), and finally, in /usr/include. So to include header files stored in /home/myname/myheaders you would do:
cc prog.c -I/home/myname/myheaders
•Note: System library header files are stored in a special place (/usr/include) and are not affected by the -I option.
•int -> integer variable
•short -> short integer
•long -> long integer
•float -> single precision real (floating point) variable
•double -> double precision real (floating point) variable
•char -> character variable (single byte)
PRINTF FUNCTION
•The general syntax of printf function:
printf( "format", variables );
•where "format" specifies the converstion specification and variables is a list of quantities to print.
–%.nd integer (optional n = number of columns; if 0, pad with zeroes)
–%ld long
–%m.nf float or double (optional m = number of columns, n = number of decimal places)
–%ns string (optional n = number of columns)
–%c character
–\n \t to introduce new line or tab
–\g ring the bell (''beep'') on the terminal
While Loop
•while loop:
while (expression)
{
...block of statements to execute...
}
Eg.
#include "stdio.h"
void main()
{
int count;
count = 0;
while (count < 6) {
printf("The value of count is %d\n",count);
count = count + 1;
}
}
•Do …. while loop:
do
{
...block of statements to execute...
} while (expression)
Eg.
#include
int main() {
int number = 44;
int guess;
printf("Guess a number between 1 and 100\n");
do {
printf("Enter your guess: ");
scanf("%d",&guess);
if (guess > number)
printf("Too high\n");
if (guess < number)
printf("Too low\n");
} while (guess != number);
printf("You win. The answer is %d",number);
}
For Loop
•for loop:
for (expression_1; expression_2; expression_3)
{
...block of statements to execute...
}
•This structure may be rewritten in the easier syntax of the for loop as:
for (i = initial_i; i <= i_max; i = i + i_increment)
{
...block of statements...
}
#include "stdio.h"
void main()
{
int index;
for(index = 0; index < 6; index = index + 1)
{
printf("The value of the index is %d\n",index);
} /* end of for loop */
}
Symbolic Constants
•You can define constants of any type by using the #define compiler directive.
#define ANGLE_MIN 0
#define ANGLE_MAX 360
•The values of #define cannot be changed in the programming running.
•Conditionals are logical operations involving comparison of quantities (of the same type) using the
–conditional operators:
< smaller than
<= smaller than or equal to
== equal to
!= not equal to
>= greater than or equal to
> greater than
–boolean operators
&& and
|| or
! not
#include "stdio.h"
void main()
{
int xx;
for(xx = 5; xx < 15; xx = xx + 1) {
if (xx == 8)
break;
printf("In the break loop, xx is now %d\n",xx);
}
for(xx = 5; xx < 15; xx = xx + 1) {
if (xx == 8)
continue;
printf("In the continue loop, xx is now %d\n",xx);
}
}
( condition ? true : false )
•( condition ? Executed if true
: Executed if false )
•Find maximum:
x = ( a > b ? a : b )
•Find minimum:
x = ( a < b ? a : b )
Switch Function
•Another conditional use is in the switch construct:
switch (expression)
{
case const_expression_1:
{
...block of statements...
break;
}
case const_expression_2:
{
...block of statements...
break;
}
default:
{
...block of statements..
}
}
#include "stdio.h"
void main()
{
int truck;
for (truck = 3; truck < 13; truck = truck + 1) {
switch (truck) {
case 3 : printf("The value is three\n");
break;
case 4 : printf("The value is four\n");
break;
case 5 :
case 6 :
case 7 :
case 8 : printf("The value is between 5 & 8\n");
break;
case 11 : printf("The value is eleven\n");
break;
default : printf("The value is undefined\n");
break;
} /* end of switch */
} /* end of for loop */
}
•double exp(double x); exponential of x
•double log(double x); natural logarithm of x
•double log10(double x); base-10 logarithm of x
•double pow(double x, double y); x raised to power y
•double sqrt(double x); square root of x
•double ceil(double x); smallest integer not less than x
•double floor(double x); largest integer not greater than x
•double fabs(double x); absolute value of x
•double sin(double x); sine of x
•double cos(double x); cosine of x
•double tan(double x); tangent of x
•double asin(double x); arc-sine of x
•double acos(double x); arc-cosine of x
•double atan(double x); arc-tangent of x
Pointers
•All variables in a program reside in memory
float x;
x = 6.5;
the compiler reserve 4 bytes of memory (on a 32-bit computer) for the floating-point variable x, then put the '' ''value'' 6.5 in it.
•Sometimes we want to know where a variable resides in memory. The address (location in memory) of any variable is obtained by placing the operator ''&'' before its name. Therefore &x is the address of x. C allows us to go one stage further and define a variable, called a pointer which is the address of variables.
float x;
float* px;
x = 6.5;
px = &x;
• defines px to be a pointer to objects of type float, and
sets it equal to the address of x
• The content of the memory location referenced by a
pointer is obtained using the ''*'' operator (this is
called dereferencing the pointer). Thus, *px refers to the
value of x.
•C allows us to perform arithmetic operations using pointers
•For example, if px is a pointer to a variable x of type float, then the expression px + 1 refers not to the next bit or byte in memory but to the location of the next float after x (4 bytes away on most workstations)
void main()
{
float x, y; /* x and y are of float type */
float *fp, *fp2; /* fp and fp2 are pointers to float */
x = 6.5; /* x now contains the value 6.5 */
printf("Value of x is %f, address of x %ld\n", x, &x);
fp = &x; /* fp now points to location of x */
printf("Value in memory location fp is %f\n", *fp);
*fp = 9.2;
printf("New value of x is %f = %f \n", *fp, x);
*fp = *fp + 1.5; /* perform arithmetic */
printf("Final value of x is %f = %f \n", *fp, x);
y = *fp; /* transfer values */
fp2 = fp;
printf("Transfered value into y = %f and fp2 = %f \n", y, *fp2);
}
•Arrays of any type can be formed in C.
type name[dim];
•In C, arrays starts at position 0.
•if v is an array, *v is the same thing as v[0], *(v+1) is the same thing as v[1], and so on.
CHARACTER ARRAY
•A string constant , such as "I am a string" is an array of characters, but it terminated by the special null character "\0'' so programs can find the end of the string.
•Since strings are conventionally terminated by the null character ''\0'', we require one extra storage location in the array!
•C does not provide any operator which manipulate entire strings at once. Special functions available from the standard string library string.h only.
void main()
{
char text_1[100], text_2[100], text_3[100];
char *ta, *tb;
int i;
/* set message to be an arrray of characters; initialize it to the constant string "..." */
/* let the compiler decide on its size by using [] */
char message[] = "Hello, I am a string; what are you?";
printf("Original message: %s\n", message);
/* copy the message to text_1 the hard way */
i=0;
while ( (text_1[i] = message[i]) != '\0' )
i++;
printf("Text_1: %s\n", text_1);
/* use explicit pointer arithmetic */
ta=message;
tb=text_2;
while ( ( *tb++ = *ta++ ) != '\0' )
;
printf("Text_2: %s\n", text_2);
}
''string.h'' Library Functions
char *strcpy(s,ct) -> copy ct into s, including ''\0''; return s
char *strncpy(s,ct,n) -> copy ncharcater of ct into s, return s
char *strncat(s,ct) -> concatenate ct to end of s; return s
char *strncat(s,ct,n) -> concatenate n character of ct to end
of s, terminate with ''\0''; return s
int strcmp(cs,ct) -> compare cs and ct; return 0 if cs=ct,
<0 if cs0 if cs>ct
char *strchr(cs,c) -> return pointer to first occurence of c
in cs or NULL if not encountered
size_t strlen(cs) -> return length of cs
#include < string.h>
void main()
{
char line[100], *sub_text;
strcpy(line,"hello, I am a string;"); /* initialize string */
printf("Line: %s\n", line); /* add to end of string */
strcat(line," what are you?");
printf("Line: %s\n", line);
/* find length of string; strlen brings back length as type size_t */
printf("Length of line: %d\n", (int)strlen(line));
/* find occurence of substrings */
if ( (sub_text = strchr ( line, 'W' ) )!= NULL )
printf("String starting with \"W\" ->%s\n", sub_text);
if ( ( sub_text = strchr ( line, 'w' ) )!= NULL )
printf("String starting with \"w\" ->%s\n", sub_text);
if ( ( sub_text = strchr ( sub_text, 'u' ) )!= NULL )
printf("String starting with \"w\" ->%s\n", sub_text);
}
I/O Capabilities
•
C provides (through its libraries) a variety of I/O routines. At the character level, getchar() reads one character at a time from stdin, while putchar() writes one character at a time to stdout.
#include < stdio.h>
void main()
{
int i, nc;
nc = 0;
i = getchar();
while (i != EOF) {
nc = nc + 1;
i = getchar();
}
printf("Number of characters in file = %d\n", nc);
}
Higher-Level I/O capabilities
•We have already seen that printf handles formatted output to stdout. The counterpart statement for reading from stdin is scanf()
scanf("format string", variables);
I/O to and from files
•Similar statements also exist for handling I/O to and from files. The statements are fscanf() and fprintf()
#include < stdio.h>
FILE *fp;
fp = fopen(name, mode);
fscanf(fp, "format string", variable list);
fprintf(fp, "format string", variable list);
fclose(fp );
•The ''mode'' argument in the fopen specifies the purpose/positioning in opening the file: ''r'' for reading, ''w'' for writing, and ''a'' for appending to the file.
#include < stdio.h>
void main()
{
FILE *fp;
int i;
fp = fopen("foo.dat", "w"); /* open foo.dat for writing */
fprintf(fp, "\nSample Code\n\n"); /* write some info */
for (i = 1; i <= 10 ; i++)
fprintf(fp, "i = %d\n", i);
fclose(fp); /* close the file */
}
Functions
•A function has the following layout:
return-type function-name ( argument-list-if-necessary )
{
...local-declarations...
...statements...
return return-value;
}
• If return-type is omitted, C defaults to int.
The return-value must be of the declared type.
•Arguments are always passed by value in C function calls. This means that local ''copies'' of the values of the arguments are passed to the routines. Any change made to the arguments internally in the function are made only to the local copies of the arguments.
•To change (or define) an argument in the argument list, this argument must be passed as an address.
#include < stdio.h>
void exchange(int a, int b);
void main()
{ /* The argument value won’t be exchanged */
int a, b;
a = 5;
b = 7;
printf("From main: a = %d, b = %d\n", a, b);
exchange(a, b);
printf("Back in main: ");
printf("a = %d, b = %d\n", a, b);
}
void exchange(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
printf(" From function exchange: ");
printf("a = %d, b = %d\n", a, b);
}
#include < stdio.h>
void exchange ( int *a, int *b );
void main()
{/* The argument value will be exchanged */
int a, b;
a = 5;
b = 7;
printf("From main: a = %d, b = %d\n", a, b);
exchange(&a, &b);
printf("Back in main: ");
printf("a = %d, b = %d\n", a, b);
}
void exchange ( int *a, int *b )
{
int temp;
temp = *a;
*a = *b;
*b = temp;
printf(" From function exchange: ");
printf("a = %d, b = %d\n", *a, *b);
}
•The full statement of the first line of the program is:
main(int argc, char** argv)
•The commmand-line arguments are stored in an array of character strings called argv.
•An integer, called argc, which specifies the number of string in the argv array.
•For example,
a.out -i 2 -g -x 3 4
the program would receive
argc = 7
argv[0] = "a.out"
argv[1] = "-i"
argv[2] = "2"
argv[3] = "-g"
argv[4] = "-x"
argv[5] = "3"
argv[6] = "4"
BASIC TIME FUNCTION
•Prototypes:
–Time Data Type: time_t
–time_t time(time_t *tloc) -- returns the time since 00:00:00 GMT, Jan. 1, 1970, measured in seconds.
–If tloc is not NULL, the return value is also stored in the location to which tloc points
–time() returns the value of time on success
–On failure, it returns (time_t) -1. time_t is typedefed to a long (int) in and header files
Example 1: Time (in seconds) to perform some computation
/* timer.c */
#include
#include
#include
main() {
int i;
time_t start_t, end_t;
(void) time(&start_t);
for (i=1;i<=300;++i)
printf(''%d %d %d\n'',i, i*i, i*i*i); (void)
time(&end_t);
printf(''\n Time to do 300 squares and cubes= %d seconds\n'',
(int) end_t – start_t);
}
•lrand48() returns non-negative long integers uniformly distributed over the interval (0, 2**31)
•A similar function drand48() returns double precision numbers in the range [0.0,1.0)
•srand48() sets the seed for these random number generators. It is important to have different seeds when we call the functions otherwise the same set of pseudo-random numbers will generated. time() always provides a unique seed
Suggestion Solution
Solution: Write a program that counts from 1 to 12 and prints the count and its inversion to 5 decimal places for each count. This will require a floating point number.
1 1.00000
2 0.50000
3 0.33333
……
#include
main() {
int i;
float f;
for (i=1; i<=12; i++) {
f=1/(float)i;
printf("Inverse of %d is %.5f\n", i, f);
}
}
Solution: Write a C program to print out the square root from 1 to 100 using math.h function.
#include
main() {
int i;
printf("\t Number \t\t Square Root of Number\n\n");
for (i=0; i<=100; ++i)
printf("\t %d \t\t\t %f \n",i, sqrt((double) i));
}
Solution: Try to write a program simply to print out all the arguments and the name of the program.
#include < stdio.h>
main(int argc, char** argv)
{
int i;
printf("argc = %d\n", argc);
for (i = 0; i < argc; i++)
printf("argv[%d] = \"%s\"\n", i, argv[i]);
}
0 comments:
Post a Comment