|
Latest News
Homework 9 is announced.
Homework 8 is announced.
Grade of programming exam is announced.
|
Sample CodesSample 1: Your First C Program - Hello World.
// header file
#include <stdio.h>
#include <stdlib.h>
int
main() // function main begins program execution
{
printf("Hello World\n"); // print a line of "Hello World" on the screen
return 0; // indicate that program ended successfully
}
Result: Hello World Sample 2: printf & scanf
//header file
#include <stdio.h>
#include <stdlib.h>
int
main() // function main begins program execution
{
int a;
printf("Please enter a integer: ");
scanf("%d", &a);
printf("An integer is %d.\n", a);
return 0;
}
Result: Please enter a integer: 14 An integer is 14. Sample 3: Palindrome - word or phrase that reads the same backwards as forwards
//header file
#include <stdio.h>
#include <string.h> //strlen的定義在這裡頭
int
main()
{
char string[1000];
int i, j, len;
int flag = 1;
printf("Please input a string: ");
scanf("%s", string);
len = strlen(string); //傳回字串長度
for(i = 0, j = len -1; i < j; i++, j--)
{
if(string[i] != string[j])
flag = 0;
}
if(!flag)
{
printf("%s is not a palindrome\n", string);
}
else
{
printf("%s is a palindrome\n", string);
}
}
Result: Please input a string: abbbcbbba abbbcbbba is a palindrome Sample 4: Read and Write Text File
//header file
#include <stdio.h>
#include <string.h> //strlen的定義在這裡頭
#define MAX 65500
int
main()
{
FILE *fp, *fp2;
char infile[MAX];
char outfile[MAX];
char buffer[MAX];
printf("Please input a input file name: ");
scanf("%s", &infile);
printf("Please input a output file name: ");
scanf("%s", &outfile);
fp = fopen(infile, "r");
fp2 = fopen(outfile, "w");
if(!fp && !fp2)
{
printf("File not found!");
exit(0);
}
while(fgets(buffer, MAX, fp) != NULL)
{
buffer[strlen(buffer) - 1] = '\0';
fprintf(fp2, "%s\n", buffer);
}
fclose(fp);
fclose(fp2);
}
|