Using #if, #elif, and #else

Thursday, November 13, 2014
/* 2303.c: Using #if, #elif, and #else */
#include <stdio.h>

#define C_LANG 'C'
#define B_LANG 'B'
#define NO_ERROR 0

main(void)
{
    #if C_LANG == 'C' && B_LANG == 'B'
        #undef C_LANG
        #define C_LANG "I know the C language.\n"
        #undef B_LANG
        #define B_LANG "I know BASIC.\n"
        printf("%s %s", C_LANG, B_LANG);
    #elif C_LANG == 'C'
        #undef C_LANG
        #define C_LANG "I only know C language.\n"
        printf("%s", C_LANG);
    #elif B_LANG == 'B'
        #undef B_LANG
        #define B_LANG "I only know BASIC.\n"
        printf("%s", B_LANG);
    #else
        printf("I don't know C or BASIC.\n");
    #endif

    return NO_ERROR;
}

Nesting #if

/* 2304.c: Nesting #if */
#include <stdio.h>

/* macro definitions */
#define ZERO 0
#define ONE 1
#define TWO (ONE + ONE)
#define THREE (ONE + TWO)
#define TEST_1 ONE
#define TEST_2 TWO
#define TEST_3 THREE
#define MAX_NUM THREE
#define NO_ERROR ZERO
/* function declaration */
void StrPrint(char **ptr_s, int max);
/* the main() function */
main(void)
{
    char *str[MAX_NUM] = {"The choice of a point of view",
    "is the initial act of culture.",
    "--- by O. Gasset"};

    #if TEST_1 == 1
        #if TEST_2 == 2
            #if TEST_3 == 3
                StrPrint(str, MAX_NUM);
            #else
                StrPrint(str, MAX_NUM - ONE);
            #endif
        #else
            StrPrint(str, MAX_NUM - TWO);
        #endif
    #else
        printf("No TEST macro has been set.\n");
    #endif

    return NO_ERROR;
}
/* function definition */
void StrPrint(char **ptr_s, int max)
{
    int i;

    for (i=0; i<max; i++)
    printf("Content: %s\n",ptr_s[i]);
}

Using #define

/* 2301.c: Using #define */
#include <stdio.h>

#define METHOD "ABS"
#define ABS(val) ((val) < 0 ? -(val) : (val))
#define MAX_LEN 8
#define NEGATIVE_NUM -10

main(void)
{
    char *str = METHOD;
    int array[MAX_LEN];
    int i;

    printf("The orignal values in array:\n");
    for (i=0; i<MAX_LEN; i++){
    array[i] = (i + 1) * NEGATIVE_NUM;
    printf("array[%d]: %d\n", i, array[i]);
    }

    printf("\nApplying the %s macro:\n", str);
    for (i=0; i<MAX_LEN; i++){
    printf("ABS(%d): %3d\n", array[i], ABS(array[i]));
    }

    return 0;
}

Using #ifdef, #ifndef, and #endif

/* 2302.c: Using #ifdef, #ifndef, and #endif */
#include <stdio.h>

#define UPPER_CASE 0
#define NO_ERROR 0

main(void)
{
    #ifdef UPPER_CASE
    printf("THIS LINE IS PRINTED OUT,\n");
    printf("BECAUSE UPPER_CASE IS DEFINED.\n");
    #endif
    #ifndef LOWER_CASE
    printf("\nThis line is printed out,\n");
    printf("because LOWER_CASE is not defined.\n");
    #endif

    return NO_ERROR;
}

Using the fscanf() and fprintf() functions

/* 2203.c: Using the fscanf() and fprintf() functions */
#include <stdio.h>

enum {SUCCESS, FAIL,
MAX_NUM = 3,
STR_LEN = 23};
void DataWrite(FILE *fout);
void DataRead(FILE *fin);
int ErrorMsg(char *str);

main(void)
{
    FILE *fptr;
    char filename[]= "strnum.mix";
    int reval = SUCCESS;

    if ((fptr = fopen(filename, "w+")) == NULL){
        reval = ErrorMsg(filename);
    }
    else {
        DataWrite(fptr);
        rewind(fptr);
        DataRead(fptr);
        fclose(fptr);
    }

    return reval;
}
/* function definition */
void DataWrite(FILE *fout)
{
    int i;
    char cities[MAX_NUM][STR_LEN] = {"St.Louis->Houston:","Houston->Dallas:","Dallas->Philadelphia:"};
    int miles[MAX_NUM] = {845,243,1459};

    printf("The data written:\n");
    for (i=0; i<MAX_NUM; i++){
        printf("%-23s %d miles\n", cities[i], miles[i]);
        fprintf(fout, "%s %d", cities[i], miles[i]);
    }
}
/* function definition */
void DataRead(FILE *fin)
{
    int i;
    int miles;
    char cities[STR_LEN];

    printf("\nThe data read:\n");
    for (i=0; i<MAX_NUM; i++){
        fscanf(fin, "%s%d", cities, &miles);
        printf("%-23s %d miles\n", cities, miles);
}
}
/* function definition */
int ErrorMsg(char *str)
{
    printf("Cannot open %s.\n", str);
    return FAIL;
}

Redirecting a standard stream

/* 2204.c: Redirecting a standard stream */
#include <stdio.h>

enum {SUCCESS, FAIL,
STR_NUM = 4};

void StrPrint(char **str);
int ErrorMsg(char *str);

main(void)
{
char *str[STR_NUM] = {
"Be bent, and you will remain straight.",
"Be vacant, and you will remain full.",
"Be worn, and you will remain new.",
"---- by Lao Tzu"};
char filename[]= "LaoTzu.txt";
int reval = SUCCESS;

StrPrint(str);
if (freopen(filename, "w", stdout) == NULL){
reval = ErrorMsg(filename);
} else {
StrPrint(str);
fclose(stdout);
}
return reval;
}
/* function definition */
void StrPrint(char **str)
{
int i;

for (i=0; i<STR_NUM; i++)
printf("%s\n", str[i]);
}
/* function definition */
int ErrorMsg(char *str)
{
printf("Cannot open %s.\n", str);
return FAIL;
}

Reading and writing one block at a time

/* 2104.c: Reading and writing one block at a time */
#include <stdio.h>

enum {SUCCESS, FAIL, MAX_LEN = 80};

void BlockReadWrite(FILE *fin, FILE *fout);
int ErrorMsg(char *str);

main(void)
{
    FILE *fptr1, *fptr2;
    char filename1[]= "test1.txt";
    char filename2[]= "test2.txt";
    int reval = SUCCESS;

    if ((fptr1 = fopen(filename1, "w")) == NULL){
        reval = ErrorMsg(filename1);
    }
    else if ((fptr2 = fopen(filename2, "r")) == NULL){
        reval = ErrorMsg(filename2);
    }
    else {
        BlockReadWrite(fptr2, fptr1);
        fclose(fptr1);
        fclose(fptr2);
    }

    return reval;
}
/* function definition */
void BlockReadWrite(FILE *fin, FILE *fout)
{
    int num;
    char buff[MAX_LEN + 1];

    while (!feof(fin)){
        num = fread(buff, sizeof(char), MAX_LEN, fin);
        buff[num * sizeof(char)] = '\0'; /* append a null character */
        printf("%s", buff);
        fwrite(buff, sizeof(char), num, fout);
    }
}
/* function definition */
int ErrorMsg(char *str)
{
    printf("Cannot open %s.\n", str);
    return FAIL;
}

Random access to a file

/* 2201.c: Random access to a file */
#include <stdio.h>

enum {SUCCESS, FAIL, MAX_LEN = 80};

void PtrSeek(FILE *fptr);
long PtrTell(FILE *fptr);
void DataRead(FILE *fptr);
int ErrorMsg(char *str);

main(void)
{
FILE *fptr;
char filename[]= "test1.txt";
int reval = SUCCESS;

if ((fptr = fopen(filename, "r")) == NULL){
reval = ErrorMsg(filename);
} else {
PtrSeek(fptr);
fclose(fptr);
}

return reval;
}
/* function definition */
void PtrSeek(FILE *fptr)
{
long offset1, offset2, offset3;

offset1 = PtrTell(fptr);
DataRead(fptr);
offset2 = PtrTell(fptr);
DataRead(fptr);
offset3 = PtrTell(fptr);
DataRead(fptr);

printf("\nRe-read the haiku:\n");
/* re-read the third verse of the haiku */
fseek(fptr, offset3, SEEK_SET);
DataRead(fptr);
/* re-read the second verse of the haiku */
fseek(fptr, offset2, SEEK_SET);
DataRead(fptr);
/* re-read the first verse of the haiku */
fseek(fptr, offset1, SEEK_SET);
DataRead(fptr);
}
/* function definition */
long PtrTell(FILE *fptr)
{
long reval;

reval = ftell(fptr);
printf("The fptr is at %ld\n", reval);

return reval;
}
/* function definition */
void DataRead(FILE *fptr)
{
char buff[MAX_LEN];

fgets(buff, MAX_LEN, fptr);
printf("---%s", buff);
}
/* function definition */
int ErrorMsg(char *str)
{
printf("Cannot open %s.\n", str);
return FAIL;
}

Reading and writing binary data

/* 2202.c: Reading and writing binary data */
#include <stdio.h>

enum {SUCCESS, FAIL, MAX_NUM = 3};

void DataWrite(FILE *fout);
void DataRead(FILE *fin);
int ErrorMsg(char *str);

main(void)
{
    FILE *fptr;
    char filename[]= "double.bin";
    int reval = SUCCESS;

    if ((fptr = fopen(filename, "wb+")) == NULL){
        reval = ErrorMsg(filename);
    }
    else {
        DataWrite(fptr);
        rewind(fptr); /* reset fptr */
        DataRead(fptr);
        fclose(fptr);
        }

return reval;
}
/* function definition */
void DataWrite(FILE *fout)
{
    int i;
    double buff[MAX_NUM] = {123.45,567.89,100.11};

    printf("The size of buff: %d-byte\n", sizeof(buff));
    for (i=0; i<MAX_NUM; i++){
        printf("%5.2f\n", buff[i]);
        fwrite(&buff[i], sizeof(double), 1, fout);
    }
}
/* function definition */
void DataRead(FILE *fin)
{
    int i;
    double x;

    printf("\nRead back from the binary file:\n");
    for (i=0; i<MAX_NUM; i++){
        fread(&x, sizeof(double), (size_t)1, fin);
        printf("%5.2f\n", x);
    }
}
/* function definition */
int ErrorMsg(char *str)
{
    printf("Cannot open %s.\n", str);
    return FAIL;
}

Opening and closing a file

/* 2101.c: Opening and closing a file */
#include <stdio.h>

enum {SUCCESS, FAIL};

main(void)
{
    FILE *fptr;
    char filename[]= "test.txt";
    int reval = SUCCESS;

    if ((fptr = fopen(filename, "r")) == NULL){
        printf("Cannot open %s.\n", filename);
        reval = FAIL;
    }
    else {
        printf("The value of fptr: 0x%p\n", fptr);
        printf("Ready to close the file.");
        fclose(fptr);
    }

    return reval;
}

Reading and writing one character at a time

/* 2102.c: Reading and writing one character at a time */
#include <stdio.h>

enum {SUCCESS, FAIL};

void CharReadWrite(FILE *fin, FILE *fout);

main(void)
{
    FILE *fptr1, *fptr2;
    char filename1[]= "test1.txt";
    char filename2[]= "test2.txt";
    int reval = SUCCESS;

    if ((fptr1 = fopen(filename1, "w")) == NULL){
        printf("Cannot open %s.\n", filename1);
        reval = FAIL;
    }
    else if ((fptr2 = fopen(filename2, "r")) == NULL){
        printf("Cannot open %s.\n", filename2);
        reval = FAIL;
    }
    else {
        CharReadWrite(fptr2, fptr1);
        fclose(fptr1);
        fclose(fptr2);
    }

    return reval;
}
/* function definition */
void CharReadWrite(FILE *fin, FILE *fout)
{
    int c;

    while ((c=fgetc(fin)) != EOF){
        fputc(c, fout); /* write to a file */
        putchar(c); /* put the character on the screen */
    }
}

Reading and writing one line at a time

/* 2103.c: Reading and writing one line at a time */
#include <stdio.h>

enum {SUCCESS, FAIL, MAX_LEN = 81};

void LineReadWrite(FILE *fin, FILE *fout);

main(void)
{
    FILE *fptr1, *fptr2;
    char filename1[]= "test1.txt";
    char filename2[]= "test2.txt";
    int reval = SUCCESS;

    if ((fptr1 = fopen(filename1, "w")) == NULL){
        printf("Cannot open %s for writing.\n", filename1);
        reval = FAIL;
    }
    else if ((fptr2 = fopen(filename2, "r")) == NULL){
        printf("Cannot open %s for reading.\n", filename2);
        reval = FAIL;
    }
    else {
        LineReadWrite(fptr2, fptr1);
        fclose(fptr1);
        fclose(fptr2);
    }

    return reval;
}
/* function definition */
void LineReadWrite(FILE *fin, FILE *fout)
{
    char buff[MAX_LEN];

    while (fgets(buff, MAX_LEN, fin) != NULL){
        fputs(buff, fout);
        printf("%s", buff);
    }
}

Referencing the same memory in different ways

/* 2004.c: Referencing the same memory in different ways */
#include <stdio.h>

union u{
char ch[2];
int num;
};

int UnionInitialize(union u val);

main(void)
{
    union u val;
    int x;

    x = UnionInitialize(val);

    printf("The two character constants held by the union:\n");
    printf("%c\n", x & 0x00FF);
    printf("%c\n", x >> 8);

    return 0;
    }
    /* function definition */
    int UnionInitialize(union u val)
    {
    val.ch[0] = 'H';
    val.ch[1] = 'i';

    return val.num;
}

Using unions

/* 2005.c: Using unions */
#include <stdio.h>
#include <string.h>

struct survey {
char name[20];
char c_d_p;
int age;
int hour_per_week;
union {
char cable_company[16];
char dish_company[16];
} provider;
};

void DataEnter(struct survey *s);
void DataDisplay(struct survey *s);

main(void)
{
    struct survey tv;

    DataEnter(&tv);
    DataDisplay(&tv);

    return 0;
}
/* function definition */
void DataEnter(struct survey *ptr)
{
    char is_yes[4];

    printf("Are you using cable at home? (Yes or No)\n");
    gets(is_yes);
    if ((is_yes[0] == 'Y') || (is_yes[0] == 'y')){
        printf("Enter the cable company name:\n");
        gets(ptr->provider.cable_company);
        ptr->c_d_p = 'c';
    }
    else {
        printf("Are you using a satellite dish? (Yes or No)\n");
        gets(is_yes);
        if ((is_yes[0] == 'Y') || (is_yes[0] == 'y')){
            printf("Enter the satellite dish company name:\n");
            gets(ptr->provider.dish_company);
            ptr->c_d_p = 'd';
        }
        else {
            ptr->c_d_p = 'p';
        }
    }
    printf("Please enter your name:\n");
    gets(ptr->name);
    printf("Your age:\n");
    scanf("%d", &ptr->age);
    printf("How many hours you spend on watching TV per week:\n");
    scanf("%d", &ptr->hour_per_week);
}
/* function definition */
void DataDisplay(struct survey *ptr)
{
    printf("\nHere's what you've entered:\n");
    printf("Name: %s\n", ptr->name);
    printf("Age: %d\n", ptr->age);
    printf("Hour per week: %d\n", ptr->hour_per_week);
    if (ptr->c_d_p == 'c')
        printf("Your cable company is: %s\n",ptr->provider.cable_company);
    else if (ptr->c_d_p == 'd')
        printf("Your satellite dish company is: %s\n",ptr->provider.dish_company);
    else
        printf("You don't have cable or a satellite dish.\n");
        printf("\nThanks and Bye!\n");
}

Applying bit fields

/* 2006.c: Applying bit fields */
#include <stdio.h>
#include <string.h>

struct bit_field {
int cable: 1;
int dish: 1;
};

struct survey {
char name[20];
struct bit_field c_d;
int age;
int hour_per_week;
union {
char cable_company[16];
char dish_company[16];
} provider;
};

void DataEnter(struct survey *s);
void DataDisplay(struct survey *s);

main(void)
{
    struct survey tv;

    DataEnter(&tv);
    DataDisplay(&tv);

    return 0;
}
/* function definition */
void DataEnter(struct survey *ptr)
{
    char is_yes[4];

    printf("Are you using cable at home? (Yes or No)\n");
    gets(is_yes);
    if ((is_yes[0] == 'Y') || (is_yes[0] == 'y')){
        printf("Enter the cable company name:\n");
        gets(ptr->provider.cable_company);
        ptr->c_d.cable = 1;
        ptr->c_d.dish = 0;
        }
    else {
        printf("Are you using a satellite dish? (Yes or No)\n");
        gets(is_yes);
        if ((is_yes[0] == 'Y') ||(is_yes[0] == 'y')){
            printf("Enter the satellite dish company name:\n");
            gets(ptr->provider.dish_company);
            ptr->c_d.cable = 0;
            ptr->c_d.dish = 1;
        }
        else {
            ptr->c_d.cable = 0;
            ptr->c_d.dish = 0;
        }
    }
    printf("Please enter your name:\n");
    gets(ptr->name);
    printf("Your age:\n");
    scanf("%d", &ptr->age);
    printf("How many hours you spend on watching TV per week:\n");
    scanf("%d", &ptr->hour_per_week);
}
/* function definition */
void DataDisplay(struct survey *ptr)
{
    printf("\nHere's what you've entered:\n");
    printf("Name: %s\n", ptr->name);
    printf("Age: %d\n", ptr->age);
    printf("Hour per week: %d\n", ptr->hour_per_week);
    if (ptr->c_d.cable && !ptr->c_d.dish)
        printf("Your cable company is: %s\n",
        ptr->provider.cable_company);
    else if (!ptr->c_d.cable && ptr->c_d.dish)
        printf("Your satellite dish company is: %s\n",
        ptr->provider.dish_company);
    else
        printf("You don't have cable or a satellite dish.\n");
        printf("\nThanks and Bye!\n");
}

Forward-referencing structures

/* 1907.c Forward-referencing structures */
#include <stdio.h>
/* forward-referencing structure,
It's not legal in C to use forward references in a typedef statement.*/
struct resume {
char name[16];
struct date *u;
struct date *g;
};
/* referenced structure */
struct date {
int year;
char school[32];
char degree[8];
};

typedef struct resume RSM;
typedef struct date DATE;

void InfoDisplay(RSM *ptr);

main(void)
{
    DATE under = {1985,"Rice University","B.S."};
    DATE graduate = {1987,"UT Austin","M.S."};
    RSM new_employee = {"Tony",&under,&graduate};

    printf("Here is the new employee's resume:\n");
    InfoDisplay(&new_employee);

    return 0;
}
/* function definition */
void InfoDisplay(RSM *ptr)
{
    printf("Name: %s\n", ptr->name);
    /* undergraduate */
    printf("School name: %s\n", ptr->u->school);
    printf("Graduation year: %d\n", ptr->u->year);
    printf("Degree: %s\n", ptr->u->degree);
    /* graduate */
    printf("School name: %s\n", ptr->g->school);
    printf("Graduation year: %d\n", ptr->g->year);
    printf("Degree: %s\n", ptr->g->degree);
}

Referencing a union

/* 2001.c Referencing a union */
#include <stdio.h>
#include <string.h>

main(void)
{
    union menu {
    char name[23];
    double price;
    } dish;

    printf("The content assigned to the union separately:\n");
    /* reference name */
    strcpy(dish.name, "Sweet and Sour Chicken");
    printf("Dish Name: %s\n", dish.name);
    /* reference price */
    dish.price = 9.95;
    printf("Dish Price: %5.2f\n", dish.price);

    return 0;
}

Memory sharing in unions

/* 2002.c: Memory sharing in unions */
#include <stdio.h>

main(void)
{
    union employee {
    int start_year;
    int dpt_code;
    int id_number;
    } info;

    /* initialize start_year */
    info.start_year = 1997;
    /* initialize dpt_code */
    info.dpt_code = 8;
    /* initialize id */
    info.id_number = 1234;

    /* display content of union */
    printf("Start Year: %d\n", info.start_year);
    printf("Dpt. Code: %d\n", info.dpt_code);
    printf("ID Number: %d\n", info.id_number);
    return 0;
}

The size of a union

/* 2003.c The size of a union */
/*The size of a union is the same as the size of the largest member in the union.
The size of a structure is equal to the sum of sizes of its members instead of the size of the largest member. */

#include <stdio.h>
#include <string.h>

main(void)
{
    union u {
    double x;
    int y;
    } a_union;

    struct s {
    double x;
    int y;
    } a_struct;

    printf("The size of double: %d-byte\n",
    sizeof(double));
    printf("The size of int: %d-byte\n",
    sizeof(int));

    printf("The size of a_union: %d-byte\n",
    sizeof(a_union));
    printf("The size of a_struct: %d-byte\n",
    sizeof(a_struct));

    return 0;
}

Pointing to a structure

/* 1904.c Pointing to a structure */
#include <stdio.h>

struct computer {
float cost;
int year;
int cpu_speed;
char cpu_type[16];
};

typedef struct computer SC;

void DataReceive(SC *ptr_s);

main(void)
{
    SC model;

    DataReceive(&model);
    printf("Here are what you entered:\n");
    printf("Year: %d\n", model.year);
    printf("Cost: $%6.2f\n", model.cost);
    printf("CPU type: %s\n", model.cpu_type);
    printf("CPU speed: %d MHz\n", model.cpu_speed);

    return 0;
}
/* function definition */
void DataReceive(SC *ptr_s)
{
    printf("The type of the CPU inside your computer?\n");
    gets((*ptr_s).cpu_type);
    printf("The speed(MHz) of the CPU?\n");
    scanf("%d", &(*ptr_s).cpu_speed);
    printf("The year your computer was made?\n");
    scanf("%d", &(*ptr_s).year);
    printf("How much you paid for the computer?\n");
    scanf("%f", &(*ptr_s).cost);
}

Arrays of structures

/* 1905.c Arrays of structures */
#include <stdio.h>

struct haiku {
int start_year;
int end_year;
char author[16];
char str1[32];
char str2[32];
char str3[32];
};

typedef struct haiku HK;

void DataDisplay(HK *ptr_s);

main(void)
{
    HK poem[2] = {
    { 1641,1716,"Sodo","Leading me along","my shadow goes back home","from looking at the moon."},
    { 1729,1781,"Chora","A storm wind blows","out from among the grasses","the full moon grows."}
    };
    int i;

    for (i=0; i<2; i++)
    DataDisplay(&poem[i]);

    return 0;
}
/* function definition */
void DataDisplay(HK *ptr_s)
{
    printf("%s\n", ptr_s->str1);
    printf("%s\n", ptr_s->str2);
    printf("%s\n", ptr_s->str3);
    printf("--- %s\n", ptr_s->author);
    printf(" (%d-%d)\n\n", ptr_s->start_year, ptr_s->end_year);
}

Using nested structures

/* 1906.c Using nested structures */
#include <stdio.h>

struct department {
int code;
char name[32];
char position[16];
};

typedef struct department DPT;

struct employee {
DPT d;
int id;
char name[32];
};

typedef struct employee EMPLY;

void InfoDisplay(EMPLY *ptr);
void InfoEnter(EMPLY *ptr);

main(void)
{
    EMPLY info = {
    { 1,"Marketing","Manager"},1,"B. Smith"};

    printf("Here is a sample:\n");
    InfoDisplay(&info);

    InfoEnter(&info);

    printf("\nHere are what you entered:\n");
    InfoDisplay(&info);

    return 0;
}
/* function definition */
void InfoDisplay(EMPLY *ptr)
{
    printf("Name: %s\n", ptr->name);
    printf("ID #: %04d\n", ptr->id);
    printf("Dept. name: %s\n", ptr->d.name);
    printf("Dept. code: %02d\n", ptr->d.code);
    printf("Your position: %s\n", ptr->d.position);
}
/* function definition */
void InfoEnter(EMPLY *ptr)
{
    printf("\nPlease enter your information:\n");
    printf("Your name:\n");
    gets(ptr->name);
    printf("Your position:\n");
    gets(ptr->d.position);
    printf("Dept. name:\n");
    gets(ptr->d.name);
    printf("Dept. code:\n");
    scanf("%d", &(ptr->d.code));
    printf("Your employee ID #:\n");
    scanf("%d", &(ptr->id));
}

Access to structure members

/* 1901.c Access to structure members */
#include <stdio.h>
main(void)
{
    struct computer {
    float cost;
    int year;
    int cpu_speed;
    char cpu_type[16];
    } model;

    printf("The type of the CPU inside your computer?\n");
    gets(model.cpu_type);
    printf("The speed(MHz) of the CPU?\n");
    scanf("%d", &model.cpu_speed);
    printf("The year your computer was made?\n");
    scanf("%d", &model.year);
    printf("How much you paid for the computer?\n");
    scanf("%f", &model.cost);

    printf("Here are what you entered:\n");
    printf("Year: %d\n", model.year);
    printf("Cost: $%6.2f\n", model.cost);
    printf("CPU type: %s\n", model.cpu_type);
    printf("CPU speed: %d MHz\n", model.cpu_speed);

    return 0;
}

Initializing a structure

/* 1902.c Initializing a structure */
#include <stdio.h>

main(void)
{
    struct employee {
    int id;
    char name[32];
    };
    /* structure initialization */
    struct employee info = {1,"B. Smith"};

    printf("Here is a sample:\n");

    printf("Employee Name: %s\n", info.name);
    printf("Employee ID #: %04d\n\n", info.id);

    printf("What's your name?\n");
    gets(info.name);
    printf("What's your ID number?\n");
    scanf("%d", &info.id);

    printf("\nHere are what you entered:\n");
    printf("Name: %s\n", info.name);
    printf("ID #: %04d\n", info.id);

    return 0;
}

Passing a structure to a function

/* 1903.c Passing a structure to a function */
#include <stdio.h>

struct computer {
float cost;
int year;
int cpu_speed;
char cpu_type[16];
};
/* create synonym */
typedef struct computer SC;
/* function declaration */
SC DataReceive(SC s);

main(void)
{
    SC model;

    model = DataReceive(model);
    printf("Here are what you entered:\n");
    printf("Year: %d\n", model.year);
    printf("Cost: $%6.2f\n", model.cost);
    printf("CPU type: %s\n", model.cpu_type);
    printf("CPU speed: %d MHz\n", model.cpu_speed);

    return 0;
}
/* function definition */
SC DataReceive(SC s)
{
    printf("The type of the CPU inside your computer?\n");
    gets(s.cpu_type);
    printf("The speed(MHz) of the CPU?\n");
    scanf("%d", &s.cpu_speed);
    printf("The year your computer was made?\n");
    scanf("%d", &s.year);
    printf("How much you paid for the computer?\n");
    scanf("%f", &s.cost);
    return s;
}

Calling a recursive function

/* 1804.c: Calling a recursive function */
#include <stdio.h>

enum con{MIN_NUM = 0,MAX_NUM = 100};

int fRecur(int n);

main()
{
    int i, sum1, sum2;

    sum1 = sum2 = 0;
    for (i=1; i<=MAX_NUM; i++)
    sum1 += i;
    printf("The value of sum1 is %d.\n", sum1);
    sum2 = fRecur(MAX_NUM);
    printf("The value returned by fRecur() is %d.\n", sum2);

    return 0;
}
/* function definition */
int fRecur(int n)
{
    if (n == MIN_NUM)
        return 0;
    return fRecur(n - 1) + n;
}

Command-line arguments

/* 1805.c: Command-line arguments */
#include <stdio.h>

main (int argc, char *argv[])
{
    int i;

    printf("The value received by argc is %d.\n", argc);
    printf("There are %d command-line arguments passed to main().\n",argc);

    printf("The first command-line argument is: %s\n", argv[0]);
    printf("The rest of the command-line arguments are:\n");
    for (i=1; i<argc; i++)
        printf("%s\n", argv[i]);

    return 0;
}

Defining enum data types

/* 1801.c: Defining enum data types */
#include <stdio.h>
/* main() function */
main()
{
    enum language {human=100, animal=50, computer};
    enum days{SUN,MON,TUE,WED,THU,FRI,SAT};

    printf("human: %d, animal: %d, computer: %d\n", human, animal, computer);
    printf("SUN: %d\n", SUN);
    printf("MON: %d\n", MON);
    printf("TUE: %d\n", TUE);
    printf("WED: %d\n", WED);
    printf("THU: %d\n", THU);
    printf("FRI: %d\n", FRI);
    printf("SAT: %d\n", SAT);

    return 0;
}

Using the enum data type

/* 1802.c: Using the enum data type */
#include <stdio.h>
/* main() function */
main()
{
    enum units{penny = 1,nickel = 5,dime = 10,quarter = 25,dollar = 100};
    int money_units[5] = {dollar,quarter,dime,nickel,penny};
    char *unit_name[5] = {"dollar(s)","quarter(s)","dime(s)","nickel(s)","penny(s)"};
    int cent, tmp, i;

    printf("Enter a monetary value in cents:\n");
    scanf("%d", &cent); /* get input from the user */
    printf("Which is equivalent to:\n");
    tmp = 0;
    for (i=0; i<5; i++){
        tmp = cent / money_units[i];
        cent -= tmp * money_units[i];
        if (tmp)
        printf("%d %s ", tmp, unit_name[i]);
    }
    printf("\n");
    return 0;
}

Using typedef definitions

/* 1803.c: Using typedef definitions */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum constants{ITEM_NUM = 3,DELT='a'-'A'};
typedef char *STRING[ITEM_NUM];
typedef char *PTR_STR;
typedef char BIT8;
typedef int BIT16;

void Convert2Upper(PTR_STR str1, PTR_STR str2);

main()
{
    STRING str;
    STRING moon = {"Whatever we wear","we become beautiful","moon viewing!"};
    BIT16 i;
    BIT16 term = 0;

    for (i=0; i<ITEM_NUM; i++){
        str[i] = malloc((strlen(moon[i])+1) * sizeof(BIT8));
        if (str[i] == NULL){
            printf("malloc() failed.\n");
            term = 1;
            i = ITEM_NUM; /* break the for loop */
        }
        Convert2Upper(moon[i], str[i]);
        printf("%s\n", moon[i]);
    }
    for (i=0; i<ITEM_NUM; i++){
        printf("\n%s", str[i]);
        free (str[i]);
    }

return term;
}
/* function definition */
void Convert2Upper(PTR_STR str1, PTR_STR str2)
{
    BIT16 i;

    for (i=0; str1[i]; i++){
        if ((str1[i] >= 'a') && (str1[i] <= 'z'))
            str2[i] = str1[i] - DELT;
        else
            str2[i] = str1[i];
    }
    str2[i] = '\0'; /* add null character */
}

Using the free() function

/* 1702.c: Using the free() function */
#include <stdio.h>
#include <stdlib.h>
/* function declarations */
void DataMultiply(int max, int *ptr);
void TablePrint(int max, int *ptr);
/* main() function */
main()
{
    int *ptr_int, max;
    int termination;
    char key = 'c';

    max = 0;
    termination = 0;
    while (key != 'x'){
        printf("Enter a single digit number:\n");
        scanf("%d", &max);

        ptr_int = malloc(max * max * sizeof(int)); /* call malloc() */
        if (ptr_int != NULL){
            DataMultiply(max, ptr_int);
            TablePrint(max, ptr_int);
            free(ptr_int);
        }
        else{
            printf("malloc() function failed.\n");
            termination = 1;
            key = 'x'; /* stop while loop */
        }
        printf("\n\nPress x key to quit; other key to continue.\n");
        scanf("%s", &key);
    }
    printf("\nBye!\n");
    return termination;
}
/* function definition */
void DataMultiply(int max, int *ptr)
{
int i, j;

for (i=0; i<max; i++)
for (j=0; j<max; j++)
*(ptr + i * max + j) = (i+1) * (j+1);
}
/* function definition */
void TablePrint(int max, int *ptr)
{
    int i, j;

    printf("The multiplication table of %d is:\n",max);
    printf(" ");
    for (i=0; i<max; i++)
    printf("%4d", i+1);
    printf("\n ");
    for (i=0; i<max; i++)
    printf("----", i+1);
    for (i=0; i<max; i++){
        printf("\n%d|", i+1);
        for (j=0; j<max; j++)
        printf("%3d ", *(ptr + i * max + j));
    }
}

Using the calloc() function

/* 1703.c: Using the calloc() function */
#include <stdio.h>
#include <stdlib.h>
/* main() function */
main()
{
    float *ptr1, *ptr2;
    int i, n;
    int termination = 1;

    n = 5;
    ptr1 = calloc(n, sizeof(float));
    ptr2 = malloc(n * sizeof(float));
    if (ptr1 == NULL)
        printf("malloc() failed.\n");
    else if (ptr2 == NULL)
        printf("calloc() failed.\n");
    else {
        for (i=0; i<n; i++)
        printf("ptr1[%d]=%5.2f, ptr2[%d]=%5.2f\n",i, *(ptr1 + i), i, *(ptr2 + i));
        free(ptr1);
        free(ptr2);
        termination = 0;
    }
    return termination;
}

Using the realloc() function

/* 1704.c: Using the realloc() function */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* function declaration */
void StrCopy(char *str1, char *str2);
/* main() function */
main()
{
    char *str[4] = {"There's music in the sighing of a reed;",
    "There's music in the gushing of a rill;",
    "There's music in all things if men had ears;",
    "There earth is but an echo of the spheres.\n"
    };
    char *ptr;
    int i;

    int termination = 0;
    ptr = malloc((strlen(str[0]) + 1) * sizeof(char));
    if (ptr == NULL){
        printf("malloc() failed.\n");
        termination = 1;
    }
    else{
        StrCopy(str[0], ptr);
        printf("%s\n", ptr);
        for (i=1; i<4; i++){
            ptr = realloc(ptr, (strlen(str[i]) + 1) * sizeof(char));
            if (ptr == NULL){
                printf("realloc() failed.\n");
                termination = 1;
                i = 4; /* break the fro loop */
            }
            else{
                StrCopy(str[i], ptr);
                printf("%s\n", ptr);
            }
        }
    }
    free(ptr);
    return termination;
}
/* function definition */
void StrCopy(char *str1, char *str2)
{
    int i;

    for (i=0; str1[i]; i++)
    str2[i] = str1[i];
    str2[i] = '\0';
}

Using the malloc function

/* 1701.c: Using the malloc function */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* function declaration */
void StrCopy(char *str1, char *str2);
/* main() function */
main()
{
    char str[] = "Use malloc() to allocate memory.";
    char *ptr_str;
    int result;
    /* call malloc() */
    ptr_str = malloc( strlen(str) + 1);
    if (ptr_str != NULL){
        StrCopy(str, ptr_str);
        printf("The string pointed to by ptr_str is:\n%s\n",ptr_str);
        result = 0;
    }
    else{
        printf("malloc() function failed.\n");
        result = 1;
    }
    return result;
}
/* function definition */
void StrCopy(char *str1, char *str2)
{
    int i;

    for (i=0; str1[i]; i++)
    str2[i] = str1[i];
    str2[i] = '\0';
}

Passing multidimensional arrays to functions

/* 1606.c: Passing multidimensional arrays to functions */
#include <stdio.h>
/* function declarations */
int DataAdd1(int list[][5], int max1, int max2);
int DataAdd2(int *list, int max1, int max2);
/* main() function */
main()
{
    int list[2][5] = {1, 2, 3, 4, 5,5, 4, 3, 2, 1};
    int *ptr_int;

    printf("The sum returned by DataAdd1(): %d\n",
    DataAdd1(list, 2, 5));
    ptr_int = &list[0][0];
    printf("The sum returned by DataAdd2(): %d\n",
    DataAdd2(ptr_int, 2, 5));

    return 0;
}
/* function definition */
int DataAdd1(int list[][5], int max1, int max2)
{
    int i, j;
    int sum = 0;

    for (i=0; i<max1; i++)
    for (j=0; j<max2; j++)
    sum += list[i][j];
    return sum;
}
/* function definition */
int DataAdd2(int *list, int max1, int max2)
{
    int i, j;
    int sum = 0;

    for (i=0; i<max1; i++){
        for (j=0; j<max2; j++){
            sum += *(list + i*max2 + j);
            //printf("%d,%d,%d,%d,%d,%d\n",*list,i,max2,j,*list + i*max2 + j,sum);}
            //printf("------------------\n");
            }
    }
    return sum;
}

Using an array of pointers

/* 1607.c: Using an array of pointers */
#include <stdio.h>
/* function declarations */
void StrPrint1(char **str1, int size);
void StrPrint2(char *str2);
/* main() function */
main()
{
    char *str[4] = {"There's music in the sighing of a reed;",
    "There's music in the gushing of a rill;",
    "There's music in all things if men had ears;",
    "There earth is but an echo of the spheres.\n"
    };
    int i, size = 4;

    StrPrint1(str, size);
    for (i=0; i<size; i++)
    StrPrint2(str[i]);

    return 0;
}
/* function definition */
void StrPrint1(char **str1, int size)
{
    int i;
    /* Print all strings in an array of pointers to strings */
    for (i=0; i<size; i++)
        printf("%s\n", str1[i]);
}
/* function definition */
void StrPrint2(char *str2)
{
    /* Prints one string at a time */
    printf("%s\n", str2);
}

Pointing to a function

/* 1608.c: Pointing to a function */
#include <stdio.h>
/* function declaration */
int StrPrint(char *str);
/* main() function */
main()
{
    char str[24] = "Pointing to a function.";
    /* declaration of a pointer (ptr) to the StrPrint() function */
    int (*ptr)(char *str);
    /* StrPrint() function is assigned to the ptr pointer */
    ptr = StrPrint;
    /* calls the StrPrint() function via the dereferenced pointer ptr */
    if (!(*ptr)(str))
        printf("Done!\n");

    return 0;
}
/* function definition */
int StrPrint(char *str)
{
    printf("%s\n", str);
    return 0;
}

Passing arrays to functions

/* 1604.c: Passing arrays to functions */
#include <stdio.h>

int AddThree(int list[]);

main()
{
    int sum, list[3];

    printf("Enter three integers separated by spaces:\n");
    scanf("%d%d%d", &list[0], &list[1], &list[2]);
    sum = AddThree(list);
    printf("The sum of the three integers is: %d\n", sum);

    return 0;
}
int AddThree(int list[])
{
    int i;
    int result = 0;

    for (i=0; i<3; i++)
        result += list[i];
    return result;
}

Passing pointers to functions

/* 1605.c: Passing pointers to functions */
#include <stdio.h>

void ChPrint(char *ch);
int DataAdd(int *list, int max);
main()
{
    char str[] = "It's a string!";
    char *ptr_str;
    int list[5] = {1, 2, 3, 4, 5};
    int *ptr_int;

    /* assign address to pointer */
    ptr_str = str;
    ChPrint(ptr_str);
    ChPrint(str);

    /* assign address to pointer */
    ptr_int = list;
    printf("The sum returned by DataAdd(): %d\n",DataAdd(ptr_int, 5));
    printf("The sum returned by DataAdd(): %d\n",DataAdd(list, 5));
return 0;
}
/* function definition */
void ChPrint(char *ch)
{
    printf("%s\n", ch);
}
/* function definition */
int DataAdd(int *list, int max)
{
    int i;
    int sum = 0;

    for (i=0; i<max; i++)
    sum += list[i];
    return sum;
}

Accessing arrays via pointers

/* 1603.c: Accessing arrays via pointers */
#include <stdio.h>

main()
{
    char str[] = "It's a string!";
    char *ptr_str;
    int list[] = {1, 2, 3, 4, 5};
    int *ptr_int;

    /* access char array */
    ptr_str = str;
    printf("Before the change, str contains: %s\n", str);
    printf("Before the change, str[5] contains: %c\n", str[5]);
    *(ptr_str + 5) = 'A';
    printf("After the change, str[5] contains: %c\n", str[5]);
    printf("After the change, str contains: %s\n", str);
    /* access int array */
    ptr_int = list;
    printf("Before the change, list[2] contains: %d\n", list[2]);
    *(ptr_int + 2) = -3;
    printf("After the change, list[2] contains: %d\n", list[2]);

    return 0;
}

Pointer arithmetic

/* 1601.c: Pointer arithmetic */
#include <stdio.h>

main()
{
char *ptr_ch;
int *ptr_int;
double *ptr_db;
/* char pointer ptr_ch */
printf("Current position of ptr_ch: 0x%p\n", ptr_ch);
printf("The position after ptr_ch + 1: 0x%p\n", ptr_ch + 1);
printf("The position after ptr_ch + 2: 0x%p\n", ptr_ch + 2);
printf("The position after ptr_ch - 1: 0x%p\n", ptr_ch - 1);
printf("The position after ptr_ch - 2: 0x%p\n", ptr_ch - 2);
/* int pointer ptr_int */
printf("Current position of ptr_int: 0x%p\n", ptr_int);
printf("The position after ptr_int + 1: 0x%p\n", ptr_int + 1);
printf("The position after ptr_int + 2: 0x%p\n", ptr_int + 2);
printf("The position after ptr_int - 1: 0x%p\n", ptr_int - 1);
printf("The position after ptr_int - 2: 0x%p\n", ptr_int - 2);
/* double pointer ptr_ch */
printf("Current position of ptr_db: 0x%p\n", ptr_db);
printf("The position after ptr_db + 1: 0x%p\n", ptr_db + 1);
printf("The position after ptr_db + 2: 0x%p\n", ptr_db + 2);
printf("The position after ptr_db - 1: 0x%p\n", ptr_db - 1);
printf("The position after ptr_db - 2: 0x%p\n", ptr_db - 2);

return 0;
}
Copyright @ 2015 Tron!

Labels