cplusplus:c_examples
This is an old revision of the document!
Table of Contents
C Examples
adapted from
Differences Between C and C++
by Robert Niemann (Century College)
11/22/2015
Input/output
- example01.c
#include <stdio.h> int main() { int num; printf( "Please enter a number: " ); scanf( "%d", &num ); printf( "You entered %d", num ); getchar(); return 0; }
- example02.c
#include <stdio.h> main() { int dec = 5; char str[] = "abc"; char ch = 's'; float pi = 3.14; printf("%d %s %f %c\n", dec, str, pi, ch); }
- example03.c
#include <stdio.h> main() { char ch; int x; double y; printf("Enter a character, an integer, and a double:\n"); scanf("%c %d %lf", &ch, &x, &y); printf("%c %d %lf\n", ch, x, y); }
File access
- example04.c
/* Writing a text file. */ #include <stdio.h> int main() { FILE *ptr_file; int x; ptr_file =fopen("output.txt", "w"); if (!ptr_file) return 1; for (x = 1; x <= 10; x++) fprintf(ptr_file,"%d\n", x); fclose(ptr_file); return 0; }
- example05.c
/* Reading a text file. */ #include <stdio.h> int main() { FILE *ptr_file; char buf[1000]; ptr_file =fopen("input.txt","r"); if (!ptr_file) return 1; while (fgets(buf,1000, ptr_file)!=NULL) printf("%s",buf); fclose(ptr_file); return 0; }
cplusplus/c_examples.1493596108.txt.gz · Last modified: 2017/04/30 23:48 by mithat