Introduction to C | C Language Introduction | Learn C Programming

What is C Programming Language?

C is a general purpose, procedural, structured programming language developed at AT & T’s (American Telephone and Telegraph) Bell Laboratories of USA in the year 1972. It was originally developed by Dennis Ritchie and hence he is known as the founder of C.

C has emerged as the most widely used programming language for software development. C programming is considered as the base for other programming languages, therefore it is known as mother language. In the late seventies C began to replace the more familiar languages of that time like PL/I, ALGOL, etc. It was developed to overcome the difficulties found in previous programming languages such as BCPL (Basic Combined Programming Language), CPL (Combined Programming Language), B etc. It was initially designed for programming UNIX operating system. It inherits many features of previous languages such as B, BCPL, CPL etc. 

The programming languages that were developed before C language are:


Language

Year

Developed By

Algol

1960

International Committee

CPL(Combined Programming Language)

1963

Cambridge University

BCPL(Basic Combined Programming Language

1967

Martin Richards, Cambridge

B

1970

Ken Thompson, Bell Labs

C

1972

Dennis Ritchie



In 1978, Brian Kernighan and Dennis Ritchie published the first edition of the C programming language, now known as the K&R standard.

In 1983, the ANSI formed a committee, X3J11to establish a standard specification of C. The standard was completed in 1989.

C has been standardized by American National Standard Institute (ANSI) since 1989. Later, it was approved by the International Standards Organization (ISO) in 1990.


Applications of ‘C’ Language:


C has emerged as the most widely used programming language for software development. It was originally developed for writing system software. Being one of the oldest languages, it is still runs the world and it can be used for various purposes. The applications of C is not only limited to the development of system software like Windows or Linux operating system, but also in the development of GUIs (Graphical User Interfaces) and, IDEs (Integrated Development Environments). It is widely used for writing application software including word processing, spreadsheets, games, robotics and graphics programs. It is still the most preferred language for programmers and back-end developers.

Some important applications of C programming language are:

  • Operating System Design
  • Embedded Systems
  • GUI (Graphical User Interface) Design
  • Development of New programming languages
  • Browser Design
  • Database Design
  • Compiler Design
  • Gaming and Animation



Features of C Language:


C is a general purpose, procedural programming language supporting major programming language features. It is a feature-rich programming language. It offers various features and functionalities to the programmers. C has many features that make it a good choice for a programming language. 

Following are the key features or characteristics of C language:

  • Portability
  • Flexibility
  • Versatility
  • Fast and Efficient
  • Structured or Modular Programming language
  • Powerful
  • Libraries with rich functions
  • General Purpose Language
  • Statically Type
  • Extensible
  • Middle-Level Language
  • Dynamic Memory Allocation or memory Management



Basic Structure of ‘C’ Program: 

Every C program is basically a group of different section that is used for different purpose. The structure gives us a basic idea of the order of the sections in a program. A well-defined structured layout makes program more readable, easy to modify, consistent format and gives better clarity and the concept of a program. Whenever we write a program in ‘C’ language, we can divide that program into six different sections.

These sections are as follows:

  • Documentation section
  • Linkage section
  • User definition section
  • Global declaration section
  • Main() function section
  • Subprogram section






Compiling and Executing C Program:


The compilation and execution process of C program follows multiple steps. A brief explanation of each step is given below:


Step 1: Creating Source Code

Step 2: Compiling the program

Step 3: Executing / Running the program


The following diagram will show how a C Source Code can be executed.




Importance of C Language:

Despite the familiarity of higher level languages, ‘C’ continues to be very popular among programmers. It is flexible, efficient, powerful, and widely available. ‘C’ has become the backbone of modern computing systems-operating systems, compilers, interpreters, databases, device driver programs etc.

Following are some of the major importance of ‘C’ language:

  • C is a robust language, which has so many built-in functions, data types and operators can be used to write any complex program.
  • Generally, we use to call ‘C’ as a middle level language. Because, the ‘C’ combines the features of both high-level and low-level languages. Therefore, it is best for writing both system software and application software.
  • Programs written in ‘C’ are efficient due to several varieties of data types and powerful operators.
  • C is highly portable, that is, ‘C’ programs written on one computer can be run on another with slight changes or no changes.
  • ‘C’ language is best for structured programming, which allows a complex program to be broken into simpler programs called functions or modules. A collection of these modules make a program debugging and testing easier.
  • ‘C’ language has the ability to extend itself.  A ‘C’ program is basically a collection of functions, which is supported by the ‘C’ library. We can add our own functions to the library with the availability of large number of functions.
  • ‘C’ has a strong set of built-in functions. This facilitates the reusability of code. That is, when we a make a set of programs for a primitive task then it can be made available to other users in the form of a library. This ensures that other developers need not write those routines all over again. This is referred to as software reusability. Thereby the man hours involved in developing large systems is reduced.
  • ‘C’ is used to develop system software as it has many low level functions embedded in it. The operating system interacting features of ‘C’ are extremely handy, when system software is developed. In fact, system programmers will feel at home when a system work is being developed under ‘C’.



Sample C Program:


This sample program will print Welcome to C programming.


// Sample C program

#include<stdio.h>

#include<conio.h>

int main()

{

clrscr();

printf(“ Welcome to C programming”);

getch();

return 0;

}


Brief explanation of each line of the program is given below:                                


(1)    // Sample C program

This is a comment line. Comments are used to document the program. It is like a remark from the programmer. They can appear in any part of the program. We write comments for better understanding of the program. The comments are ignored by the compiler. Comments are useful for software maintenance.

 

(2)   #include<stdio.h>

This command includes standard input/output header file, stdio.h from the C library in the program before compiling. The stdio.h file contains functions such as scanf() and printf() to take input and display output respectively.


(3)    #include<conio.h>

This command includes console input/output header file, conio.h from the C library in the program. The conio.h file contains functions such as clrscr() and getch() to clear the output  screen and  pause the output screen.


(4)   int main()

Here main() is the function name and int is the return type of this function. It is a compulsory part of every C program. It is a special function used to inform the compiler that the program starts from there. Execution of every C program starts from main() function. Logically every program must have exactly one main() function.


(5)   {  and }

The opening curly bracket ‘{’ indicates the beginning of the main function and the closing curly bracket ‘}’ indicates the end of the main function.


(6)    clrscr();

It is a library function used to clear the console screen. It is defined in conio.h header file. Using of clrscr() function in C is always optional . If the function is to be used, then it should be placed after variable or function declaration only.

 

(7)  printf(“Welcome to C programming”) ;

This command tells the compiler to display the message “Welcome to C programming”. printf()  is a library function used in C to display the output onto the screen. The text to be printed is enclosed in double quotes.

 

(8) Use of Semicolon “;”

The semicolon serves as the statement terminator. Semicolon character at the end of the statement is used to indicate that the statement is ending there. Each executable statement should have a ‘;’ to inform the compiler that the statement has ended. Thus, in ‘C’ the semicolon terminates each statement.


(9) getch();

getch() function pauses the output console screen until a key is pressed. It is defined in conio.h header file. This function is used to hold the output screen for some time until the user presses a key from the keyboard.


(10) return 0;

The return statement is used to return a value from a function and indicates the finishing of a function. The value ‘0’ means successful execution of this function. This statement is basically used in functions to return the results of the operations performed by a function. 



Character Set in C:

A character set in C programming language is the set of all valid characters that can be used in source program to represent information. The character set helps in defining the valid characters that we can use in source program for forming words, expressions and numbers.

Just like we use a set of various words, numbers, statements, etc., in any language for communication, the C programming language also consists of a set of different types of characters. These are known as the character set in C. They include alphabets, digits, special symbols etc.


Types of Characters in C:

The C programming language provides support for the following types of characters.

  • Letters or Alphabets
  • Digits or Numbers
  • Special Characters
  • White Spaces


All of these serve a different set of purposes, and we use them in different contexts in the C language.


Letters or Alphabets:

The C programming language provides support for all the alphabets that we use in the English language. Thus, in simpler words, a C program would support a total of 52 different characters- 26 uppercase and 26 lowercase.


Type of Character

Description

Characters

Lowercase Alphabets

a to z

a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z

Uppercase Alphabets

A to Z

A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z


Digits or Numbers:


The C programming language provides the support for all the digits that help in construct the numeric values or expressions in a program. These range from 0 to 9 and also help in defining an identifier.

Thus, the C language supports a total of 10 digits for constructing the numeric values or expressions in any program.


Type of Character

Description

Characters

Digits

0 to 9

0, 1, 2, 3, 4, 5, 6, 7, 8, 9


Special Characters:


C language supports a rich set of special character for some special purposes, such as logical operations, mathematical operations, checking of conditions etc.

We can also use these characters for defining the identifiers in a much better way. For instance, we use underscores for constructing a longer name for a variable, etc.

The C programming language provides support for the following types of special characters:


Character

Description

Character

Description

,

Comma

&

Ampersand

.

Period

^

Caret

;

Semicolon

*

Asterisk

:

Colon

-

Minus sign

?

Question Mark

+

Plus sign

Apostrophe

< 

Less than

!

Exclamation

> 

Greater than

|

Vertical Slash

=

Equal to

/

Slash

(

Left parenthesis

\

Back slash

)

Right parenthesis

Quotation mark

[

Left square bracket

~

Tilde

]

Right square bracket

_

Underscore

{

Left curly bracket

$

Dollar Sign

}

Right curly bracket

%

Percentage sign

#

Number sign(hash)




















White Spaces:

The white spaces in the C programming language contain the following:

  • Blank Spaces
  • Carriage Return
  • Horizontal Tab
  • New Line



Escape Sequence:


Escape Sequence in C is a sequence of character which is used for formatting the output in a structured way. But it did not get displayed on the screen while printing the output. In an escape sequence, a character denotes a different meaning from its actual meaning and undergoes a change from its normal form.

It is a sequence of characters that doesn’t represent itself when used inside a character or a string but has its own specific function.

Escape sequences are special character denoted by a backslash (\) and a character after it. E.g. \t is an escape sequence because the \ causes an ‘escape’ from the normal way the characters are interpreted. In the example given above, it is interpreted as the ‘tab’ character and not as character ‘t’. Escape sequences can be used in both character and string constants.


Some of the common escape sequence characters are:


Escape Sequence

Meaning

\a

Bell (beep)

\b

Backspace

\f

Form feed                  

\n

New Line

\t

Tab

\r

Return (Enter key)

\0

Null character

\\

Backslash

\’

single Quotation Mark

\”

Double Quotation Mark




Variables:

Variables are named storage locations in memory. The primary purpose of variable is to store data for later use. Variable is like a container (storage area) with a name in which we can store data. To indicate the storage area, each variable should be given a unique name. Variable names are just the symbolic representation of a memory location. By using a variable name we are referring to the data stored in the location.

The value of a variable may change during program execution, and we can also reuse it multiple times. Every variable in C language has some specific type that determines the size of the memory of the variable, the range of values that the memory can hold and the set of operations that one can perform on that variable.



Rules for Naming a variable in C:

There are some rules on choosing variable names. The following rules must be followed while naming variables:

  • A variable name consists of letters (both uppercase and lowercase letters), digits, and the underscore.
  • The first character must be a letter or an underscore. It can’t start with a digit.
  • Variable names are case sensitive. The compiler treats the upper and lower case letters as different.
  • No whitespace is allowed within the variable name.
  • Special symbols such as period, semicolon, comma, slash etc. are not allowed other than underscore.
  • Any reserved word (keyword) cannot be used as a variable name. e.g. int, float etc.



Declaring and Initializing Variables:

 

Variable Declaration:

 

In C programming, variables must be declared before they are used. The declaration of a variable informs the compiler about two things:

  • The name of the variable
  • The type of data the variable will stored

 

Variable names should be user friendly. The name should be chosen to describe the role that the variable is designed to play e.g., Emp_no for employee number. A meaningful name given to a variable always helps in better understanding of the program.

 

Variable declaration begins with the data type, followed by the name of one or more variables. All declaration statement must end with a semicolon. The general syntax for declaration of a variable is given below:

Syntax:

data_type variable_name;


To declare more than one variable of the specified type, use a comma separated list.

Syntax:

data_type variable1, variable2, …,variablen;

Example: 

int roll_no;

char choice;

float fees,avg;

 

 

Variable Initialization:

 

Variable initialization means assigning values to the variablesC variables declared can be initialized with the help of assignment operator.

Different ways of initializing a variable in C:

 

Method 1:

Declaring the variable and then initializing it

int roll_no;                  

roll_no=1;

 

Method 2:

Declaring and initializing the variable together

int roll_no=1;

 

Method 3:

Declaring multiple variables simultaneously and then initializing them simultaneously

int a,b,c;

a=b=c=10;



Declaring a variable as constant:

Variables can be declared as constant by using the const keyword or the #define preprocessor directive. Details about these are given as follows.

 

 

The const keyword:


Variables can be declared as constants by using the “const” keyword before the data type of the variable. The constant variables can be initialized only once. The default value of constant variables is zero.

The correct way to declare a constant in C is:

const datatype variable_name = value.

 

For example: const int var = 15.

Adding the const keyword in the definition of the variable ensures that its value remains unchanged in the program.

 

A program that demonstrates the declaration of constant variables in C using const keyword is given as follows.


Example:

 

#include<stdio.h>

int main()

{

const int a;

const int b=5;

printf(“ The default value of variable a : %d”, a);

printf(“ The default value of variable b : %d”, b);

return 0;

}


Output:

The default value of variable a : 0

The default value of variable b : 5



#define preprocessor directive:

Variables can be declared as constants by using the #define preprocessor directiveThis directive is used to declare an alias name for any value. We can use this to declare a constant as shown below:

#define variable_name value

 

  variable_name: It is the name given to constant.

  value: This refers to any value assigned to variable.

 

A program that demonstrates the declaration of constant variables in C using #define preprocessor directive is given as follows.

 
Example:

 

#include<stdio.h>

#define num 10

int main()

{

printf(“The value of num is: %d”, num);

return 0;

}


Output:

The value of num is: 10



Declaring a variable as volatile:


C's volatile keyword is a type qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time without any action being taken by the code the compiler finds nearby. The implications of this can be quite serious, and sometimes software experts testify in regard to product failures. 



Proper Use of C's volatile Keyword:


A variable should be declared volatile whenever its value could change unexpectedly. In practice, only three types of variables could change:
  • Memory-mapped peripheral registers
  • Global variables modified by an interrupt service routine
  • Global variables accessed by multiple tasks within a multi-threaded application


Data Types :

As the name suggests, a data type refers to the type of data being used. The data type defines an attribute to the variable. It defines the set of legal values that the variable can store. A data type specifies the type of data that a variable can store such as integer, float, character etc.

Each variable in C has an associated data type. This determines the type and size of data associated with variables. Whenever we define a variable or use any data in the C language program, we have to specify the type of data, so that the compiler knows exactly what type of data it must expect from the given program.


Following are the primary (basic) data types used in C:

  • Integer (int)
  • Floating point type (float)
  • Character data type (char)


Integer (int): 

The data type ‘int’ represents whole numbers with a range of values supported by a particular machine. For instance, in a 16 bit word length machine, the integer values lie between -32768 to 32767.

C facilitates some control over the integer data type by providing sub data types namely short intintlong int.

The sub type short int represents a fairly small integer value and requires half the amount of storage as a normal int uses.

Similarly a long int represents a fairly higher integer value and requires generally twice the number of bits as a normal int uses.

Another option in integer data type is declaring it as unsigned. This unsigned integer uses all bits for the magnitude of the number and is always positive. For instance, in a 16 bit machine the range of unsigned integer is 0 to65, 535. Thus long and unsigned are intended for increasing the range of values.

Keyword “int” is used for declaring an integer variable. To define an integer variable to store the roll number of a student:

int roll;


Floating point (float)

It is used to store floating point numberFloating point numbers are numbers that have a decimal point. This data type in ‘C’ is an attribute for real numbers. The required declaration is,

          float a;

which instructs the compiler that the variable ‘a’ belongs to the data type real. If we want to initialize the variable, then

          float a;

a=14.752 ;

This can also be achieved through a single statement.

float a=14.752;

The keyword float defines the floating point number.

When more accuracy is required, another sub-data type, double can be used. Double data type uses twice the storage as that of the float data type. Float is just a single-precision data type, double is the double-precision data type.


Character data type (char):

It is usually used to store a single character in 1 byte (8 bits) of internal storage. The char keyword defines a character data type. Thus the declaration for this is

          char x;

          x= ‘a’;

The variable x is of type character and is initialized to the character ‘a’. The same effect could be achieved as,

          char x= ‘a’;



Data Type

Description

Format

Specification

Storage
(machine dependent)

int

short int

long int

unsigned int

Integer data type

%d or %i

%hd

%ld

%u

2 Bytes

2 Bytes

4 Bytes

2 Bytes

float

double

 

long double

Floating point representation

For better precision of floating point /scientific notation

An extended precision floating point number

%f or %e

%f or %e

 

%lf or %le

4 Bytes

8 Bytes

 

10 Bytes

Char

Character representation

String representation

%c

%s

1 Byte

No. of characters + 1 Byte



Tokens:


Each and every smallest individual unit in a C program is known as tokens. Tokens are the basic building blocks in C language which are constructed together to write a program. A compiler breaks a C program into tokens and then proceeds ahead to the next stage used in the compilation process.

 

C has following six types of tokens:


  • Keywords       e.g. int, for
  • Identifiers       e.g. sum, total
  • Constants       e.g. 10, 20
  • Strings            e.g. “welcome”
  • Operators       e.g. +, -, *, /
  • Special Characters   e.g. ( ), { }



Keywords:

Keywords are reserved words whose meaning has already been fixed to the C compiler. Each keyword is meant to perform a specific function in a program. Since keywords are referred names for a compiler, they cannot be used as variable names because if we do so, we are trying to assign a new meaning to the keyword, which is not allowed. We canoe redefine keywords. All keywords have a predefined meaning and these meanings cannot be changed. All keywords must be written in lowercase.


For example:


int age;

Here, int is a keyword that indicates age is a variable of type int (integer).

There are 32 keywords available in C.


auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

 

 

Identifiers:

Identifiers are user defined words. These are used to name the variables, functions, arrays, structures, etc. These names can be in uppercase letters, lowercase letter or a combinationIdentifiers must be unique. They are created to give a unique name to an entity to identify it during the execution of the program.


For example:

int age;

int roll;

Here, age and roll are identifiers.

Identifier names must be different from keywords. We cannot use int as an identifier because int is a keyword.


Constants:

Constants in C are fixed values that do not change throughout the program. The constant can be viewed as a read only memory variable. Constants can be declared using the keyword const

Syntax: const variable_name=value;


Constants are broadly classified into numeric constants and character constants.


 Numeric Constants:

    i. Integer Constants

    ii. Real Constants

2    

      Character Constants:

        i. Character constants

        ii. String Constants




Integer Constant:

Integer constants are whole number which has no decimal point. In ‘C’ there can be three types of integer constants:

·    Decimal Integer:            0-------9(base 10)

·    Octal Integer:                 0-------7(base 8)

·    Hexadecimal Integer:    0----9, A------F(base 16)


     Example: 15, -265, 0, 99818, +25, 045, 0X6


Real Constant:

Real constant is also called floating point constant. These have fractional parts to represent quantities like average, fees, height, area etc. which cannot be represented by integer number precisely.

A real constant can be represented in 2 forms.

1.  Decimal form      E.g. 15.5

2.  Exponent form    E.g. 1275E-2, -14E-2

 


Character Constant:
 

A character constant is a single character surrounded by a pair of single quotes. A character value occupies 1 byte of memory.


Example:        'X', '5', ';' 

The character constant '5' is not the same as the integer 5. Each character constant has an ASCII (American Standard Code for Information Interchange) value associated with it. For example, the following statement will print 65 and A respectively:

printf(“%d”, ‘A’);

printf(“%c”, ‘65’);

 


String Constant:

 

A string constant is a group of characters surrounded by double quotes. These characters may be letters, numbers or any special characters.

Example:   "2015", "welcome"






Post a Comment

0 Comments