Introduction to C Programming Language
C is a general-purpose, structured programming language.
Its instructions consists of terms that resemble algebraic
expression, augmented by certain English keywords such as if,
else, for, do and while, etc.
C contains additional features that allow it to be used at a
lower level, thus bridging the gap between machine language
and the more conventional high level language.
This flexibility allows C to be used for system programming
(e.g. for writing
operating systems as well as for applications programming
such as for writing a program to solve mathematical equation
or for writing a program to bill customers).
It also resembles other high level structure programming
language such as Pascal and FORTRAN.
Historical Development of C
C was an offspring of the ‘Basic Combined Programming
Language’ (BCPL) called B, developed in 1960s at Cambridge
University. B language was modified by Dennis Ritchie
and was implemented at Bell Laboratories in 1972. The new
language was named C. Since it was developed along with the
UNIX operating system, it is strongly associated with UNIX.
This operating system was developed at Bell Laboratories and
was coded almost entirely in C.
C was used mainly in academic environments for many years,
but eventually with the release of C compiler for commercial
use and the increasing popularity of UNIX, it began to
gain popularized among compiler professionals.
C was now standardized by American National Standard
Institute (ANSI) . Such type of C was named ANSI C.
Importance of C
•Now-a-days, the popularity of C is increasing probably due to
its many desirable qualities. It is a robust language whose rich
set of built-in functions and operators can be used of built-in
functions and operators can be used to write any complex
program. The C compiler combines the capabilities of an
assemble language with the features of a high-level language
and therefore it well suited for writing both system software
and business packages.
•In fact, many of the C compilers available in the market are
written in C.
•Programs written in C are efficient and fast. This is due to its
variety of data types and powerful operators. It is many times
faster than BASIC (Beginners All Purpose Symbolic
•Instruction Code – a high level programming language).
•Several standard functions are available which can be used
for developing programs.
•C is highly portable. This means that C programs written for
one computer can be seen on another with little or no
modification. Portability is important if we plan to use a new
computer with a different operating system.
•C Language is well suited for structure programming thus
requiring the user to think of a problem in terms of function
modules or blocks. A proper collection of these modules
•would make a complete program. This modular structure
makes program debugging, testing and maintenance.
•Another important feature of C is its ability to extend itself. A
C program is basically a collection of functions that are
supported by the C library. We can continuously add our own
•function to the C library. With the availability of a large
number of functions, the programming task becomes simple.
Fundamentals of C
FUNDAMENTALS OF C
1. C character set
The C character sets are used to form words, numbers and expressions. Different categories of character sets
are – letters, digits and special characters.
Letters – upper case: A…Z
Lower case: a…z
Digits – 0…9
Special characters: „ “ , . : ; { } [ ] ! # $ & ^ ( ) _ - + * < > ? / \ | !
White spaces: blank, tab, newline
2. Identifiers and keywords
Identifiers
Identifiers are user defined names of variables, functions and arrays. It may be a combination of character
(letter and digits) set with the first character as letter.
Rules for identifiers:
Legal characters are a-z, A-Z, 0-9, and _.
Case is significant. Since C is case sensitive, the lower case letters are not equal to uppercase.
The first character must be a letter or _.
The blank space is not allowed but can include (_) between two identifiers.
Identifiers can be of any length (although only the first 31 characters are guaranteed to be significant).
Here are some examples of legal identifiers:
i
count
NumberOfAardvarks
number_of_aardvarks
MAX_LENGTH
Keywords
Keywords are the reserved words having fixed meaning in C. They cannot be used as identifiers. C makes use
of only 32 keywords which combine with the formal syntax to the form the C programming language. Note that
all keywords are written in lower case – C uses upper and lowercase text to mean different things. If you are
not sure what to use then always use lowercase text in writing your C programs. A keyword may not be used
for any other purposes. For example, you cannot have a variable called auto. If we try to use keyword as
variable name, then we‟ll be trying to assign new meaning to the keyword, which is not allowed by the
computer.
The following are reserved keywords, and may not be used as identifiers:
auto double int struct break else long switch case enum register typedef
char extern return union const float short for do if continue
signed void default goto sizeof while volatile unsigned static
3. Header files
Header file defines certain values, symbols and operations which is included in the file to obtain access to its
contents. The header file have the suffix „.h‟. It contains only the prototype of the function in the corresponding
source file. For e.g., stdio.h contains the prototype for „printf‟ while the corresponding source file contains its
definition. It saves time for writing and debugging the code.
4. Constants and variables
Constants
ANSI C allows you to declare constants. Constant is an identifier that is always associated with the same
data value and is taken in its absolute terms. When you declare a constant it is a bit like a variable declaration
except the value cannot be changed. There are two types of constants - literal constant and symbolic
constant.
A literal constant is a value typed directly into your computer and its value must match with the corresponding
data type. A symbolic constant is represented by a name just like as the variable is represented. Unlike a
variable, however a constant is initialized. There are two ways to declare symbolic constant:
Page 1 of 5
Fundamentals of C
1. The const keyword is to declare a constant, as shown below:
Syntax:
<const><datatype><identifier> = <constant value>
int const a = 1;
const int a =2;
Note:
You can declare the const before or after the type.
It is usual to initialize a const with a value, as it cannot get a value any other way.
2. The preprocessor #define is another more flexible method to define constants in a program. #define makes the
preprocessor replace every occurrence of the constant. For e.g., the line #define PI 3.14 appearing at the
beginning of the program specifies that the identifier PI will be replaced by the 3.14 through out the program.
Variables
Variables are the most fundamental part of any programming language. Variable is a symbolic name which is used to
store different types of data in the computer‟s memory. When the user gives the value to the variable, that value is stored
at the same location occupied by the variable. Variables may be of integer, character, string, or floating type.
Variable declaration and initialization
Before you can use a variable you have to declare it. As we have seen above, to do this you state its type and then give
its name. For example, int i; declares an integer variable. You can declare any number of variables of the same type
with a single statement.
To declare a variable in C, do:
<Data type>< list variables >;
For example:
int a, b, c;
float x,y,z;
char ch;
declares three integers: a, b and c, three floating variables: x, y and z and one character: ch. You have to declare all the
variables that you want to use at the start of the program.
Variables are defined in the following way:-
main()
{
short number,sum;
int bignumber,bigsum;
char letter;
}
It is also possible to initialize variables using the = operator for assignment.
For example:-
main()
{
float sum=0.0;
int bigsum=0;
char letter=`A';
}
This is the same as:-
main()
{
float sum;
int bigsum;
char letter;
sum=0.0;
bigsum=0;
letter=`A';
}
...but is more efficient.
C also allows multiple assignment statements using =, for example:
a=b=c=d=3;
...which is the same as, but more efficient than:
Page 2 of 5
Fundamentals of C
a=3;
b=3;
c=3;
d=3;
This kind of multiple assignment is only possible if all the variable types in the statement are the same.
Furthermore, you can assign an initial value to a variable when you declare it. For example:
int i=1;
sets the int variable to one as soon as it's created. This is just the same as:
int i;
i=1;
but the compiler may be able to speed up the operation if you initialize the variable as part of its declaration. Don't
assume that an uninitialized variable has a sensible value stored in it. Some C compilers store 0 in newly created numeric
variables but nothing in the C language compels them to do so.
5. Data types
The first thing we need to know is that we can create variables to store values in. A variable is just a named area of
storage that can hold a single value (numeric or character). C is very fussy about how you create variables and what you
store in them. It demands that you declare the name of each variable that you are going to use and its type, before you
actually try to do anything with it. Hence, data type can be defined as the storage representation and machine instruction
to handle constants and variables.
There are four basic data types associated with variables:
Primary or fundamental data type
User defined data type
Derived data type
Empty data set
Primary/fundamental data type
The data type that is used without any modifier is known as primary data type. The primary data type can be categorized
as follows:
1. Integral type
a. signed integer type
i. int
ii. short int
iii. long int
b. unsigned integer type
i. unsigned int
ii. unsigned short int
iii. unsigned long int
2. Character type
a. signed char
b. unsigned char
3. Floating point type
a. float
b. double
c. long double
int - integer: a whole number. We can think of it as a positive or negative whole number. But, no fractional part is
allowed
To declare an int you use the instruction:
int variable name;
For example:
int a;
declares that you want to create an int variable called a.
float - floating point or real value, i.e., a number with a fractional part.
double - a double-precision floating point value.
char - a single character.
To declare a variable of type character we use the keyword char. - A single character stored in one byte.
For example:
char c;
To assign, or store, a character value in a char data type is easy - a character variable is just a symbol enclosed
by single quotes. For example, if c is a char variable you can store the letter A in it using the following C
statement:
Page 3 of 5
Fundamentals of C
c='A'
Notice that you can only store a single character in a char variable. But, a string constant is written between
double quotes. Remember that a char variable is 'A' and not "A".
Here are the list of data types with their corresponding required memory range of value it can take:
Data type Size (bytes) Range
int 2 -32,768 to 32,737
unsigned int 2 0 to 65,535
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
unsigned long int 4 0 to 4,294,967,295
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
signed char 1 128 to +127
unsigned char 1 0 to 255
6. Operators
C provides rich set of operator environment. Operators are symbols that tell the computer to perform certain
mathematical and logical manipulations. They are used to form a part of mathematical and logical expressions. The
variable/quantity on which operation is to be performed is called operand. The operators can be categorized as:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Conditional operators
5. Unary operators
6. Assignment operators
7. Special operators
Arithmetic Operators
C provides arithmetic operators found in most languages. These operators work on all data types. Each operator require
at least two operands. There are 5 different arithmetic operators- addition (+), subtraction (-), multiplication (*), division (/)
and remainder or modulus (%). The % (modulus) operator only works with integers. Division / is for both integer and float
division.
There are three modes of arithmetic operations:
Integer arithmetic: Both operands are integer. Hence the result will also be integer.
For example, if a=11, b=4 then,
a+ b = 15 ; a-b = 7 ; a/b = 2 ; a*b = 44 ; a%b = 3
Real arithmetic: Both operands are real.
For example, if a=1.0, b=3.0 then,
a+ b = 4.000000 ; a-b = -2.000000 ; a/b = 0.333333 ; a*b = 3.000000
Mixed mode arithmetic: If both real and integer operands are used. The result will be real.
For example, if a=11.0, b=4 then,
a+ b = 15.0 ; a-b = 7.0 ; a/b = 2.75 ; a*b = 44 .0
Note: The answer to: x = 3 / 2 is 1 even if x is declared a float. But x=3.0/2.0 will give the result 1.5. also note that
x=3.0/2.0 is 1 if X is declared as integer.
Relational operators
Relational operators compare two quantities. The result of comparison is TRUE or FALSE. They are used for decision-
making. The operators < (less than) , > (greater than), <= (less than or equals), >= (greater than or equals), == (equals
to), != (not equal to) are relational operators. The operators == and != are also known as equality operators.
For example: in the expression x<y, it returns „true‟ if x is greater than y otherwise returns „false‟.
warning: Beware of using ``='' instead of ``=='', such as writing accidentally
if ( i = j ) .....
This is a perfectly LEGAL C statement (syntactically speaking), which copies the value in "j" into "i", and delivers this
value, which will then be interpreted as TRUE if j is non-zero. This is called assignment by value -- a key feature of C.
Page 4 of 5
Fundamentals of C
Assignment operators
The assignment operator us used to assign result of an expression to a variable. The assignment operator „=‟ assigns the
value of right operand to left. For e.g., in an expression x=y, the value of y is assigned to x.
There is also a convenient shorthand way to express computations in C. It is very common to have expressions like: i = i
+ 3 or x = x*(y + 2)
In C (generally) in a shorthand form like this:
expr1 <op>= expr2
which is equivalent to (but more efficient than):
expr1 = expr1 <op> expr2
= assignment
+= addition assignment
-= subtraction assignment
*= multiplication assignment
/= division assignment
%= remainder/modulus assignment
So we can rewrite i = i + 3 as i += 3
and x = x*(y + 2) as x *= y + 2.
NOTE: that x *= y + 2 means x = x*(y + 2) and NOT x = x*y + 2.
Logical Operators
Logical operators are usually used with conditional statements. It performs test on multiple relations and Boolean
operation. It also returns either true or false. The three basic logical operators are: && for logical AND, || for logical OR , !
for logical NOT. The truth table for AND and OR is as follows:
Operand1 Operand2 Operand1 && Operand2 Operand1 || Operand2
F F F F
F T F T
T F F T
T T T T
For example,
if(a>=1 && a<=6)
printf(“a lies between 1 and 6”); // prints the message if both conditions are satisfied.
Beware & and | have a different meaning for bitwise AND and bitwise OR.
Unary operators
The two operators that are used frequently are ++ and --. ++ specifies increment, the -- specifies decrement. You can
place these in front or on the back of variables. If the operator is placed in front, it is prefix if it is placed behind, it is
postfix. Prefix means, increment before any operations are performed, postfix is increment afterwards. These are
important considerations when using these operators.
Increment ++, Decrement -- which are more efficient than their long hand equivalents, for example:- x++ is faster than
x=x+1.
For e.g., if a=5, x=a++, y=++a and z= a--, then the values of x, y, and z will be 5, 7 and 7 respectively.
Conditional operators
C includes special ternary (3 way) operator that can replace certain if-else statement. The ?: operator is called ternary
operator. The general form of this operator is:
Expression1 ? expression2 : expression3
That means if expression1 is true, then expression2 is executed else expression3 is executed.
For e.g., X= (a<2) ? (a+10) : (a+5);
This is equivalent to,
if (a<2)
X= a+10;
else
X= a+5;
Page 5 of 5
Chapter 3. Input and Output
4.1 Formatted I/O
4.2 Character I/O
4.3 Programs Using I/O statement
Input / Output
Reading, processing and writing of data are three essential functions of a computer program.
C has variety of methods for reading and writing of data.
Input/Output functions are the set of rules to define input and output of data in C programming.
These functions are responsible for the data receiving from different input peripherals like keyboard, etc.
Each function is a keyword which is already mentioned in library files called ‘stdio.h’ header file.
Input and Output Functions/Statements
The C language comprises of several library functions that carry out various commonly used operation or
calculations.
For example, there are library functions that carry out standard input / output operations, functions that perform
operations on the characters, functions that operate on strings, and functions that carry out various
mathematical calculations.
Input and output functions are that functions which help to determine the input value and output value while
coding a program in C. They don’t need to be declared or defined while coding as they are already defined in
library files.
Some of the keywords are defined as the input functions whereas some are defined as output functions. This
makes coding easier as we can easily use the keywords. There are different keywords that are already defined
in C. C has many input output functions in order to read data from input devices and display the results on the
screen. Some of them are as follows:
Functions Input Functions Output Functions
getc( )
putc( )
getchar( )
putchar( )
getch( )
getche( )
putch( )
gets( )
puts( )
scanf( )
printf( )
Types of Input/Output (I/O) Functions
The I/O functions/statements can be categorized as follows:
1. Unformatted input/output functions
2. Formatted input/output functions
The I/O statements can be categorized as unformatted and formatted I/O. The unformatted I/O statements do
not specify how the input and output are carried out. But the formatted I/O statements determine the formats
in which the input and output are executed.
The functions such as getc(), putc(), getchar(), putchar() are considered as unformatted I/O because they do
not contain any information about the format specifiers, field width and any escape sequences. They simply
take variable as parameter.
Formatted I/O generates output under the control of a format string (its first argument) which consists of literal
characters to be printed and also special character sequences--format specifiers--which request that other
arguments be fetched, formatted, and inserted into the string.
Page 1 of 6
Unformatted input/output functions Formatted input/output functions
The unformatted I/O statements do not specify how The formatted I/O statements determine the formats
the input and output are carried out. in which the input and output are executed.
They do not contain any information about the They contain information about the format
format specifiers, field width and any escape specifiers, field width and any escape sequences.
sequences.
Eg. getc( ), putc( ), getchar( ), etc. Eg. scanf( ), printf( )
Conversion Specifier/Format Specifier
Conversion specifier is also known as format specifier. It tells the compiler what data type the variable or
string needs to store. It uses conversion character ‘%’ and type specifier. The type conversion specifier does
what we ask of it - it convert a given bit pattern into a sequence of characters that a user can read. The more
frequently used format specifiers for scanf () and printf() functions are listed below:
Memory Space
Data Type Conversion Specifier
(Byte)
int 2 %d or %i
long int 4 %ld
float 4 %f or %g
double 8 %lf
long double 10 %Lf
char 1 %c
char (for string) (depends on string size) %s
White Spaces/Escape Sequences:
The escape sequences comprises of escape character backslash symbol (\) followed by a character with special
meaning. The escape sequences cause an escape from normal interpretation of a string so that the next string
is recognized as having a special meaning. The escape sequences are considered as single character rather than
a string. Here are some of the mostly used escape sequences:
\n new line
\t horizontal tab
\' single quote
\” double quote
\\ backslash
\0 null character
If we include any of these in the control string then the corresponding ASCII control code is sent to the screen,
or output device, which should produce the effect listed.
Unformatted I/O Functions
Character Input and Output Functions
getc() and putc()
Single character can be entered into the computer and displayed using the C library function getc() and putc().
Syntax:
character_variable =getc(stdin); //stdin means the input is going to take from keyboard buffer
putc(character_variable,stdout); //stdout means the output is going to print on the screen
For example:
char ch; //where ch is a character variable
ch=getc(stdin);
putc(ch,stdout);
Page 2 of 6
//Program to illustrate getc() and putc()
Source code:
#include<stdio.h>
main()
{
char ch;
printf("\nEnter any key: ");
ch=getc(stdin);
printf("\nYou entered: ");
putc(ch,stdout);
}
Output:
Enter any key: h
You entered: h
getchar()
Single character can be entered into the computer using the C library function getchar(). The function does
not require any arguments/parameters, though the pair of empty parenthesis must follow the word getchar.
This function is used to read one character at a time from the key board.
Syntax: character_variable = getchar( );
For example: ch = getchar(); //(ch is a character variable
When this function is executed, the computer will wait for a key to be pressed and assigns the value to the
variable when the “enter” key pressed.
putchar()
Single character output can be displayed using the C library function putchar(). The character being
transmitted will be normally represented as a character-type variable. It must be expressed as an argument to
the function, following the word putchar. This function is used to display one character at a time on the
monitor.
Syntax: putchar(character_variable);
For example:
char ch = M;
putchar(ch);
The Computer displays the value char variable ‘ch’ i.e. M on the Screen.
//Program to illustrate getchar() and putchar()
Source code:
#include<stdio.h>
main()
{
char a;
printf(“\nEnter any key: ”);
a=getchar();
printf(“\n\nYou entered: ”);
putchar(a);
}
Output:
Enter any key: z
You entered: z
getch()
This function is used to read a character from a key board and does not expect the “enter” key press.
Syntax: character_variable = getch();
Page 3 of 6
For example: char ch;
ch=getch()
When this function is executed, computer waits for a key to be pressed from the keyboard. As soon as a key
is pressed, the control is transferred to the next line of the program and the value is assigned to the char
variable. It is noted that the char pressed will not be display on the screen.
getche()
This function is used to read a char from the key board without expecting the enter key to be pressed. The char
read will be displayed on the monitor.
Syntax: character_variable = getche( );
For example: char ch;
ch=getche()
Note: getche() is similar to getch() except that getche() displays the key pressed from the keyboard on the
monitor. In getche() ‘e’ stands for echo. getch() does not echoes(displays) the variable on the screen.
putch()
Single character output can be displayed using the C library function putch(). The character being transmitted
will be normally represented as a character-type variable. It must be expressed as an argument to the function,
following the word putch. This function is used to display one character at a time on the monitor.
Syntax: putch(character_variable);
For example: putch(ch);
//Program to illustrate getch(), getche() and putch()
Source code:
#include<stdio.h>
main()
{
char ch1, ch2;
printf("\nEnter any character1: ");
ch1=getch();
printf("\nEnter any character2: ");
ch2=getche();
printf("\n\nYou entered character1 via getch(): ");
putch(ch1);
printf("\n\nYou entered character2 via getche(): ");
putch(ch2);
}
Output:
Enter any character1:
Enter any character2: v
You entered character1 via getch(): i
You entered character2 via getche(): v
String input/output functions
gets() and puts()
C provides the functions gets() and puts() for string input-output. Though these operations can be done using
the scanf and printf functions with %s conversion character, but the limitation is that with scanf, a string which
has a blank space within it can never be accepted. The function gets() is the solution then. The function gets()
accepts the string variable into the location where the input string is to be stored.
The function puts() accepts as a parameter, a string variable or a string constant for displayed on the standard
output.
Syntax: gets(string_variable);
puts(string_variable);
For example char name[20]; //where name is the string variable
Page 4 of 6
gets(name);
puts(name);
When this function is executed the computer waits for the string to be entered.
//Program to illustrate gets() and puts()
Source code:
#include<stdio.h>
main()
{
char name[20];
printf("\nEnter your name: ");
gets(name); //scanf("%[^\n]",name);
printf("\nYour name is: ");
puts(name);
}
Output:
Enter your name: Anamika Sharma
Your name is: Anamika Sharma
Formatted I/O functions
String input/output functions
Entering input data- scanf()
Input data can be entered into the computer from a standard input device by means of the C library function
scanf(). This function can be used to enter any combination of numerical values, single character and strings
or floating point numbers.
Syntax: scanf(“format string”, list_of_addresses_of_variables);
Eg: scanf(“ %d %f %c”, &x, &y, &z).
‘&’ is called the “address” operator.
In scanf() the ‘&’ operator indicates the memory location of the variable. So that the value read would be
placed at that location.
Writing output data- printf()
Output data can be written from computer into a standard output device using C library function printf(). This
function can be used to output any combination of numerical values, single character and strings or floating
point numbers.
Syntax: printf(“format String”, list_of_arguments);
Eg: printf(“The value of x=%d, Floating No. y=%f and Entered character for z=%c”, x, y, z);
printf(“The value of \’x\’=%d, Floating No. \’y\’=%f and Entered character for \’z\’=%c”, x, y, z); //Using \’
printf(“Your name is \”%s\”, name); //Using \”
OR simply to display the texts on screen: printf(“\n\t WELCOME to C Programming!”);
Control String or Format String
A general form of control string is as follows:
% <flag><width_specifier>.<precision_specifier><conversion_character>
Each part of control string is described below:
Part Description
% First character of control string (compulsory)
Flag (It affects the appearance of the output. It is optional.)
flags meanings
- left justify space
+ always display sign
Blank space display space if there is no sign
0 0 pad with leading zeros
Page 5 of 6
width specifier (w) w is an integer number that specifies the total number of columns for the output value.
(optional)
. Period separating width from precision. (optional)
precision specifier (p) p is also an integer number that specifies the number of digits to the right of the decimal
point of a real number to be printed. (optional)
conversion character There may be a character according to data type to be printed.
For example Field
width
specifier
Precision
Flag specifier
Beginning of
Data type
the control
specifier
string
Variable
printf(“\n Marks: % - 10 . 2f ”, M)
Period
Figure: Illustration of parts of control string
NOTE: WAP to illustrate printf() and scanf() functions
Page 6 of 6