Anatomy of a C Program

C language has a bundle of protocols that define its programming activities. The C programming language came into existence when its developers were working on the development of the Unix operating system using the B language, out of which C evolved. The B language lacked certain features that led to the introduction of a C language. These features constituted the part of the C program upon which it was is built.

Parts of C program

 

include <stdio.h>

This command is a preprocessor directive in C  that includes all standard input-output files before compiling any C program so as to make use of all those functions in our C program.

int main()

This is the line from where the execution of the program starts. The main() function starts the execution of any C program.

{ (Opening bracket)

This indicates the beginning of any function in the program (Here it indicates the beginning of the main function).

/* some comments */

Whatever is inside /*——-*/ are not compiled and executed; they are only written for user understanding or for making the program interactive by inserting a comment line. These are known as multiline comments. Single line comments are represented with the help of 2 forward slashes “//——”.

printf(“Hello World”);

The printf() command is included in the C stdio.h library, which helps to display the message on the output screen.

getch()

This command helps to hold the screen.

return 0

This command terminates the C program and returns a null value, that is, 0.

} (Closing brackets)

This indicates the end of the function. (Here it indicates the end of the main function)

 

Example of C Program Structure

 

The “Hello World!” example is the most popular and basic program that will help you get started with programming. This program helps you display the output “Hello World” on the output screen.

With the help of this example, we can easily understand the basic structure of a C program.

#include <stdio.h>

int main()

{

// Our first basic program in C

printf("Hello World!\n\n");

return 0;

}

 

Steps involved to get the desired output

Well, when you run a C program and get the output on your screen, there is a series of steps that come in the way. To get the desired output, you need to follow all the steps.

 

These are the steps involved while writing a program in C.

1. Create

2. Compile

3. Execute or run

4. Desired output

 

First of all, try to code the program in the most precise manner following the protocols of C programming like,

  • C is a case-sensitive programming language.

  • Each line of code in C ends with a semicolon(;), except the function definition.

Once, your code gets executed you will surely get the desired output on your output screen.

 

Basic Structure of C Program

The components of the basic structure of a C program consists of 7 parts

 

1. Document section

2. Preprocessor / link Section

3. Definition section

4. Global declaration section

5. Function declaration section

6. Main function

7. User-defined function section

 
1. Documentation Section

 

It is the section in which you can give comments to make the program more interactive. The compiler won’t compile this and hence this portion would not be displayed on the output screen.

 
2. Preprocessor directives Section

 

This section involves the use of header files that are to included necessarily program.

 
3. Definition section

 

This section involves the variable definition and declaration in C.

 
4. Global declaration Section

 

This section is used to define the global variables to be used in the programs, that means you can use these variables throughout the program.

 
5. Function prototype declaration section

 

This section gives the information about a function that includes, the data type or the return type, the parameters passed or the arguments.

 
6. Main function

 

It is the major section from where the execution of the program begins. The main section involves the declaration and executable section.

 
7. User-defined function section

 

When you want to define your function that fulfills a particular requirement, you can define them in this section.

 

Elements of C Language. 

Every language has some basic elements and grammatical rules.Before understanding programming.These basic elements are character set, variables, data types, constants, keywords,variable declaration,expression statements etc.
 
C Character Set
 
The characters that are used in C programs are given below-

Alphabets
 
A,B,C,..........Z
a,b,c,........z
 
Digits
 
0,1,2,3,4,5,6,7,8,9
 
Special Characters


Character Meaning Character Meaning
+ plus sign - minus sign
* asterisk % percent sign
\ Backward slash / forward sign
< less than sign = equal to sign
> grater than sign _ underscore
( left parenthesis ) right parenthesis
{ left braces } right braces
[ left brackets ] right brackets
, comma . period
' single quotes " double quotes
: colon ; semicolon
? Question mark ! Exclamation sign
& ampersand | vertical bar
@ at the rate ^ caret sign
$ dollar sign # hash sign
~ tilde sign ` back quotation mark

 

What is Escape Sequence in C?

 

An escape sequence is a sequence of characters used in formatting the output and are not displayed while printing text on to the screen, each having its own specific function. All the escape sequences in C are represented by 2 or more characters, one compulsorily being backslash (\) and the other any character present in the C character set.

 

Significance of Escape Sequence in C

 

In order to acknowledge the significance of escape sequences, let us consider a simple problem at hand where we want to display some text in a new line in order to enhance code readability. A novice at C programming would say that this task can be ambiguously achieved by placing multiple white spaces in the printf() function.

This is not an appropriate method to solve this problem, as it proves to be quite inconvenient and requires multiple test cases to get the output according to the user’s wish. We can solve this problem by using \n escape sequence. Not only this, the C language offers about 15 escape sequences that allow the user to format the output on the screen.

Here is a simple code in C which illustrates the use of \n escape sequence:

 

#include<stdio.h>

int main()

{

printf("Welcome\n");

printf("to\n");

printf("DataFlair\n");

printf("tutorials!\n");

return 0;

}

 

Types of Escape Sequence in C

There are 15 types of escape sequence in C to achieve various purposes.

 

Here is a table which illustrates the use of escape sequences in C:

\n (New line)

We use it to shift the cursor control to the new line

\t (Horizontal tab)

We use it to shift the cursor to a couple of spaces to the right in the same line.

\a (Audible bell)

A beep is generated indicating the execution of the program to alert the user.

\r (Carriage Return)

We use it to position the cursor to the beginning of the current line.

\\ (Backslash)

We use it to display the backslash character.

\’ (Apostrophe or single quotation mark)

We use it to display the single-quotation mark.

\” (Double quotation mark)

We use it to display the double-quotation mark.

\0 (Null character)

We use it to represent the termination of the string.

\? (Question mark)

We use it to display the question mark. (?)

\nnn (Octal number)

We use it to represent an octal number.

\xhh (Hexadecimal number)

We use it to represent a hexadecimal number.

\v (Vertical tab)

 

\b (Backspace)

 

\e (Escape character)

 

\f (Form Feed page break.

 

 

Here is a code in C that illustrates the commonly used escape sequences in C:

#include<stdio.h>

int main()

{

/* To illustrate the use of \n escape sequence */

printf("Welcome\v");

printf("to\n");

printf("My\v");

printf("Blog\n");

/* To illustrate the use of \n escape sequence */

printf("Welcome\tto\tmy\tblog");

/* To illustrate the use of \v escape sequence */

printf("Welcome\vto\vmy\vblog");

return 0;

}

 

Trigraphs

 

The symbols [ ] { } ^ \ | ~ # are frequently used in C programs, but in the late 1980s, there were code sets in use (ISO 646 variants, for example, in Scandinavian countries) where the ASCII character positions for these were used for national language variant characters (e.g. £ for # in the UK; Æ Ã… æ Ã¥ ø Ø for { } { } | \ in Denmark; there was no ~ in EBCDIC). This meant that it was hard to write C code on machines that used these sets.

To solve this problem, the C standard suggested the use of combinations of three characters to produce a single character called a trigraph. A trigraph is a sequence of three characters, the first two of which are question marks.

The following is a simple example that uses trigraph sequences instead of#,{ and }.
 
??=include <stdio.h>
int main()
??<
    printf("Hello World!\n");
??>
 

This will be changed by the C preprocessor by replacing the trigraphs with their single-character equivalents as if the code had been written:

 

Trigraphs

Equivalent

??=

#

??/

\

??'

^

??(

[

??)

]

??!

|

??<

{

??>

}

??-

~

 
 

Note that trigraphs are problematic because, for example, ??/ is a backslash and can affect the meaning of continuation lines in comments, and have to be recognized inside strings and character literals (e.g. '??/??/' is a single character, a backslash).

 

Delimiters

 

A delimiter is one or more characters that separate text strings. Common delimiters are commas (,), semicolons (;),quotes ( ", ' ),braces ({}),pipes (|), or slashes ( / \ ). When a program stores sequential or tabular data, it delimits each item of data with a predefined character.

 

Reserved Keywords

 

In C, we have 32 keywords, which have their predefined meaning and cannot be used as a variable name. These words are also known as “reserved words”. It is good practice to avoid using these keywords as variable name. These are –

auto

break

case

char

cont

continue

default

do

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

double

else

enum

extern

float

for

goto

if

 

Basics usage of these keywords –

 

if, else, switch, case, default – Used for decision control programming structure.

 

break – Used with any loop OR switch case.

 

int, float, char, double, long – These are the data types and used during variable declaration.

 

for, while, do – types of loop structures in C.

 

void – One of the return type.

 

goto – Used for redirecting the flow of execution.

 

auto, signed, const, extern, register, unsigned – defines a variable.

 

return – This keyword is used for returning a value.

 

continue – It is generally used with for, while and dowhile loops, when compiler encounters this statement it performs the next iteration of the loop, skipping rest of the statements of current iteration.

 

enum – Set of constants.

 

sizeof – It is used to know the size.

 

struct, typedef  – Both of these keywords used in structures (Grouping of data types in a single record).

 

union – It is a collection of variables, which shares the same memory location and memory storage.

 

volatile 

 

What is a Constant?

In C programming language and other languages, constants are variables with a exception that the value of a constant can be set only once and can not be modified later. This exception differs a constant variable from other variables and are called constant because their values are not variable. Value of a constant can not vary during the execution of a program, thus it can not be called a variable.

Using constants for unchangeable values ensure that the value remains the same over the period of execution, will not change mistakenly.
In programs which embeds third party codes or scripts, constants make sure that the value will not be changed by third party codes intentionally or mistakenly.

In C programming language, there are a few types of constants. The different types of constants are as follows

  1. Integer constant

  2. Real constant

  3. Single Character constant

  4. String constant

Integer constants: 

An integer constant can hold an integer as its value. There are three types of integer constants, namely, decimal integer, octal integer and hexadecimal integer.

Decimal integer 

consists of a set of digits from 0 to 9, preceded by an optional + or – sign. 
Examples,      123     -321    0          64932


Octal integer 

consists of a set of digits from 0 to 7, with a leading 0. 

Examples, 037     0      0437         0551


Hexadecimal integers

are a sequence of digits preceded by 0x or 0X. They may also includes letters from A to F or from a to f. The letters represents the numbers from 10 to 15.

Examples,            0X2     0x9F   0Xbcd    0x

 

Real constants

Real constants can be assigned real values, that is values with floating points. Real constants are used to represent quantities that are very continuous, such as distances, temperature etc. These quantities are represented by numbers containing fractional parts.

Examples,      0.00832          -0.75               33.337


Single character constants

A single character constants contains a single character enclosed within a pair of single quote marks.

Example, ‘5’         ‘X’       ‘;’


String constants

A string constant contains a string of characters enclosed within a pair of double quote marks.

Examples,    “Hello !”         “1987”            “?….!”


 

Variables in C Language

 

When we want to store any information (data) on our computer/laptop, we store it in the computer's memory space. Instead of remembering the complex address of that memory space where we have stored our data, our operating system provides us with an option to create folders, name them, so that it becomes easier for us to find it and access it.

Similarly, in C language, when we want to use some data value in our program, we can store it in a memory space and name the memory space so that it becomes easier to access it.

The naming of an address is known as variable. Variable is the name of memory location. Unlike constant, variables are changeable, we can change value of a variable during execution of a program. A programmer can choose a meaningful variable name. Example : average, height, age, total etc.

 

Data type of Variable

 

A variable in C language must be given a type, which defines what type of data the variable will hold.

It can be:

  • char: Can hold/store a character in it.

  • int: Used to hold an integer.

  • float: Used to hold a float value.

  • double: Used to hold a double value.

  • void

 

Rules to name a Variable

1. Variable name must not start with a digit.

2. Variable name can consist of alphabets, digits and special symbols like

    underscore _.

3. Blank or spaces are not allowed in variable name.

4. Keywords are not allowed as variable name.

5. Upper and lower case names are treated as different, as C is case-sensitive, so it

    is suggested to keep the variable names in lower case.

 

Declaring, Defining and Initializing a variable

 

Declaration of variables must be done before they are used in the program. Declaration does the following things.

  1. It tells the compiler what the variable name is.

  2. It specifies what type of data the variable will hold.

  3. Until the variable is defined the compiler doesn't have to worry about allocating memory space to the variable.

  4. Declaration is more like informing the compiler that there exist a variable with following datatype which is used in the program.

  5. A variable is declared using the extern keyword, outside the main() function.

extern int a;
extern float b;
extern double c, d;

 

Defining a variable means the compiler has to now assign a storage to the variable because it will be used in the program. It is not necessary to declare a variable using extern keyword, if you want to use it in your program. You can directly define a variable inside the main() function and use it. To define a function we must provide the data type and the variable name. We can even define multiple variables of same data type in a single line by using comma to separate them.

int a;
float b, c;

Initializing a variable means to provide it with a value. A variable can be initialized and defined in a single statement, like:

int a = 10;

Let's write a program in which we will use some variables.

#include <stdio.h>

// Variable declaration (optional)
extern int a, b;
extern int c;

int main () {

    /* variable definition: */
    int a, b;
 
    /* actual initialization */
    a = 7;
    b = 14;
    /* using addition operator */
    c = a + b;
    /* display the result */
    printf("Sum is : %d \n", c);
    
    return 0;
}

Sum is : 21

 

Difference between Variable and Identifier?

 

An Identifier is a name given to any variable, function, structure, pointer or any other entity in a programming language. While a variable, as we have just learned in this tutorial is a named memory location to store data which is used in the program.

Identifier

Variable

Identifier is the name given to a variable, function etc.

While, variable is used to name a memory location which stores data.

An identifier can be a variable, but not all indentifiers are variables.

All variable names are identifiers.

Example:

// a variable
int studytonight;
// or, a function
int studytonight() { 
    .. 
}

Example:

// int variable
int a;
// float variable
float a;

Another great analogy to understand the difference between Identifier and Variable is:

You can think of an Identifier int x to be a variable's name, but it can also be a function's name int x() { } and still be an identifier.

Just like Obama is a name of a person, but also the name of a foundation.

There are three types of variables in C program They are,

  1. Local variable

  2. Global variable

  3. Environment variable

1. Example program for local variable in C:

  • The scope of local variables will be within the function only.

  • These variables are declared within the function and can’t be accessed outside the function.

  • In the below example, m and n variables are having scope within the main function only. These are not visible to test function.

  • Like wise, a and b variables are having scope within the test function only. These are not visible to main function.
     

#include<stdio.h>

void test();

 

int main()

{

   int m = 22, n = 44;

        // m, n are local variables of main function

        /*m and n variables are having scope

        within this main function only.

        These are not visible to test funtion.*/

        /* If you try to access a and b in this function,

        you will get 'a' undeclared and 'b' undeclared error */

   printf("\nvalues : m = %d and n = %d", m, n);

   test();

}

 

void test()

{

   int a = 50, b = 80;

        // a, b are local variables of test function

        /*a and b variables are having scope

        within this test function only.

        These are not visible to main function.*/

        /* If you try to access m and n in this function,

        you will get 'm' undeclared and 'n' undeclared

        error */

   printf("\nvalues : a = %d and b = %d", a, b);

}

Output:

values : m = 22 and n = 44

values : a = 50 and b = 80

2. Example program for global variable in C:

  • The scope of global variables will be throughout the program. These variables can be accessed from anywhere in the program.

  • This variable is defined outside the main function. So that, this variable is visible to main function and all other sub functions.

#include<stdio.h>

void test();int m = 22, n = 44;

int a = 50, b = 80;

 

int main()

{

   printf("All variables are accessed from main function");

   printf("\nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);

   test();

}

 

void test()

{

   printf("\n\nAll variables are accessed from" \

   " test function");

   printf("\nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);

}

Output:

All variables are accessed from main function
values : m = 22 : n = 44 : a = 50 : b = 80
All variables are accessed from test function
values : m = 22 : n = 44 : a = 50 : b = 80

3. Environment variables in C:

  • Environment variable is a variable that will be available for all C  applications and C programs.

  • We can access these variables from anywhere in a C program without declaring and initializing in an application or C program.

  • The inbuilt functions which are used to access, modify and set these environment variables are called environment functions.

  • There are 3 functions which are used to access, modify and assign an environment variable in C. They are,

1. setenv()
2. getenv()
3. putenv()

Example program for getenv() function in C:

This function gets the current value of the environment variable. Let us assume that environment variable DIR is assigned to “/usr/bin/test/”.

#include <stdio.h>

#include <stdlib.h>

 

int main()

{

printf("Directory = %s\n",getenv("DIR"));

return 0;

}

Output:

/usr/bin/test/

Example program for setenv() function in C:

This function sets the value for environment variable. Let us assume that environment variable “FILE” is to be assigned “/usr/bin/example.c”

#include <stdio.h>

#include <stdlib.h>

 

int main()

{

setenv("FILE", "/usr/bin/example.c",50);

printf("File = %s\n", getenv("FILE"));

return 0;

}

Output:

File = /usr/bin/example.c

Example program for putenv() function in C:

This function modifies the value for environment variable. Below example program shows that how to modify an existing environment variable value.

#include <stdio.h>

#include <stdlib.h>

 

int main()

{

setenv("DIR", "/usr/bin/example/",50);

printf("Directory name before modifying = " \

"%s\n", getenv("DIR"));

putenv("DIR=/usr/home/");

printf("Directory name after modifying = " \

"%s\n", getenv("DIR"));

return 0;

}

Output:

Directory name before modifying = /usr/bin/example/
Directory name after modifying = /usr/home/

 

There are three types of variables in C program They are,

  1. Local variable

  2. Global variable

  3. Environment variable

1. Example program for local variable in C:

  • The scope of local variables will be within the function only.

  • These variables are declared within the function and can’t be accessed outside the function.

  • In the below example, m and n variables are having scope within the main function only. These are not visible to test function.

  • Like wise, a and b variables are having scope within the test function only. These are not visible to main function.

#include<stdio.h>

void test();

 

int main()

{

   int m = 22, n = 44;

        // m, n are local variables of main function

        /*m and n variables are having scope

        within this main function only.

        These are not visible to test funtion.*/

        /* If you try to access a and b in this function,

        you will get 'a' undeclared and 'b' undeclared error */

   printf("\nvalues : m = %d and n = %d", m, n);

   test();

}

 

void test()

{

   int a = 50, b = 80;

        // a, b are local variables of test function

        /*a and b variables are having scope

        within this test function only.

        These are not visible to main function.*/

        /* If you try to access m and n in this function,

        you will get 'm' undeclared and 'n' undeclared

        error */

   printf("\nvalues : a = %d and b = %d", a, b);

}

Output:

values : m = 22 and n = 44

values : a = 50 and b = 80

2. Example program for global variable in C:

  • The scope of global variables will be throughout the program. These variables can be accessed from anywhere in the program.

  • This variable is defined outside the main function. So that, this variable is visible to main function and all other sub functions.

#include<stdio.h>

void test();int m = 22, n = 44;

int a = 50, b = 80;

 

int main()

{

   printf("All variables are accessed from main function");

   printf("\nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);

   test();

}

 

void test()

{

   printf("\n\nAll variables are accessed from" \

   " test function");

   printf("\nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);

}

 

Output:

All variables are accessed from main function
values : m = 22 : n = 44 : a = 50 : b = 80
All variables are accessed from test function
values : m = 22 : n = 44 : a = 50 : b = 80

3. Environment variables in C:

  • Environment variable is a variable that will be available for all C  applications and C programs.

  • We can access these variables from anywhere in a C program without declaring and initializing in an application or C program.

  • The inbuilt functions which are used to access, modify and set these environment variables are called environment functions.

  • There are 3 functions which are used to access, modify and assign an environment variable in C. They are,

1. setenv()
2. getenv()
3. putenv()

 

Example program for getenv() function in C:

 

This function gets the current value of the environment variable. Let us assume that environment variable DIR is assigned to “/usr/bin/test/”.

#include <stdio.h>

#include <stdlib.h>

 

int main()

{

printf("Directory = %s\n",getenv("DIR"));

return 0;

}

Output:

/usr/bin/test/

Example program for setenv() function in C:

This function sets the value for environment variable. Let us assume that environment variable “FILE” is to be assigned “/usr/bin/example.c”

#include <stdio.h>

#include <stdlib.h>

 

int main()

{

setenv("FILE", "/usr/bin/example.c",50);

printf("File = %s\n", getenv("FILE"));

return 0;

}

Output:

File = /usr/bin/example.c

Example program for putenv() function in C:

This function modifies the value for environment variable. Below example program shows that how to modify an existing environment variable value.

#include <stdio.h>

#include <stdlib.h>

 

int main()

{

setenv("DIR", "/usr/bin/example/",50);

printf("Directory name before modifying = " \

"%s\n", getenv("DIR"));

putenv("DIR=/usr/home/");

printf("Directory name after modifying = " \

"%s\n", getenv("DIR"));

return 0;

}

Output:

Directory name before modifying = /usr/bin/example/
Directory name after modifying = /usr/home/

Data types in C Language

 

Data types specify how we enter data into our programs and what type of data we enter. C language has some predefined set of data types to handle various kinds of data that we can use in our program. These datatypes have different storage capacities.

C language supports 2 different type of data types:

  1. Primary data types:

    These are fundamental data types in C namely integer(int), floating point(float), character (char) and void.
  2. Derived data types:

    Derived data types are nothing but primary datatypes but a little twisted or grouped together like array, structure, union and pointers.These are discussed in details later.

Data type determines the type of data a variable will hold. If a variable x is declared as int. it means x can hold only integer values. Every variable which is used in the program must be declared as what data-type it is.

 


Integer type

 

Integers are used to store whole numbers.

 

Size and range of Integer type on 16-bit machine:

 

Type

Size (bytes)

Range

int or signed int

2

-32,768 to 32767

unsigned int

2

0 to 65535

short int or signed short int

1

-128 to 127

unsigned short int

1

0 to 255

long int or signed long int

4

-2,147,483,648 to 2,147,483,647

unsigned long int

4

0 to 4,294,967,295

 

Floating point type

 

Floating types are used to store real numbers.

 

Size and range of Integer type on 16-bit machine

 

Type

Size (bytes)

Range

Float

4

3.4E-38 to 3.4E+38

double

8

1.7E-308 to 1.7E+308

long double

10

3.4E-4932 to 1.1E+4932

 

Character type

Character types are used to store characters value.

 

Size and range of Integer type on 16-bit machine

 

Type

Size (bytes)

Range

char or signed char

1

-128 to 127

unsigned char

1

0 to 255

 

void type

void type means no value. This is usually used to specify the type of functions which returns nothing. We will get acquainted to this data type as we start learning more advanced topics in C language, like functions, pointers etc.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.