Professional Documents
Culture Documents
C Example Programs
C Example Programs
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
Computer Centre
Introduction to C.
C Example Programs
This document contains numerous example programs to provide a practical aid for learning C programming language.
This program combines printf and scanf whereby printf displays the input from scanf.
#include <stdio.h> main() { int i; printf("%c\n",scanf("%i",i)); }
1 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
This program uses do-while and for loop constructions and standard library mathematical functions.
#include <stdio.h> #include <math.h> main() { int i , j , k; double a=10.0 , b=.0; do { printf("%f\n" , pow(a,b)); /* standard function */ b++; } while (b<100); i = 2;
2 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
&& ch!='D');
3 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
main() { int a,b; char ch; printf("Do you want to:\n"); printf("Add, Subtract, Multipy, or Divide\n"); /* force user to enter valid response */ do ( printf("Enter first letter: "); ch =getchar(); printf("\n"); } while (ch!='A' && ch!='S' && ch!='M' && ch!='D'); printf("Enter first number: "); scanf("%d", &a); printf("Enter second number: "); scanf("%d", &b); switch (ch) { case 'A' : printf("%d", a+b); break; case 'S' : printf("%d", a-b); break; case 'M' : printf("%d", a*b); break; case 'D' : if (b!=0) printf("%d", a/b); break; } }
The statement sequence associated with a case may be empty allowing two or more cases to share a common statement sequence.
#include <stdio.h> #include <conio.h> main() { char ch; printf("Enter the letter: "); ch=getchar(); switch(ch) { case 'a' : case 'e' : case 'i' : case 'o' : case 'u' : printf(" is a vowel \n"); break; default: printf(" is a consonant"); } }
4 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
for ( x=0 ; x<=100 ; x++) { if (x%2) continue; /* using modulus operation */ printf("%d\n" , x); }
This program jumps out of an infinite loop using the break statement.
#include <stdio.h> main() { int t ; for ( ; ; ) { scanf("%d" , &t) ; if ( t==10 ) break ; } printf("End of an infinite loop...\n"); }
5 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
6 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
factor(int t) /* function */ { int sum = 1; int i ; for (i = 1 ; i <= t ; i++) sum = sum*i; printf("Factorial %d is %d\n" , t , sum); }
Recursion when applied to a computer language means that a function can call itself. An example follows:
#include <stdio.h> void recurse(int i); void main(void) { recurse(0); } void recurse(int i) { if (i<10) { recurse(i+1); printf("%d ",i); } }
on the screen.
Array programs
This section contains example programs demonstrating the use of arrays. A simple program to demonstrate the definition and use of an array.
7 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
#include <stdio.h> main() { int i[10],j; for ( j=0 ; j<10 ; j++) i[j] = j ; for ( j=0 ; j<10 ; j++) printf("%d\n" , i[j]) ; }
8 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
for (a=1; a<count; a++) for (b=count-1; b>=a; --b) { /* compare adjacent elements */ if (item[b-1] > item[b]) { /* exchange elements */ t= item[b-1]; item[b-1] - item[b]; item[b] = t; } } /* display sorted list */ for (t=0; t<count; t++) printf("%d ", item[t]); }
Pointer programs
This section contains example programs demonstrating the use of pointers. An example program using simple pointers.
#include <stdio.h> main() { int balance; int *address; int value; balance = 5000; address = &balance; value = *address; printf("Balance is : %d\n" , value); }
9 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
10 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
printf("%s\n" , token); } }
String programs
This section contains example programs to demonstrate the use of strings. A simple string example.
#include <stdio.h> main() { char str[80] ; printf("Enter a string: ") ; gets(str) ; printf("%s" , str); printf("\n"); }
The follow program requests the input of two strings, then demonstrates the four string functions with them.
#include <string.h> #include <stdio.h> main() { char str1[80], str2[80]; int i; printf("Enter the first string: "); getstr(str1); printf("Enter the second string: "); getstr(str2); /* see how long the strings are */ printf("%s is %d chars long\n", str1, strlen(str1)); printf("%s is %d chars long\n", str2, strlen(str2)); /* compare the strings */ i= strcmp(str1, str2); if (!i) printf("The strings are equal.\n"); else if (i<0) printf ("%s is less than %s\n", str1,str2); else printf("%s is greater than %s\n", str1, str2); /* concatenate str2 to end of str1 if there is enough room*/ if (strlen(str1)+ strlen(str2) < 80) { strcat(str1, str2); printf("%s\n", str1); } /* copy str2 to str1 */ strcpy(str1, str1); printf("%s %s\n", str1, str2); }
Structure programs
11 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
This section contains example programs to demonstrate the use of structures. This program stores data in a structure and displays the values.
#include <stdio.h> void main(void) { struct s_type { int i; int j; } s; int i; i=10; s.i=100; s.j=101; printf("%d %d %d", i, s.i, s.j); }
The variable i and the structure element i have no relationship to each other. A function may return a structure to the calling procedure.
#include <stdio.h> struct s_type { int i; double d; } var1; struct s-type f(void); void main(void) { var1=f(); printf("%d %1f", var1.i, var1.d); } struct s_type f(void) { struct s_type temp; temp.i=100; temp.d = 123.23; return temp; }
12 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
void main(void) { var1.i=99; var1.d = 98.6; f(var1); } void f(struct s_type temp) { printf("%d %1f", temp.i, temp.d); }
13 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
} while ((ch=fgetchar(fp)) !=EOF) { ch = toupper(ch); if (ch>='A' && ch<='Z') count[ch-'A']++; } for (i=0; i<26; i++) printf("%c occurred %d times\n", i+'A', count[i]); fclose(fp); }
This program uses command line arguments to read and display the contents of a file supplied as an argument.
#include <stdio.h> #define CLEARS 12 /* constant */ main(int argc , char *argv[]) { FILE *fp , *fopen(); int c; putchar(CLEARS); while ( --argc > 0 ) if ((fp=fopen(argv[1], "r"))==NULL) { printf("I can't open %s\n", argv[1]); break; } else { while ((c= getc(fp)) !=EOF) putc(c,stdout); /* display to the screen */ fclose(fp); } }
This program gives a further example of the use of argc & argv
#include <stdio.h> #include <stdlib.h> main(int argc , char *argv[]) { double a , b; if (argc != 3) { printf("Usage: add number number ...\n"); exit(1); } a = atof(argv[1]); b = atof(argv[2]); printf("%lf\n" , a + b); }
14 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
for(;;) { choice = menu_select(); /* get user's selection*/ case 1: enter(); /* enter a new entry */ break; case 2: del(); /* delete an entry */ break; case 3: show_list(); /* display the list */ break; case 4: search(); /* find an entry */ break; case 5: save(); /* save to disk */ break; case 6: load(); /* read from disk */ break; case 7: exit(0); } } } /*********************************************************/ /* Function del */ /*********************************************************/ del() { int i; char str[255]; inputs("enter name: " , str , 30); i = find(str); if (i>=0) *list[i].name = '\0' ; else printf("not found\n") ; }
switch(choice) {
15 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
printf("%s\n" , list[i].name); printf("%s\n" , list[i].street); printf("%s\n" , list[i].town); printf("%s\n" , list[i].county); printf("%s\n" , list[i].code); } /**********************************************************/ /* Function enter */ /**********************************************************/ enter() { int i; for(;;) { i = find_free(); /* find a free structure */ if(i<0) { printf("list full\n"); return; } inputs("enter name: ", list[i].name,30); if(!*list[i].name) break; inputs("enter street: ", list[i].street, 40); inputs("enter town: ", list[i].town, 20); inputs("enter county: ", list[i].county, 20); inputs("enter Postal code: ", list[i].code, 10); } } /**********************************************************/ /* Function find */ /**********************************************************/ find(char *name) { int i; for(i=0 ; i<MAX ; i++) if(!strcmp(name ,list[i].name)) break; if(i==MAX) return else return i; } /**********************************************************/ /* Function find_free */ /**********************************************************/ find_free() { register int i; for(i=0; i<MAX; i++) if(!*list[i].name) return i; return } /**********************************************************/ /* Function init_list */ /**********************************************************/ init_list() { register int i; for (i=0 ; i<MAX ; i++) *list[i].name = '\0' } /**********************************************************/ /* Function inputs */ /**********************************************************/ inputs( char *prompt , char *s , int count) {
/* stop entering */
16 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
char str[255]; do { printf(prompt); gets(str); if(strlen(str) 1; 1; ;>=count) printf("\ntoo long\n"); } while(strlen(str)>=count); strcpy(s , str); } /**********************************************************/ /* Function load */ /**********************************************************/ load() { FILE *fp; if ( (fp=fopen("mlist" , "rb")) == NULL) { printf("cannot open file\n"); return; } printf("\nloading file\n"); fread(list , sizeof list , 1 , fp); if (ferror(fp)) printf("An error occurred while reading file.\n"); fclose(fp); } /**********************************************************/ /* Function menu_select */ /**********************************************************/ menu_select() { char s[80]; int c; printf("1. Enter a name\n") ; printf("2. Delete a name\n") ; printf("3. List the File \n"); printf("4. Search\n") ; printf("5. Save the file\n") ; printf("6. Load the file\n") ; printf("7. Quit\n") ; do { printf("\nEnter your choice: "); gets(s); c = atoi(s); } while(c<0 || c>7); return c; } /**********************************************************/ /* Function save */ /**********************************************************/ save() { FILE *fp; if ( (fp=fopen("mlist" , "wb")) == NULL) { printf("cannot open file\n"); return; } printf("\nsaving file\n");
17 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
fwrite(list , sizeof list , 1 , fp); if (ferror(fp)) printf("An error occurred while writing file.\n"); fclose(fp); } /**********************************************************/ /* Function search */ /**********************************************************/ search() { int i; char name[30]; inputs("enter name to find: " , name , 30); if ((i=find(name))<0) printf("not found\n"); else display(i); } /**********************************************************/ /* Function show_list */ /**********************************************************/ show_list() { int i; for(i=0 ; i<MAX ; i++) { if(*list[i].name) { display(i); printf("\n\n"); } } printf("\n\n"); }
[program] The second example program uses functions to play a simple game of tic tac toe.
#include <stdio.h> #include <stdlib.h> char matrix[3][3]; main() { char done; printf("This is the game of tic tac toe...\n"); printf("You will be playing against the computer.\n") ; done = ' '; init_matrix(); do { disp_matrix(); get_player_move(); done = check(); if (done != ' ') break; get_computer_move(); done = check();
18 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
} while (done == ' '); if (done == 'X') printf("\n\nYou won!!!\n"); else printf("I won!!!\n"); disp_matrix(); } /**********************************************************/ /* fuction to initialise matrix */ /**********************************************************/ init_matrix() { int i , j ; for (i=0 ; i<3 ; i++) for (j=0 ; j<3 ; j++) matrix[i][j] = ' '; } /**********************************************************/ /* fuction to get players move */ /**********************************************************/ get_player_move() { int x , y ; printf("Enter coordinates of your X: "); scanf("%d%d" , &x , &y); x--; y--; if (matrix[x][y] != ' ') { printf("Invalid move, try again...\n"); get_player_move(); } else matrix[x][y] = 'X'; } /**********************************************************/ /* fuction to get computer move */ /**********************************************************/ get_computer_move() { int i , j ; for (i=0 ; i<3 ; i++) { for (j=0 ; j<3 ; j++) if(matrix[i][j]==' ') break; if (matrix[i][j] == ' ') break; } if (i*j == 9) { printf("draw....\n"); exit(0); } else matrix[i][j] = 'O'; } /**********************************************************/ /* fuction to display matrix */ /**********************************************************/ disp_matrix() { int t ; printf(" 1 2 3\n");
19 de 20
file:///C:/Documents%20and%20Settings/Alberto/Mis%20documentos/...
for (t=0 ; t<3 ; t++) { printf(" %c | %c | %c %d" , matrix[t][0], matrix[t][1], matrix[t][2] , t+1); if (t!=2) printf("\n---|---|---\n"); } printf("\n"); } /**********************************************************/ /* fuction to check matrix */ /**********************************************************/ check() { int i ; for (i=0 ; i<3 ; i++) if(matrix[i][0] == matrix[i][1] && matrix[i][0] == return matrix[i][0]; for (i=0 ; i<3 ; i++) if(matrix[0][i] == matrix[1][i] && matrix[0][i] == return matrix[0][i]; if(matrix[0][0] == matrix[1][1] && matrix[1][1] == return matrix[0][0]; if(matrix[0][2] == matrix[1][1] && matrix[1][1] == return matrix[0][2]; return ' '; } [program]
matrix[i][2])
matrix[2][i])
matrix[2][2])
matrix[2][0])
Back
Continue
Information Suppliers: Richard Mobbs, Head of Learning Technology, University of Leicester, Computer Centre
Last updated: 09 July 2001 09:59 Document owner: University CWIS Maintainer Computer Centre Web maintainer
20 de 20