This blog is under construction

Thursday, 26 December 2013

Structure of a c program

Let us try to understand the structure of a c program using an example.  Below is the simple c program that adds two number and prints the result on the output screen.

    * Hello Friend, I am inside block comment
    * No one can execute me.. Yahoooo!!!
  #include <stdio.h>  // includes standard i/o library
  #define NAME "TOM"  // macro - substitutes token with char sequence

  main() { // function main with no argument
        int a = 10, b = 20, res; // integer variables
        res = a + b; // arithmetic operation
        printf("%s!! Result is %d\n",
                          NAME, res); // printing result using lib function

  TOM!! Result is 30

Structure of a C program:
Basically, comments are written to provide detailed information about the logic behind the written source code.  So that, anyone walks through the code can understand the logic so easily.  They are ignored by compilers and interpreters.  So, they won't get executed.  There are two types of comments.

  • Block comments(/*  */)
  • Line comments(//)

Block comments:
Allows us to add multiple comment lines in source code.  Block comment lines need to be enclosed within /* and */

   * Hello Friend, I am inside block comment
   * No one can execute me.. Yahoooo!!!

Line comment:
Allows us to add single comment and it needs to be delimited by //

  // macro - substitutes token with char sequence

Preprocessor directive:
Any line that starts with #(hash) is a preprocessor directive.
#include - includes contents library file during compilation.

#include <stdio.h>  => includes information about standar i/o library

#define - provides symbolic name for constants

#define NAME "TOM"  => provides symbolic name NAME for the string constant "TOM"

A function where the execution of the c program starts.  The instruction to be executed for any function will be enclosed inside set braces {}.

int a = 10, b = 20, res;
a, b and res are integer variables.  Basically, variables are used to store values.  Here, value of a is 10 and the value of b is 20.

What is integer?
Integer is a data type and its size is 4 byte.  Range of an integer is from -2,147,483,648 to 2,147,483,647.

Below is the arithmetic expression.
res = a + b;
Calculates the sum of a and b.  Then, stores the result in the variable res.

Library Functions:
C library provides us various services via library functions.  printf() is one of the library function that prints formatted data.
printf() - library function used to print formatted data.

printf("%s!! Result is %d\n", NAME, res);

%s - format specifier for integer
%d - format specifier for integer

Value of NAME is "TOM"
Value of res is 30

Now, replace the format specifier with the above values.  Then, the output will be the following.
TOM!! Result is 32

No comments:

Post a Comment