C PROGRAMMING

AN INTRODUCTION TO C PROGRAMMING

It is one of the most used programming languages in software development. Initially, C was designed and developed for the UNIX operating system. Today, C is widely used to develop many types of application software such as basic calculators, word processors, games, operating systems, etc.

Editing in C language

  • Editing is the process of writing the C source code. Programmers write C source code using editor programs. Widely used editing programs are Linux, Platform VI, and Emacs.
  • On Windows platform, Notepad can be used as an editor program, but most use software packages for C such as C++ Builder, DOS C++. These software provide a complete programming environment for writing, managing, compiling, debugging, and testing C source code. This is known as Integrated Development Environment (IDE).

Compiling in C language

The C source code has to be translated into machine language code. Machine language is a language in the form of binary numbers that a computer understands. The process of code translation is called compiling. During compilation, the compiler can detect any syntax errors.

Execution

The execution stage is where you run the program to check whether it produces the desired output. This stage can be a testing stage where you verify if you get the desired output.

C program layout

Basically, a C program consists of two sections:

  1. Pre-processor directives
  2. Main function
Simple C program example

A simple C program

The following program is written in the C programming language which can display the word “Programming in C is easy”.

#include int main(){    printf("Programming in C is easy.n");    return 0;}

Sample Program Output

Programming in C is easy.

A NOTE ABOUT C PROGRAMS

In C, lowercase and uppercase characters are very important! All commands in C must be lowercase. The C program’s starting point is identified by the word main(). This informs the computer where the program actually starts. The brackets that follow the keyword main indicate that there are no arguments supplied to this program. The two braces, { and }, signify the beginning and end segments of the program. The purpose of the statement #include is to allow the use of the printf statement to provide program output. Text to be displayed by printf() must be enclosed in double quotes. The program has only one statement:

printf("Programming in C is easy.n");

printf() is actually a function (procedure) in C that is used for printing variables and text. Text in double quotes is printed without modification. There are some exceptions involving the backslash and percent % characters. For example, n represents a newline character. Thus the program prints:

Programming in C is easy.

and the cursor is set to the beginning of the next line. All C statements are terminated by a semicolon ;.


Summary of major points so far

  • Program execution begins at main().
  • Keywords are written in lowercase.
  • Statements are terminated with a semicolon.
  • Text strings are enclosed in double quotes.
  • C is case sensitive; use lowercase and avoid capitalizing variable names.
  • n means position the cursor at the beginning of the next line.
  • printf() can be used to display text to the screen.
  • Curly braces { } define the beginning and end of a program block.

DATA TYPES AND CONSTANTS

The four basic data types are:

INTEGER

These are whole numbers, both positive and negative. Unsigned integers (positive values only) are supported. In addition, there are short and long integers.

ecolebooks.com

The keyword used to define integers is:

int

An example of an integer value is 32. An example of declaring an integer variable called sum is:

int sum;sum = 20;

FLOATING POINT

These are numbers which contain fractional parts, both positive and negative. The keyword used to define float variables is:

float

An example of a float value is 34.12. An example of declaring a float variable called money is:

float money;money = 0.12;

DOUBLE

These are exponential numbers, both positive and negative. The keyword used to define double variables is:

double

An example of a double value is 3.0E2. An example of declaring a double variable called big is:

double big;big = 312E+7;

CHARACTER

These are single characters. The keyword used to define character variables is:

char

An example of a character value is the letter A. An example of declaring a character variable called letter is:

char letter;letter = 'A';

Note the assignment of the character A to the variable letter is done by enclosing the value in single quotes. Remember the golden rule: Single character – Use single quotes.

Sample program illustrating each data type

#include int main(){    int sum;    float money;    char letter;    double pi;    sum = 10;       /* assign integer value */    money = 2.21;   /* assign float value */    letter = 'A';   /* assign character value */    pi = 2.01E6;    /* assign a double value */    printf("value of sum = %dn", sum );    printf("value of money = %fn", money );    printf("value of letter = %cn", letter );    printf("value of pi = %en", pi );    return 0;}

Sample program output

value of sum = 10
value of money = 2.210000
value of letter = A
value of pi = 2.010000e+06

PREPROCESSOR STATEMENTS

The #define statement is used to make programs more readable. Consider the following examples:

#define TRUE 1   /* Don't use a semicolon, # must be first character on line */#define FALSE 0#define NULL 0#define AND define OR |#define EQUALS ==

Example usage:

game_over = TRUE;while( list_pointer != NULL ){    ...}

Note that preprocessor statements begin with a # symbol and are NOT terminated by a semicolon. Traditionally, preprocessor statements are listed at the beginning of the source file.

Preprocessor statements are handled by the compiler (or preprocessor) before the program is actually compiled. All # statements are processed first, and the symbols (like TRUE) which occur in the C program are replaced by their value (like 1). Once this substitution has taken place by the preprocessor, the program is then compiled.

In general, preprocessor constants are written in UPPERCASE.

Class Exercise C4

Use preprocessor statements to replace the following constants:

  • 0.312
  • W
  • 37

Answer:

#define SMALLVALUE 0.312#define LETTER 'W'#define SMALLINT 37

LITERAL SUBSTITUTION OF SYMBOLIC CONSTANTS USING #define

Let’s examine a few examples of using these symbolic constants in our programs. Consider the following program which defines a constant called TAX_RATE.

#include #define TAX_RATE 0.10int main(){    float balance;    float tax;    balance = 72.10;    tax = balance * TAX_RATE;    printf("The tax on %.2f is %.2fn", balance, tax);    return 0;}

The preprocessor first replaces all symbolic constants before the program is compiled, so after preprocessing the file (and before it’s compiled), it now looks like:

#include #define TAX_RATE 0.10int main(){    float balance;    float tax;    balance = 72.10;    tax = balance * 0.10;    printf("The tax on %.2f is %.2fn", balance, tax);    return 0;}

YOU CANNOT ASSIGN VALUES TO THE SYMBOLIC CONSTANTS

Considering the above program as an example, look at the changes below where a statement tries to change the TAX_RATE to a new value.

#include #define TAX_RATE 0.10int main(){    float balance;    float tax;    balance = 72.10;    TAX_RATE = 0.15;  /* Illegal: cannot re-assign a symbolic constant */    tax = balance * TAX_RATE;    printf("The tax on %.2f is %.2fn", balance, tax);    return 0;}

This is illegal. You cannot re-assign a new value to a symbolic constant.

ITS LITERAL SUBSTITUTION, SO BEWARE OF ERRORS

As shown above, the preprocessor performs literal substitution of symbolic constants. Let’s modify the previous program slightly and introduce an error to highlight a problem.

#include #define TAX_RATE 0.10;  /* Incorrect: semicolon at the end */int main(){    float balance;    float tax;    balance = 72.10;    tax = (balance * TAX_RATE) + 10.02;    printf("The tax on %.2f is %.2fn", balance, tax);    return 0;}

In this case, the error is that the #define is terminated with a semicolon. The preprocessor performs the substitution and the offending line (flagged as an error by the compiler) looks like:

tax = (balance * 0.10; ) + 10.02;

However, you do not see the output of the preprocessor. If you are using TURBO C, you will only see:

tax = (balance * TAX_RATE) + 10.02;

flagged as an error, and this actually looks okay (but it’s not after substitution).

MAKING PROGRAMS EASY TO MAINTAIN BY USING #define

The whole point of using #define in your programs is to make them easier to read and modify. Considering the above programs as examples, what changes would you need to make if the TAX_RATE was changed to 20%?

Obviously, the answer is once, where the #define statement which declares the symbolic constant and its value occurs. You would change it to read:

#define TAX_RATE 0.20

Without the use of symbolic constants, you would hard code the value 0.20 in your program, and this might occur several times (or tens of times). This would make changes difficult because you would need to search and replace every occurrence in the program. However, as the programs get larger, what would happen if you actually used the value 0.20 in a calculation that had nothing to do with the TAX_RATE!

SUMMARY OF #define

  • Allow the use of symbolic constants in programs.
  • In general, symbols are written in uppercase.
  • Are not terminated with a semicolon.
  • Generally occur at the beginning of the file.
  • Each occurrence of the symbol is replaced by its value.
  • Makes programs readable and easy to maintain.

HEADER FILES

Header files contain definitions of functions and variables which can be incorporated into any C program by using the preprocessor #include statement. Standard header files are provided with each compiler and cover a range of areas: string handling, mathematical, data conversion, printing, and reading of variables.

To use any of the standard functions, the appropriate header file should be included at the beginning of the C source file. For example, to use the function printf() in a program, the line:

#include 

should be at the beginning of the source file because the definition for printf() is found in the file stdio.h. All header files have the extension .h and generally reside in the /include subdirectory.

The use of angle brackets <> informs the compiler to search the compiler’s include directory for the specified file. The use of double quotes "" around the filename informs the compiler to search in the current directory for the specified file.

Practice Exercise 1: Defining Variables

  1. Declare an integer called sum.
  2. Declare a character called letter.
  3. Define a constant called TRUE which has a value of 1.
  4. Declare a variable called money which can be used to hold currency.
  5. Declare a variable called arctan which will hold scientific notation values (+e).
  6. Declare an integer variable called total and initialize it to zero.
  7. Declare a variable called loop, which can hold an integer value.
  8. Define a constant called GST with a value of 0.125.

Answers to Practice Exercise 1: Defining Variables

int sum;char letter;#define TRUE 1float money;double arctan;int total;total = 0;int loop;#define GST 0.125

ARITHMETIC OPERATORS

The symbols of the arithmetic operators are:

OperationOperatorCommentValue of sum beforeValue of sum after
Multiply*sum = sum * 2;48
Divide/sum = sum / 2;42
Addition+sum = sum + 2;46
Subtractionsum = sum – 2;42
Increment++++sum;45
Decrement–sum;43
Modulus%sum = sum % 3;41

The following code fragment adds the variables loop and count together, leaving the result in the variable sum:

sum = loop + count;

Note: If the modulus % sign is needed to be displayed as part of a text string, use two, i.e., %%.

#include int main(){    int sum = 50;    float modulus;    modulus = sum % 10;    printf("The %% of %d by 10 is %fn", sum, modulus);    return 0;}

Sample Program Output

The % of 50 by 10 is 0.000000

CLASS EXERCISE C5

What does the following change do to the printed output of the previous program?

printf("The %% of %d by 10 is %.2fn", sum, modulus);

ANSWERS: CLASS EXERCISE C5

#include int main(){    int sum = 50;    float modulus;    modulus = sum % 10;    printf("The %% of %d by 10 is %.2fn", sum, modulus);    return 0;}

The % of 50 by 10 is 0.00

Practice Exercise 2: Assignments

  1. Assign the value of the variable number1 to the variable total.
  2. Assign the sum of the two variables loop_count and petrol_cost to the variable sum.
  3. Divide the variable total by the value 10 and leave the result in the variable discount.
  4. Assign the character W to the char variable letter.
  5. Assign the result of dividing the integer variable sum by 3 into the float variable costing. Use type casting to ensure that the remainder is also held by the float variable.

Answers: Practice Exercise 2: Assignments

total = number1;sum = loop_count + petrol_cost;discount = total / 10;letter = 'W';costing = (float) sum / 3;

PRE/POST INCREMENT/DECREMENT OPERATORS

PRE means do the operation first followed by any assignment operation; POST means do the operation after any assignment operation. Consider the following statements:

++count; /* PRE Increment, means add one to count */count++; /* POST Increment, means add one to count */

Because the value of count is not assigned to any variable, the effects of the PRE/POST operation are not clearly visible.

Let’s examine what happens when we use the operator along with an assignment operation. Consider the following program:

#include int main(){    int count = 0, loop;    loop = ++count; /* same as count = count + 1; loop = count; */    printf("loop = %d, count = %dn", loop, count);    loop = count++; /* same as loop = count; count = count + 1; */    printf("loop = %d, count = %dn", loop, count);    return 0;}

Sample Program Output

loop = 1, count = 1
loop = 1, count = 2

If the operator precedes (is on the left hand side) of the variable, the operation is performed first, so the statement:

loop = ++count;

really means increment count first, then assign the new value of count to loop.

Which way do you write it?

Where the increment/decrement operation is used to adjust the value of a variable, and is not involved in an assignment operation, which should you use?

++loop_count;orloop_count++;

The answer is, it really does not matter. It seems there is a preference among C programmers to use the post form.

Something to watch out for

Do not get into the habit of using spaces between the variable name and the pre/post operator.

Good form:

loop_count++;

Try to be explicit in binding the operator tightly by leaving no gap.

Good form example

#include int main(){    int sum, loop, kettle = 0, job;    char whoknows;    sum = 9;    loop = 7;    whoknows = 'A';    printf("Whoknows = %c, kettle = %dn", whoknows, kettle);    return 0;}

We have corrected mistakes and improved readability by aligning braces, inserting spaces, and initializing variables.

KEYBOARD INPUT

There is a function in C which allows the programmer to accept input from a keyboard. The following program illustrates the use of this function:

#include int main() /* program which introduces keyboard input */{    int number;    printf("Type in a numbern");    scanf("%d", &number);    printf("The number you typed was %dn", number);    return 0;}

Sample Program Output

Type in a number
23
The number you typed was 23

An integer called number is defined. A prompt to enter a number is printed using printf("Type in a numbern");. The scanf routine accepts the response with two arguments. The first (“%d”) specifies the expected data type. The second argument (&number) specifies the variable into which the typed response will be placed. The ampersand & means the address of the variable.

Sample program illustrating use of scanf() to read integers, characters, and floats

#include int main(){    int sum;    char letter;    float money;    printf("Please enter an integer value ");    scanf("%d", &sum );    printf("Please enter a character ");    /* the leading space before %c ignores space characters in the input */    scanf(" %c", &letter );    printf("Please enter a float variable ");    scanf("%f", &money );    printf("nThe variables you entered weren");    printf("value of sum = %dn", sum );    printf("value of letter = %cn", letter );    printf("value of money = %fn", money );    return 0;}

Sample Program Output

Please enter an integer value
34
Please enter a character
W
Please enter a float variable
32.3
The variables you entered were
value of sum = 34
value of letter = W
value of money = 32.300000

THE RELATIONAL OPERATORS

These allow the comparison of two or more variables.

OperatorMeaning
==equal to
!=not equal
<less than
<=less than or equal to
>greater than
>=greater than or equal to

These operators will be used in for loops and if statements.

ITERATION, FOR LOOPS

The basic format of the for statement is:

for (start condition; continue condition; re-evaluation)    program statement;

Sample program using a for statement:

#include int main() /* Program introduces the for statement, counts to ten */{    int count;    for (count = 1; count <= 10; count = count + 1)        printf("%d ", count);    printf("n");    return 0;}

Sample Program Output

1 2 3 4 5 6 7 8 9 10

An example of using a for loop to print out characters

#include int main(){    char letter;    for (letter = 'A'; letter <= 'E'; letter = letter + 1) {        printf("%c ", letter);    }    printf("n");    return 0;}

Sample Program Output

A B C D E

An example of using a for loop to count numbers, using two initializations

#include int main(){    int total, loop;    for (total = 0, loop = 1; loop <= 10; loop = loop + 1) {        total = total + loop;    }    printf("Total = %dn", total);    return 0;}

Sample Program Output

Total = 55

THE WHILE STATEMENT

The while provides a mechanism for repeating C statements whilst a condition is true. Its format is:

while (condition)    program statement;

Somewhere within the body of the while loop a statement must alter the value of the condition to allow the loop to finish.

Sample program including while:

#include int main(){    int loop = 0;    while (loop <= 10) {        printf("%dn", loop);        ++loop;    }    return 0;}

Sample Program Output

0
1

10

THE DO WHILE STATEMENT

The do { } while statement allows a loop to continue whilst a condition evaluates as TRUE (non-zero). The loop is executed at least once.

/* Demonstration of DO...WHILE */#include int main(){    int value, r_digit;    printf("Enter the number to be reversed.n");    scanf("%d", &value);    do {        r_digit = value % 10;        printf("%d", r_digit);        value = value / 10;    } while (value != 0);    printf("n");    return 0;}

This program reverses a number entered by the user by extracting the rightmost digit and printing it, then dividing the number by 10 and repeating until the number is zero.

This programming construct is generally discouraged due to lack of control and potential problems.

SELECTION (IF STATEMENTS)

The if statement allows branching (decision making) depending upon the value or state of variables. The basic format is:

if (expression)    program statement;

Example:

if (students < 65)    ++student_count;

The following program uses an if statement to validate user input to be in the range 1-10:

#include int main(){    int number;    int valid = 0;    while (valid == 0) {        printf("Enter a number between 1 and 10 -->");        scanf("%d", &number);        valid = 1; /* assume number is valid */        if (number  10) {            printf("Number is above 10. Please re-entern");            valid = 0;        }    }    printf("The number is %dn", number);    return 0;}

Sample Program Output

Enter a number between 1 and 10 –> 56
Number is above 10. Please re-enter
Enter a number between 1 and 10 –> 4
The number is 4

COMPOUND RELATIONALS (AND, NOT, OR, EOR)

These allow the testing of more than one condition as part of selection statements. The symbols are:

  • LOGICAL AND: && (requires all conditions to be TRUE)
  • LOGICAL OR: || (true if any one condition is TRUE)
  • LOGICAL NOT: ! (negates a condition)
  • LOGICAL EOR: ^ (true if either condition is TRUE, but not both)

The following program uses an if statement with logical OR to validate user input to be in the range 1-10:

#include int main(){    int number;    int valid = 0;    while (valid == 0) {        printf("Enter a number between 1 and 10 -->");        scanf("%d", &number);        if ((number  10)) {            printf("Number is outside range 1-10. Please re-entern");            valid = 0;        } else {            valid = 1;        }    }    printf("The number is %dn", number);    return 0;}

witch() case:

The switch case statement is a better way of writing a program when a series of if else statements occurs. The general format is:

switch (expression) {    case value1:        program statements;        break;    case valueN:        program statements;        break;    default:        program statements;        break;}

The keyword break must be included at the end of each case statement. The default clause is optional and is executed if none of the cases are met.

#include int main(){    int menu, numb1, numb2, total;    printf("enter in two numbers -->");    scanf("%d %d", &numb1, &numb2);    printf("enter in choicen");    printf("1=additionn");    printf("2=subtractionn");    scanf("%d", &menu);    switch (menu) {        case 1: total = numb1 + numb2; break;        case 2: total = numb1 - numb2; break;        default: printf("Invalid option selectedn");    }    if (menu == 1)        printf("%d plus %d is %dn", numb1, numb2, total);    else if (menu == 2)        printf("%d minus %d is %dn", numb1, numb2, total);    return 0;}

Sample Program Output

enter in two numbers –> 37 23
enter in choice
1=addition
2=subtraction
2
37 minus 23 is 14

ACCEPTING SINGLE CHARACTERS FROM THE KEYBOARD

getchar() function example:

#include int main(){    int i;    int ch;    for (i = 1; i <= 5; ++i) {        ch = getchar();        putchar(ch);    }    return 0;}

Sample Program Output

AACCddEEtt

The program reads five characters (one for each iteration of the for loop) from the keyboard. Note that getchar() gets a single character from the keyboard, and putchar() writes a single character to the console screen.

BUILT IN FUNCTIONS FOR STRING HANDLING

You may want to look at the section on arrays first! The following macros are built into the file string.h:

  • strcat – Appends a string
  • strchr – Finds first occurrence of a given character
  • strcmp – Compares two strings
  • strcmpi – Compares two strings, non-case sensitive
  • strcpy – Copies one string to another
  • strlen – Finds length of a string
  • strlwr – Converts a string to lowercase
  • strncat – Appends n characters of string
  • strncmp – Compares n characters of two strings
  • strncpy – Copies n characters of one string to another
  • strnset – Sets n characters of string to a given character
  • strrchr – Finds last occurrence of given character in string
  • strrev – Reverses string
  • strset – Sets all characters of string to a given character
  • strspn – Finds first substring from given character set in string
  • strupr – Converts string to uppercase

To convert a string to uppercase

#include #include int main(){    char name[80]; /* declare an array of characters 0-79 */    int loop;    printf("Enter in a name in lowercasen");    scanf("%s", name);    for (loop = 0; name[loop] != 0; loop++)        name[loop] = toupper(name[loop]);    printf("The name in uppercase is %sn", name);    return 0;}

Sample Program Output

Enter in a name in lowercase
samuel
The name in uppercase is SAMUEL

BUILT IN FUNCTIONS FOR CHARACTER HANDLING

The following character handling functions are defined in ctype.h:

  • isalnum – Tests for alphanumeric character
  • isalpha – Tests for alphabetic character
  • isascii – Tests for ASCII character
  • iscntrl – Tests for control character
  • isdigit – Tests for 0 to 9
  • isgraph – Tests for printable character
  • islower – Tests for lowercase
  • isprint – Tests for printable character
  • ispunct – Tests for punctuation character
  • isspace – Tests for space character
  • isupper – Tests for uppercase character
  • isxdigit – Tests for hexadecimal
  • toascii – Converts character to ASCII code
  • tolower – Converts character to lowercase
  • toupper – Converts character to uppercase



');}
Bc0138c3d2dab0944d91d638547c2715

subscriber

Leave a Reply

Your email address will not be published. Required fields are marked *

Accept Our Privacy Terms.*