Unit 1
Unit 1
CPL is common Programming Language.In 1967, BCPL Language ( Basic CPL ) was
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 .
5 Year 1972
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.
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;
}
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.
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.
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.
int x, y, total;
x = 10, y = 20;
total = x + y;
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.
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:
Name Remark
_A9 Valid
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.
Integer constants consisting of sequence of digits from the set 0 through 7 starting with 0 is said
to be octal 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.
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.
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.
3. Character Constants
A character constant contains one single character enclosed within single quotes.
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.
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.
a Audible alert(bell)
b Backspace
f Form feed
n New line
r Carriage return
t Horizontal tab
v Vertical tab
\ Backslash
? 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.
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.
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,
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.
In this tutorial we will only focus on primitive data types, user defined and derived data types
will be discussed separately.
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 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 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;
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;
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
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.
Union
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:
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.
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:
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.
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.
/*
* 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.
For example:
OR
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.