C Lecture 1
[Lecture Index]
[Next Lecture]
hello.c
#include <stdio.h>
int
main()
{
/* A very simple program... */
printf("Hello, world\n");
return 0;
}
count.c
#include <stdio.h>
#include <string.h>
int
main()
{
char buf[1024];
int char_count = 0;
int line_count;
line_count = 0;
while (fgets(buf, sizeof(buf), stdin)) {
char_count += strlen(buf);
line_count++;
}
printf(
"File has %d characters in %d lines\n",
char_count, line_count);
return 0;
}
Data types
Integer data types:
char c;
int i, j;
short int s;
long int l;
Real numbers:
double d;
float f;
Pointers:
int *p;
Arrays:
char buf[1024];
int nums[10];
Structures (records):
struct tm {
int tm_sec;
int tm_min;
int tm_hour;
...
};
Unions (`variant' records):
union name {
int i;
char str[12];
};
Enumerations (groups of integer constants):
enum Suits {
SPADE, HEART, CLUB, DIAMOND
};
Strings in C
- strings are characters stored sequentially in memory
- the end is marked by a 0 (null) byte
- arrays of characters often used to `create' memory for strings
- only starting location is passed around
(e.g., to functions)
printf()
int printf(char *fmt, ...);
- first argument is the format string
- ... means any number & type of other arguments
- returns number of characters output
(EOF (-1) on error)
- % in format string (fmt) introduces
formatted argument:
- %d: replaced with integer argument
- %c: replaced with character argument
- %s: replaced with string argument
- %f: replaced with floating point argument
- %%: print a %.
Examples:
int i = 10;
double pi = 3.1415926535897932385;
char letter = 'A';
char *mesg = "hi";
char buf[10] = "there";
printf("i is %d, pi is %f\n",
i, pi);
printf("more exact pi: %.20f\n", pi);
printf("letter=%c mesg: %s, buf: %s\n",
letter, mesg, buf);
While statement
while (expr)
statement
Examples:
while (fgets(buf, sizeof(buf), stdin))
lines++;
int i;
i = 0;
while (i < 10) {
printf("%d\n", i);
i++;
}
Do statement
do
statement
while (expr);
Example:
do {
printf("Feed me: ");
fflush(stdout);
} while (fgets(buf, sizeof(buf),
stdin));
If statement
if (expr)
statement
else
statement
Example:
if (grade < 0 || grade > 100) {
printf(
"Error: grade not in range 0..100\n"
);
return -1;
}
passed = 1;
if (grade >= 80)
letter = 'A';
else if (grade >= 65)
letter = 'B';
else if (grade >= 55)
letter = 'C';
else if (grade >= 50)
letter = 'D';
else {
letter = 'F';
passed = 0;
}
For statement
for (expr; expr; expr)
statement
Examples:
for (i = 0; i < 10; i++)
printf("%d\n", i);
factorial = 1;
for (i = 0; i < 10; i++) {
if (i)
factorial *= i;
printf("factorial of %d is %d\n",
i, factorial);
}
Switch statement
switch (expr) {
case const-expr:
statements
case const-expr:
statements
...
default:
statements
}
Example:
int optc;
int verbose = 0;
.
.
switch (optc) {
case 'v':
verbose = 1;
break;
case 'h':
case 'H':
print_help();
exit(0);
default:
printf("Unknown option `%c'\n",
optc);
exit(1);
}
[Lecture Index]
[Next Lecture]