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;
}

Processing variable arguments

Wednesday, October 15, 2014
/* 1503.c: Processing variable arguments */
#include <stdio.h>
#include <stdarg.h>

double AddDouble(int x, ...);

main ()
{
    double d1 = 1.5;
    double d2 = 2.5;
    double d3 = 3.5;
    double d4 = 4.5;

    printf("Given an argument: %2.1f\n", d1);
    printf("The result returned by AddDouble() is: %2.1f\n\n",
    AddDouble(1, d1));
    printf("Given arguments: %2.1f and %2.1f\n", d1, d2);
    printf("The result returned by AddDouble() is: %2.1f\n\n",
    AddDouble(2, d1, d2));
    printf("Given arguments: %2.1f, %2.1f and %2.1f\n", d1, d2, d3);
    printf("The result returned by AddDouble() is: %2.1f\n\n",
    AddDouble(3, d1, d2, d3));
    printf("Given arguments: %2.1f, %2.1f, %2.1f, and %2.1f\n", d1, d2, d3, d4);
    printf("The result returned by AddDouble() is: %2.1f\n",
    AddDouble(4, d1, d2, d3, d4));
    return 0;
    }
    /* definition of AddDouble() */
    double AddDouble(int x, ...)
    {
    va_list arglist;
    int i;
    double result = 0.0;

    printf("The number of arguments is: %d\n", x);
    va_start (arglist, x);
    for (i=0; i<x; i++)
    result += va_arg(arglist, double);
    va_end (arglist);
    return result;
}

Pointer subtraction

/* 1602.c: Pointer subtraction */
#include <stdio.h>

main()
{
    int *ptr_int1, *ptr_int2, i;

    printf("The position of ptr_int1: 0x%p\n", ptr_int1);
    ptr_int2 = ptr_int1 + 5;
    printf("The position of ptr_int2 = ptr_int1 + 5: 0x%p\n", ptr_int2);
    printf("The subtraction of ptr_int2 - ptr_int1: %d\n", ptr_int2 - ptr_int1);
    ptr_int2 = ptr_int1 - 5;
    printf("The position of ptr_int2 = ptr_int1 - 5: 0x%p\n", ptr_int2);
    printf("The subtraction of ptr_int2 - ptr_int1: %d\n", ptr_int2 - ptr_int1);

    return 0;
}

Functions with no arguments

/* 1502.c: Functions with no arguments */
#include <stdio.h>
#include <time.h>

void GetDateTime(void);

main()
{
    printf("Before the GetDateTime() function is called.\n");
    GetDateTime();
    printf("After the GetDateTime() function is called.\n");
    return 0;
}
/* GetDateTime() definition */
void GetDateTime(void)
{
    time_t now;

    printf("Within GetDateTime().\n");
    time(&now);
    printf("Current date and time is: %s\n", asctime(localtime(&now)));
}

Using the register specifier

/* 1404.c: Using the register specifier */
#include <stdio.h>

int main()
{
    /* block scope with the register specifier */
    register int i;
    int MAX_NUM=10;
    for (i=0; i<MAX_NUM; i++){
        printf("Value of i:%d\n",i);
    }
    return 0;
}

Using the volatile variable

/* 1405.c: Using the volatile variable */
#include <stdio.h>

int main()
{
    read_keyboard();
    return 0;
}

void read_keyboard()
{
volatile char keyboard_ch[100];
printf("Enter a string:\n");
scanf("%s", keyboard_ch);
printf("Keyboard read = %s\n",keyboard_ch);
}

Making function calls

/* 1501.c: Making function calls */
#include <stdio.h>

int function_1(int x, int y);
double function_2(double x, double y)
{
printf("Within function_2.\n");
return (x - y);
}

main()
{
    int x1 = 80;
    int y1 = 10;
    double x2 = 100.123456;
    double y2 = 10.123456;

    printf("Pass function_1 %d and %d.\n", x1, y1);
    printf("function_1 returns %d.\n", function_1(x1, y1));
    printf("Pass function_2 %f and %f.\n", x2, y2);
    printf("function_2 returns %f.\n", function_2(x2, y2));
    return 0;
}
/* function_1() definition */
int function_1(int x, int y)
{
    printf("Within function_1.\n");
    return (x + y);
}

Scopes in nested block

/* 1401.c: Scopes in nested block */
#include <stdio.h>

main()
{
    int i = 32; /* block scope 1*/

    printf("Within the outer block: i=%d\n", i);

    { /* the beginning of the inner block */
    int i, j; /* block scope 2, int i hides the outer int i*/

    printf("Within the inner block:\n");
    for (i=0, j=10; i<=10; i++, j--)
    printf("i=%2d, j=%2d\n", i, j);
    } /* the end of the inner block */
    printf("Within the outer block: i=%d\n", i);
    return 0;
}

program scope

/* 1402.c: Program scope vs block scope */
#include <stdio.h>

int x = 1234; /* program scope */
double y = 1.234567; /* program scope */

void function_1()
{
    printf("From function_1:\n x=%d, y=%f\n", x, y);
}

main()
{
    int x = 4321; /* block scope 1*/

    function_1();
    printf("Within the main block:\n x=%d, y=%f\n", x, y);
    /* a nested block */
    {
    double y = 7.654321; /* block scope 2 */
    function_1();
    printf("Within the nested block:\n x=%d, y=%f\n", x, y);
    }
    return 0;
}

Using the static specifier

/* 1403.c: Using the static specifier */
#include <stdio.h>
/* the add_two function */
int add_two(int x, int y)
{
    static int counter = 1;

    printf("This is the function call of %d,\n", counter++);
    return (x + y);
}
/* the main function */
main()
{
    int i, j;

    for (i=0, j=5; i<5; i++, j--)
    printf("the addition of %d and %d is %d.\n\n",i, j, add_two(i, j));
    return 0;
}

Using gets() and puts()

/* 1304.c: Using gets() and puts() */
#include <stdio.h>

main()
{
    char str[80];
    int i, delt = 'a' - 'A';

    printf("Enter a string less than 80 characters:\n");
    gets( str );
    i = 0;
    while (str[i]){
    if ((str[i] >= 'a') && (str[i] <= 'z'))
    str[i] -= delt; /* convert to upper case */
    ++i;
    }
    printf("The entered string is (in uppercase):\n");
    puts( str );
    return 0;
}

Using scanf()

/* 1305.c: Using scanf() */
#include <stdio.h>

main()
{
    char str[80];
    int x, y;
    float z;

    printf("Enter two integers separated by a space:\n");
    scanf("%d %d", &x, &y);
    printf("Enter a floating-point number:\n");
    scanf("%f", &z);
    printf("Enter a string:\n");
    scanf("%s", str);
    printf("Here are what you've entered:\n");
    printf("%d %d\n%f\n%s\n", x, y, z, str);
    return 0;
}

Initializing strings

/* 1301.c: Initializing strings */
#include <stdio.h>

main()
{
    char str1[] = {'A', ' ',
    's', 't', 'r', 'i', 'n', 'g', ' ',
    'c', 'o', 'n', 's', 't', 'a', 'n', 't', '\0'};
    char str2[] = "Another string constant";
    char *ptr_str;
    int i;

    /* print out str2 */
    for (i=0; str1[i]; i++)
    printf("%c", str1[i]);
    printf("\n");
    /* print out str2 */
    for (i=0; str2[i]; i++)
    printf("%c", str2[i]);
    printf("\n");
    /* assign a string to a pointer */
    ptr_str = "Assign a string to a pointer.";
    for (i=0; *ptr_str; i++)
    printf("%c", *ptr_str++);
    return 0;
}

Measuring string length

/* 1302.c: Measuring string length */
#include <stdio.h>
#include <string.h>

main()
{
    char str1[] = {'A', ' ',
    's', 't', 'r', 'i', 'n', 'g', ' ',
    'c', 'o', 'n', 's', 't', 'a', 'n', 't', '\0'};
    char str2[] = "Another string constant";
    char *ptr_str = "Assign a string to a pointer.";

    printf("The length of str1 is: %d bytes\n", strlen(str1));
    printf("The length of str2 is: %d bytes\n", strlen(str2));
    printf("The length of the string assigned to ptr_str is: %d bytes\n",
    strlen(ptr_str));
    return 0;
}

Copying strings

/* 1303.c: Copying strings */
#include <stdio.h>
#include <string.h>

main()
{
    char str1[] = "Copy a string.";
    char str2[15];
    char str3[15];
    int i;

    /* with strcpy() */
    strcpy(str2, str1);
    /* without strcpy() */
    for (i=0; str1[i]; i++)
    str3[i] = str1[i];
    str3[i] = '\0';
    /* display str2 and str3 */
    printf("The content of str2: %s\n", str2);
    printf("The content of str3: %s\n", str3);
    return 0;
}

Stopping at the null character

/* 1205.c: Stopping at the null character */
#include <stdio.h>

main()
{
    char array_ch[15] = {'C', ' ' ,
    'i', 's', ' ',
    'p', 'o', 'w', 'e', 'r',
    'f', 'u', 'l', '!', '\0'};
    int i;
    /* array_ch[i] in logical test */
    for (i=0; array_ch[i] != '\0'; i++)
    printf("%c", array_ch[i]);
    return 0;
}

Printing out a 2-D array

/* 1206.c: Printing out a 2-D array */
#include <stdio.h>

main()
{
    int two_dim[3][5] = {1, 2, 3, 4, 5,
    10, 20, 30, 40, 50,
    100, 200, 300, 400, 500};
    int i, j;

    for (i=0; i<3; i++){
        printf("\n");
        for (j=0; j<5; j++)
        printf("%6d", two_dim[i][j]);
    }
    return 0;
}

Initializing unsized arrays

/* 1207.c: Initializing unsized arrays */
#include <stdio.h>

main()
{
    char array_ch[] = {'C', ' ' ,
    'i', 's', ' ' ,
    'p', 'o', 'w', 'e', 'r',
    'f', 'u', 'l', '!', '\0'};
    int list_int[][3] = {
    1, 1, 1,
    2, 2, 8,
    3, 9, 27,
    4, 16, 64,
    5, 25, 125,
    6, 36, 216,
    7, 49, 343};

    printf("The size of array_ch[] is %d bytes.\n", sizeof (array_ch));
    printf("The size of list_int[][3] is %d bytes.\n", sizeof (list_int));
    return 0;
}

Total bytes of an array

/* 1202.c: Total bytes of an array */
#include <stdio.h>

main()
{
    int total_byte;
    int list_int[10];

    total_byte = sizeof (int) * 10;
    printf( "The size of int is %d-byte long.\n", sizeof (int));
    printf( "The array of 10 ints has total %d bytes.\n", total_byte);
    printf( "The address of the first element: 0x%x\n", &list_int[0]);
    /* also first element address can be obtained by */
    printf( "The address of the first element: 0x%x\n", &list_int);
    printf( "The address of the last element: 0x%x\n", &list_int[9]);
    return 0;
}

Referencing an array with a pointer

/* 1203.c: Referencing an array with a pointer */
#include <stdio.h>

main()
{
    int *ptr_int;
    int list_int[10];
    int i;

    for (i=0; i<10; i++)
    list_int[i] = i + 1;
    ptr_int = list_int;
    printf( "The start address of the array: 0x%p\n", ptr_int);
    printf( "The value of the first element: %d\n", *ptr_int);
    ptr_int = &list_int[0];
    printf( "The address of the first element: 0x%p\n", ptr_int);
    printf( "The value of the first element: %d\n", *ptr_int);
    ptr_int = ptr_int + 1;
    printf( "The second address of the array: 0x%p\n", ptr_int);
    printf( "The value of the second element: %d\n", *ptr_int);

    return 0;
}

Printing out an array of characters

/* 1204.c: Printing out an array of characters */
#include <stdio.h>

main()
{
    char array_ch[7] = {'H', 'e', 'l', 'l', 'o', '!', '\0'};
    int i;

    for (i=0; i<7; i++)
    printf("array_ch[%d] contains: %c\n", i, array_ch[i]);
    /*--- method I ---*/
    printf( "Put all elements together(Method I):\n");
    for (i=0; i<7; i++)
    printf("%c", array_ch[i]);
    /*--- method II ---*/
    printf( "\nPut all elements together(Method II):\n");
    printf( "%s\n", array_ch);

    return 0;
}

Changing values via pointers

/* 1103.c: Changing values via pointers */
#include <stdio.h>

main()
{
    char c, *ptr_c;

    c = 'A';
    printf("c: address=0x%p, content=%c\n", &c, c);
    ptr_c = &c;
    printf("ptr_c: address=0x%p, content=0x%p\n", &ptr_c, ptr_c);
    printf("*ptr_c => %c\n", *ptr_c);
    *ptr_c = 'B';
    printf("ptr_c: address=0x%p, content=0x%p\n", &ptr_c, ptr_c);
    printf("*ptr_c => %c\n", *ptr_c);
    printf("c: address=0x%p, content=%c\n", &c, c);
    return 0;
}

Pointing to the same thing

/* 1104.c: Pointing to the same thing */
#include <stdio.h>

main()
{
    int x;
    int *ptr_1, *ptr_2, *ptr_3;

    x = 1234;
    printf("x: address=0x%p, content=%d\n", &x, x);
    ptr_1 = &x;
    printf("ptr_1: address=0x%p, content=0x%p\n", &ptr_1, ptr_1);
    printf("*ptr_1 => %d\n", *ptr_1);
    ptr_2 = &x;
    printf("ptr_2: address=0x%p, content=0x%p\n", &ptr_2, ptr_2);
    printf("*ptr_2 => %d\n", *ptr_2);
    ptr_3 = ptr_1;
    printf("ptr_3: address=0x%p, content=0x%p\n", &ptr_3, ptr_3);
    printf("*ptr_3 => %d\n", *ptr_3);
    return 0;
}

Initializing an array

/* 1201.c: Initializing an array */
#include <stdio.h>

main()
{
    int i;
    int list_int[10];

    for (i=0; i<10; i++){
    list_int[i] = i + 1;
    printf( "list_int[%d] is initialized with %d.\n", i, list_int[i]);
    }
    return 0;
}

Obtaining addresses

/* 1101.c: Obtaining addresses */
#include <stdio.h>

main()
{
    char c;
    int x;
    float y;

    printf("c: address=0x%p, content=%c\n", &c, c);
    printf("x: address=0x%p, content=%d\n", &x, x);
    printf("y: address=0x%p, content=%5.2f\n", &y, y);
    c = 'A';
    x = 7;
    y = 123.45;
    printf("c: address=0x%p, content=%c\n", &c, c);
    printf("x: address=0x%p, content=%d\n", &x, x);
    printf("y: address=0x%p, content=%5.2f\n", &y, y);
    return 0;
}

Declaring and assigning values to pointers

/* 1102.c: Declaring and assigning values to pointers */
#include <stdio.h>

main()
{
    char c, *ptr_c;
    int x, *ptr_x;
    float y, *ptr_y;

    c = 'A';
    x = 7;
    y = 123.45;
    printf("c: address=0x%p, content=%c\n", &c, c);
    printf("x: address=0x%p, content=%d\n", &x, x);
    printf("y: address=0x%p, content=%5.2f\n", &y, y);
    ptr_c = &c;
    printf("ptr_c: address=0x%p, content=0x%p\n", &ptr_c, ptr_c);
    printf("*ptr_c => %c\n", *ptr_c);
    ptr_x = &x;
    printf("ptr_x: address=0x%p, content=0x%p\n", &ptr_x, ptr_x);
    printf("*ptr_x => %d\n", *ptr_x);
    ptr_y = &y;
    printf("ptr_y: address=0x%p, content=0x%p\n", &ptr_y, ptr_y);
    printf("*ptr_y => %5.2f\n", *ptr_y);
    return 0;
}

Using the continue statement

Tuesday, October 14, 2014
/* 1007.c: Using the continue statement */
#include <stdio.h>

main()
{
    int i, sum;

    sum = 0;
    for (i=1; i<8; i++){
        if ((i==3) || (i==5))
        continue;
        sum += i;
        }
    printf("The sum of 1, 2, 4, 6, and 7 is: %d\n", sum);
    return 0;
}

Using the switch statement

/* 1004.c Using the switch statement */
#include <stdio.h>

main()
{
    int day;

    printf("Please enter a single digit for a day\n");
    printf("(within the range of 1 to 3):\n");
    day = getchar();
    switch (day){
        case '1':
        printf("Day 1\n");
        case '2':
        printf("Day 2\n");
        case '3':
        printf("Day 3\n");
        default: ;
        }
    return 0;
}

Adding the break statement

/* 1005.c Adding the break statement */
#include <stdio.h>

main()
{
    int day;

    printf("Please enter a single digit for a day\n");
    printf("(within the range of 1 to 7):\n");
    day = getchar();
    switch (day){
    case '1':
        printf("Day 1 is Sunday.\n");
        break;
    case '2':
        printf("Day 2 is Monday.\n");
        break;
    case '3':
        printf("Day 3 is Tuesday.\n");
        break;
    case '4':
        printf("Day 4 is Wednesday.\n");
        break;
    case '5':
        printf("Day 5 is Thursday.\n");
        break;
    case '6':
        printf("Day 6 is Friday.\n");
        break;
    case '7':
        printf("Day 7 is Saturday.\n");
        break;
    default:
        printf("The digit is not within the range of 1 to 7.\n");
        break;
    }
    return 0;
}

Breaking an infinite loop

/* 1006.c: Breaking an infinite loop */
#include <stdio.h>

main()
{
    int c;

    printf("Enter a character:\n(enter x to exit)\n");
    while (1) {
        c = getc(stdin);
        if (c == 'x')
        break;
        }
    printf("Break the infinite while loop. Bye!\n");
    return 0;
}

Using the if statement

/* 1001.c Using the if statement */
#include <stdio.h>

main()
{
    int i;

    printf("Integers that can be divided by both 2 and 3\n");
    printf("(within the range of 0 to 100):\n");
    for (i=0; i<=100; i++){
        if ((i%2 == 0) && (i%3 == 0))
        printf(" %d\n", i);
    }
    return 0;
}

Using the if-else statement

/* 1002.c Using the if-else statement */
#include <stdio.h>

main()
{
    int i;

    printf("Even Number Odd Number\n");
    for (i=0; i<10; i++)
        if (i%2 == 0)
            printf("%d", i);
        else
            printf("%14d\n", i);

    return 0;
}

Using nested if statements

/* 1003.c Using nested if statements */
#include <stdio.h>

main()
{
    int i;

    for (i=-5; i<=5; i++){
        if (i > 0)
            if (i%2 == 0)
                printf("%d is an even number.\n", i);
            else
                printf("%d is an odd number.\n", i);
        else if (i == 0)
            printf("The number is zero.\n");
        else
            printf("Negative number: %d\n", i);
        }
    return 0;
}

Using %hd, %ld, and %lu specifiers

/* 0903.c: Using %hd, %ld, and %lu specifiers */
#include <stdio.h>

main()
{
    short int x;
    unsigned int y;
    long int s;
    unsigned long int t;

    x = 0xFFFF;
    y = 0xFFFFU;
    s = 0xFFFFFFFFl;
    t = 0xFFFFFFFFL;
    printf("The short int of 0xFFFF is %hd.\n", x);
    printf("The unsigned int of 0xFFFF is %u.\n", y);
    printf("The long int of 0xFFFFFFFF is %ld.\n", s);
    printf("The unsigned long int of 0xFFFFFFFF is %lu.\n", t);
    return 0;
}

Using sin(), cos(), and tan() functions

/* 0904.c: Using sin(), cos(), and tan() functions */
#include <stdio.h>
#include <math.h>

main()
{
    double x;

    x = 45.0; /* 45 degree */
    x *= 3.141593 / 180.0; /* convert to radians */
    printf("The sine of 45 is: %f.\n", sin(x));
    printf("The cosine of 45 is: %f.\n", cos(x));
    printf("The tangent of 45 is: %f.\n", tan(x));
    return 0;
}

Using pow() and sqrt() functions

/* 0905.c: Using pow() and sqrt() functions */
#include <stdio.h>
#include <math.h>

main()
{
    double x, y, z;

    x = 64.0;
    y = 3.0;
    z = 0.5;
    printf("pow(64.0, 3.0) returns: %7.0f\n", pow(x, y));
    printf("sqrt(64.0) returns: %2.0f\n", sqrt(x));
    printf("pow(64.0, 0.5) returns: %2.0f\n", pow(x, z));
    return 0;
}

Using the ?: operator

/* 0807.c: Using the ?: operator */
#include <stdio.h>

main()
{
    int x;

    x = sizeof(int);
    printf("%s\n",
        (x == 2) ? "The int data type has 2 bytes." : "int doesn't have 2 bytes.");
    printf("The maximum value of int is: %d\n",
        (x != 2) ? ~(1 << x * 8 - 1) : ~(1 << 15) );
    return 0;
}

Using signed and unsigned modifiers

/* 0901.c: Using signed and unsigned modifiers */
#include <stdio.h>

main()
{
    signed char ch;
    int x;
    unsigned int y;

    ch = 0xFF;
    x = 0xFFFF;
    y = 0xFFFFu;
    printf("The decimal of signed 0xFF is %d.\n", ch);
    printf("The decimal of signed 0xFFFF is %d.\n", x);
    printf("The decimal of unsigned 0xFFFFu is %u.\n", y);
    printf("The hex of decimal 12345 is 0x%X.\n", 12345);
    printf("The hex of decimal -12345 is 0x%X.\n", -12345);
    return 0;
}

Using short and long modifiers

/* 0902.c: Using short and long modifiers */
#include <stdio.h>

main()
{
    printf("The size of short int is: %d.\n",
    sizeof(short int));
    printf("The size of long int is: %d.\n",
    sizeof(long int));
    printf("The size of float is: %d.\n",
    sizeof(float));
    printf("The size of double is: %d.\n",
    sizeof(double));
    printf("The size of long double is: %d.\n",
    sizeof(long double));
    return 0;
}

Using shift operators

/* 0806.c: Using shift operators */
/*
The operation of the shift-right operator (>>) is equivalent to dividing by powers of 2. In other words,
the following:
x >> y
x / 2y
Here x is a non-negative integer.
On the other hand, shifting to the left is equivalent to multiplying by powers of 2; that is,
x << y
x * 2y
*/

#include <stdio.h>

main()
{
    int x, y, z;

    x = 255;
    y = 5;
    printf("Given x = %4d, i.e., 0X%04X\n", x, x);
    printf(" y = %4d, i.e., 0X%04X\n", y, y);
    z = x >> y;
    printf("x >> y returns: %6d, i.e., 0X%04X\n", z, z);
    z = x << y;
    printf("x << y returns: %6d, i.e., 0X%04X\n", z, z);
    return 0;
}

Using the logical OR operator

/* 0803.c: Using the logical OR operator */
#include <stdio.h>

main()
{
    int num;

    printf("Enter a single digit that can be divided\nby both 2 and 3:\n");
    for (num = 1; (num%2 != 0) || (num%3 != 0); )
        num = getchar() - 48;
        printf("You got such a number: %d\n", num);
    return 0;
}

Using the logical negation operator

/* 0804.c: Using the logical negation operator */
#include <stdio.h>

main()
{
    int num;

    num = 7;
    printf("Given num = 7\n");
    printf("!(num < 7) returns: %d\n", !(num < 7));
    printf("!(num > 7) returns: %d\n", !(num > 7));
    printf("!(num == 7) returns: %d\n", !(num == 7));
    return 0;
}

Using bitwise operators

/* 0805.c: Using bitwise operators */
#include <stdio.h>

main()
{
    int x, y, z;

    x = 4321;
    y = 5678;
    printf("Given x = %u, i.e., 0X%04X\n", x, x);
    printf(" y = %u, i.e., 0X%04X\n", y, y);
    z = x & y;
    printf("x & y returns: %6u, i.e., 0X%04X\n", z, z);
    z = x | y;
    printf("x | y returns: %6u, i.e., 0X%04X\n", z, z);
    z = x ^ y;
    printf("x ^ y returns: %6u, i.e., 0X%04X\n", z, z);
    printf(" ~x returns: %6u, i.e., 0X%04X\n", ~x, ~x);
    return 0;
}

Using the sizeof operator

/* 0801.c: Using the sizeof operator */
#include <stdio.h>

main()
{
    char ch = ' ';
    int int_num = 0;
    float flt_num = 0.0f;
    double dbl_num = 0.0;

    printf("The size of char is: %d-byte\n", sizeof(char));
    printf("The size of ch is: %d-byte\n", sizeof ch );
    printf("The size of int is: %d-byte\n", sizeof(int));
    printf("The size of int_num is: %d-byte\n", sizeof int_num);
    printf("The size of float is: %d-byte\n", sizeof(float));
    printf("The size of flt_num is: %d-byte\n", sizeof flt_num);
    printf("The size of double is: %d-byte\n", sizeof(double));
    printf("The size of dbl_num is: %d-byte\n", sizeof dbl_num);
    return 0;
}

Using the logical AND operator

/* 0802.c: Using the logical AND operator */
#include <stdio.h>

main()
{
    int num;

    num = 0;
    printf("The AND operator returns: %d\n",
    (num%2 == 0) && (num%3 == 0));
    num = 2;
    printf("The AND operator returns: %d\n",
    (num%2 == 0) && (num%3 == 0));
    num = 3;
    printf("The AND operator returns: %d\n",
    (num%2 == 0) && (num%3 == 0));
    num = 6;
    printf("The AND operator returns: %d\n",
    (num%2 == 0) && (num%3 == 0));

return 0;
}
Copyright @ 2015 Tron!

Labels

Blog Archive