You are on page 1of 20

Introduction to ‘C’ Language & Language Fundamentals

History of C Programming Language :


 C is a programming language which born at “AT & T’s Bell Laboratory” of USA in
1972.
 C was written by Dennis Ritchie, thats why he is also called as father of c programming
language.
 C language was created for a specific purpose i.e designing the UNIX operating system
(which is currently base of many UNIX based OS).
 From the beginning, C was intended to be useful to allow busy programmers to get things
done because C is such a powerful, dominant and supple language
 Its use quickly spread beyond Bell Labs in the late 70’s because of its long list of strong
features.
Why Name “C” was given to Language ?
Many of C’s principles and ideas were derived from the earlier language B. (Ken Thompson was the
developer of B Language.)

 BCPL and CPL are the earlier ancestors of B Language

 CPL is common Programming Language.In 1967, BCPL Language ( Basic CPL ) was

created as a scaled down version of CPL

 As many of the features were derived from “B” Language thats why it was named as “C”.

 After 7-8 years C++ came into existence which was first example of object oriented

programming .

Summary of C Programming Language History


Summary –

1 B Language Developed By Ken Thompson

2 Operating System Developed in C UNIX

3 Developed at AT & T Bell Laboratory

4 Creator of Traditional C Dennis Ritchie

5 Year 1972

C Programming Language Timeline :


Programming Development
Developed by
Language Year

ALGOL 1960 International Group

BCPL 1967 Martin Richards

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

Brain Kernighan and


K&R C 1978
Dennis Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

Structures of ‘C’ Programming

Before we study the basic building blocks of the C programming language, let us look at a bare
minimum C program structure so that we can take it as a reference in the upcoming chapters.

Hello World Example


A C program basically consists of the following parts −

 Preprocessor Commands
 Functions
 Variables
 Statements & Expressions
 Comments

Let us look at a simple code that would print the words "Hello World" –

#include <stdio.h>

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

return 0;
}

Let us take a look at the various parts of the above program −

 The first line of the program #include <stdio.h> is a preprocessor command, which tells
a C compiler to include stdio.h file before going to actual compilation.
 The next line int main() is the main function where the program execution begins.
 The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. So such lines are called comments in the program.
 The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen.
 The next line return 0; terminates the main() function and returns the value 0.

Function as building blocks

If you look at any program in C – you’ll find that it’s actually made up of various “functions”. A
function is a basic building block of every C program. All the code that we write is a part of a C
function.

The “main function” in C is called the “main function”. It is the first function your compiler is
gonna look for. Apart from the main function, we can define and use our own functions.

Also, Some functions are used very commonly and cannot be defined again & again in every
program – like functions to get input and show output – these are already defined in a standard
program and can be used in our own program by “including” their source file. These files of code
included in our program for ready-made functions are called header files.

Now, all the code & the syntax goes inside these functions.

Language Fundamentals
C Character Set :
Whenever we write any C program then it consists of different statements. Each C Program is set of
statements and each statement is set of different c programming expressions. In C Programming each and
every character is considered as single expressions.

Character Set Consists Of –


Types Character Set
Lowercase Letters a-z
Uppercase Letters A to Z
Digits 0-9
Special Characters !@#$%^&*
White Spaces Tab Or New line Or Space

Valid C Characters : Special Characters are listed below –


Symbol Meaning
~ Tilde
! Exclamation mark
# Number sign
$ Dollar sign
% Percent sign
^ Caret
& Ampersand
* Asterisk
( Left parenthesis
) Right parenthesis
_ Underscore
+ Plus sign
| Vertical bar
\ Backslash
` Apostrophe
– Minus sign
= Equal to sign
{ Left brace
} Right brace
[ Left bracket
] Right bracket
: Colon
” Quotation mark
; Semicolon
< Opening angle bracket
> Closing angle bracket
? Question mark
, Comma
. Period
/ Slash

C tokens, Identifiers and Keywords are the basics in a C program. All are explained in this
page with definition and simple example programs.

1. C tokens:

 C tokens are the basic buildings blocks in C language which are constructed together to write a C
program.
 Each and every smallest individual units in a C program are known as C tokens.

C tokens are of six types. They are,

1. Keywords (eg: int, while),


2. Identifiers (eg: main, total),
3. Constants (eg: 10, 20),
4. Strings (eg: “total”, “hello”),
5. Special symbols (eg: (), {}),
6. Operators (eg: +, /,-,*)

C tokens example program:


1 int main()

2{

3 int x, y, total;

4 x = 10, y = 20;

5 total = x + y;

6 printf ("Total = %d \n", total);

7}

where,

 main – identifier
 {,}, (,) – delimiter
 int – keyword
 x, y, total – identifier
 main, {, }, (, ), int, x, y, total – tokens

C Keywords
C keywords are the words that convey a special meaning to the c compiler. The keywords
cannot be used as variable names because by doing so, we are trying to assign a new meaning to
the keyword which is not allowed.

The list of C keywords is given below:

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

C Identifiers
Identifiers are used as the general terminology for the names of variables, functions and arrays.
These are user defined names consisting of arbitrarily long sequence of letters and digits with
either a letter or the underscore(_) as a first character.

There are certain rules that should be followed while naming c identifiers:

 They must begin with a letter or underscore(_).


 They must consist of only letters, digits, or underscore. No other special character is allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only first 31 characters are significant.

Some examples of c identifiers:

Name Remark

_A9 Valid

Temp.var Invalid as it contains special character other than the underscore


void Invalid as it is a keyword

C Constants
C constants refers to the data items that do not change their value during the program execution.
Several types of C constants that are allowed in C are:

1. Integer Constants

Integer constants are whole numbers without any fractional part. It must have at least one digit
and may contain either + or – sign. A number with no sign is assumed to be positive.

There are three types of integer constants:

1.1. Decimal Integer Constants

Integer constants consisting of a set of digits, 0 through 9, preceded by an optional – or + sign.

Example of valid decimal integer constants


341, -341, 0, 8972

1.2. Octal Integer Constants

Integer constants consisting of sequence of digits from the set 0 through 7 starting with 0 is said
to be octal integer constants.

Example of valid octal integer constants


010, 0424, 0, 0540

1.3. Hexadecimal Integer Constants

Hexadecimal integer constants are integer constants having sequence of digits preceded by 0x or
0X. They may also include alphabets from A to F representing numbers 10 to 15.

Example of valid hexadecimal integer constants


0xD, 0X8d, 0X, 0xbD

It should be noted that, octal and hexadecimal integer constants are rarely used in programming.

2. Real Constants

The numbers having fractional parts are called real or floating point constants. These may be
represented in one of the two forms called fractional form or the exponent form and may also
have either + or – sign preceding it.

Example of valid real constants in fractional form or decimal notation


0.05, -0.905, 562.05, 0.015
Representing a real constant in exponent form

The general format in which a real number may be represented in exponential or scientific form
is

mantissa e exponent

The mantissa must be either an integer or a real number expressed in decimal notation.
The letter e separating the mantissa and the exponent can also be written in uppercase i.e. E
And, the exponent must be an integer.

Examples of valid real constants in exponent form are:


252E85, 0.15E-10, -3e+8

3. Character Constants

A character constant contains one single character enclosed within single quotes.

Examples of valid character constants


‘a’ , ‘Z’, ‘5’

It should be noted that character constants have numerical values known as ASCII values, for
example, the value of ‘A’ is 65 which is its ASCII value.

Escape Characters/ Escape Sequences

C allows us to have certain non graphic characters in character constants. Non graphic characters
are those characters that cannot be typed directly from keyboard, for example, tabs, carriage
return, etc.

These non graphic characters can be represented by using escape sequences represented by a
backslash() followed by one or more characters.

NOTE: An escape sequence consumes only one byte of space as it represents a single character.

Escape Sequence Description

a Audible alert(bell)

b Backspace

f Form feed

n New line

r Carriage return

t Horizontal tab

v Vertical tab

\ Backslash
“ Double quotation mark

‘ Single quotation mark

? Question mark

Null

String Constants
String constants are sequence of characters enclosed within double quotes. For example,
“hello”
“abc”
“hello911”

Every sting constant is automatically terminated with a special character ‘’ called the null
character which represents the end of the string.

For example, “hello” will represent “hello” in the memory.

Thus, the size of the string is the total number of characters plus one for the null character.

Special Symbols
The following special symbols are used in C having some special meaning and thus, cannot be
used for some other purpose.

[] () {} , ; : * … = #

Braces{}: These opening and ending curly braces marks the start and end of a block of code
containing more than one executable statement.

Parentheses(): These special symbols are used to indicate function calls and function
parameters.

Brackets[]: Opening and closing brackets are used as array element reference. These indicate
single and multidimensional subscripts.

C Operators
C operators are symbols that triggers an action when applied to C variables and other objects.
The data items on which operators act upon are called operands.

Depending on the number of operands that an operator can act upon, operators can be classified
as follows:

1. Unary Operators: Those operators that require only single operand to act upon are known as
unary operators.
2. Binary Operators: Those operators that require two operands to act upon are called binary
operators.
3. Ternary Operators: These operators requires three operands to act upon.

C Variables: Declaration & Initialization of C Variables

C variables are names used for storing a data value to locations in memory. The value stored in
the c variables may be changed during program execution.

Declaration of Variable
Declaration of variable in c can be done using following syntax:

data_type variable_name;
or
data_type variable1, variable2,…,variablen;

where data_type is any valid c data type and variable_name is any valid identifier.

For example,

1int a;

2float variable;

3float a, b;

Initialization of Variable
C variables declared can be initialized with the help of assignment operator ‘=’.

Syntax

data_type variable_name=constant/literal/expression;
or
variable_name=constant/literal/expression;

Example

1int a=10;

2 int a=b+c;

3 a=10;

4 a=b+c;

Multiple variables can be initialized in a single statement by single value, for example,
a=b=c=d=e=10;
NOTE: C variables must be declared before they are used in the c program. Also, since c is a
case sensitive programming language, therefore the c variables, abc, Abc and ABC are all
different.

Constant and Volatile Variables


Constant Variables

C variables having same or unchanged value during the execution of a program are called
constant variables. A variable can be declared as constant using keyword const.
For example,

1const int a=100;

Now, if we try to change its value, then it is invalid.

Volatile Variables

Those variables that can be changed at any time by some external sources from outside or same
program are called volatile variables.
Any variable in c can be declared as volatile using keyword volatile.

Syntax
volatile data_type variable_name;

NOTE: If the value of a variable in the current program is to be maintained constant and desired
not to be changed by any other external operation, then the variable declaration will be volatile
const d=10;

Data Types in C:

Data types in C programming language enables the programmers to appropriately select the data
as per requirements of the program and the associated operations of handling it.

Data types in c language can be broadly classified as:

1. Primitive Data Types


2. User Defined Data Types, for example, enum, structure, union
3. Derived Data Types, for example, array, pointers

In this tutorial we will only focus on primitive data types, user defined and derived data types
will be discussed separately.

Primitive Data Types


The primitive data types in c language are the inbuilt data types provided by the c language itself.
Thus, all c compilers provide support for these data types.

The following primitive data types in c are available:


Integer Data Type, int

Integer data type is used to declare a variable that can store numbers without a decimal. The
keyword used to declare a variable of integer type is “int”. Thus, to declare integer data type
following syntax should be followed:

int variable_name;

Float data Type, float

Float data type declares a variable that can store numbers containing a decimal number.

Syntax

float variable_name;

Double Data Type, double

Double data type also declares variable that can store floating point numbers but gives precision
double than that provided by float data type. Thus, double data type are also referred to as double
precision data type.

Syntax

double variable_name;

Character Data Type, char

Character data type declares a variable that can store a character constant. Thus, the variables
declared as char data type can only store one single character.

Syntax

char variable_name;

Void Data Type, void

Unlike other primitive data types in c, void data type does not create any variable but returns an
empty set of values. Thus, we can say that it stores null.

Syntax

void variable_name;

Data Type Qualifiers


Apart from the primitive data types mentioned above, there are certain data type qualifiers that
can be applied to them in order to alter their range and storage space and thus, fit in various
situations as per the requirement.

The data type qualifiers available in c are:

 short
 long
 signed
 unsigned

It should be noted that the above qualifiers cannot be applied to float and can only be applied to
integer and character data types.

The entire list of data types in c available for use is given below:

C Data Types Size(in bytes) Range

int 2 -32,768 to 32,767

signed int 2 -32,768 to 32,767

unsigned int 2 0 to 65535

short int 1 -128 to 127


Integer Data Types
signed short int 1 -128 to 127

unsigned short int 1 0 to 255

long int 4 -2,147,483,648 to 2,147,483,647

signed long int 4 Same as Above

unsigned long int 4 0 to 4,294,967,295


float 4 3.4E-38 to 3.4E+38

Floating Point Data Types


double 8 1.7E-308 to 1.7E+308

long double 10 3.4E-4932 to 1.1E+4932


char 1 -128 to 127

Character Data Types


signed char 1 -128 to 127

unsigned char 1 0 to 255

(2) User Defined Data Types


C support user-defined data types. Once a user-defined type has been established, then new
variables, array, structures etc. can be declared in the terms of this new data type. In C language
user-defined data types are: typedef & enum.

 typedef
 enum
 structure
 union

Typedef

typedef is an abbreviation used for “Type Definition”. Its purpose is to redefine the name of an
existing data type. This can be later used to declare variables. Its general form is:
typedef standard-datatype userdefined-datatype.
Ex:
(i) typedef int age;
int x;
age p,q,r,s;
Here, all the variables are holding integer value but age helps us to understand
that these 4 variables will hold age. It helps users debugging the program.
(ii) struct student

{
char name [30];
int roll_no;
float percent;
};
struct student s;
Using typedef:
struct student

{
char name [30];
int roll_no;
float percent;
};
typedef struct student STU;
STU s1, s2;

 Enum

The enumerated data type gives us an opportunity to invent our own data type and define what
values the variables of this data type can take. Its general form is:
enum datatype-name {val1,val2,…..,valn};
Ex:-
(i)
enum weekdays
{Sunday, Monday, Thursday, Wednesday, Thursday, Friday, Saturday};
weekdays x, y;

(ii)
enum marks {gradeA=1, gradeB=2, gradeC=3};
enum marks s1, s2;
The values declared by enum are ordinal nos. Ordinal values starts from zero.

 Structures

A Structure can be defined as a collection or a group of variables that are referenced under one
name. it is used to keep related information together. Here we use a ‘struct’ keyword to construct
a structure.
Example:
Struct bank
{
Char name[30];

Int account_no;

Int amount;
};
Struct b;
In the above example bank is the name of the structure, then we have declared the variables
which are the elements of this structure. And b is the object of the structure which is used to refer
the elements of the structure.

Elements will be referred as :


b.amount=5000;
b.account_no=2546321;

 Union

Groups variables which share the same storage space.


A union is similar to a struct, except it allows you to define variables that share storage space.
The syntax for defining unions is:
union [union-type-name] { type variable-names; ... } [union-variables] ;
For example,union short_or_long { short i; long l; } a_number;
The compiler will allocate enough storage in a number to accommodate the largest element in
the union. Elements of a union are accessed in the same manner as a struct.
Unlike a struct, the variables 'a_number.i' and 'a_number.l' occupy the same location in memory.
Thus, writing into one will overwrite the other.

(3) Derived Data Types

Derived data types in C Programming Language are those C data types which are derived from
the fundamental data types using some declaration operators.

 Array

 Function

 Pointers

Arrays:
Arrays can be defined as a set of finite and homogeneous data elements. Each element of an
array is referenced using an index.
For example:
If we the name of an array is AR which have 5 elements then the array will be represented as :
AR[0], AR[1], AR[2], AR[3], AR[4]
Here, these subscripts which are containing the digit is known as an index.
There are various types of arrays namely:

* One dimensional
* Two dimensional
* Multi dimensional
The elements of an array are indexed from 0 to size-1. It is necessary to declare the size of an
array before initialization. An array can be initialize by placing the elements of an array within
the curly braces.
For example, an array initialization can be done in following manner:

int AR[5] = {5, 2, 6, 8, 3};


A sample program of an array:
Void main()
{
int arr[10];
arr[10] = {1,5,4,6,3,9,14,81,7,11};
printf(“\n %d”,arr[i]);
}

2. Functions
A function can be defined as a part of the program which is declared by the programmer in any
part of the program and a function can be of any name depending upon the choice of the
programmer. The function declared can be invoked from other part of the program.
Example of a function:
#include
Float square(float);
Void main()
{
Float num=3.14;
Float sq;
Sq=square(num);

Printf(“%f”,sq);
}
Float square(float x)
{
Return x * x;
}

The above code will print the square of the above given number. square is the name of the
function used. And sq is the variable used to store the value of the square. The use of the
function before the main function is known as declaration of the function, then comes the
definition of a function which takes place outside the main function. Then finally comes the
calling of the function which takes place inside the main function.

3. Pointers
A pointer is a variable that holds the address of the memory space. We can say that if one
variable can hold the address of the another variable then it is said that the first variable is
pointing to the second.
A pointer is declared in a following manner:

int *temp;

i.e. first we have to declare the type and then the variable name precede by an * (asterisk) sign.

The pointer variable always occupies 2 bytes of memory.

C Language: Comments

In the C Programming Language, you can place comments in your source code that are not
executed as part of the program.

Comments provide clarity to the C source code allowing others to better understand what the
code was intended to accomplish and greatly helping in debugging the code. Comments are
especially important in large projects containing hundreds or thousands of lines of source code or
in projects in which many contributors are working on the source code.

A comment starts with a slash asterisk /* and ends with a asterisk slash */ and can be anywhere in
your program. Comments can span several lines within your C program. Comments are typically
added directly above the related C source code.
Adding source code comments to your C source code is a highly recommended practice. In
general, it is always better to over comment C source code than to not add enough.

Syntax
The syntax for a comment is:

/* comment goes here */

OR

/*
* comment goes here
*/

Note
 It is important that you choose a style of commenting and use it consistently throughout
your source code. Doing so makes the code more readable.

Example - Comment in Single Line


You can create an comment on a single line.

For example:

/* Author: TechOnTheNet.com */

C++ introduced a double slash comment prefix // as a way to comment single lines. The
following is an example of this:

// Author: TechOnTheNet.com

This form of commenting may be used with most modern C compilers if they also understand the
C++ language.

Example - Comment Spans Multiple Lines


You can create a comment that spans multiple lines. For example:

/*
* Author: TechOnTheNet.com
* Purpose: To show a comment that spans multiple lines.
* Language: C
*/

The compiler will assume that everything after the /* symbol is a comment until it reaches the */
symbol, even if it spans multiple lines within the C program.

Example - Comment at End of Code Line


You can create a comment that displays at the end of a line of code.

For example:

#define AGE 6 /* This constant is called AGE */

OR

#define AGE 6 // This constant is called AGE

In these examples, the compiler will define a constant called AGE that contains the value of 6.
The comment is found at the end of the line of code after the constant has been defined.

Important / Practice Questions

1. Why C language is known as procedural language?


2. Distinguish between pre-increment and post-increment operators in C.
3. Explain the block structure of a C program.
4. What is identifier? Explain the rules for identifier name.
5. What are data types supported by C? Explain basic data type with suitable example.
6. What are keywords in C and their importance in C . Also write any 5 keywords name.

You might also like