Introduction

C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R standard.

C was initially used for system development work, particularly the programs that make-up the operating system. C was adopted as a system development language because it produces code that runs nearly as fast as the code written in assembly language.

A C program can vary from 3 lines to millions of lines and it should be written into one or more text files with extension .c; for example, hello.c.

Some Applications of C Programming

Hello World

Just to give you a little excitement about C programming, below is a small conventional C Programming Hello World program

          
          #include <stdio.h>

          int main() {
             /* my first program in C */
             printf("Hello, World! \n");
             return 0;
            }
          
        

Basic Syntax

Semicolons

In a C program, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity.

Given below are two different statements -

          
          printf("Hello, World! \n");
          return 0;
          
        

Comments

Comments are like helping text in your C program and they are ignored by the compiler. They start with /* and terminate with the characters */ as shown below -

          
          /* my first program in C */
          
        

Identifiers

A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more letters, underscores, and digits (0 to 9).

C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in C.

Whitespace

A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler totally ignores it. Whitespace is the term used in C to describe blanks, tabs, newline characters and comments.

Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement -

          
          int age;
          
        

there must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement -

          
          fruit = apples + oranges;   // get the total fruit
          
        

no whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish to increase readability.

Data Types

Data types in c refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.

The types in C can be classified as follows -

Basic Types

They are arithmetic types and are further classified into: (a) integer types and (b) floating-point types.

Enumerated types

They are again arithmetic types and they are used to define variables that can only assign certain discrete integer values throughout the program.

The type void

The type specifier void indicates that no value is available.

Derived types

They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types.

Variables

A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based on the basic types explained in the previous chapter, there will be the following basic variable types -

char

Typically a single octet(one byte). It is an integer type.

int

The most natural size of integer for the machine.

float

A single-precision floating point value.

double

A double-precision floating point value.

void

Represents the absence of type.

A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows -

          
          type variable_list;
          
        

Some valid declarations are shown here -

          
          int    i, j, k;
          char   c, ch;
          float  f, salary;
          double d;
          
        

Constants

There are two simple ways in C to define constants -

Given below is the form to use #define preprocessor to define a constant -

          
          #define identifier value
          
        

You can use const prefix to declare constants with a specific type as follows -

          
          const type variable = value;
          
        

Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C language is rich in built-in operators and provides the following types of operators -

Decision Making

Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

C programming language provides the following types of decision making statements.

Below are the syntaxes

          
          //if statement
          if(boolean_expression) {
             /* statement(s) will execute if the boolean expression is true */
          }
          //if...else statement]
          if(boolean_expression) {
             /* statement(s) will execute if the boolean expression is true */
          } else {
             /* statement(s) will execute if the boolean expression is false */
          }
          //nested if statement
          if( boolean_expression 1) {

             /* Executes when the boolean expression 1 is true */
             if(boolean_expression 2) {
                /* Executes when the boolean expression 2 is true */
             }
          }
          //switch statement
          switch(expression) {

             case constant-expression  :
                statement(s);
                break; /* optional */

             case constant-expression  :
                statement(s);
                break; /* optional */

             /* you can have any number of case statements */
             default : /* Optional */
             statement(s);
          }
          //nested switch statements
          switch(ch1) {

             case 'A': 
                printf("This A is part of outer switch" );

                switch(ch2) {
                   case 'A':
                      printf("This A is part of inner switch" );
                      break;
                   case 'B': /* case code */
                }

                break;
             case 'B': /* case code */
          }
          
        
      

Loops

You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

A loop statement allows us to execute a statement or group of statements multiple times.

Below are the syntaxes

          
          //while loop
          while(condition) {
             statement(s);
          }
          //for loop
          for ( init; condition; increment ) {
             statement(s);
          }
          //do...while loop
          do {
             statement(s);
          } while( condition );
          //nested loops
          for ( init; condition; increment ) {

             for ( init; condition; increment ) {
                statement(s);
             }
             statement(s);
          }
          
        

Functions

A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.

The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions.

The general form of a function definition in C programming language is as follows -

          
          return_type function_name( parameter list ) {
             body of the function
          }
          
        

A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. A function declaration has the following parts -

          
          return_type function_name( parameter list );
          
        

Arrays

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows -

          
          type arrayName [ arraySize ];
          
        

You can initialize an array in C either one by one or using a single statement as follows -

          
          double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
          
        

An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example -

          
          double salary = balance[9];
          
        

he above statement will take the 10th element from the array and assign the value to salary variable. The following example Shows how to use all the three above mentioned concepts viz. declaration, assignment, and accessing arrays -

          
          #include <stdio.h>
 
          int main () {

             int n[ 10 ]; /* n is an array of 10 integers */
             int i,j;

             /* initialize elements of array n to 0 */         
             for ( i = 0; i < 10; i++ ) {
                n[ i ] = i + 100; /* set element at location i to i + 100 */
             }

             /* output each array element's value */
             for (j = 0; j < 10; j++ ) {
                printf("Element[%d] = %d\n", j, n[j] );
             }

             return 0;
          }
          
        

Pointers

A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is -

          
          type *var-name;
          
        

The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Take a look at some of the valid pointer declarations -

          
          int    *ip;    /* pointer to an integer */
          double *dp;    /* pointer to a double */
          float  *fp;    /* pointer to a float */
          char   *ch     /* pointer to a character */
          
        

A pointer that is assigned NULL is called a null pointer. The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the following program -

          
          #include <stdio.h>

          int main () {

             int  *ptr = NULL;

             printf("The value of ptr is : %x\n", ptr  );

             return 0;
          }
          
      

Strings

Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.

The following declaration and initialization create a string consisting of the word "Hello".

          
          char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
          
        

If you follow the rule of array initialization then you can write the above statement as follows -

          
          char greeting[] = "Hello";
          
        

Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print the above mentioned string -

          
          #include <stdio.h>

          int main () {

             char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
             printf("Greeting message: %s\n", greeting );
             return 0;
          }
          
        

Input And Output

When we say Input, it means to feed some data into a program. An input can be given in the form of a file or from the command line. C programming provides a set of built-in functions to read the given input and feed it to the program as per requirement.

When we say Output, it means to display some data on screen, printer, or in any file. C programming provides a set of built-in functions to output the data on the computer screen as well as to save it in text or binary files.

The int scanf(const char *format, ...) function reads the input from the standard input stream stdin and scans that input according to the format provided.

The int printf(const char *format, ...) function writes the output to the standard output stream stdout and produces the output according to the format provided. Below is a simple example to understand the concepts better -

          
          #include <stdio.h>
          int main( ) {

             char str[100];
             int i;

             printf( "Enter a value :");
             scanf("%s %d", str, &i);

             printf( "\nYou entered: %s %d ", str, i);

             return 0;
          }
          
        

Variable Arguments

Sometimes, you may come across a situation, when you want to have a function, which can take variable number of arguments, i.e., parameters, instead of predefined number of parameters. The C programming language provides a solution for this situation and you are allowed to define a function which can accept variable number of parameters based on your requirement. The following example shows the definition of such a function.

          
          int func(int, ... ) {
             .
             .
             .
          }

          int main() {
             func(1, 2, 3);
             func(1, 2, 3, 4);
          }
          
        

It should be noted that the function func() has its last argument as ellipses, i.e. three dotes (...) and the one just before the ellipses is always an int which will represent the total number variable arguments passed.