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


printf()

int printf(char *fmt, ...); 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]